Upload now stages the checked original under staging/, and one transaction moves the intent to queued, inserts the job (pipeline version 1, attempt 1), its outbox row and an audit event; the 202 is the in-memory snapshot, never a reread. Content answers 409 until the attachment is ready, the thumbnail variant is served from the published version and absent variants are 404. The relay publishes outbox rows through FastStream with publisher confirms, mandatory routing and persistent delivery, marks a row only after the broker acked it, returns jobs whose lease expired and deletes the staging object of ready attachments. The worker consumes the quorum queue through a FastStream subscriber that declares nothing, takes prefetch from WORKER_CONCURRENCY and acks manually after the result commit, rejects messages off jobs.schema.json to the dead letter exchange and requeues after an infrastructure error. A job is claimed under a lease token; the original is copied to originals/ and a 256 px JPEG thumbnail is written under a content-addressed key; the commit is fenced by the token, inserts variants with ON CONFLICT DO NOTHING and publishes only a newer pipeline version. A transient error reschedules the same job with an exponential delay and a new outbox row, the last attempt fails with retry_exhausted, an undecodable image fails at once with invalid_image, and a redelivered finished job is a recorded no-op. The worker and the relay are assembled in worker.py and relay.py with the dishka FastStream integration and the platform providers of the API; the shared core imports neither FastStream nor aio-pika. Tests cover the thumbnail geometry and rendering, the job message against the contract, the pipeline against PostgreSQL (duplicates, parallel copies, retries, the attempt bound, leases and fencing) and the broker adapters against a throwaway RabbitMQ with the stand's topology and permissions. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
6.8 KiB
6.8 KiB
1. Схема
- 1.1 Миграция
0004_jobs.sql: статусыqueued/processing/failed,staging_key,original_key,published_version,error_codeуattachments(переносobject_keyлабы 4), таблицыattachment_variants,jobs,outbox,job_events, частичные индексыoutbox_pending_idx,jobs_lease_idx,attachments_staged_idx - 1.2 Проверка группы: тест миграций — версия
0004, повтор без изменений, колонки из.prep/lab5/tools/schema.reference.sqlна месте, дубль ключа эффекта отклоняется первичным ключом
2. Зона attachments: домен и приложение
- 2.1 Домен: статусы
queued/processing/failed,Attachment.enqueue,Variant, геометрияfit,Jobи его сообщение поjobs.schema.json,Lease,RetryPolicy,FailureCode,Outcome, событияAttachmentQueued,AttachmentReady,AttachmentFailed,JobRescheduled, ошибкаAttachmentNotReady - 2.2 Порты:
ObjectStorage.read/copy,VariantRenderer,JobPublisher,Faults, репозиторииjobsиoutboxвAttachmentsUnitOfWork,AttachmentDirectory.visible - 2.3 Upload:
queuedвместоready, задание и outbox в той же транзакции; запросыGetAttachment/OpenAttachmentс409доreadyи вариантами опубликованной версии - 2.4 Обработчики
ProcessJob(захват, staging → оригинал, рендер, запись вариантов, фиксация с fencing, повтор/финальная ошибка),PublishOutbox,RecoverExpiredLeases,CleanStaging - 2.5 Проверка группы: unit-тесты
fit,RetryPolicy, сообщения задания противcontracts/jobs.schema.json
3. Зона attachments: инфраструктура
- 3.1 PostgreSQL: вложение с ключами и вариантами, задания, outbox, события, захват аренды, фиксация с fencing и
published_version < v, повтор, финальная ошибка, истёкшие аренды, staging к уборке - 3.2 S3:
readиcopy; Pillow:PillowVariantRenderer(EXIF orientation, 16 бит, alpha на белом,fit, JPEG без метаданных, классификацияinvalid_image) - 3.3 FastStream: адаптер
JobPublisher(exchange без объявления,persist,mandatory, confirm,message_id),FAULT_POINTс точкойtransient_error; зависимостиfaststream[rabbit],dishka-faststreamвuv.lock - 3.4 Проверка группы: тест рендера (fixture 320×200 → 256×160, RGBA на белом, EXIF 6, 17×1000 → 4×256, битые данные →
invalid_image)
4. Точки входа и сборка процессов
- 4.1 HTTP:
202upload,variantиз четырёх значений,409, схемаAttachmentOutсо статусом и вариантами, реестр ошибок, журнал - 4.2
PipelineSettings,PipelineProvider, точка входа worker (FastStream-подписчик, проверка сообщения,ack/reject/nack), циклы relay, heartbeat - 4.3 Сборки
relay.pyиworker.py, тест графа импортов: сборки процессов знают одну зону,shared/не импортирует FastStream - 4.4 Проверка группы: тесты pipeline против одноразового PostgreSQL с памятью вместо S3 —
ready, дубль послеreadyбез новых строк, параллельные копии, временная ошибка →queuedи новая строка outbox, исчерпание →retry_exhausted,invalid_imageбез повторов, fencing чужой аренды, возврат истёкшей аренды, уборка staging, публикация outbox
5. Связь зон
- 5.1
messaging: портAttachmentStates, ошибкаAttachmentUnavailable→409, проверка только для первого исполнения (повтор по ключу возвращает исходный ответ) - 5.2
main.py: адаптер порта поверхAttachmentDirectory, версия 1.5.0 - 5.3 Проверка группы: API-тесты —
202 queued,409на/contentдоready,400на неизвестныйvariant,404наcrop, сообщение сqueued—201, сfailed—409
6. Стенд
- 6.1
infra/rabbitmq/,infra/s3/worker-policy.json,infra/compose.faults.yamlиз.prep/lab5; пользователь worker вinfra/s3/init.sh - 6.2
compose.yaml:broker,relay,worker, volumebroker-data, секреты брокера и S3-ключа worker;scripts/broker-secrets.shвmake secrets;.env.example(BROKER_MANAGEMENT_PORT,JOB_BACKOFF_BASE_SECONDS,OUTBOX_POLL_SECONDS,SWEEP_INTERVAL_SECONDS) - 6.3 Хуки:
restart.shс relay, worker и broker;worker.sh,broker.sh - 6.4 Проверка группы:
docker compose config --quiet,make upиз чистого состояния, все сервисыhealthy, топология и consumer сprefetch_count, опубликованы толькоlbи UI брокера на127.0.0.1
7. Сценарии и обвязка
- 7.1
scripts/pipeline_suite.py,scripts/make_images.pyиз.prep/lab5; цели Makefilequeues,worker-stop,worker-start,broker-restart,suite-preflight,level3,topology; ruff для новыхscripts/*.py - 7.2 CI-job под лабу 5: брокер, relay и worker в стенде, сценарии уровня «3»
- 7.3 Проверка группы:
make test,make test-persistence ACTION_SCRIPT=scripts/restart.sh,make test-failover ACTION_SCRIPT=scripts/stop-one.shсmake restore,make suite-preflight,make level3
8. Отчёт
- 8.1
evidence/: smoke, persistence и failover с состояниями контейнеров, level3, topology, student-tests, contract-checks, окружение - 8.2
REPORT.md: запуск из чистого clone, архитектура и решения, таблица ролей, соответствие переменных.env.example, строки уровня «3», таблица отказов уровня «3» - 8.3 Проверка группы:
make check,make validate,make lint,make student-testзелёные