forked from mtusi2026/mtusi2026lab5
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
@@ -0,0 +1,259 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
from collections.abc import AsyncIterator, Iterator
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from dishka import Provider, Scope, make_async_container, provide
|
||||
from dishka_faststream import setup_dishka
|
||||
from faststream.rabbit import Channel, RabbitBroker
|
||||
|
||||
from conftest import ROOT, STARTUP_SECONDS, container, image, published
|
||||
from fakes import NullLogger
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import ProcessJob
|
||||
from messenger.attachments.domain.jobs import Job, Outcome
|
||||
from messenger.attachments.entrypoints.worker import subscribe
|
||||
from messenger.attachments.infrastructure.rabbitmq import RabbitJobPublisher
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
RABBITMQ_IMAGE = re.compile(r"image: (rabbitmq:\S+)")
|
||||
PASSWORDS = {role: os.urandom(12).hex() for role in ("api", "worker", "ops")}
|
||||
GRANTS = {
|
||||
"api": ("^$", "^attachments$", "^$"),
|
||||
"worker": ("^$", "^$", "^attachments\\.process$"),
|
||||
"ops": (".*", ".*", ".*"),
|
||||
}
|
||||
|
||||
|
||||
def user(role: str) -> dict[str, Any]:
|
||||
salt = os.urandom(4)
|
||||
digest = hashlib.sha256(salt + PASSWORDS[role].encode()).digest()
|
||||
return {
|
||||
"name": f"messenger-{role}",
|
||||
"password_hash": base64.b64encode(salt + digest).decode(),
|
||||
"hashing_algorithm": "rabbit_password_hashing_sha256",
|
||||
"tags": ["administrator"] if role == "ops" else [],
|
||||
}
|
||||
|
||||
|
||||
def definitions() -> dict[str, Any]:
|
||||
return {
|
||||
"users": [user(role) for role in PASSWORDS],
|
||||
"permissions": [
|
||||
{
|
||||
"user": f"messenger-{role}",
|
||||
"vhost": "messenger",
|
||||
**dict(zip(("configure", "write", "read"), grant, strict=True)),
|
||||
}
|
||||
for role, grant in GRANTS.items()
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def ready(name: str) -> bool:
|
||||
probe = ["docker", "exec", name, "rabbitmq-diagnostics", "-q", "check_port_connectivity"]
|
||||
return subprocess.run(probe, capture_output=True, check=False).returncode == 0
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def rabbitmq() -> Iterator[dict[str, Any]]:
|
||||
name = f"mtusi-lab5-test-rabbitmq-{uuid4().hex[:8]}"
|
||||
folder = ROOT / "build" / name
|
||||
folder.mkdir(parents=True)
|
||||
users = folder / "20-users.json"
|
||||
users.write_text(json.dumps(definitions()))
|
||||
users.chmod(0o644)
|
||||
infra = ROOT / "infra" / "rabbitmq"
|
||||
mounts = [
|
||||
f"{infra / 'rabbitmq.conf'}:/etc/rabbitmq/conf.d/20-messenger.conf:ro",
|
||||
f"{infra / 'enabled_plugins'}:/etc/rabbitmq/enabled_plugins:ro",
|
||||
f"{infra / 'definitions.json'}:/etc/rabbitmq/definitions.d/10-topology.json:ro",
|
||||
f"{users}:/etc/rabbitmq/definitions.d/20-users.json:ro",
|
||||
]
|
||||
volumes = [part for mount in mounts for part in ("-v", mount)]
|
||||
container(
|
||||
name,
|
||||
"--hostname",
|
||||
"broker",
|
||||
"--user",
|
||||
"100:101",
|
||||
*volumes,
|
||||
"-p",
|
||||
"127.0.0.1::5672",
|
||||
image(RABBITMQ_IMAGE),
|
||||
)
|
||||
try:
|
||||
deadline = time.monotonic() + STARTUP_SECONDS * 2
|
||||
while not ready(name):
|
||||
assert time.monotonic() < deadline, "RabbitMQ не стал готов"
|
||||
time.sleep(1)
|
||||
port = published(name, 5672)
|
||||
urls = {
|
||||
role: f"amqp://messenger-{role}:{secret}@127.0.0.1:{port}/messenger"
|
||||
for role, secret in PASSWORDS.items()
|
||||
}
|
||||
yield {"name": name, "urls": urls}
|
||||
finally:
|
||||
subprocess.run(["docker", "rm", "-f", name], capture_output=True, check=False)
|
||||
users.unlink()
|
||||
folder.rmdir()
|
||||
|
||||
|
||||
def depth(broker: dict[str, Any], queue: str) -> int:
|
||||
listing = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"exec",
|
||||
broker["name"],
|
||||
"rabbitmqctl",
|
||||
"-q",
|
||||
"list_queues",
|
||||
"-p",
|
||||
"messenger",
|
||||
"name",
|
||||
"messages",
|
||||
"--formatter",
|
||||
"json",
|
||||
],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
text=True,
|
||||
).stdout
|
||||
return {row["name"]: row["messages"] for row in json.loads(listing)}[queue]
|
||||
|
||||
|
||||
async def wait_for(probe: Any, seconds: float = 20) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while not probe():
|
||||
assert time.monotonic() < deadline
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
class NoEvents:
|
||||
@asynccontextmanager
|
||||
async def transaction(self) -> AsyncIterator[None]:
|
||||
yield
|
||||
|
||||
async def commit(self) -> None: ...
|
||||
|
||||
def record(self, event: object) -> None: ...
|
||||
|
||||
def collect_new_events(self) -> list[Any]:
|
||||
return []
|
||||
|
||||
|
||||
class Recorder:
|
||||
def __init__(self) -> None:
|
||||
self.jobs: list[Job] = []
|
||||
self.failures = 0
|
||||
|
||||
async def __call__(self, command: ProcessJob) -> Outcome:
|
||||
if self.failures:
|
||||
self.failures -= 1
|
||||
raise Unavailable("PostgreSQL недоступен")
|
||||
self.jobs.append(command.job)
|
||||
return Outcome.DONE
|
||||
|
||||
|
||||
class FakeBus(Provider):
|
||||
def __init__(self, recorder: Recorder) -> None:
|
||||
super().__init__()
|
||||
self._recorder = recorder
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def logger(self) -> Logger:
|
||||
return NullLogger()
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def bus(self) -> AttachmentsCommandBus:
|
||||
return AttachmentsCommandBus({ProcessJob: self._recorder}, NoEvents(), NoPublisher())
|
||||
|
||||
|
||||
class NoPublisher:
|
||||
async def publish(self, events: Any) -> None: ...
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def worker(rabbitmq: dict[str, Any], recorder: Recorder) -> AsyncIterator[None]:
|
||||
broker = RabbitBroker(rabbitmq["urls"]["worker"], logger=None, graceful_timeout=2)
|
||||
subscribe(broker, 2)
|
||||
setup_dishka(make_async_container(FakeBus(recorder)), broker=broker, auto_inject=True)
|
||||
await broker.start()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await broker.stop()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def publisher(
|
||||
rabbitmq: dict[str, Any], role: str = "api"
|
||||
) -> AsyncIterator[RabbitJobPublisher]:
|
||||
broker = RabbitBroker(
|
||||
rabbitmq["urls"][role],
|
||||
default_channel=Channel(publisher_confirms=True, on_return_raises=True),
|
||||
logger=None,
|
||||
)
|
||||
await broker.connect()
|
||||
try:
|
||||
yield RabbitJobPublisher(broker, 5)
|
||||
finally:
|
||||
await broker.stop()
|
||||
|
||||
|
||||
def job() -> Job:
|
||||
return Job(uuid4(), uuid4(), 1, 1, datetime.now(UTC))
|
||||
|
||||
|
||||
def body(payload: dict[str, Any]) -> bytes:
|
||||
return json.dumps(payload).encode()
|
||||
|
||||
|
||||
async def test_confirmed_job_is_consumed_and_acked(rabbitmq: dict[str, Any]) -> None:
|
||||
recorder, sent = Recorder(), job()
|
||||
async with publisher(rabbitmq) as jobs:
|
||||
await jobs.publish(sent.id, body(sent.payload()))
|
||||
await wait_for(lambda: depth(rabbitmq, "attachments.process") == 1)
|
||||
async with worker(rabbitmq, recorder):
|
||||
await wait_for(lambda: recorder.jobs)
|
||||
await wait_for(lambda: depth(rabbitmq, "attachments.process") == 0)
|
||||
assert recorder.jobs == [sent]
|
||||
|
||||
|
||||
async def test_message_off_the_schema_goes_to_the_dead_letter_queue(
|
||||
rabbitmq: dict[str, Any],
|
||||
) -> None:
|
||||
before = depth(rabbitmq, "attachments.process.dlq")
|
||||
async with publisher(rabbitmq) as jobs:
|
||||
await jobs.publish(uuid4(), body({"schema_version": 2, "job_id": str(uuid4())}))
|
||||
async with worker(rabbitmq, Recorder()):
|
||||
await wait_for(lambda: depth(rabbitmq, "attachments.process.dlq") == before + 1)
|
||||
assert depth(rabbitmq, "attachments.process") == 0
|
||||
|
||||
|
||||
async def test_failed_processing_is_requeued_and_retried(rabbitmq: dict[str, Any]) -> None:
|
||||
recorder, sent = Recorder(), job()
|
||||
recorder.failures = 1
|
||||
async with publisher(rabbitmq) as jobs:
|
||||
await jobs.publish(sent.id, body(sent.payload()))
|
||||
async with worker(rabbitmq, recorder):
|
||||
await wait_for(lambda: recorder.jobs)
|
||||
assert recorder.jobs == [sent]
|
||||
|
||||
|
||||
async def test_worker_account_cannot_publish(rabbitmq: dict[str, Any]) -> None:
|
||||
sent = job()
|
||||
with pytest.raises(Unavailable):
|
||||
async with publisher(rabbitmq, "worker") as jobs:
|
||||
await jobs.publish(sent.id, body(sent.payload()))
|
||||
@@ -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)
|
||||
|
||||
@@ -154,22 +154,46 @@ def test_every_zone_owns_its_http_layer() -> None:
|
||||
assert (SOURCE / zone / "entrypoints" / part).is_file(), f"{zone}: нет {part}"
|
||||
|
||||
|
||||
PROCESSES = {"relay.py": (ATTACHMENTS,), "worker.py": (ATTACHMENTS,)}
|
||||
|
||||
|
||||
def test_only_main_knows_several_zones() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for path in SOURCE.rglob("*.py"):
|
||||
relative = path.relative_to(SOURCE)
|
||||
if path.name in {"__init__.py", "main.py"} or relative.parts[0] in ZONES:
|
||||
continue
|
||||
allowed = PROCESSES.get(str(relative), ())
|
||||
borrowed = [
|
||||
module
|
||||
for module in imports_of(path)
|
||||
if module.startswith((IDENTITY, MESSAGING, ATTACHMENTS))
|
||||
and not module.startswith(allowed or ("-",))
|
||||
]
|
||||
if borrowed:
|
||||
offenders[str(relative)] = borrowed
|
||||
assert not offenders
|
||||
|
||||
|
||||
def test_broker_framework_stays_out_of_shared_and_core_layers() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for path in [
|
||||
*modules_under("shared"),
|
||||
*(
|
||||
p
|
||||
for zone in ZONES
|
||||
for layer in ("domain", "application")
|
||||
for p in modules_under(zone, layer)
|
||||
),
|
||||
]:
|
||||
borrowed = [
|
||||
m for m in imports_of(path) if m.split(".")[0] in {"faststream", "aio_pika", "aiormq"}
|
||||
]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
assert not offenders
|
||||
|
||||
|
||||
def test_application_has_no_separate_entrypoints_root() -> None:
|
||||
assert not (SOURCE / "entrypoints").exists()
|
||||
assert (SOURCE / "main.py").is_file()
|
||||
@@ -233,7 +257,7 @@ def test_zone_errors_do_not_leak_transport_codes() -> None:
|
||||
|
||||
IDENTITY_TABLES = ("users", "sessions")
|
||||
MESSAGING_TABLES = ("chats", "chat_members", "messages", "idempotency_keys", "message_attachments")
|
||||
ATTACHMENT_TABLES = ("attachments",)
|
||||
ATTACHMENT_TABLES = ("attachments", "attachment_variants", "jobs", "outbox", "job_events")
|
||||
|
||||
|
||||
def sql_tables(zone: str, tables: tuple[str, ...]) -> set[str]:
|
||||
|
||||
@@ -14,7 +14,7 @@ async def attach(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any])
|
||||
content=SAMPLE,
|
||||
headers={**actor(user), "Content-Type": "image/png"},
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
assert response.status_code == 202, response.text
|
||||
return response.json()["id"]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
import asyncio
|
||||
import json
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import asyncpg
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from test_attachments import storage, trio, upload
|
||||
|
||||
from conftest import DATABASE, actor
|
||||
from messenger.attachments.domain.jobs import Job, Outcome, RetryPolicy
|
||||
from messenger.attachments.entrypoints.schemas import JobMessage
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from pictures import SAMPLE
|
||||
from pipeline import pipeline_of
|
||||
|
||||
|
||||
async def rows(sql: str, *args: Any) -> list[dict[str, Any]]:
|
||||
connection = await asyncpg.connect(DATABASE["url"])
|
||||
try:
|
||||
return [dict(row) for row in await connection.fetch(sql, *args)]
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
async def accepted(http: AsyncClient) -> tuple[dict[str, Any], dict[str, Any], str]:
|
||||
alice, bob, _, chat = await trio(http)
|
||||
response = await upload(http, alice, chat)
|
||||
assert response.status_code == 202, response.text
|
||||
return alice, bob, response.json()["id"]
|
||||
|
||||
|
||||
async def state(attachment_id: str) -> dict[str, Any]:
|
||||
(row,) = await rows(
|
||||
"SELECT a.status, a.error_code, a.published_version, a.staging_key, a.original_key, "
|
||||
"j.status AS job_status, j.attempt, j.claims FROM attachments a "
|
||||
"JOIN jobs j ON j.attachment_id = a.id WHERE a.id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
async def variants(attachment_id: str) -> list[dict[str, Any]]:
|
||||
return await rows(
|
||||
"SELECT pipeline_version, name, sha256, size_bytes, object_key FROM attachment_variants "
|
||||
"WHERE attachment_id = $1 ORDER BY name",
|
||||
attachment_id,
|
||||
)
|
||||
|
||||
|
||||
async def events(attachment_id: str) -> list[str]:
|
||||
found = await rows(
|
||||
"SELECT kind FROM job_events WHERE attachment_id = $1 ORDER BY id", attachment_id
|
||||
)
|
||||
return [row["kind"] for row in found]
|
||||
|
||||
|
||||
async def job_of(attachment_id: str) -> Job:
|
||||
(row,) = await rows(
|
||||
"SELECT payload::text AS body FROM outbox o JOIN jobs j USING (job_id) "
|
||||
"WHERE j.attachment_id = $1 ORDER BY o.id LIMIT 1",
|
||||
attachment_id,
|
||||
)
|
||||
return JobMessage.model_validate_json(row["body"]).job()
|
||||
|
||||
|
||||
async def test_job_is_processed_once_and_staging_is_cleaned(client: AsyncClient) -> None:
|
||||
_, bob, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
outcomes = await pipeline.drain()
|
||||
assert Outcome.DONE in outcomes
|
||||
done = await state(attachment_id)
|
||||
assert (done["status"], done["job_status"], done["published_version"]) == ("ready", "done", 1)
|
||||
assert done["original_key"] == f"originals/{attachment_id}"
|
||||
assert done["staging_key"] == f"staging/{attachment_id}"
|
||||
(thumbnail,) = await variants(attachment_id)
|
||||
assert thumbnail["object_key"].startswith(f"variants/{attachment_id}/1/thumbnail-")
|
||||
assert await pipeline.clean() >= 1
|
||||
assert (await state(attachment_id))["staging_key"] is None
|
||||
objects = (await storage(client)).objects
|
||||
assert f"staging/{attachment_id}" not in objects
|
||||
assert objects[f"originals/{attachment_id}"][0] == SAMPLE
|
||||
content = await client.get(f"/api/v1/attachments/{attachment_id}/content", headers=actor(bob))
|
||||
assert content.content == SAMPLE
|
||||
assert await events(attachment_id) == ["enqueued", "claimed", "done"]
|
||||
|
||||
|
||||
async def test_message_is_a_contract_job(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
mine = [
|
||||
json.loads(body)
|
||||
for body in pipeline.publisher.bodies
|
||||
if json.loads(body)["attachment_id"] == attachment_id
|
||||
]
|
||||
assert len(mine) == 1
|
||||
assert set(mine[0]) == {
|
||||
"schema_version",
|
||||
"job_id",
|
||||
"type",
|
||||
"attachment_id",
|
||||
"pipeline_version",
|
||||
"attempt",
|
||||
"created_at",
|
||||
}
|
||||
assert (mine[0]["pipeline_version"], mine[0]["attempt"]) == (1, 1)
|
||||
assert await pipeline.publish() == []
|
||||
|
||||
|
||||
async def test_redelivery_after_ready_changes_nothing(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.drain()
|
||||
before, job = await variants(attachment_id), await job_of(attachment_id)
|
||||
assert await pipeline.process(job) is Outcome.DUPLICATE
|
||||
assert await variants(attachment_id) == before
|
||||
assert (await state(attachment_id))["status"] == "ready"
|
||||
assert (await events(attachment_id))[-1] == "duplicate_noop"
|
||||
|
||||
|
||||
async def test_two_copies_in_flight_give_one_result(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
outcomes = await asyncio.gather(pipeline.process(job), pipeline.process(job))
|
||||
assert sorted(outcomes) == sorted([Outcome.DONE, Outcome.DUPLICATE])
|
||||
assert len(await variants(attachment_id)) == 1
|
||||
assert (await state(attachment_id))["claims"] == 1
|
||||
|
||||
|
||||
async def test_transient_error_reschedules_with_the_same_job(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
store = await storage(client)
|
||||
store.failing = True
|
||||
try:
|
||||
assert await pipeline.process(job) is Outcome.RESCHEDULED
|
||||
finally:
|
||||
store.failing = False
|
||||
queued = await state(attachment_id)
|
||||
assert (queued["status"], queued["job_status"], queued["attempt"]) == ("queued", "queued", 2)
|
||||
(retry,) = [j for j in await pipeline.publish() if str(j.attachment_id) == attachment_id]
|
||||
assert (retry.id, retry.attempt) == (job.id, 2)
|
||||
assert await pipeline.process(retry) is Outcome.DONE
|
||||
assert (await state(attachment_id))["status"] == "ready"
|
||||
|
||||
|
||||
async def test_attempts_are_bounded(client: AsyncClient) -> None:
|
||||
alice, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
pipeline.faults = FailingFaults()
|
||||
await pipeline.drain()
|
||||
failed = await state(attachment_id)
|
||||
assert (failed["status"], failed["error_code"], failed["job_status"]) == (
|
||||
"failed",
|
||||
"retry_exhausted",
|
||||
"failed",
|
||||
)
|
||||
assert failed["attempt"] == pipeline.policy.max_attempts
|
||||
assert (await events(attachment_id)).count("retry_scheduled") == 4
|
||||
content = await client.get(f"/api/v1/attachments/{attachment_id}/content", headers=actor(alice))
|
||||
assert content.status_code == 409
|
||||
|
||||
|
||||
async def test_undecodable_image_fails_without_retries(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
(await storage(client)).objects[f"staging/{attachment_id}"] = (b"not a png", "image/png")
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.drain()
|
||||
failed = await state(attachment_id)
|
||||
assert (failed["status"], failed["error_code"], failed["attempt"]) == (
|
||||
"failed",
|
||||
"invalid_image",
|
||||
1,
|
||||
)
|
||||
|
||||
|
||||
async def test_expired_lease_is_recovered_and_old_holder_is_fenced(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
uow = pipeline.uow()
|
||||
async with uow.transaction():
|
||||
claim = await uow.jobs.claim(job, uuid4(), pipeline.lease)
|
||||
await uow.commit()
|
||||
assert claim is not None
|
||||
assert (await state(attachment_id))["status"] == "processing"
|
||||
await rows(
|
||||
"UPDATE jobs SET lease_until = now() - interval '1 second' WHERE attachment_id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
assert await pipeline.recover() >= 1
|
||||
assert (await state(attachment_id))["status"] == "queued"
|
||||
late = pipeline.uow()
|
||||
async with late.transaction():
|
||||
outcome = await late.jobs.complete(claim.lease, [], f"originals/{attachment_id}")
|
||||
await late.commit()
|
||||
assert outcome is Outcome.FENCED
|
||||
assert await variants(attachment_id) == []
|
||||
await pipeline.drain()
|
||||
recovered = await state(attachment_id)
|
||||
assert (recovered["status"], recovered["attempt"]) == ("ready", 2)
|
||||
assert {"lease_expired", "fenced"} <= set(await events(attachment_id))
|
||||
|
||||
|
||||
async def test_unpublished_rows_stay_when_the_broker_refuses(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
pipeline.publisher.failing = True
|
||||
with pytest.raises(Unavailable):
|
||||
await pipeline.publish()
|
||||
pending = await rows(
|
||||
"SELECT o.published_at FROM outbox o JOIN jobs j USING (job_id) WHERE j.attachment_id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
assert pending == [{"published_at": None}]
|
||||
pipeline.publisher.failing = False
|
||||
assert any(str(job.attachment_id) == attachment_id for job in await pipeline.publish())
|
||||
|
||||
|
||||
async def test_backoff_delays_the_next_attempt(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client, policy=RetryPolicy(5, 30, 60))
|
||||
pipeline.faults = FailingFaults()
|
||||
await pipeline.drain()
|
||||
queued = await state(attachment_id)
|
||||
assert (queued["status"], queued["attempt"]) == ("queued", 2)
|
||||
(row,) = await rows(
|
||||
"SELECT extract(epoch FROM next_attempt_at - now()) AS wait FROM jobs "
|
||||
"WHERE attachment_id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
assert 25 < row["wait"] <= 30
|
||||
|
||||
|
||||
class FailingFaults:
|
||||
def reach(self, point: str) -> None:
|
||||
raise Unavailable(point)
|
||||
@@ -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
|
||||
|
||||
@@ -58,7 +58,20 @@ class MemoryObjectStorage:
|
||||
data = self.objects[key][0]
|
||||
return ObjectContent(size=len(data), chunks=pieces(data))
|
||||
|
||||
async def read(self, key: str) -> bytes:
|
||||
content = await self.open(key)
|
||||
return b"".join([chunk async for chunk in content.chunks])
|
||||
|
||||
async def copy(self, source: str, target: str) -> None:
|
||||
if self.failing:
|
||||
raise Unavailable("S3 недоступно")
|
||||
if source not in self.objects:
|
||||
raise ObjectMissingError(source)
|
||||
self.objects[target] = self.objects[source]
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
if self.failing:
|
||||
raise Unavailable("S3 недоступно")
|
||||
self.objects.pop(key, None)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
from datetime import timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from httpx import AsyncClient
|
||||
|
||||
from conftest import resolve
|
||||
from fakes import NullLogger
|
||||
from messenger.attachments.application.commands import (
|
||||
CleanStaging,
|
||||
ProcessJob,
|
||||
PublishOutbox,
|
||||
RecoverExpiredLeases,
|
||||
)
|
||||
from messenger.attachments.application.pipeline import (
|
||||
CleanStagingHandler,
|
||||
ProcessJobHandler,
|
||||
PublishOutboxHandler,
|
||||
RecoverExpiredLeasesHandler,
|
||||
)
|
||||
from messenger.attachments.application.ports import Faults, ObjectStorage, VariantRenderer
|
||||
from messenger.attachments.domain.jobs import Job, Outcome, RetryPolicy
|
||||
from messenger.attachments.entrypoints.schemas import JobMessage
|
||||
from messenger.attachments.infrastructure.faults import EnvironmentFaults
|
||||
from messenger.attachments.infrastructure.images import PillowVariantRenderer
|
||||
from messenger.attachments.infrastructure.postgres import PostgresAttachmentsUnitOfWork
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
||||
from messenger.shared.infrastructure.ids import Uuid7Generator
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
FAST = RetryPolicy(max_attempts=5, base_seconds=0.001, cap_seconds=0.001)
|
||||
|
||||
|
||||
class CapturingPublisher:
|
||||
__slots__ = ("bodies", "failing", "job_ids")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.bodies: list[bytes] = []
|
||||
self.job_ids: list[UUID] = []
|
||||
self.failing = False
|
||||
|
||||
async def publish(self, job_id: UUID, body: bytes) -> None:
|
||||
if self.failing:
|
||||
raise Unavailable("брокер недоступен")
|
||||
self.job_ids.append(job_id)
|
||||
self.bodies.append(body)
|
||||
|
||||
|
||||
class InlinePipeline:
|
||||
__slots__ = ("_database", "faults", "lease", "policy", "publisher", "renderer", "storage")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
database: Database,
|
||||
storage: ObjectStorage,
|
||||
*,
|
||||
policy: RetryPolicy = FAST,
|
||||
lease: timedelta = timedelta(seconds=60),
|
||||
) -> None:
|
||||
self._database = database
|
||||
self.storage = storage
|
||||
self.policy = policy
|
||||
self.lease = lease
|
||||
self.publisher = CapturingPublisher()
|
||||
self.renderer: VariantRenderer = PillowVariantRenderer(40_000_000, 2)
|
||||
self.faults: Faults = EnvironmentFaults("", NullLogger())
|
||||
|
||||
def uow(self) -> PostgresAttachmentsUnitOfWork:
|
||||
return PostgresAttachmentsUnitOfWork(self._database)
|
||||
|
||||
async def publish(self) -> list[Job]:
|
||||
start = len(self.publisher.bodies)
|
||||
await PublishOutboxHandler(self.uow(), self.publisher)(PublishOutbox(100))
|
||||
return [
|
||||
JobMessage.model_validate_json(body).job() for body in self.publisher.bodies[start:]
|
||||
]
|
||||
|
||||
async def process(self, job: Job) -> Outcome:
|
||||
handler = ProcessJobHandler(
|
||||
self.uow(),
|
||||
self.storage,
|
||||
self.renderer,
|
||||
self.faults,
|
||||
clock=MonotonicUtcClock(),
|
||||
ids=Uuid7Generator(),
|
||||
policy=self.policy,
|
||||
lease=self.lease,
|
||||
)
|
||||
return await handler(ProcessJob(job))
|
||||
|
||||
async def drain(self, rounds: int = 20) -> list[Outcome]:
|
||||
outcomes: list[Outcome] = []
|
||||
for _ in range(rounds):
|
||||
jobs = await self.publish()
|
||||
if not jobs:
|
||||
return outcomes
|
||||
outcomes.extend([await self.process(job) for job in jobs])
|
||||
return outcomes
|
||||
|
||||
async def recover(self) -> int:
|
||||
handler = RecoverExpiredLeasesHandler(self.uow(), MonotonicUtcClock(), self.policy)
|
||||
return await handler(RecoverExpiredLeases(100))
|
||||
|
||||
async def clean(self) -> int:
|
||||
return await CleanStagingHandler(self.uow(), self.storage)(CleanStaging(100))
|
||||
|
||||
|
||||
async def pipeline_of(
|
||||
http: AsyncClient, *, policy: RetryPolicy = FAST, lease: timedelta = timedelta(seconds=60)
|
||||
) -> InlinePipeline:
|
||||
database = await resolve(http, Database)
|
||||
storage = await resolve(http, ObjectStorage)
|
||||
return InlinePipeline(database, storage, policy=policy, lease=lease)
|
||||
|
||||
|
||||
async def settle(http: AsyncClient) -> list[Outcome]:
|
||||
return await (await pipeline_of(http)).drain()
|
||||
@@ -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"
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user