Files
mtusi2026lab2/student-tests/unit/test_pipeline_domain.py
T
ArtyomandClaude Opus 5.5 b152b6e07e 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>
2026-10-29 01:08:06 +03:00

87 lines
2.9 KiB
Python

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"