feat: process attachments asynchronously with RabbitMQ and a worker

Upload answers 202 after staging, a queued job in PostgreSQL and a broker
confirm; a separate worker publishes the original and a thumbnail with
bounded retries. Adds the job and variant tables, the broker service, the
worker S3 user, cleanup and reconcile support for staging and variants,
the failure stand with broker and worker, bench and driver updates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-31 06:48:20 +03:00
co-authored by Claude Opus 5.5
parent 40c709a78b
commit ff1a83b6ff
107 changed files with 9765 additions and 993 deletions
+44 -20
View File
@@ -21,6 +21,7 @@ import images
from api_client import API, Actor, Api
from contract import (
BEARER_CHALLENGE,
assert_accepted,
assert_content,
assert_error,
assert_errors,
@@ -29,8 +30,20 @@ from contract import (
assert_ok,
assert_replicas,
assert_unauthorized,
assert_variant_content,
)
# поля оригинала: не меняются после ответа на загрузку
ORIGINAL_FIELDS = (
"id",
"chat_id",
"owner_id",
"filename",
"content_type",
"size_bytes",
"sha256",
"created_at",
)
# больше лимита в 3 раза: 30 MiB
BIG_BYTES = 30 * 1024 * 1024
# сколько скачиваний ждать ответа другой реплики (round-robin LB)
@@ -56,7 +69,7 @@ def big_body() -> bytes:
def test_upload_png(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
data = images.sample_png()
attachment = api.upload(alice, chat["id"], data, filename="sample.png")
assert attachment["status"] == "ready"
assert attachment["status"] == "queued"
assert attachment["variants"] == []
assert attachment["error_code"] is None
assert attachment["content_type"] == "image/png"
@@ -167,7 +180,7 @@ def test_exactly_max_pixels(
chat: dict[str, Any],
) -> None:
data = images.png(8000, 5000, color=0, depth=1)
api.upload(alice, chat["id"], data)
api.upload_ready(alice, chat["id"], data)
@pytest.mark.spec("attachments", "Данные длиннее размеров")
@@ -247,7 +260,7 @@ def test_unsuitable_content_type(
data,
content_type="IMAGE/PNG; charset=binary",
)
assert assert_ok(resp, 201, "Attachment")["content_type"] == "image/png"
assert assert_accepted(resp)["content_type"] == "image/png"
@pytest.mark.spec("attachments", "Обрезанный файл")
@@ -329,7 +342,7 @@ def test_tail_after_end(
("image/png", images.with_tail(images.sample_png())),
("image/jpeg", images.with_tail(images.jpeg())),
):
attachment = api.upload(
attachment = api.upload_ready(
alice,
chat["id"],
data,
@@ -385,7 +398,7 @@ def test_filename_not_utf8(
chat: dict[str, Any],
) -> None:
"""Процент-коды `filename` идут в строке запроса как есть: httpx их
не перекодирует. Без строгого разбора `a%FFb.png` давал 201 с U+FFFD
не перекодирует. Без строгого разбора `a%FFb.png` давал успех с U+FFFD
в имени вместо байта."""
data = images.sample_png()
path = f"{API}/chats/{chat['id']}/attachments"
@@ -408,11 +421,7 @@ def test_filename_not_utf8(
400,
)
# верный UTF-8 в процент-кодах — то же имя, что прислано
attachment = assert_ok(
upload("filename=%C3%A9t%C3%A9.png"),
201,
"Attachment",
)
attachment = assert_accepted(upload("filename=%C3%A9t%C3%A9.png"))
assert attachment["filename"] == "été.png"
@@ -511,7 +520,7 @@ def test_other_member_reads(
chat: dict[str, Any],
) -> None:
data = images.sample_png()
attachment = api.upload(alice, chat["id"], data)
attachment = api.upload_ready(alice, chat["id"], data)
assert_ok(api.attachment_meta(bob, attachment["id"]), 200, "Attachment")
assert_content(
api.attachment_content(bob, attachment["id"]),
@@ -582,7 +591,13 @@ def test_meta_equals_upload(
200,
"Attachment",
)
assert meta == attachment
for field in ORIGINAL_FIELDS:
assert meta[field] == attachment[field], field
ready = api.wait_attachment(bob, attachment["id"])
for field in ORIGINAL_FIELDS:
assert ready[field] == attachment[field], field
assert ready["error_code"] is None
assert ready["variants"], "ready attachment has no variants"
@pytest.mark.spec("attachments", "Побайтный оригинал")
@@ -596,7 +611,7 @@ def test_original_bytes(
("image/png", images.sample_png()),
("image/jpeg", images.jpeg(size=(320, 200))),
):
attachment = api.upload(
attachment = api.upload_ready(
alice,
chat["id"],
data,
@@ -615,7 +630,7 @@ def test_variant_original(
chat: dict[str, Any],
) -> None:
data = images.sample_png()
attachment = api.upload(alice, chat["id"], data)
attachment = api.upload_ready(alice, chat["id"], data)
assert_content(
api.attachment_content(alice, attachment["id"], variant="original"),
data,
@@ -628,7 +643,7 @@ def test_variant_original(
attachment["id"],
variant=variant,
)
for variant in ("thumbnail", "")
for variant in ("big", "")
},
400,
)
@@ -643,12 +658,19 @@ def test_no_storage_traces(
data = images.sample_png()
upload = api.post_attachment(alice, chat["id"], data)
# assert_ok сверяет тело со схемой контракта: лишних полей нет
attachment = assert_ok(upload, 201, "Attachment")
attachment = assert_accepted(upload)
ready = api.wait_attachment(alice, attachment["id"])
meta = api.attachment_meta(alice, attachment["id"])
assert_ok(meta, 200, "Attachment")
content = api.attachment_content(alice, attachment["id"])
assert_content(content, data, "image/png")
for resp in (upload, meta, content):
thumbnail = api.attachment_content(
alice,
attachment["id"],
variant="thumbnail",
)
assert_variant_content(thumbnail, ready["variants"][0])
for resp in (upload, meta, content, thumbnail):
assert_no_storage_traces(resp)
@@ -660,8 +682,8 @@ def test_repeated_upload(
chat: dict[str, Any],
) -> None:
data = images.sample_png()
first = api.upload(alice, chat["id"], data)
second = api.upload(alice, chat["id"], data)
first = api.upload_ready(alice, chat["id"], data)
second = api.upload_ready(alice, chat["id"], data)
assert first["id"] != second["id"]
assert first["sha256"] == second["sha256"]
for attachment in (first, second):
@@ -711,6 +733,7 @@ def test_concurrent_uploads(api: Api, base_url: str) -> None:
overlapping = sum(started < spans[0][1] for started, _ in spans)
assert overlapping >= 2, f"uploads did not overlap: {spans}"
for number, attachment in enumerate(attachments):
api.wait_attachment(actors[0], attachment["id"])
assert_content(
api.attachment_content(actors[0], attachment["id"]),
bodies[number],
@@ -728,8 +751,9 @@ def test_download_through_other_replica(
) -> None:
data = images.sample_png()
upload = api.post_attachment(alice, chat["id"], data)
attachment = assert_ok(upload, 201, "Attachment")
attachment = assert_accepted(upload)
uploaded_via = assert_instance_id(upload)
api.wait_attachment(alice, attachment["id"])
seen = {uploaded_via}
for _ in range(REPLICA_ATTEMPTS):
resp = api.attachment_content(bob, attachment["id"])