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
+12 -6
View File
@@ -4,7 +4,7 @@ from uuid import uuid4
import pytest
from messenger.attachments.domain.errors import InvalidFilename, UnsupportedImage
from messenger.attachments.domain.events import AttachmentDiscarded, AttachmentStored
from messenger.attachments.domain.events import AttachmentDiscarded, AttachmentQueued
from messenger.attachments.domain.models import Attachment, AttachmentStatus
from messenger.attachments.domain.values import Filename, ImageInfo, ImageKind
@@ -46,7 +46,7 @@ def test_declared_type_accepts_only_png_and_jpeg(header: str | None) -> None:
ImageKind.declared(header)
def test_attachment_is_pending_until_stored() -> None:
def test_attachment_is_pending_until_queued() -> None:
attachment_id = uuid4()
attachment = Attachment.stage(
attachment_id=attachment_id,
@@ -59,13 +59,19 @@ def test_attachment_is_pending_until_stored() -> None:
now=MOMENT,
)
assert attachment.status is AttachmentStatus.PENDING
assert attachment.object_key == f"attachments/{attachment_id}"
assert attachment.staging_key == f"staging/{attachment_id}"
assert (attachment.original_key, attachment.published_version, attachment.variants) == (
None,
0,
(),
)
assert attachment.collect_events() == []
attachment.store(MOMENT - timedelta(seconds=1))
assert attachment.status is AttachmentStatus.READY
attachment.enqueue(MOMENT - timedelta(seconds=1))
assert attachment.status is AttachmentStatus.QUEUED
assert not attachment.ready
assert attachment.updated_at == MOMENT
events = attachment.collect_events()
assert [type(event) for event in events] == [AttachmentStored]
assert [type(event) for event in events] == [AttachmentQueued]
assert attachment.collect_events() == []
@@ -0,0 +1,86 @@
import json
from datetime import UTC, datetime, timedelta
from pathlib import Path
from uuid import uuid4
import pytest
from messenger.attachments.domain.jobs import Job, RetryPolicy
from messenger.attachments.domain.variants import fit, variant_key
from messenger.attachments.entrypoints.schemas import JobMessage
SCHEMA = json.loads(
(Path(__file__).resolve().parents[2] / "contracts" / "jobs.schema.json").read_text()
)
@pytest.mark.parametrize(
("size", "fitted"),
[
((320, 200), (256, 160)),
((300, 200), (256, 170)),
((801, 601), (256, 192)),
((17, 1000), (4, 256)),
((3000, 2), (256, 1)),
((2, 3000), (1, 256)),
((64, 64), (64, 64)),
((256, 100), (256, 100)),
((257, 257), (256, 256)),
],
)
def test_thumbnail_fits_the_box_rounding_down(
size: tuple[int, int], fitted: tuple[int, int]
) -> None:
assert fit(*size, 256) == fitted
def test_retry_policy_doubles_up_to_the_cap_and_stops_at_the_limit() -> None:
policy = RetryPolicy(max_attempts=5, base_seconds=2, cap_seconds=10)
delays = [policy.delay(attempt) for attempt in range(1, 6)]
assert delays == [
timedelta(seconds=2),
timedelta(seconds=4),
timedelta(seconds=8),
timedelta(seconds=10),
None,
]
def test_job_message_follows_the_contract_schema() -> None:
job = Job(uuid4(), uuid4(), 1, 3, datetime(2026, 9, 1, 12, 0, tzinfo=UTC))
payload = job.payload()
assert set(SCHEMA["required"]) <= set(payload) <= set(SCHEMA["properties"])
assert payload["schema_version"] == SCHEMA["properties"]["schema_version"]["const"]
assert payload["type"] == SCHEMA["properties"]["type"]["const"]
assert payload["created_at"] == "2026-09-01T12:00:00.000000Z"
assert JobMessage.model_validate_json(json.dumps(payload)).job() == job
assert job.retried(4).payload()["job_id"] == payload["job_id"]
@pytest.mark.parametrize("example", SCHEMA["examples"])
def test_contract_examples_are_accepted(example: dict[str, object]) -> None:
assert JobMessage.model_validate_json(json.dumps(example)).attempt == example["attempt"]
@pytest.mark.parametrize(
"change",
[
{"schema_version": 2},
{"type": "attachment.process.v2"},
{"attempt": 0},
{"pipeline_version": 0},
{"filename": "a.png"},
{"traceparent": "01-xyz"},
{"created_at": "2026-09-01T12:00:00"},
],
)
def test_messages_off_the_schema_are_rejected(change: dict[str, object]) -> None:
message = {**SCHEMA["examples"][0], **change}
with pytest.raises(ValueError, match="validation error"):
JobMessage.model_validate_json(json.dumps(message))
def test_variant_keys_carry_version_and_content_hash() -> None:
attachment = uuid4()
key = variant_key(attachment, 2, "thumbnail", "ab" * 32, "jpg")
assert key == f"variants/{attachment}/2/thumbnail-{'ab' * 8}.jpg"
+89
View File
@@ -0,0 +1,89 @@
from io import BytesIO
import pytest
from PIL import Image
from messenger.attachments.domain.errors import UnreadableImage
from messenger.attachments.infrastructure.images import render_variants
from pictures import SAMPLE
LIMIT = 40_000_000
def encoded(image: Image.Image, kind: str = "PNG", **options: object) -> bytes:
buffer = BytesIO()
image.save(buffer, kind, **options)
return buffer.getvalue()
def thumbnail(data: bytes) -> Image.Image:
(rendition,) = render_variants(data, LIMIT)
assert (rendition.name, rendition.content_type, rendition.extension) == (
"thumbnail",
"image/jpeg",
"jpg",
)
image = Image.open(BytesIO(rendition.data))
assert image.format == "JPEG"
assert image.size == (rendition.width, rendition.height)
assert not image.getexif()
return image
def test_fixture_gives_256_by_160() -> None:
assert thumbnail(SAMPLE).size == (256, 160)
@pytest.mark.parametrize(
("mode", "size", "fitted"),
[
("L", (17, 1000), (4, 256)),
("RGB", (64, 64), (64, 64)),
("RGB", (3000, 2), (256, 1)),
("I;16", (300, 200), (256, 170)),
("CMYK", (801, 601), (256, 192)),
],
)
def test_sizes_round_down_and_never_upscale(
mode: str, size: tuple[int, int], fitted: tuple[int, int]
) -> None:
kind = "JPEG" if mode == "CMYK" else "PNG"
assert thumbnail(encoded(Image.new(mode, size), kind)).size == fitted
@pytest.mark.parametrize("mode", ["RGBA", "LA"])
def test_transparency_is_composed_on_white(mode: str) -> None:
transparent = Image.new(mode, (300, 300), (0,) * len(mode))
assert thumbnail(encoded(transparent)).convert("RGB").getpixel((5, 5)) == (255, 255, 255)
def test_palette_transparency_is_composed_on_white() -> None:
palette = Image.new("P", (200, 100))
image = thumbnail(encoded(palette, transparency=0))
assert image.size == (200, 100)
assert image.convert("RGB").getpixel((5, 5)) == (255, 255, 255)
@pytest.mark.parametrize(("orientation", "fitted"), [(6, (128, 256)), (3, (256, 128))])
def test_exif_orientation_is_applied_before_sizing(
orientation: int, fitted: tuple[int, int]
) -> None:
exif = Image.Exif()
exif[0x0112] = orientation
data = encoded(Image.new("RGB", (400, 200), (10, 200, 10)), "JPEG", exif=exif)
assert thumbnail(data).size == fitted
@pytest.mark.parametrize(
"data",
[b"", b"garbage", SAMPLE[: len(SAMPLE) // 2], b"GIF89a" + bytes(20)],
ids=["empty", "garbage", "truncated", "gif"],
)
def test_undecodable_data_is_a_permanent_error(data: bytes) -> None:
with pytest.raises(UnreadableImage):
render_variants(data, LIMIT)
def test_pixel_limit_is_checked_before_decoding() -> None:
with pytest.raises(UnreadableImage):
render_variants(SAMPLE, 320 * 200 - 1)