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:
co-authored by
Claude Opus 5.5
parent
64fdaa03f2
commit
b152b6e07e
@@ -25,5 +25,13 @@ class AttachmentNotFound(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class AttachmentNotReady(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class UploadAborted(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class UnreadableImage(AttachmentError):
|
||||
pass
|
||||
|
||||
@@ -5,12 +5,12 @@ from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AttachmentStored(DomainEvent):
|
||||
class AttachmentQueued(DomainEvent):
|
||||
attachment_id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
size_bytes: int
|
||||
name: str = field(init=False, default="attachment.stored")
|
||||
name: str = field(init=False, default="attachment.queued")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -19,3 +19,15 @@ class AttachmentDiscarded(DomainEvent):
|
||||
chat_id: UUID
|
||||
reason: str
|
||||
name: str = field(init=False, default="attachment.discarded")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class JobSettled(DomainEvent):
|
||||
job_id: UUID
|
||||
attachment_id: UUID
|
||||
pipeline_version: int
|
||||
attempt: int
|
||||
outcome: str
|
||||
error_code: str | None = None
|
||||
delay_seconds: float | None = None
|
||||
name: str = field(init=False, default="job.settled")
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
from dataclasses import dataclass, replace
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
JOB_TYPE = "attachment.process.v1"
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
class FailureCode(StrEnum):
|
||||
INVALID_IMAGE = "invalid_image"
|
||||
PROCESSING_FAILED = "processing_failed"
|
||||
RETRY_EXHAUSTED = "retry_exhausted"
|
||||
|
||||
|
||||
class Outcome(StrEnum):
|
||||
DONE = "done"
|
||||
DUPLICATE = "duplicate_noop"
|
||||
FENCED = "fenced"
|
||||
SUPERSEDED = "superseded"
|
||||
RESCHEDULED = "retry_scheduled"
|
||||
LEASE_EXPIRED = "lease_expired"
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Job:
|
||||
id: UUID
|
||||
attachment_id: UUID
|
||||
pipeline_version: int
|
||||
attempt: int
|
||||
created_at: datetime
|
||||
|
||||
def payload(self) -> dict[str, Any]:
|
||||
stamp = self.created_at.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
return {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"job_id": str(self.id),
|
||||
"type": JOB_TYPE,
|
||||
"attachment_id": str(self.attachment_id),
|
||||
"pipeline_version": self.pipeline_version,
|
||||
"attempt": self.attempt,
|
||||
"created_at": stamp,
|
||||
}
|
||||
|
||||
def retried(self, attempt: int) -> Job:
|
||||
return replace(self, attempt=attempt)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Lease:
|
||||
job: Job
|
||||
token: UUID
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Claim:
|
||||
lease: Lease
|
||||
source_key: str
|
||||
staged: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RetryPolicy:
|
||||
max_attempts: int
|
||||
base_seconds: float
|
||||
cap_seconds: float
|
||||
|
||||
def delay(self, attempt: int) -> timedelta | None:
|
||||
if attempt >= self.max_attempts:
|
||||
return None
|
||||
return timedelta(seconds=min(self.cap_seconds, self.base_seconds * 2 ** (attempt - 1)))
|
||||
@@ -3,16 +3,25 @@ from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.attachments.domain.events import AttachmentDiscarded, AttachmentStored
|
||||
from messenger.attachments.domain.events import AttachmentDiscarded, AttachmentQueued
|
||||
from messenger.attachments.domain.values import Filename, ImageInfo
|
||||
from messenger.attachments.domain.variants import Variant
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
OBJECT_PREFIX = "attachments/"
|
||||
STAGING_PREFIX = "staging/"
|
||||
ORIGINALS_PREFIX = "originals/"
|
||||
|
||||
|
||||
class AttachmentStatus(StrEnum):
|
||||
PENDING = "pending"
|
||||
QUEUED = "queued"
|
||||
PROCESSING = "processing"
|
||||
READY = "ready"
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
def original_key(attachment_id: UUID) -> str:
|
||||
return f"{ORIGINALS_PREFIX}{attachment_id}"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -24,10 +33,14 @@ class Attachment:
|
||||
image: ImageInfo
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
object_key: str
|
||||
status: AttachmentStatus
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
staging_key: str | None = None
|
||||
original_key: str | None = None
|
||||
published_version: int = 0
|
||||
error_code: str | None = None
|
||||
variants: tuple[Variant, ...] = ()
|
||||
_events: list[DomainEvent] = field(init=False, default_factory=list, repr=False, compare=False)
|
||||
|
||||
@classmethod
|
||||
@@ -51,21 +64,28 @@ class Attachment:
|
||||
image=image,
|
||||
size_bytes=size_bytes,
|
||||
sha256=sha256,
|
||||
object_key=f"{OBJECT_PREFIX}{attachment_id}",
|
||||
status=AttachmentStatus.PENDING,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
staging_key=f"{STAGING_PREFIX}{attachment_id}",
|
||||
)
|
||||
|
||||
@property
|
||||
def content_type(self) -> str:
|
||||
return self.image.kind.value
|
||||
|
||||
def store(self, now: datetime) -> None:
|
||||
self.status = AttachmentStatus.READY
|
||||
@property
|
||||
def ready(self) -> bool:
|
||||
return self.status is AttachmentStatus.READY
|
||||
|
||||
def variant(self, name: str) -> Variant | None:
|
||||
return next((variant for variant in self.variants if variant.name == name), None)
|
||||
|
||||
def enqueue(self, now: datetime) -> None:
|
||||
self.status = AttachmentStatus.QUEUED
|
||||
self.updated_at = max(now, self.created_at)
|
||||
self._events.append(
|
||||
AttachmentStored(
|
||||
AttachmentQueued(
|
||||
attachment_id=self.id,
|
||||
chat_id=self.chat_id,
|
||||
owner_id=self.owner_id,
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
from dataclasses import dataclass
|
||||
from uuid import UUID
|
||||
|
||||
THUMBNAIL = "thumbnail"
|
||||
THUMBNAIL_BOX = 256
|
||||
VARIANTS_PREFIX = "variants/"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Variant:
|
||||
name: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
object_key: str
|
||||
|
||||
|
||||
def fit(width: int, height: int, box: int) -> tuple[int, int]:
|
||||
if max(width, height) <= box:
|
||||
return width, height
|
||||
if width >= height:
|
||||
return box, max(1, height * box // width)
|
||||
return max(1, width * box // height), box
|
||||
|
||||
|
||||
def variant_key(
|
||||
attachment_id: UUID, pipeline_version: int, name: str, sha256: str, extension: str
|
||||
) -> str:
|
||||
return f"{VARIANTS_PREFIX}{attachment_id}/{pipeline_version}/{name}-{sha256[:16]}.{extension}"
|
||||
Reference in New Issue
Block a user