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
@@ -11,6 +11,7 @@ from conftest import actor, make_chat, register, resolve, scalar
|
||||
from fakes import MemoryObjectStorage
|
||||
from messenger.attachments.application.ports import ObjectStorage
|
||||
from pictures import GIF, JPEG, SAMPLE, WEBP, png
|
||||
from pipeline import settle
|
||||
|
||||
LIMIT = 10_485_760
|
||||
PNG = {"Content-Type": "image/png"}
|
||||
@@ -47,7 +48,7 @@ async def trio(http: AsyncClient) -> tuple[dict[str, Any], ...]:
|
||||
async def test_member_uploads_and_another_member_downloads(client: AsyncClient) -> None:
|
||||
alice, bob, eve, chat = await trio(client)
|
||||
response = await upload(client, alice, chat)
|
||||
assert response.status_code == 201, response.text
|
||||
assert response.status_code == 202, response.text
|
||||
attachment = response.json()
|
||||
assert set(attachment) == {
|
||||
"id",
|
||||
@@ -70,13 +71,21 @@ async def test_member_uploads_and_another_member_downloads(client: AsyncClient)
|
||||
assert attachment["size_bytes"] == len(SAMPLE) == 111817
|
||||
assert attachment["sha256"] == sha256(SAMPLE).hexdigest()
|
||||
assert (attachment["status"], attachment["variants"], attachment["error_code"]) == (
|
||||
"ready",
|
||||
"queued",
|
||||
[],
|
||||
None,
|
||||
)
|
||||
assert attachment["created_at"].endswith("Z")
|
||||
path = f"/api/v1/attachments/{attachment['id']}"
|
||||
assert (await client.get(path, headers=actor(bob))).json() == attachment
|
||||
await settle(client)
|
||||
ready = (await client.get(path, headers=actor(bob))).json()
|
||||
assert (ready["status"], ready["error_code"], ready["sha256"]) == (
|
||||
"ready",
|
||||
None,
|
||||
attachment["sha256"],
|
||||
)
|
||||
assert [variant["name"] for variant in ready["variants"]] == ["thumbnail"]
|
||||
content = await client.get(
|
||||
f"{path}/content", headers={**actor(bob), "Accept": "application/json"}
|
||||
)
|
||||
@@ -93,19 +102,24 @@ async def test_member_uploads_and_another_member_downloads(client: AsyncClient)
|
||||
assert stranger.json()["error"]["code"] == "not_found"
|
||||
|
||||
|
||||
async def test_object_key_is_assigned_by_server(client: AsyncClient) -> None:
|
||||
async def test_object_keys_are_assigned_by_server(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
attachment = (await upload(client, alice, chat, filename="a.png")).json()
|
||||
key = await scalar("SELECT object_key FROM attachments WHERE id = $1", attachment["id"])
|
||||
assert key == f"attachments/{attachment['id']}"
|
||||
assert set((await storage(client)).objects) >= {key}
|
||||
staging = await scalar("SELECT staging_key FROM attachments WHERE id = $1", attachment["id"])
|
||||
assert staging == f"staging/{attachment['id']}"
|
||||
assert set((await storage(client)).objects) >= {staging}
|
||||
await settle(client)
|
||||
original = await scalar("SELECT original_key FROM attachments WHERE id = $1", attachment["id"])
|
||||
assert original == f"originals/{attachment['id']}"
|
||||
assert (await storage(client)).objects[original][0] == SAMPLE
|
||||
|
||||
|
||||
async def test_jpeg_is_accepted_by_content(client: AsyncClient) -> None:
|
||||
alice, bob, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, JPEG, headers={"Content-Type": "IMAGE/JPEG"})
|
||||
assert response.status_code == 201, response.text
|
||||
assert response.status_code == 202, response.text
|
||||
assert response.json()["content_type"] == "image/jpeg"
|
||||
await settle(client)
|
||||
download = await client.get(
|
||||
f"/api/v1/attachments/{response.json()['id']}/content", headers=actor(bob)
|
||||
)
|
||||
@@ -127,7 +141,7 @@ async def test_access_is_checked_before_content(client: AsyncClient) -> None:
|
||||
async def test_exact_limit_is_accepted(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, png(16, 16, size=LIMIT))
|
||||
assert response.status_code == 201, response.text
|
||||
assert response.status_code == 202, response.text
|
||||
assert response.json()["size_bytes"] == LIMIT
|
||||
|
||||
|
||||
@@ -154,7 +168,7 @@ async def test_one_byte_over_chunked(client: AsyncClient) -> None:
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("width", "height", "status"),
|
||||
[(8000, 5000, 201), (8001, 5000, 413), (100_000, 100_000, 413)],
|
||||
[(8000, 5000, 202), (8001, 5000, 413), (100_000, 100_000, 413)],
|
||||
)
|
||||
async def test_pixel_limit_is_read_from_header(
|
||||
client: AsyncClient, width: int, height: int, status: int
|
||||
@@ -224,16 +238,33 @@ async def test_dangerous_filename_is_rejected(client: AsyncClient, filename: str
|
||||
async def test_display_name_is_kept(client: AsyncClient, filename: str) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, filename=filename)
|
||||
assert response.status_code == 201, response.text
|
||||
assert response.status_code == 202, response.text
|
||||
assert response.json()["filename"] == filename
|
||||
|
||||
|
||||
async def test_only_original_variant_exists(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
async def test_content_waits_for_ready_and_serves_level_three_variants(
|
||||
client: AsyncClient,
|
||||
) -> None:
|
||||
alice, bob, _, chat = await trio(client)
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
path = f"/api/v1/attachments/{attachment['id']}/content"
|
||||
for variant in ("original", "thumbnail", "crop"):
|
||||
early = await client.get(f"{path}?variant={variant}", headers=actor(bob))
|
||||
assert early.status_code == 409, early.text
|
||||
assert early.json()["error"]["code"] == "conflict"
|
||||
await settle(client)
|
||||
assert (await client.get(f"{path}?variant=original", headers=actor(alice))).status_code == 200
|
||||
assert (await client.get(f"{path}?variant=thumbnail", headers=actor(alice))).status_code == 400
|
||||
thumbnail = await client.get(f"{path}?variant=thumbnail", headers=actor(bob))
|
||||
meta = (await client.get(path.removesuffix("/content"), headers=actor(bob))).json()
|
||||
(variant,) = meta["variants"]
|
||||
assert thumbnail.headers["content-type"] == "image/jpeg"
|
||||
assert len(thumbnail.content) == variant["size_bytes"]
|
||||
assert sha256(thumbnail.content).hexdigest() == variant["sha256"]
|
||||
assert (variant["width"], variant["height"]) == (256, 160)
|
||||
for absent in ("crop", "optimized"):
|
||||
missing = await client.get(f"{path}?variant={absent}", headers=actor(alice))
|
||||
assert missing.status_code == 404
|
||||
assert (await client.get(f"{path}?variant=preview", headers=actor(alice))).status_code == 400
|
||||
assert (
|
||||
await client.get("/api/v1/attachments/x/content", headers=actor(alice))
|
||||
).status_code == 400
|
||||
@@ -244,6 +275,7 @@ async def test_only_original_variant_exists(client: AsyncClient) -> None:
|
||||
async def test_storage_failure_leaves_nothing_visible(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
ready = await upload(client, alice, chat)
|
||||
await settle(client)
|
||||
store = await storage(client)
|
||||
store.failing = True
|
||||
try:
|
||||
@@ -271,6 +303,7 @@ async def test_storage_failure_leaves_nothing_visible(client: AsyncClient) -> No
|
||||
async def test_lost_object_is_not_found(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
await settle(client)
|
||||
(await storage(client)).objects.clear()
|
||||
response = await client.get(
|
||||
f"/api/v1/attachments/{attachment['id']}/content", headers=actor(alice)
|
||||
|
||||
Reference in New Issue
Block a user