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
@@ -0,0 +1,219 @@
import asyncio
from datetime import timedelta
from hashlib import sha256
from messenger.attachments.application.commands import (
CleanStaging,
ProcessJob,
PublishOutbox,
RecoverExpiredLeases,
)
from messenger.attachments.application.ports import (
AttachmentsUnitOfWork,
Faults,
JobPublisher,
ObjectStorage,
VariantRenderer,
)
from messenger.attachments.domain.errors import UnreadableImage
from messenger.attachments.domain.events import JobSettled
from messenger.attachments.domain.jobs import Claim, FailureCode, Job, Lease, Outcome, RetryPolicy
from messenger.attachments.domain.models import original_key
from messenger.attachments.domain.variants import Variant, variant_key
from messenger.shared.application.errors import Unavailable
from messenger.shared.application.ports import Clock, IdGenerator
TRANSIENT_FAULT = "transient_error"
def settled(
job: Job,
outcome: Outcome,
*,
error_code: str | None = None,
delay_seconds: float | None = None,
) -> JobSettled:
return JobSettled(
job_id=job.id,
attachment_id=job.attachment_id,
pipeline_version=job.pipeline_version,
attempt=job.attempt,
outcome=outcome.value,
error_code=error_code,
delay_seconds=delay_seconds,
)
class ProcessJobHandler:
__slots__ = ("_clock", "_faults", "_ids", "_lease", "_policy", "_renderer", "_storage", "_uow")
def __init__(
self,
uow: AttachmentsUnitOfWork,
storage: ObjectStorage,
renderer: VariantRenderer,
faults: Faults,
*,
clock: Clock,
ids: IdGenerator,
policy: RetryPolicy,
lease: timedelta,
) -> None:
self._uow = uow
self._storage = storage
self._renderer = renderer
self._faults = faults
self._clock = clock
self._ids = ids
self._policy = policy
self._lease = lease
async def __call__(self, command: ProcessJob) -> Outcome:
async with self._uow.transaction():
claim = await self._uow.jobs.claim(command.job, self._ids.new_id(), self._lease)
if claim is None:
await self._uow.jobs.note(command.job, Outcome.DUPLICATE)
self._uow.record(settled(command.job, Outcome.DUPLICATE))
await self._uow.commit()
if claim is None:
return Outcome.DUPLICATE
try:
variants = await self._produce(claim)
except UnreadableImage as error:
return await self._fail(claim.lease, FailureCode.INVALID_IMAGE, error)
except Unavailable as error:
return await self._retry(claim.lease, error)
except Exception as error:
return await self._fail(claim.lease, FailureCode.PROCESSING_FAILED, error)
return await self._complete(claim.lease, variants)
async def _produce(self, claim: Claim) -> list[Variant]:
job = claim.lease.job
self._faults.reach(TRANSIENT_FAULT)
data = await self._storage.read(claim.source_key)
renditions = await self._renderer.render(data, job.pipeline_version)
if claim.staged:
await self._storage.copy(claim.source_key, original_key(job.attachment_id))
variants: list[Variant] = []
for rendition in renditions:
digest = sha256(rendition.data).hexdigest()
key = variant_key(
job.attachment_id, job.pipeline_version, rendition.name, digest, rendition.extension
)
await self._storage.put(key, rendition.data, rendition.content_type)
variants.append(
Variant(
name=rendition.name,
content_type=rendition.content_type,
size_bytes=len(rendition.data),
width=rendition.width,
height=rendition.height,
sha256=digest,
object_key=key,
)
)
return variants
async def _complete(self, lease: Lease, variants: list[Variant]) -> Outcome:
async with self._uow.transaction():
outcome = await self._uow.jobs.complete(
lease, variants, original_key(lease.job.attachment_id)
)
self._uow.record(settled(lease.job, outcome))
await self._uow.commit()
return outcome
async def _retry(self, lease: Lease, error: Exception) -> Outcome:
delay = self._policy.delay(lease.job.attempt)
if delay is None:
return await self._fail(lease, FailureCode.RETRY_EXHAUSTED, error)
async with self._uow.transaction():
at = self._clock.now() + delay
job = await self._uow.jobs.reschedule(
lease, at, Outcome.RESCHEDULED, type(error).__name__
)
outcome = Outcome.FENCED if job is None else Outcome.RESCHEDULED
if job is None:
await self._uow.jobs.note(lease.job, outcome)
self._uow.record(settled(lease.job, outcome, delay_seconds=delay.total_seconds()))
await self._uow.commit()
return outcome
async def _fail(self, lease: Lease, code: FailureCode, error: Exception) -> Outcome:
async with self._uow.transaction():
done = await self._uow.jobs.fail(lease, code, type(error).__name__)
outcome = Outcome.FAILED if done else Outcome.FENCED
if not done:
await self._uow.jobs.note(lease.job, outcome)
self._uow.record(settled(lease.job, outcome, error_code=code.value))
await self._uow.commit()
return outcome
class PublishOutboxHandler:
__slots__ = ("_publisher", "_uow")
def __init__(self, uow: AttachmentsUnitOfWork, publisher: JobPublisher) -> None:
self._uow = uow
self._publisher = publisher
async def __call__(self, command: PublishOutbox) -> int:
failure: Unavailable | None = None
published: list[int] = []
async with self._uow.transaction():
for entry in await self._uow.outbox.pending(command.limit):
try:
await self._publisher.publish(entry.job_id, entry.body)
except Unavailable as error:
failure = error
break
published.append(entry.id)
if published:
await self._uow.outbox.published(published)
await self._uow.commit()
if failure is not None:
raise failure
return len(published)
class RecoverExpiredLeasesHandler:
__slots__ = ("_clock", "_policy", "_uow")
def __init__(self, uow: AttachmentsUnitOfWork, clock: Clock, policy: RetryPolicy) -> None:
self._uow = uow
self._clock = clock
self._policy = policy
async def __call__(self, command: RecoverExpiredLeases) -> int:
async with self._uow.transaction():
leases = await self._uow.jobs.expired(command.limit)
for lease in leases:
if self._policy.delay(lease.job.attempt) is None:
await self._uow.jobs.fail(
lease, FailureCode.RETRY_EXHAUSTED, Outcome.LEASE_EXPIRED.value
)
outcome = Outcome.FAILED
else:
await self._uow.jobs.reschedule(
lease, self._clock.now(), Outcome.LEASE_EXPIRED, Outcome.LEASE_EXPIRED.value
)
outcome = Outcome.LEASE_EXPIRED
self._uow.record(settled(lease.job, outcome))
await self._uow.commit()
return len(leases)
class CleanStagingHandler:
__slots__ = ("_storage", "_uow")
def __init__(self, uow: AttachmentsUnitOfWork, storage: ObjectStorage) -> None:
self._uow = uow
self._storage = storage
async def __call__(self, command: CleanStaging) -> int:
async with self._uow.transaction():
staged = await self._uow.attachments.staged(command.limit)
await asyncio.gather(*(self._storage.delete(item.key) for item in staged))
await self._uow.attachments.unstage([item.attachment_id for item in staged])
await self._uow.commit()
return len(staged)