Process attachment jobs through an outbox, a relay and a worker

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>
This commit is contained in:
Artyom
2026-10-29 01:08:06 +03:00
co-authored by Claude Opus 5.5
parent 64fdaa03f2
commit b152b6e07e
41 changed files with 2506 additions and 115 deletions
+130 -13
View File
@@ -1,28 +1,50 @@
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from datetime import timedelta
from dishka import Provider, Scope, provide
from faststream.rabbit import RabbitBroker
from messenger.attachments.application.bus import AttachmentsCommandBus
from messenger.attachments.application.commands import SweepAbandonedUploads, UploadAttachment
from messenger.attachments.application.commands import (
CleanStaging,
ProcessJob,
PublishOutbox,
RecoverExpiredLeases,
SweepAbandonedUploads,
UploadAttachment,
)
from messenger.attachments.application.handlers import (
SweepAbandonedUploadsHandler,
UploadAttachmentHandler,
UploadSlots,
)
from messenger.attachments.application.pipeline import (
CleanStagingHandler,
ProcessJobHandler,
PublishOutboxHandler,
RecoverExpiredLeasesHandler,
)
from messenger.attachments.application.ports import (
AttachmentDirectory,
AttachmentsUnitOfWork,
ChatMembership,
Faults,
ImageInspector,
JobPublisher,
ObjectStorage,
VariantRenderer,
)
from messenger.attachments.application.queries import GetAttachment, OpenAttachment
from messenger.attachments.config import AttachmentsSettings
from messenger.attachments.infrastructure.images import PillowImageInspector
from messenger.attachments.config import AttachmentsSettings, PipelineSettings
from messenger.attachments.domain.jobs import RetryPolicy
from messenger.attachments.infrastructure.faults import EnvironmentFaults
from messenger.attachments.infrastructure.images import PillowImageInspector, PillowVariantRenderer
from messenger.attachments.infrastructure.postgres import (
PostgresAttachmentDirectory,
PostgresAttachmentsUnitOfWork,
)
from messenger.attachments.infrastructure.rabbitmq import RabbitJobPublisher
from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client
from messenger.shared.application.commands import Command
from messenger.shared.application.messagebus import CommandHandler
@@ -30,6 +52,20 @@ from messenger.shared.application.ports import Clock, EventPublisher, IdGenerato
from messenger.shared.infrastructure.postgres import Database
@asynccontextmanager
async def object_storage(settings: AttachmentsSettings) -> AsyncIterator[ObjectStorage]:
async with s3_client(
endpoint=settings.s3_endpoint,
region=settings.s3_region,
access_key_id=settings.s3_access_key_id.get_secret_value(),
secret_access_key=settings.s3_secret_access_key.get_secret_value(),
connect_timeout=settings.s3_connect_timeout_seconds,
read_timeout=settings.s3_read_timeout_seconds,
max_attempts=settings.s3_max_attempts,
) as client:
yield S3ObjectStorage(client, settings.s3_bucket)
class AttachmentsProvider(Provider):
def __init__(self, settings: AttachmentsSettings) -> None:
super().__init__()
@@ -41,16 +77,8 @@ class AttachmentsProvider(Provider):
@provide(scope=Scope.APP)
async def storage(self, settings: AttachmentsSettings) -> AsyncIterator[ObjectStorage]:
async with s3_client(
endpoint=settings.s3_endpoint,
region=settings.s3_region,
access_key_id=settings.s3_access_key_id.get_secret_value(),
secret_access_key=settings.s3_secret_access_key.get_secret_value(),
connect_timeout=settings.s3_connect_timeout_seconds,
read_timeout=settings.s3_read_timeout_seconds,
max_attempts=settings.s3_max_attempts,
) as client:
yield S3ObjectStorage(client, settings.s3_bucket)
async with object_storage(settings) as storage:
yield storage
@provide(scope=Scope.APP)
def images(self, settings: AttachmentsSettings) -> ImageInspector:
@@ -110,3 +138,92 @@ class AttachmentsProvider(Provider):
SweepAbandonedUploads: SweepAbandonedUploadsHandler(uow, storage, clock),
}
return AttachmentsCommandBus(handlers, uow, publisher)
class PipelineProvider(Provider):
def __init__(self, settings: PipelineSettings) -> None:
super().__init__()
self._settings = settings
@provide(scope=Scope.APP)
def settings(self) -> PipelineSettings:
return self._settings
@provide(scope=Scope.APP)
async def storage(self, settings: PipelineSettings) -> AsyncIterator[ObjectStorage]:
async with object_storage(settings) as storage:
yield storage
@provide(scope=Scope.APP)
def policy(self, settings: PipelineSettings) -> RetryPolicy:
return RetryPolicy(
settings.job_max_attempts,
settings.job_backoff_base_seconds,
settings.job_backoff_cap_seconds,
)
@provide(scope=Scope.REQUEST)
def unit_of_work(self, database: Database) -> AttachmentsUnitOfWork:
return PostgresAttachmentsUnitOfWork(database)
class WorkerProvider(Provider):
@provide(scope=Scope.APP)
def renderer(self, settings: PipelineSettings) -> VariantRenderer:
return PillowVariantRenderer(settings.max_image_pixels, settings.worker_concurrency)
@provide(scope=Scope.APP)
def faults(self, settings: PipelineSettings, logger: Logger) -> Faults:
return EnvironmentFaults(settings.fault_point, logger)
@provide(scope=Scope.REQUEST)
def command_bus(
self,
uow: AttachmentsUnitOfWork,
storage: ObjectStorage,
renderer: VariantRenderer,
faults: Faults,
publisher: EventPublisher,
clock: Clock,
ids: IdGenerator,
policy: RetryPolicy,
settings: PipelineSettings,
) -> AttachmentsCommandBus:
process = ProcessJobHandler(
uow,
storage,
renderer,
faults,
clock=clock,
ids=ids,
policy=policy,
lease=timedelta(seconds=settings.job_timeout_seconds),
)
return AttachmentsCommandBus({ProcessJob: process}, uow, publisher)
class RelayProvider(Provider):
def __init__(self, broker: RabbitBroker) -> None:
super().__init__()
self._broker = broker
@provide(scope=Scope.APP)
def publisher(self, settings: PipelineSettings) -> JobPublisher:
return RabbitJobPublisher(self._broker, settings.publish_timeout_seconds)
@provide(scope=Scope.REQUEST)
def command_bus(
self,
uow: AttachmentsUnitOfWork,
storage: ObjectStorage,
jobs: JobPublisher,
publisher: EventPublisher,
clock: Clock,
policy: RetryPolicy,
) -> AttachmentsCommandBus:
handlers: dict[type[Command], CommandHandler] = {
PublishOutbox: PublishOutboxHandler(uow, jobs),
RecoverExpiredLeases: RecoverExpiredLeasesHandler(uow, clock, policy),
CleanStaging: CleanStagingHandler(uow, storage),
}
return AttachmentsCommandBus(handlers, uow, publisher)