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
@@ -1,11 +1,16 @@
from datetime import datetime
import json
from collections.abc import Sequence
from datetime import datetime, timedelta
from uuid import UUID
from asyncpg import ForeignKeyViolationError, Record
from messenger.attachments.application.ports import OutboxEntry, StagedObject
from messenger.attachments.domain.errors import ChatNotFound
from messenger.attachments.domain.jobs import Claim, FailureCode, Job, Lease, Outcome
from messenger.attachments.domain.models import Attachment, AttachmentStatus
from messenger.attachments.domain.values import Filename, ImageInfo, ImageKind
from messenger.attachments.domain.variants import Variant
from messenger.shared.application.errors import Unavailable
from messenger.shared.infrastructure.postgres import (
Connection,
@@ -16,26 +21,151 @@ from messenger.shared.infrastructure.postgres import (
INSERT = """
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
width, height, object_key, status, created_at, updated_at)
width, height, staging_key, status, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
"""
MARK = "UPDATE attachments SET status = $2, updated_at = $3 WHERE id = $1 AND status = 'pending'"
COLUMNS = """
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height,
object_key, status, created_at, updated_at
FROM attachments
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.width,
a.height, a.status, a.staging_key, a.original_key, a.published_version, a.error_code,
a.created_at, a.updated_at
FROM attachments a
"""
READY = COLUMNS + "WHERE id = $1 AND status = 'ready'"
LOCK = COLUMNS + "WHERE id = $1 FOR UPDATE"
VISIBLE = """
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.width,
a.height, a.status, a.staging_key, a.original_key, a.published_version, a.error_code,
a.created_at, a.updated_at,
(SELECT coalesce(jsonb_agg(jsonb_build_array(v.name, v.content_type, v.size_bytes, v.width,
v.height, v.sha256, v.object_key)
ORDER BY v.name), '[]')
FROM attachment_variants v
WHERE v.attachment_id = a.id AND v.pipeline_version = a.published_version) AS variants
FROM attachments a
WHERE a.id = $1 AND a.status <> 'pending'
"""
FAILED_AMONG = """
SELECT EXISTS (SELECT 1 FROM attachments
WHERE id = ANY($1::uuid[]) AND chat_id = $2 AND status = 'failed')
"""
LOCK = COLUMNS + "WHERE a.id = $1 FOR UPDATE"
ABANDONED = (
COLUMNS
+ """WHERE status = 'pending' AND created_at < $1
ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED"""
+ """WHERE a.status = 'pending' AND a.created_at < $1
ORDER BY a.created_at LIMIT 1 FOR UPDATE SKIP LOCKED"""
)
REMOVE = "DELETE FROM attachments WHERE id = $1 AND status = 'pending'"
STAGED = """
SELECT id, staging_key FROM attachments
WHERE staging_key IS NOT NULL AND status = 'ready'
ORDER BY updated_at LIMIT $1 FOR UPDATE SKIP LOCKED
"""
UNSTAGE = "UPDATE attachments SET staging_key = NULL WHERE id = ANY($1::uuid[])"
ADD_JOB = """
WITH job AS (
INSERT INTO jobs (job_id, attachment_id, pipeline_version, status, attempt,
created_at, updated_at)
VALUES ($1, $2, $3, 'queued', $4, $5, $5)
RETURNING job_id
), box AS (
INSERT INTO outbox (job_id, payload, available_at)
SELECT job_id, $6::jsonb, now() FROM job
)
INSERT INTO job_events (job_id, attachment_id, kind, attempt)
SELECT job_id, $2, 'enqueued', $4 FROM job
"""
CLAIM = """
WITH claimed AS (
UPDATE jobs
SET status = 'processing', lease_token = $4, claims = claims + 1, updated_at = now(),
lease_until = now() + make_interval(secs => $5)
WHERE job_id = $1 AND attachment_id = $2 AND pipeline_version = $3
AND ((status = 'queued' AND coalesce(next_attempt_at, '-infinity') <= now())
OR (status = 'processing' AND lease_until < now()))
RETURNING job_id, attachment_id, attempt, created_at
), moved AS (
UPDATE attachments a SET status = 'processing', updated_at = greatest(now(), a.created_at)
FROM claimed c WHERE a.id = c.attachment_id AND a.status = 'queued'
), audit AS (
INSERT INTO job_events (job_id, attachment_id, kind, attempt)
SELECT job_id, attachment_id, 'claimed', attempt FROM claimed
)
SELECT c.attempt, c.created_at, a.staging_key, a.original_key
FROM claimed c JOIN attachments a ON a.id = c.attachment_id
"""
FINISH = """
UPDATE jobs SET status = 'done', lease_token = NULL, lease_until = NULL, next_attempt_at = NULL,
last_error = NULL, updated_at = now()
WHERE job_id = $1 AND status = 'processing' AND lease_token = $2
"""
ADD_VARIANTS = """
INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type,
size_bytes, width, height, sha256, created_at)
SELECT $1, $2, v.name, v.object_key, v.content_type, v.size_bytes, v.width, v.height, v.sha256,
now()
FROM unnest($3::text[], $4::text[], $5::text[], $6::bigint[], $7::int[], $8::int[], $9::text[])
AS v (name, object_key, content_type, size_bytes, width, height, sha256)
ON CONFLICT DO NOTHING
"""
PUBLISH = """
UPDATE attachments
SET status = 'ready', published_version = $2, error_code = NULL, original_key = $3,
updated_at = greatest(now(), created_at)
WHERE id = $1 AND published_version < $2
"""
SUPERSEDE = "UPDATE jobs SET status = 'superseded', updated_at = now() WHERE job_id = $1"
RESCHEDULE = """
WITH job AS (
UPDATE jobs
SET status = 'queued', attempt = attempt + 1, lease_token = NULL, lease_until = NULL,
next_attempt_at = $3, last_error = $4, updated_at = now()
WHERE job_id = $1 AND status = 'processing' AND lease_token = $2
RETURNING job_id, attachment_id, attempt
), moved AS (
UPDATE attachments a SET status = 'queued', updated_at = greatest(now(), a.created_at)
FROM job WHERE a.id = job.attachment_id AND a.status = 'processing'
), audit AS (
INSERT INTO job_events (job_id, attachment_id, kind, attempt, detail)
SELECT job_id, attachment_id, $5, attempt,
jsonb_build_object('error', $4::text, 'next_attempt_at', $3::timestamptz)
FROM job
)
SELECT attempt FROM job
"""
ENQUEUE = "INSERT INTO outbox (job_id, payload, available_at) VALUES ($1, $2::jsonb, $3)"
FAIL = """
WITH job AS (
UPDATE jobs SET status = 'failed', lease_token = NULL, lease_until = NULL, last_error = $4,
updated_at = now()
WHERE job_id = $1 AND status = 'processing' AND lease_token = $2
RETURNING job_id, attachment_id, attempt
), moved AS (
UPDATE attachments a SET status = 'failed', error_code = $3,
updated_at = greatest(now(), a.created_at)
FROM job WHERE a.id = job.attachment_id AND a.status IN ('queued', 'processing')
), audit AS (
INSERT INTO job_events (job_id, attachment_id, kind, attempt, detail)
SELECT job_id, attachment_id, 'failed', attempt,
jsonb_build_object('error_code', $3::text, 'error', $4::text)
FROM job
)
SELECT attempt FROM job
"""
NOTE = "INSERT INTO job_events (job_id, attachment_id, kind, attempt) VALUES ($1, $2, $3, $4)"
EXPIRED = """
SELECT job_id, attachment_id, pipeline_version, attempt, created_at, lease_token FROM jobs
WHERE status = 'processing' AND lease_until < now()
ORDER BY lease_until LIMIT $1 FOR UPDATE SKIP LOCKED
"""
PENDING = """
SELECT id, job_id, payload::text AS body FROM outbox
WHERE published_at IS NULL AND available_at <= now()
ORDER BY available_at, id LIMIT $1 FOR UPDATE SKIP LOCKED
"""
PUBLISHED = "UPDATE outbox SET published_at = now() WHERE id = ANY($1::bigint[])"
def attachment_of(row: Record) -> Attachment:
def attachment_of(row: Record, variants: tuple[Variant, ...] = ()) -> Attachment:
return Attachment(
id=row["id"],
chat_id=row["chat_id"],
@@ -44,13 +174,21 @@ def attachment_of(row: Record) -> Attachment:
image=ImageInfo(ImageKind(row["content_type"]), row["width"], row["height"]),
size_bytes=row["size_bytes"],
sha256=row["sha256"],
object_key=row["object_key"],
status=AttachmentStatus(row["status"]),
created_at=row["created_at"],
updated_at=row["updated_at"],
staging_key=row["staging_key"],
original_key=row["original_key"],
published_version=row["published_version"],
error_code=row["error_code"],
variants=variants,
)
def payload(job: Job) -> str:
return json.dumps(job.payload(), separators=(",", ":"))
class PostgresAttachmentRepository:
__slots__ = ("_connection", "_seen")
@@ -71,7 +209,7 @@ class PostgresAttachmentRepository:
attachment.sha256,
attachment.image.width,
attachment.image.height,
attachment.object_key,
attachment.staging_key,
attachment.status.value,
attachment.created_at,
attachment.updated_at,
@@ -100,6 +238,127 @@ class PostgresAttachmentRepository:
await self._connection.execute(REMOVE, attachment.id)
self._seen.append(attachment)
async def staged(self, limit: int) -> list[StagedObject]:
rows = await self._connection.fetch(STAGED, limit)
return [StagedObject(row["id"], row["staging_key"]) for row in rows]
async def unstage(self, attachment_ids: Sequence[UUID]) -> None:
if attachment_ids:
await self._connection.execute(UNSTAGE, list(attachment_ids))
class PostgresJobRepository:
__slots__ = ("_connection",)
def __init__(self, connection: Connection) -> None:
self._connection = connection
async def add(self, job: Job) -> None:
await self._connection.execute(
ADD_JOB,
job.id,
job.attachment_id,
job.pipeline_version,
job.attempt,
job.created_at,
payload(job),
)
async def claim(self, job: Job, token: UUID, lease: timedelta) -> Claim | None:
row = await self._connection.fetchrow(
CLAIM,
job.id,
job.attachment_id,
job.pipeline_version,
token,
lease.total_seconds(),
)
if row is None:
return None
claimed = Job(
job.id, job.attachment_id, job.pipeline_version, row["attempt"], row["created_at"]
)
staged = row["staging_key"] is not None
source = row["staging_key"] if staged else row["original_key"]
return Claim(Lease(claimed, token), source, staged)
async def complete(
self, lease: Lease, variants: Sequence[Variant], original_key: str
) -> Outcome:
job = lease.job
if await self._connection.execute(FINISH, job.id, lease.token) == "UPDATE 0":
await self.note(job, Outcome.FENCED)
return Outcome.FENCED
await self._connection.execute(
ADD_VARIANTS,
job.attachment_id,
job.pipeline_version,
[v.name for v in variants],
[v.object_key for v in variants],
[v.content_type for v in variants],
[v.size_bytes for v in variants],
[v.width for v in variants],
[v.height for v in variants],
[v.sha256 for v in variants],
)
published = await self._connection.execute(
PUBLISH, job.attachment_id, job.pipeline_version, original_key
)
outcome = Outcome.SUPERSEDED if published == "UPDATE 0" else Outcome.DONE
if outcome is Outcome.SUPERSEDED:
await self._connection.execute(SUPERSEDE, job.id)
await self.note(job, outcome)
return outcome
async def reschedule(self, lease: Lease, at: datetime, kind: Outcome, error: str) -> Job | None:
attempt = await self._connection.fetchval(
RESCHEDULE, lease.job.id, lease.token, at, error, kind.value
)
if attempt is None:
return None
job = lease.job.retried(attempt)
await self._connection.execute(ENQUEUE, job.id, payload(job), at)
return job
async def fail(self, lease: Lease, code: FailureCode, error: str) -> bool:
attempt = await self._connection.fetchval(
FAIL, lease.job.id, lease.token, code.value, error
)
return attempt is not None
async def note(self, job: Job, kind: Outcome) -> None:
await self._connection.execute(NOTE, job.id, job.attachment_id, kind.value, job.attempt)
async def expired(self, limit: int) -> list[Lease]:
rows = await self._connection.fetch(EXPIRED, limit)
return [
Lease(
Job(
row["job_id"],
row["attachment_id"],
row["pipeline_version"],
row["attempt"],
row["created_at"],
),
row["lease_token"],
)
for row in rows
]
class PostgresOutboxRepository:
__slots__ = ("_connection",)
def __init__(self, connection: Connection) -> None:
self._connection = connection
async def pending(self, limit: int) -> list[OutboxEntry]:
rows = await self._connection.fetch(PENDING, limit)
return [OutboxEntry(row["id"], row["job_id"], row["body"].encode()) for row in rows]
async def published(self, entry_ids: Sequence[int]) -> None:
await self._connection.execute(PUBLISHED, list(entry_ids))
class PostgresAttachmentsUnitOfWork(PostgresUnitOfWork):
__slots__ = ()
@@ -108,6 +367,18 @@ class PostgresAttachmentsUnitOfWork(PostgresUnitOfWork):
def attachments(self) -> PostgresAttachmentRepository:
return PostgresAttachmentRepository(self.connection, self.seen)
@property
def jobs(self) -> PostgresJobRepository:
return PostgresJobRepository(self.connection)
@property
def outbox(self) -> PostgresOutboxRepository:
return PostgresOutboxRepository(self.connection)
def variants_of(raw: str) -> tuple[Variant, ...]:
return tuple(Variant(*item) for item in json.loads(raw))
class PostgresAttachmentDirectory:
__slots__ = ("_database",)
@@ -115,7 +386,11 @@ class PostgresAttachmentDirectory:
def __init__(self, database: Database) -> None:
self._database = database
async def ready(self, attachment_id: UUID) -> Attachment | None:
async def visible(self, attachment_id: UUID) -> Attachment | None:
async with self._database.connection() as connection:
row = await connection.fetchrow(READY, attachment_id)
return None if row is None else attachment_of(row)
row = await connection.fetchrow(VISIBLE, attachment_id)
return None if row is None else attachment_of(row, variants_of(row["variants"]))
async def failed_among(self, chat_id: UUID, attachment_ids: Sequence[UUID]) -> bool:
async with self._database.connection() as connection:
return bool(await connection.fetchval(FAILED_AMONG, list(attachment_ids), chat_id))