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
@@ -3,6 +3,7 @@ from dataclasses import dataclass
from datetime import timedelta
from uuid import UUID
from messenger.attachments.domain.jobs import Job
from messenger.shared.application.commands import Command
@@ -19,3 +20,23 @@ class UploadAttachment(Command):
class SweepAbandonedUploads(Command):
grace: timedelta
limit: int
@dataclass(frozen=True, slots=True)
class ProcessJob(Command):
job: Job
@dataclass(frozen=True, slots=True)
class PublishOutbox(Command):
limit: int
@dataclass(frozen=True, slots=True)
class RecoverExpiredLeases(Command):
limit: int
@dataclass(frozen=True, slots=True)
class CleanStaging(Command):
limit: int
@@ -10,6 +10,7 @@ from messenger.attachments.application.ports import (
ObjectStorage,
)
from messenger.attachments.domain.errors import ChatNotFound, PayloadTooLarge
from messenger.attachments.domain.jobs import Job
from messenger.attachments.domain.models import Attachment, AttachmentStatus
from messenger.attachments.domain.values import Filename, ImageKind
from messenger.shared.application.ports import Clock, IdGenerator, Logger
@@ -35,7 +36,8 @@ async def read_limited(body: AsyncIterator[bytes], limit: int) -> tuple[bytes, s
async def drop(
uow: AttachmentsUnitOfWork, storage: ObjectStorage, attachment: Attachment, reason: str
) -> None:
await storage.delete(attachment.object_key)
if attachment.staging_key is not None:
await storage.delete(attachment.staging_key)
attachment.discard(reason)
await uow.attachments.remove(attachment)
await uow.commit()
@@ -49,6 +51,7 @@ class UploadAttachmentHandler:
"_limit",
"_logger",
"_membership",
"_pipeline_version",
"_slots",
"_storage",
"_uow",
@@ -66,6 +69,7 @@ class UploadAttachmentHandler:
limit: int,
slots: UploadSlots,
logger: Logger,
pipeline_version: int = 1,
) -> None:
self._uow = uow
self._membership = membership
@@ -76,6 +80,7 @@ class UploadAttachmentHandler:
self._limit = limit
self._slots = slots
self._logger = logger
self._pipeline_version = pipeline_version
async def __call__(self, command: UploadAttachment) -> Attachment:
if not await self._membership.is_member(command.chat_id, command.owner_id):
@@ -84,10 +89,13 @@ class UploadAttachmentHandler:
declared = ImageKind.declared(command.content_type)
async with self._slots:
attachment = await self._write(command, filename, declared)
attachment.store(self._clock.now())
now = self._clock.now()
attachment.enqueue(now)
job = Job(self._ids.new_id(), attachment.id, self._pipeline_version, 1, now)
try:
async with self._uow.transaction():
await self._uow.attachments.save(attachment)
await self._uow.jobs.add(job)
await self._uow.commit()
except Exception:
await self._compensate(attachment)
@@ -112,7 +120,7 @@ class UploadAttachmentHandler:
async with self._uow.transaction():
await self._uow.attachments.add(attachment)
await self._uow.commit()
await self._storage.put(attachment.object_key, data, attachment.content_type)
await self._storage.put(str(attachment.staging_key), data, attachment.content_type)
return attachment
async def _compensate(self, staged: Attachment) -> None:
@@ -120,7 +128,7 @@ class UploadAttachmentHandler:
async with self._uow.transaction():
current = await self._uow.attachments.lock(staged.id)
if current is None:
await self._storage.delete(staged.object_key)
await self._storage.delete(str(staged.staging_key))
elif current.status is AttachmentStatus.PENDING:
await drop(self._uow, self._storage, current, "compensation")
except Exception as error:
@@ -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)
+87 -3
View File
@@ -1,11 +1,13 @@
from collections.abc import AsyncIterator
from collections.abc import AsyncIterator, Sequence
from dataclasses import dataclass
from datetime import datetime
from datetime import datetime, timedelta
from typing import Protocol, runtime_checkable
from uuid import UUID
from messenger.attachments.domain.jobs import Claim, FailureCode, Job, Lease, Outcome
from messenger.attachments.domain.models import Attachment
from messenger.attachments.domain.values import ImageInfo, ImageKind
from messenger.attachments.domain.variants import Variant
from messenger.shared.application.ports import UnitOfWork
@@ -15,12 +17,39 @@ class ObjectContent:
chunks: AsyncIterator[bytes]
@dataclass(frozen=True, slots=True)
class Rendition:
name: str
content_type: str
extension: str
data: bytes
width: int
height: int
@dataclass(frozen=True, slots=True)
class OutboxEntry:
id: int
job_id: UUID
body: bytes
@dataclass(frozen=True, slots=True)
class StagedObject:
attachment_id: UUID
key: str
@runtime_checkable
class ObjectStorage(Protocol):
async def put(self, key: str, data: bytes, content_type: str) -> None: ...
async def open(self, key: str) -> ObjectContent: ...
async def read(self, key: str) -> bytes: ...
async def copy(self, source: str, target: str) -> None: ...
async def delete(self, key: str) -> None: ...
@@ -29,6 +58,21 @@ class ImageInspector(Protocol):
async def inspect(self, data: bytes, declared: ImageKind) -> ImageInfo: ...
@runtime_checkable
class VariantRenderer(Protocol):
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]: ...
@runtime_checkable
class JobPublisher(Protocol):
async def publish(self, job_id: UUID, body: bytes) -> None: ...
@runtime_checkable
class Faults(Protocol):
def reach(self, point: str) -> None: ...
@runtime_checkable
class ChatMembership(Protocol):
async def is_member(self, chat_id: UUID, user_id: UUID) -> bool: ...
@@ -46,13 +90,53 @@ class AttachmentRepository(Protocol):
async def remove(self, attachment: Attachment) -> None: ...
async def staged(self, limit: int) -> list[StagedObject]: ...
async def unstage(self, attachment_ids: Sequence[UUID]) -> None: ...
@runtime_checkable
class JobRepository(Protocol):
async def add(self, job: Job) -> None: ...
async def claim(self, job: Job, token: UUID, lease: timedelta) -> Claim | None: ...
async def complete(
self, lease: Lease, variants: Sequence[Variant], original_key: str
) -> Outcome: ...
async def reschedule(
self, lease: Lease, at: datetime, kind: Outcome, error: str
) -> Job | None: ...
async def fail(self, lease: Lease, code: FailureCode, error: str) -> bool: ...
async def note(self, job: Job, kind: Outcome) -> None: ...
async def expired(self, limit: int) -> list[Lease]: ...
@runtime_checkable
class OutboxRepository(Protocol):
async def pending(self, limit: int) -> list[OutboxEntry]: ...
async def published(self, entry_ids: Sequence[int]) -> None: ...
@runtime_checkable
class AttachmentsUnitOfWork(UnitOfWork, Protocol):
@property
def attachments(self) -> AttachmentRepository: ...
@property
def jobs(self) -> JobRepository: ...
@property
def outbox(self) -> OutboxRepository: ...
@runtime_checkable
class AttachmentDirectory(Protocol):
async def ready(self, attachment_id: UUID) -> Attachment | None: ...
async def visible(self, attachment_id: UUID) -> Attachment | None: ...
async def failed_among(self, chat_id: UUID, attachment_ids: Sequence[UUID]) -> bool: ...
@@ -7,10 +7,12 @@ from messenger.attachments.application.ports import (
ObjectContent,
ObjectStorage,
)
from messenger.attachments.domain.errors import AttachmentNotFound
from messenger.attachments.domain.errors import AttachmentNotFound, AttachmentNotReady
from messenger.attachments.domain.models import Attachment
from messenger.shared.application.ports import Logger
ORIGINAL = "original"
class GetAttachment:
__slots__ = ("_attachments", "_membership")
@@ -20,7 +22,7 @@ class GetAttachment:
self._membership = membership
async def __call__(self, attachment_id: UUID, user_id: UUID) -> Attachment:
attachment = await self._attachments.ready(attachment_id)
attachment = await self._attachments.visible(attachment_id)
if attachment is None or not await self._membership.is_member(attachment.chat_id, user_id):
raise AttachmentNotFound("вложение не найдено")
return attachment
@@ -35,12 +37,21 @@ class OpenAttachment:
self._logger = logger
async def __call__(
self, attachment_id: UUID, user_id: UUID
) -> tuple[Attachment, ObjectContent]:
self, attachment_id: UUID, user_id: UUID, variant: str = ORIGINAL
) -> tuple[str, ObjectContent]:
attachment = await self._get(attachment_id, user_id)
if not attachment.ready:
raise AttachmentNotReady("вложение ещё не обработано или обработка не удалась")
if variant == ORIGINAL:
key, content_type = attachment.original_key, attachment.content_type
else:
found = attachment.variant(variant)
if found is None:
raise AttachmentNotFound("у вложения нет такого варианта")
key, content_type = found.object_key, found.content_type
try:
content = await self._storage.open(attachment.object_key)
content = await self._storage.open(str(key))
except ObjectMissingError as error:
self._logger.warning("attachment.object_missing", attachment_id=str(attachment.id))
raise AttachmentNotFound("вложение не найдено") from error
return attachment, content
return content_type, content