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
+19 -9
View File
@@ -13,6 +13,7 @@ from messenger.attachments.domain.events import AttachmentDiscarded
from messenger.attachments.entrypoints.sweeper import UploadSweeper
from messenger.shared.application.messagebus import EventBus
from pictures import SAMPLE
from pipeline import settle
AGED = "UPDATE attachments SET created_at = created_at - interval '1 hour' WHERE id = $1"
@@ -51,7 +52,7 @@ async def intent(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any])
"SELECT id::text FROM attachments WHERE filename = $1 AND status = 'pending'", name
)
assert found is not None
store.objects[f"attachments/{found}"] = (SAMPLE, "image/png")
store.objects[f"staging/{found}"] = (SAMPLE, "image/png")
return found
@@ -68,7 +69,7 @@ async def test_commit_failure_after_put_is_compensated(client: AsyncClient) -> N
f"""CREATE FUNCTION {trigger}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'injected' USING ERRCODE = '55P03'; END $$;
CREATE TRIGGER {trigger} BEFORE UPDATE ON attachments FOR EACH ROW
WHEN (NEW.filename = '{name}' AND NEW.status = 'ready') EXECUTE FUNCTION {trigger}()"""
WHEN (NEW.filename = '{name}' AND NEW.status = 'queued') EXECUTE FUNCTION {trigger}()"""
)
before, seen = set(store.objects), await discarded(client)
try:
@@ -78,6 +79,14 @@ async def test_commit_failure_after_put_is_compensated(client: AsyncClient) -> N
assert response.status_code == 503
assert response.json()["error"]["code"] == "unavailable"
assert await scalar("SELECT count(*) FROM attachments WHERE filename = $1", name) == 0
assert (
await scalar(
"SELECT count(*) FROM jobs j JOIN attachments a ON a.id = j.attachment_id "
"WHERE a.filename = $1",
name,
)
== 0
)
assert set(store.objects) == before
assert [event.reason for event in seen] == ["compensation"]
@@ -87,7 +96,7 @@ async def test_lost_intent_gives_503_and_no_object(client: AsyncClient) -> None:
store = await storage(client)
async def swept_meanwhile(key: str) -> None:
await execute("DELETE FROM attachments WHERE object_key = $1", key)
await execute("DELETE FROM attachments WHERE staging_key = $1", key)
store.after_put = swept_meanwhile
before = set(store.objects)
@@ -107,12 +116,13 @@ async def test_failed_put_leaves_an_intent_until_grace_ends(client: AsyncClient)
await execute(AGED, pending)
assert await sweeper(client).sweep() >= 1
assert not await exists(pending)
assert f"attachments/{pending}" not in (await storage(client)).objects
assert f"staging/{pending}" not in (await storage(client)).objects
async def test_sweep_keeps_fresh_intents_and_ready_attachments(client: AsyncClient) -> None:
alice, bob, _, chat = await trio(client)
ready = (await upload(client, alice, chat)).json()
await settle(client)
sent = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "", "attachment_ids": [ready["id"]]},
@@ -125,9 +135,9 @@ async def test_sweep_keeps_fresh_intents_and_ready_attachments(client: AsyncClie
assert await sweeper(client).sweep() == 1
objects = (await storage(client)).objects
assert not await exists(old)
assert f"attachments/{old}" not in objects
assert f"staging/{old}" not in objects
assert await exists(fresh)
assert f"attachments/{fresh}" in objects
assert f"staging/{fresh}" in objects
download = await client.get(f"/api/v1/attachments/{ready['id']}/content", headers=actor(bob))
assert download.status_code == 200
assert download.content == SAMPLE
@@ -146,7 +156,7 @@ async def test_parallel_sweeps_share_the_work(client: AsyncClient) -> None:
assert {event.reason for event in seen} == {"abandoned"}
assert await sweeper(client).sweep() == 0
objects = (await storage(client)).objects
assert not any(f"attachments/{attachment_id}" in objects for attachment_id in pending)
assert not any(f"staging/{attachment_id}" in objects for attachment_id in pending)
async def test_background_sweeper_removes_abandoned_intents() -> None:
@@ -183,7 +193,7 @@ async def test_upload_waits_for_a_free_slot() -> None:
await asyncio.sleep(0.3)
assert read == ["first"]
gate.set()
assert [(await first).status_code, (await second).status_code] == [201, 201]
assert [(await first).status_code, (await second).status_code] == [202, 202]
assert read == ["first", "second"]
@@ -241,4 +251,4 @@ async def test_stalled_upload_times_out_and_frees_the_slot() -> None:
assert response.status_code == 503
assert response.json()["error"]["code"] == "unavailable"
assert await scalar("SELECT count(*) FROM attachments WHERE filename = $1", name) == 0
assert (await upload(http, alice, chat)).status_code == 201
assert (await upload(http, alice, chat)).status_code == 202