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)
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user