forked from mtusi2026/mtusi2026lab5
feat: крролик, по тщ 5 лаба
This commit is contained in:
@@ -86,7 +86,7 @@ def send_message(api: httpx.Client) -> Callable[..., dict]:
|
||||
|
||||
@pytest.fixture
|
||||
def upload(api: httpx.Client) -> Callable[..., dict]:
|
||||
"""Успешная загрузка вложения: 201 и Attachment"""
|
||||
"""Приём 202 queued и ожидание ready для прежних сквозных проверок"""
|
||||
|
||||
def create(
|
||||
user: dict,
|
||||
@@ -98,8 +98,11 @@ def upload(api: httpx.Client) -> Callable[..., dict]:
|
||||
response = upload_raw(
|
||||
api, user, chat["id"], content or png_bytes(), content_type, filename
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
assert response.status_code == 202, response.text
|
||||
assert response.json()["status"] == "queued"
|
||||
from helpers import wait_attachment
|
||||
|
||||
return wait_attachment(api, user, response.json()["id"])
|
||||
|
||||
return create
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""Общие проверки для собственных black-box тестов"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import io
|
||||
import json
|
||||
import struct
|
||||
import subprocess
|
||||
import uuid
|
||||
@@ -212,5 +212,28 @@ def container_json(service: str, script: str) -> dict:
|
||||
|
||||
def run_janitor(*args: str) -> dict:
|
||||
"""Один проход janitor внутри его контейнера; отчёт сверки"""
|
||||
output = compose("exec", "-T", "janitor", "python", "src/janitor.py", "--once", *args)
|
||||
output = compose(
|
||||
"exec", "-T", "janitor", "python", "src/janitor.py", "--once", *args
|
||||
)
|
||||
return last_json_line(output)
|
||||
|
||||
|
||||
def wait_attachment(
|
||||
api: httpx.Client,
|
||||
user: dict,
|
||||
attachment_id: str,
|
||||
terminal: str = "ready",
|
||||
timeout: float = 60,
|
||||
) -> dict:
|
||||
import time
|
||||
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
response = api.get(f"/api/v1/attachments/{attachment_id}", headers=auth(user))
|
||||
assert response.status_code == 200, response.text
|
||||
result = response.json()
|
||||
if result["status"] in {"ready", "failed"}:
|
||||
assert result["status"] == terminal, result
|
||||
return result
|
||||
time.sleep(0.1)
|
||||
raise AssertionError(f"Вложение {attachment_id} не достигло {terminal}")
|
||||
|
||||
@@ -13,7 +13,7 @@ import subprocess
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import ROOT, auth, png_bytes, upload_raw
|
||||
from helpers import ROOT, auth, png_bytes, upload_raw, wait_attachment
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
os.environ.get("RUN_FAILURE_TESTS") != "1",
|
||||
@@ -44,12 +44,13 @@ def test_download_survives_stop_of_uploading_replica(
|
||||
content = png_bytes(800, 600, noise=True)
|
||||
|
||||
uploaded = upload_raw(api, alice, chat["id"], content)
|
||||
assert uploaded.status_code == 201, uploaded.text
|
||||
assert uploaded.status_code == 202, uploaded.text
|
||||
attachment = uploaded.json()
|
||||
uploader = uploaded.headers["X-Instance-Id"]
|
||||
|
||||
run_script("stop-one.sh", TARGET_INSTANCE_ID=uploader)
|
||||
try:
|
||||
attachment = wait_attachment(api, bob, attachment["id"])
|
||||
served_by = set()
|
||||
for _ in range(DOWNLOADS_AFTER_STOP):
|
||||
response = api.get(
|
||||
|
||||
@@ -63,7 +63,12 @@ def test_upload_and_download_byte_exact(
|
||||
|
||||
assert set(attachment) == ATTACHMENT_FIELDS
|
||||
assert attachment["status"] == "ready"
|
||||
assert attachment["variants"] == [] and attachment["error_code"] is None
|
||||
assert {v["name"] for v in attachment["variants"]} == {
|
||||
"thumbnail",
|
||||
"crop",
|
||||
"optimized",
|
||||
}
|
||||
assert attachment["error_code"] is None
|
||||
assert attachment["chat_id"] == chat["id"] and attachment["owner_id"] == alice["id"]
|
||||
assert attachment["content_type"] == content_type
|
||||
assert attachment["size_bytes"] == len(content)
|
||||
@@ -118,8 +123,12 @@ def test_outsider_and_unknown_get_indistinguishable_404(
|
||||
attachment = upload(alice, chat)
|
||||
|
||||
for suffix in ("", "/content"):
|
||||
foreign = api.get(f"/api/v1/attachments/{attachment['id']}{suffix}", headers=auth(eve))
|
||||
missing = api.get(f"/api/v1/attachments/{uuid.uuid4()}{suffix}", headers=auth(eve))
|
||||
foreign = api.get(
|
||||
f"/api/v1/attachments/{attachment['id']}{suffix}", headers=auth(eve)
|
||||
)
|
||||
missing = api.get(
|
||||
f"/api/v1/attachments/{uuid.uuid4()}{suffix}", headers=auth(eve)
|
||||
)
|
||||
assert_error(foreign, 404, "not_found")
|
||||
assert_error(missing, 404, "not_found")
|
||||
assert foreign.json()["error"]["message"] == missing.json()["error"]["message"]
|
||||
@@ -135,7 +144,9 @@ def test_outsider_cannot_upload_into_foreign_chat(
|
||||
assert_error(upload_raw(api, eve, str(uuid.uuid4()), png_bytes()), 404, "not_found")
|
||||
|
||||
|
||||
def test_authentication_is_required(api: httpx.Client, make_user, make_chat, upload) -> None:
|
||||
def test_authentication_is_required(
|
||||
api: httpx.Client, make_user, make_chat, upload
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
attachment = upload(alice, chat)
|
||||
@@ -153,7 +164,9 @@ def test_authentication_is_required(api: httpx.Client, make_user, make_chat, upl
|
||||
assert_error(response, 401, "unauthorized")
|
||||
|
||||
|
||||
def test_variants_and_malformed_ids(api: httpx.Client, make_user, make_chat, upload) -> None:
|
||||
def test_variants_and_malformed_ids(
|
||||
api: httpx.Client, make_user, make_chat, upload
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
attachment = upload(alice, chat)
|
||||
@@ -161,9 +174,10 @@ def test_variants_and_malformed_ids(api: httpx.Client, make_user, make_chat, upl
|
||||
|
||||
original = api.get(path, params={"variant": "original"}, headers=auth(alice))
|
||||
assert original.status_code == 200
|
||||
# Вариант из контракта, но в lab4 его нет у ready-вложения
|
||||
missing = api.get(path, params={"variant": "thumbnail"}, headers=auth(alice))
|
||||
assert_error(missing, 404, "not_found")
|
||||
# Производный вариант pipeline v1 доступен через авторизованный API
|
||||
thumbnail = api.get(path, params={"variant": "thumbnail"}, headers=auth(alice))
|
||||
assert thumbnail.status_code == 200
|
||||
assert thumbnail.headers["content-type"] == "image/jpeg"
|
||||
unknown = api.get(path, params={"variant": "../../etc"}, headers=auth(alice))
|
||||
assert_error(unknown, 400, "invalid_request")
|
||||
malformed = api.get("/api/v1/attachments/not-a-uuid", headers=auth(alice))
|
||||
@@ -173,7 +187,9 @@ def test_variants_and_malformed_ids(api: httpx.Client, make_user, make_chat, upl
|
||||
# --- Размер ---
|
||||
|
||||
|
||||
def test_exactly_max_bytes_is_accepted(api: httpx.Client, make_user, make_chat, upload) -> None:
|
||||
def test_exactly_max_bytes_is_accepted(
|
||||
api: httpx.Client, make_user, make_chat, upload
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
content = png_of_size(MAX_UPLOAD_BYTES)
|
||||
@@ -182,7 +198,9 @@ def test_exactly_max_bytes_is_accepted(api: httpx.Client, make_user, make_chat,
|
||||
assert download(api, alice, attachment["id"]).content == content
|
||||
|
||||
|
||||
def test_too_large_file_is_rejected_by_api(api: httpx.Client, make_user, make_chat) -> None:
|
||||
def test_too_large_file_is_rejected_by_api(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
"""10 MiB + 1 байт отклоняет реплика (X-Instance-Id), а не только LB"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
@@ -191,7 +209,9 @@ def test_too_large_file_is_rejected_by_api(api: httpx.Client, make_user, make_ch
|
||||
assert response.headers["X-Instance-Id"]
|
||||
|
||||
|
||||
def test_huge_body_is_rejected_by_balancer(api: httpx.Client, make_user, make_chat) -> None:
|
||||
def test_huge_body_is_rejected_by_balancer(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = upload_raw(api, alice, chat["id"], b"\x00" * (12 * 1024 * 1024))
|
||||
@@ -207,7 +227,7 @@ def test_empty_body_is_rejected(api: httpx.Client, make_user, make_chat) -> None
|
||||
@pytest.mark.parametrize(
|
||||
("width", "height", "status"),
|
||||
[
|
||||
(8000, 5000, 201),
|
||||
(8000, 5000, 202),
|
||||
(8000, 5001, 413),
|
||||
(20000, 20000, 413),
|
||||
],
|
||||
@@ -221,9 +241,9 @@ def test_pixel_limit_applies_before_decoding(
|
||||
content = bilevel_png(width, height)
|
||||
assert len(content) < 1024 * 1024
|
||||
response = upload_raw(api, alice, chat["id"], content)
|
||||
if status == 201:
|
||||
if status == 202:
|
||||
assert width * height == MAX_IMAGE_PIXELS
|
||||
assert response.status_code == 201, response.text
|
||||
assert response.status_code == 202, response.text
|
||||
else:
|
||||
assert_error(response, 413, "payload_too_large")
|
||||
|
||||
@@ -252,7 +272,12 @@ def corrupted_payloads() -> list[tuple[str, bytes, str]]:
|
||||
ids=[item[0] for item in corrupted_payloads()],
|
||||
)
|
||||
def test_corrupted_image_is_rejected(
|
||||
api: httpx.Client, make_user, make_chat, name: str, content: bytes, content_type: str
|
||||
api: httpx.Client,
|
||||
make_user,
|
||||
make_chat,
|
||||
name: str,
|
||||
content: bytes,
|
||||
content_type: str,
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
@@ -302,7 +327,7 @@ def test_content_type_parameters_are_ignored(
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = upload_raw(api, alice, chat["id"], png_bytes(), "Image/PNG; foo=bar")
|
||||
assert response.status_code == 201, response.text
|
||||
assert response.status_code == 202, response.text
|
||||
assert response.json()["content_type"] == "image/png"
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Сквозные свойства pipeline v1 без остановки сервисов"""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
from helpers import assert_error, auth, png_bytes, psql, upload_raw, wait_attachment
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def test_variants_have_real_dimensions_checksums_and_no_metadata(
|
||||
api, make_user, make_chat, upload
|
||||
):
|
||||
alice = make_user("pipeline")
|
||||
chat = make_chat(alice, [alice])
|
||||
image = Image.new("RGBA", (320, 200), (255, 0, 0, 0))
|
||||
source = io.BytesIO()
|
||||
image.save(source, "PNG")
|
||||
ready = upload(alice, chat, source.getvalue())
|
||||
expected = {
|
||||
"thumbnail": ((256, 160), "JPEG"),
|
||||
"crop": ((128, 128), "JPEG"),
|
||||
"optimized": ((320, 200), "WEBP"),
|
||||
}
|
||||
for variant in ready["variants"]:
|
||||
response = api.get(
|
||||
f"/api/v1/attachments/{ready['id']}/content",
|
||||
params={"variant": variant["name"]},
|
||||
headers=auth(alice),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert len(response.content) == variant["size_bytes"]
|
||||
assert hashlib.sha256(response.content).hexdigest() == variant["sha256"]
|
||||
assert response.headers["content-type"] == variant["content_type"]
|
||||
with Image.open(io.BytesIO(response.content)) as actual:
|
||||
assert (actual.size, actual.format) == expected[variant["name"]]
|
||||
assert actual.size == (variant["width"], variant["height"])
|
||||
assert not actual.getexif() and not actual.info.get("icc_profile")
|
||||
assert min(actual.convert("RGB").getpixel((0, 0))) >= 250 # alpha → белый
|
||||
|
||||
|
||||
def test_orientation_and_no_upscale(api, make_user, make_chat, upload):
|
||||
alice = make_user("orientation")
|
||||
chat = make_chat(alice, [alice])
|
||||
source = io.BytesIO()
|
||||
image = Image.new("RGB", (12, 24), "red")
|
||||
exif = Image.Exif()
|
||||
exif[274] = 6
|
||||
exif[315] = "must be stripped"
|
||||
image.save(source, "JPEG", exif=exif)
|
||||
ready = upload(alice, chat, source.getvalue(), "image/jpeg")
|
||||
by_name = {v["name"]: v for v in ready["variants"]}
|
||||
for name in ("thumbnail", "optimized"):
|
||||
assert (by_name[name]["width"], by_name[name]["height"]) == (24, 12)
|
||||
response = api.get(
|
||||
f"/api/v1/attachments/{ready['id']}/content?variant={name}",
|
||||
headers=auth(alice),
|
||||
)
|
||||
with Image.open(io.BytesIO(response.content)) as actual:
|
||||
assert not actual.getexif()
|
||||
assert (by_name["crop"]["width"], by_name["crop"]["height"]) == (128, 128)
|
||||
original = api.get(
|
||||
f"/api/v1/attachments/{ready['id']}/content", headers=auth(alice)
|
||||
)
|
||||
assert original.content == source.getvalue()
|
||||
|
||||
|
||||
def broken_idat() -> bytes:
|
||||
"""Корректная структура/CRC, но недекодируемый zlib: обнаруживает именно worker"""
|
||||
data = png_bytes(32, 32)
|
||||
result = bytearray(data[:8])
|
||||
offset = 8
|
||||
while offset < len(data):
|
||||
size = struct.unpack(">I", data[offset : offset + 4])[0]
|
||||
kind = data[offset + 4 : offset + 8]
|
||||
body = data[offset + 8 : offset + 8 + size]
|
||||
if kind == b"IDAT":
|
||||
body = b"invalid zlib"
|
||||
result += (
|
||||
struct.pack(">I", len(body))
|
||||
+ kind
|
||||
+ body
|
||||
+ struct.pack(">I", zlib.crc32(kind + body))
|
||||
)
|
||||
offset += size + 12
|
||||
return bytes(result)
|
||||
|
||||
|
||||
def test_permanent_failure_is_observable_and_not_linkable(
|
||||
api, make_user, make_chat, send_attachments
|
||||
):
|
||||
alice = make_user("invalid")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = upload_raw(api, alice, chat["id"], broken_idat())
|
||||
assert response.status_code == 202 and response.json()["status"] == "queued"
|
||||
attachment = wait_attachment(api, alice, response.json()["id"], terminal="failed")
|
||||
assert attachment["error_code"] == "invalid_image" and not attachment["variants"]
|
||||
assert_error(
|
||||
api.get(f"/api/v1/attachments/{attachment['id']}/content", headers=auth(alice)),
|
||||
409,
|
||||
"conflict",
|
||||
)
|
||||
assert_error(send_attachments(alice, chat, [attachment["id"]]), 409, "conflict")
|
||||
row = json.loads(
|
||||
psql(
|
||||
f"SELECT json_build_object('attempt', attempt, 'failures', failures) FROM attachment_jobs WHERE attachment_id = '{attachment['id']}';"
|
||||
)
|
||||
)
|
||||
assert row == {"attempt": 1, "failures": 1}
|
||||
@@ -0,0 +1,390 @@
|
||||
"""Остановка именно своего стенда; запуск: make test-pipeline-failures"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from subprocess import CalledProcessError
|
||||
|
||||
import pytest
|
||||
from helpers import (
|
||||
auth,
|
||||
compose,
|
||||
message_headers,
|
||||
png_bytes,
|
||||
psql,
|
||||
upload_raw,
|
||||
wait_attachment,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
os.getenv("RUN_PIPELINE_FAILURE_TESTS") != "1",
|
||||
reason="явные остановки/инъекции: make test-pipeline-failures",
|
||||
)
|
||||
|
||||
|
||||
def wait_for(check, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = check()
|
||||
except CalledProcessError:
|
||||
value = False
|
||||
if value:
|
||||
return value
|
||||
time.sleep(0.2)
|
||||
raise AssertionError("Состояние не достигнуто вовремя")
|
||||
|
||||
|
||||
def wait_queue_empty():
|
||||
wait_for(
|
||||
lambda: "attachments.process.v1\t0"
|
||||
in compose(
|
||||
"exec", "-T", "broker", "rabbitmqctl", "list_queues", "name", "messages"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def job_row(attachment_id):
|
||||
return json.loads(
|
||||
psql(f"""SELECT row_to_json(r) FROM (
|
||||
SELECT j.id, j.attempt, j.failures, j.lease_until, a.status, a.staging_key,
|
||||
(SELECT count(*) FROM attachment_variants WHERE attachment_id = a.id) AS variants
|
||||
FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE a.id = '{attachment_id}') r;""")
|
||||
)
|
||||
|
||||
|
||||
def accept(api, alice, chat, content=None):
|
||||
response = upload_raw(
|
||||
api, alice, chat["id"], content if content is not None else png_bytes(320, 200)
|
||||
)
|
||||
assert response.status_code == 202, response.text
|
||||
assert response.json()["status"] == "queued"
|
||||
return response.json()
|
||||
|
||||
|
||||
def test_commit_publish_gap_worker_down_and_broker_volume(api, make_user, make_chat):
|
||||
alice = make_user("handoff")
|
||||
chat = make_chat(alice, [alice])
|
||||
compose("stop", "dispatcher", "worker")
|
||||
try:
|
||||
content = png_bytes(320, 200)
|
||||
attachment = accept(api, alice, chat, content)
|
||||
row = job_row(attachment["id"])
|
||||
assert row["status"] == "queued" and row["staging_key"]
|
||||
assert (
|
||||
psql(
|
||||
f"SELECT count(*) FROM attachment_outbox WHERE job_id = '{row['id']}' AND published_at IS NULL;"
|
||||
)
|
||||
== "1"
|
||||
)
|
||||
linked = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "", "attachment_ids": [attachment["id"]]},
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert linked.status_code == 201
|
||||
assert (
|
||||
api.get(
|
||||
f"/api/v1/attachments/{attachment['id']}/content", headers=auth(alice)
|
||||
).status_code
|
||||
== 409
|
||||
)
|
||||
compose("restart", "api") # COMMIT уже был; publish ещё не было.
|
||||
wait_for(lambda: api.get("/health/ready").status_code == 200)
|
||||
compose("start", "dispatcher")
|
||||
wait_for(
|
||||
lambda: psql(
|
||||
f"SELECT count(*) FROM attachment_outbox WHERE job_id = '{row['id']}' AND published_at IS NOT NULL;"
|
||||
)
|
||||
== "1"
|
||||
)
|
||||
compose("restart", "broker")
|
||||
wait_for(
|
||||
lambda: "attachments.process.v1\t1"
|
||||
in compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"broker",
|
||||
"rabbitmqctl",
|
||||
"list_queues",
|
||||
"name",
|
||||
"messages_ready",
|
||||
)
|
||||
)
|
||||
compose("start", "worker")
|
||||
ready = wait_attachment(api, alice, attachment["id"])
|
||||
assert len(ready["variants"]) == 3
|
||||
assert (
|
||||
api.get(
|
||||
f"/api/v1/attachments/{attachment['id']}/content", headers=auth(alice)
|
||||
).content
|
||||
== content
|
||||
)
|
||||
print(
|
||||
"HANDOFF: COMMIT -> API restart -> publish -> broker restart with volume -> ready",
|
||||
attachment["id"],
|
||||
)
|
||||
finally:
|
||||
compose("start", "dispatcher", "worker")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("point", ["after-objects", "after-result"])
|
||||
def test_crash_before_ack_does_not_duplicate_effect(api, make_user, make_chat, point):
|
||||
alice = make_user("crash")
|
||||
chat = make_chat(alice, [alice])
|
||||
compose("exec", "-T", "worker", "touch", f"/tmp/lab5-crash-{point}")
|
||||
try:
|
||||
attachment = accept(api, alice, chat)
|
||||
if point == "after-objects":
|
||||
wait_for(lambda: job_row(attachment["id"])["status"] == "processing")
|
||||
# Реальный SIG-exit без COMMIT; ждём штатный lease (90 с), не меняя его.
|
||||
ready = wait_attachment(api, alice, attachment["id"], timeout=120)
|
||||
row = job_row(attachment["id"])
|
||||
assert row["attempt"] == 2 and row["failures"] == 1
|
||||
else:
|
||||
ready = wait_attachment(api, alice, attachment["id"])
|
||||
row = job_row(attachment["id"])
|
||||
assert row["attempt"] == 1
|
||||
assert row["variants"] == 3
|
||||
before = ready
|
||||
# Явный дубль уже завершённой job: публикация через тот же adapter с confirm.
|
||||
compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"dispatcher",
|
||||
"python",
|
||||
"-c",
|
||||
f'''
|
||||
import asyncio, sys
|
||||
sys.path.insert(0, 'src')
|
||||
from infrastructure import database_pool_manager as db
|
||||
from infrastructure.broker import RabbitBrokerManager
|
||||
from config.settings import BROKER_URL_FILE
|
||||
from domain.jobs import JobMessageSchema
|
||||
async def main():
|
||||
await db.create_pool(30)
|
||||
async with db.acquire() as conn:
|
||||
r = await conn.fetchrow("SELECT id AS job_id, attachment_id, pipeline_version, attempt, created_at FROM attachment_jobs WHERE id = $1::uuid", "{row["id"]}")
|
||||
b = RabbitBrokerManager(BROKER_URL_FILE, 2)
|
||||
await b.publish(JobMessageSchema(**dict(r)))
|
||||
await b.close()
|
||||
await db.close()
|
||||
asyncio.run(main())
|
||||
''',
|
||||
)
|
||||
wait_queue_empty() # Проверяем фактический ack, а не только статус в БД.
|
||||
for variant in ready["variants"]:
|
||||
response = api.get(
|
||||
f"/api/v1/attachments/{attachment['id']}/content",
|
||||
params={"variant": variant["name"]},
|
||||
headers=auth(alice),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert hashlib.sha256(response.content).hexdigest() == variant["sha256"]
|
||||
assert wait_attachment(api, alice, attachment["id"]) == before
|
||||
assert job_row(attachment["id"])["variants"] == 3
|
||||
print(
|
||||
"CRASH/REDELIVERY:",
|
||||
point,
|
||||
"attempt",
|
||||
row["attempt"],
|
||||
"variants=3",
|
||||
attachment["id"],
|
||||
)
|
||||
finally:
|
||||
compose("exec", "-T", "worker", "rm", "-f", f"/tmp/lab5-crash-{point}")
|
||||
compose("start", "worker")
|
||||
|
||||
|
||||
def test_retry_exhaustion_and_safe_operator_replay(api, make_user, make_chat):
|
||||
alice = make_user("retry")
|
||||
chat = make_chat(alice, [alice])
|
||||
compose("stop", "worker")
|
||||
name = "lab5_fault_" + uuid.uuid4().hex
|
||||
attachment = accept(api, alice, chat)
|
||||
row = job_row(attachment["id"])
|
||||
psql(f"""CREATE FUNCTION {name}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN IF NEW.id = '{attachment["id"]}' AND NEW.status = 'ready' THEN
|
||||
RAISE EXCEPTION 'injected commit failure'; END IF; RETURN NEW; END; $$;
|
||||
CREATE TRIGGER {name} BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION {name}();""")
|
||||
try:
|
||||
compose("start", "worker")
|
||||
failed = wait_attachment(
|
||||
api, alice, attachment["id"], terminal="failed", timeout=90
|
||||
)
|
||||
assert failed["error_code"] == "retry_exhausted"
|
||||
row = job_row(attachment["id"])
|
||||
assert row["attempt"] == row["failures"] == 5 and row["variants"] == 0
|
||||
times = json.loads(
|
||||
psql(
|
||||
f"SELECT json_agg(available_at ORDER BY attempt) FROM attachment_outbox WHERE job_id = '{row['id']}';"
|
||||
)
|
||||
)
|
||||
from datetime import datetime
|
||||
|
||||
deltas = [
|
||||
(datetime.fromisoformat(b) - datetime.fromisoformat(a)).total_seconds()
|
||||
for a, b in zip(times, times[1:])
|
||||
]
|
||||
assert len(deltas) == 4
|
||||
assert all(delay >= 2**index for index, delay in enumerate(deltas))
|
||||
psql(f"DROP TRIGGER {name} ON attachments; DROP FUNCTION {name}();")
|
||||
result = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"dispatcher",
|
||||
"python",
|
||||
"src/jobs.py",
|
||||
"replay",
|
||||
"--job-id",
|
||||
row["id"],
|
||||
"--operator",
|
||||
"lab-test",
|
||||
"--reason",
|
||||
"fault removed",
|
||||
)
|
||||
assert "queued:" in result
|
||||
ready = wait_attachment(api, alice, attachment["id"])
|
||||
assert len(ready["variants"]) == 3
|
||||
again = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"dispatcher",
|
||||
"python",
|
||||
"src/jobs.py",
|
||||
"replay",
|
||||
"--job-id",
|
||||
row["id"],
|
||||
"--operator",
|
||||
"lab-test",
|
||||
"--reason",
|
||||
"duplicate replay",
|
||||
)
|
||||
assert "no-op:" in again
|
||||
assert (
|
||||
psql(
|
||||
f"SELECT count(*) FROM attachment_replays WHERE job_id = '{row['id']}';"
|
||||
)
|
||||
== "1"
|
||||
)
|
||||
print(
|
||||
"RETRY: attempts=5, backoff seconds",
|
||||
deltas,
|
||||
"failed -> audited replay -> ready; ready replay no-op",
|
||||
)
|
||||
finally:
|
||||
psql(
|
||||
f"DROP TRIGGER IF EXISTS {name} ON attachments; DROP FUNCTION IF EXISTS {name}();"
|
||||
)
|
||||
compose("start", "worker")
|
||||
|
||||
|
||||
def test_publisher_crash_after_confirm_recovers_outbox(api, make_user, make_chat):
|
||||
alice = make_user("confirm")
|
||||
chat = make_chat(alice, [alice])
|
||||
compose("exec", "-T", "dispatcher", "touch", "/tmp/lab5-crash-after-publish")
|
||||
try:
|
||||
attachment = accept(api, alice, chat)
|
||||
ready = wait_attachment(api, alice, attachment["id"])
|
||||
row = job_row(attachment["id"])
|
||||
wait_for(
|
||||
lambda: psql(
|
||||
f"SELECT count(*) FROM attachment_outbox WHERE job_id = '{row['id']}' AND published_at IS NOT NULL;"
|
||||
)
|
||||
== "1",
|
||||
timeout=30,
|
||||
)
|
||||
wait_queue_empty()
|
||||
assert len(ready["variants"]) == 3 and row["attempt"] == 1
|
||||
print(
|
||||
"CONFIRM GAP: confirmed publish -> crash -> outbox lease -> duplicate no-op",
|
||||
attachment["id"],
|
||||
)
|
||||
finally:
|
||||
compose("exec", "-T", "dispatcher", "rm", "-f", "/tmp/lab5-crash-after-publish")
|
||||
compose("start", "dispatcher")
|
||||
|
||||
|
||||
def test_staging_cleanup_retention_and_replay_guard(api, make_user, make_chat, upload):
|
||||
from subprocess import CalledProcessError
|
||||
|
||||
from test_pipeline import broken_idat
|
||||
|
||||
alice = make_user("retention")
|
||||
chat = make_chat(alice, [alice])
|
||||
ready = upload(alice, chat)
|
||||
failed = accept(api, alice, chat, broken_idat())
|
||||
wait_attachment(api, alice, failed["id"], terminal="failed")
|
||||
failed_job = job_row(failed["id"])
|
||||
compose("stop", "worker")
|
||||
try:
|
||||
active = accept(api, alice, chat)
|
||||
psql(
|
||||
f"UPDATE attachments SET created_at = clock_timestamp() - interval '2 days' WHERE id = '{active['id']}';"
|
||||
)
|
||||
psql(
|
||||
f"UPDATE attachments SET updated_at = clock_timestamp() - interval '2 days' WHERE id = '{failed['id']}';"
|
||||
)
|
||||
compose("exec", "-T", "janitor", "python", "src/janitor.py", "--once")
|
||||
assert job_row(ready["id"])["staging_key"] is None
|
||||
assert job_row(failed["id"])["staging_key"] is None
|
||||
assert job_row(active["id"])["staging_key"] is not None
|
||||
assert job_row(active["id"])["status"] == "queued"
|
||||
with pytest.raises(CalledProcessError):
|
||||
compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"dispatcher",
|
||||
"python",
|
||||
"src/jobs.py",
|
||||
"replay",
|
||||
"--job-id",
|
||||
failed_job["id"],
|
||||
"--operator",
|
||||
"lab-test",
|
||||
"--reason",
|
||||
"expired source",
|
||||
)
|
||||
assert (
|
||||
api.get(
|
||||
f"/api/v1/attachments/{ready['id']}/content", headers=auth(alice)
|
||||
).status_code
|
||||
== 200
|
||||
)
|
||||
compose("start", "worker")
|
||||
wait_attachment(api, alice, active["id"])
|
||||
print(
|
||||
"CLEANUP: ready staging removed; expired failed retired; active queued preserved; expired replay rejected"
|
||||
)
|
||||
finally:
|
||||
compose("start", "worker")
|
||||
|
||||
|
||||
def test_worker_process_has_effective_memory_limit():
|
||||
result = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"worker",
|
||||
"python",
|
||||
"-c",
|
||||
"""
|
||||
import subprocess, sys, tempfile
|
||||
from pathlib import Path
|
||||
from PIL import Image
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
source = root / 'source.png'
|
||||
with Image.new('1', (8000, 5000)) as image:
|
||||
image.save(source)
|
||||
result = subprocess.run([sys.executable, 'src/infrastructure/media/image_transform.py',
|
||||
str(source), str(root), '40000000', '128', '30'], capture_output=True, text=True)
|
||||
assert result.returncode == 2, (result.returncode, result.stderr)
|
||||
assert result.stdout.strip() == 'image_resource_limit', result.stdout
|
||||
print('Linux RLIMIT_AS=128MiB: decoder refused 40Mpx without killing worker')
|
||||
""",
|
||||
)
|
||||
assert "decoder refused" in result
|
||||
print(result.strip())
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Конкурентные границы retirement/replay на настоящем PostgreSQL"""
|
||||
|
||||
from subprocess import CalledProcessError
|
||||
|
||||
from helpers import compose, psql, upload_raw, wait_attachment
|
||||
from test_pipeline import broken_idat
|
||||
|
||||
|
||||
def checked_compose(*args):
|
||||
try:
|
||||
return compose(*args)
|
||||
except CalledProcessError as error:
|
||||
raise AssertionError(error.stderr) from None
|
||||
|
||||
|
||||
def test_replay_waiting_for_cleanup_rechecks_retired_source(api, make_user, make_chat):
|
||||
alice = make_user("replay_race")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = upload_raw(api, alice, chat["id"], broken_idat())
|
||||
assert response.status_code == 202
|
||||
attachment = wait_attachment(api, alice, response.json()["id"], terminal="failed")
|
||||
job_id = psql(
|
||||
f"SELECT id FROM attachment_jobs WHERE attachment_id = '{attachment['id']}';"
|
||||
)
|
||||
# Удерживаем lock job, запускаем replay и дожидаемся его реального ожидания
|
||||
# в pg_stat_activity. Затем retirement меняет только attachment и коммитит.
|
||||
result = checked_compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"dispatcher",
|
||||
"python",
|
||||
"-c",
|
||||
f"""
|
||||
import asyncio, sys
|
||||
from uuid import UUID
|
||||
sys.path.insert(0, 'src')
|
||||
from infrastructure import database_pool_manager as db
|
||||
from infrastructure.dependencies.jobs import create_job_repository
|
||||
from domain.errors import ConflictError
|
||||
|
||||
async def main():
|
||||
await db.create_pool(30)
|
||||
job_id = UUID('{job_id}')
|
||||
task = None
|
||||
try:
|
||||
async with db.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
await conn.fetchval('SELECT id FROM attachment_jobs WHERE id = $1 FOR UPDATE', job_id)
|
||||
pid = await conn.fetchval('SELECT pg_backend_pid()')
|
||||
task = asyncio.create_task(create_job_repository().replay(job_id, 'race-test', 'concurrent retirement'))
|
||||
for _ in range(200):
|
||||
blocked = await conn.fetchval('SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid)))', pid)
|
||||
if blocked:
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
else:
|
||||
raise AssertionError('replay did not wait for the job lock')
|
||||
await conn.execute('UPDATE attachments SET staging_key = NULL WHERE id = $1', UUID('{attachment["id"]}'))
|
||||
try:
|
||||
changed = await task
|
||||
except ConflictError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError(f'replay accepted retired source: changed={{changed}}')
|
||||
print('PASS: replay rechecks attachment after waiting; retired source rejected')
|
||||
finally:
|
||||
if task is not None and not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
# Оставляем только эту синтетическую запись в терминальном состоянии
|
||||
# и при обнаружении регрессии, не допуская processing без исходника.
|
||||
async with db.acquire() as conn, conn.transaction():
|
||||
await conn.fetchval('SELECT id FROM attachment_jobs WHERE id = $1 FOR UPDATE', job_id)
|
||||
await conn.execute('UPDATE attachment_jobs SET lease_token = NULL, lease_until = NULL WHERE id = $1', job_id)
|
||||
await conn.execute("UPDATE attachments SET status = 'failed', staging_key = NULL, error_code = 'invalid_image' WHERE id = $1", UUID('{attachment["id"]}'))
|
||||
await db.close()
|
||||
asyncio.run(main())
|
||||
""",
|
||||
)
|
||||
assert "retired source rejected" in result
|
||||
@@ -24,6 +24,7 @@ from helpers import (
|
||||
psql,
|
||||
run_janitor,
|
||||
upload_raw,
|
||||
wait_attachment,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
@@ -49,7 +50,7 @@ def wait_upload_works(api: httpx.Client, user: dict, chat_id: str) -> httpx.Resp
|
||||
deadline = time.monotonic() + READY_TIMEOUT_SEC
|
||||
while True:
|
||||
response = upload_raw(api, user, chat_id, png_bytes())
|
||||
if response.status_code == 201 or time.monotonic() > deadline:
|
||||
if response.status_code == 202 or time.monotonic() > deadline:
|
||||
return response
|
||||
time.sleep(1)
|
||||
|
||||
@@ -89,7 +90,8 @@ def test_s3_outage_is_isolated_and_leaves_no_garbage(
|
||||
compose("up", "-d", "--wait", "s3")
|
||||
|
||||
after = wait_upload_works(api, alice, chat["id"])
|
||||
assert after.status_code == 201, after.text
|
||||
assert after.status_code == 202, after.text
|
||||
wait_attachment(api, alice, after.json()["id"])
|
||||
content = api.get(f"/api/v1/attachments/{before['id']}/content", headers=auth(bob))
|
||||
assert content.status_code == 200
|
||||
|
||||
|
||||
+36
-12
@@ -47,14 +47,19 @@ class FakeChatRepository(ChatRepository):
|
||||
def __init__(self) -> None:
|
||||
self.foreign: set[UUID] = set()
|
||||
|
||||
async def create(self, title: str, created_by: UUID, member_ids: list[UUID]) -> ChatSchema:
|
||||
async def create(
|
||||
self, title: str, created_by: UUID, member_ids: list[UUID]
|
||||
) -> ChatSchema:
|
||||
raise NotImplementedError
|
||||
|
||||
async def get_for_member(self, chat_id: UUID, member_id: UUID) -> ChatSchema | None:
|
||||
if chat_id in self.foreign:
|
||||
return None
|
||||
return ChatSchema(
|
||||
id=chat_id, title="chat", member_ids=[member_id], created_at=datetime.now(UTC)
|
||||
id=chat_id,
|
||||
title="chat",
|
||||
member_ids=[member_id],
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
|
||||
async def list_for_member(
|
||||
@@ -69,7 +74,9 @@ class FakeAttachmentRepository(FaultInjection, AttachmentRepository):
|
||||
self.rows: dict[UUID, dict] = {}
|
||||
self.ready_returns_none = False
|
||||
|
||||
def add_row(self, object_key: str, status: AttachmentStatus, age_seconds: float) -> UUID:
|
||||
def add_row(
|
||||
self, object_key: str, status: AttachmentStatus, age_seconds: float
|
||||
) -> UUID:
|
||||
attachment_id = uuid4()
|
||||
self.rows[attachment_id] = {
|
||||
"status": status,
|
||||
@@ -81,21 +88,30 @@ class FakeAttachmentRepository(FaultInjection, AttachmentRepository):
|
||||
|
||||
async def create_pending(self, attachment: NewAttachmentSchema) -> UUID:
|
||||
await self._enter("create_pending")
|
||||
attachment_id = self.add_row(attachment.object_key, AttachmentStatus.PENDING, 0)
|
||||
attachment_id = self.add_row(
|
||||
"staging/" + attachment.object_key, AttachmentStatus.PENDING, 0
|
||||
)
|
||||
self.rows[attachment_id]["new"] = attachment
|
||||
return attachment_id
|
||||
|
||||
async def mark_ready(self, attachment_id: UUID, grace_seconds: int) -> AttachmentSchema | None:
|
||||
await self._enter("mark_ready")
|
||||
async def mark_queued(
|
||||
self, attachment_id: UUID, grace_seconds: int
|
||||
) -> AttachmentSchema | None:
|
||||
await self._enter("mark_queued")
|
||||
row = self.rows.get(attachment_id)
|
||||
if self.ready_returns_none or row is None or row["status"] != AttachmentStatus.PENDING:
|
||||
if (
|
||||
self.ready_returns_none
|
||||
or row is None
|
||||
or row["status"] != AttachmentStatus.PENDING
|
||||
):
|
||||
return None
|
||||
if row["created_at"] <= datetime.now(UTC) - timedelta(seconds=grace_seconds):
|
||||
return None
|
||||
row["status"] = AttachmentStatus.READY
|
||||
row["status"] = AttachmentStatus.QUEUED
|
||||
new: NewAttachmentSchema = row["new"]
|
||||
return AttachmentSchema(
|
||||
id=attachment_id,
|
||||
status="queued",
|
||||
chat_id=new.chat_id,
|
||||
owner_id=new.owner_id,
|
||||
filename=new.filename,
|
||||
@@ -120,10 +136,15 @@ class FakeAttachmentRepository(FaultInjection, AttachmentRepository):
|
||||
attachment_id
|
||||
for attachment_id, row in self.rows.items()
|
||||
if row["status"] == AttachmentStatus.DELETING
|
||||
or (row["status"] == AttachmentStatus.PENDING and row["created_at"] < threshold)
|
||||
or (
|
||||
row["status"] == AttachmentStatus.PENDING
|
||||
and row["created_at"] < threshold
|
||||
)
|
||||
]
|
||||
|
||||
async def claim_unfinished(self, grace_seconds: int, limit: int) -> list[UnfinishedUploadSchema]:
|
||||
async def claim_unfinished(
|
||||
self, grace_seconds: int, limit: int
|
||||
) -> list[UnfinishedUploadSchema]:
|
||||
await self._enter("claim_unfinished")
|
||||
# Повторный вызов в том же проходе не должен возвращать те же строки
|
||||
claimed = [
|
||||
@@ -135,10 +156,13 @@ class FakeAttachmentRepository(FaultInjection, AttachmentRepository):
|
||||
self.rows[attachment_id]["status"] = AttachmentStatus.DELETING
|
||||
self.rows[attachment_id]["claimed_now"] = True
|
||||
return [
|
||||
UnfinishedUploadSchema(id=i, object_key=self.rows[i]["object_key"]) for i in claimed
|
||||
UnfinishedUploadSchema(id=i, object_key=self.rows[i]["object_key"])
|
||||
for i in claimed
|
||||
]
|
||||
|
||||
async def list_unfinished(self, grace_seconds: int, limit: int) -> list[UnfinishedUploadSchema]:
|
||||
async def list_unfinished(
|
||||
self, grace_seconds: int, limit: int
|
||||
) -> list[UnfinishedUploadSchema]:
|
||||
await self._enter("list_unfinished")
|
||||
return [
|
||||
UnfinishedUploadSchema(id=i, object_key=self.rows[i]["object_key"])
|
||||
|
||||
@@ -82,18 +82,18 @@ def run(coro):
|
||||
return asyncio.run(coro)
|
||||
|
||||
|
||||
def test_success_stores_object_and_ready_row() -> None:
|
||||
def test_success_stores_staging_and_queued_row() -> None:
|
||||
stand = Stand()
|
||||
data = png()
|
||||
attachment = run(stand.upload(data))
|
||||
assert attachment.sha256 == hashlib.sha256(data).hexdigest()
|
||||
assert stand.attachments.statuses() == [AttachmentStatus.READY]
|
||||
assert stand.attachments.statuses() == [AttachmentStatus.QUEUED]
|
||||
[(stored, _)] = stand.storage.objects.values()
|
||||
assert stored == data
|
||||
[key] = stand.storage.objects
|
||||
assert key.startswith("originals/") and "a.png" not in key
|
||||
assert key.startswith("staging/originals/") and "a.png" not in key
|
||||
# Строка записана до PUT, подтверждена после
|
||||
assert stand.attachments.calls[:2] == ["create_pending", "mark_ready"]
|
||||
assert stand.attachments.calls[:2] == ["create_pending", "mark_queued"]
|
||||
|
||||
|
||||
def test_s3_failure_after_write_is_compensated() -> None:
|
||||
@@ -109,7 +109,7 @@ def test_s3_failure_after_write_is_compensated() -> None:
|
||||
def test_db_failure_between_s3_and_commit_is_compensated() -> None:
|
||||
"""Объект записан в S3, подтверждение в БД не прошло"""
|
||||
stand = Stand()
|
||||
stand.attachments.fail.add("mark_ready")
|
||||
stand.attachments.fail.add("mark_queued")
|
||||
with pytest.raises(UnavailableError):
|
||||
run(stand.upload())
|
||||
assert stand.storage.objects == {}
|
||||
@@ -122,7 +122,7 @@ def test_db_down_leaves_pending_row_that_janitor_cleans() -> None:
|
||||
строкой pending; janitor после grace period удаляет и объект, и строку.
|
||||
"""
|
||||
stand = Stand()
|
||||
stand.attachments.fail.update({"mark_ready", "claim_pending"})
|
||||
stand.attachments.fail.update({"mark_queued", "claim_pending"})
|
||||
with pytest.raises(UnavailableError):
|
||||
run(stand.upload())
|
||||
assert len(stand.storage.objects) == 1
|
||||
@@ -140,7 +140,7 @@ def test_db_down_leaves_pending_row_that_janitor_cleans() -> None:
|
||||
|
||||
def test_s3_down_during_compensation_leaves_deleting_row_for_janitor() -> None:
|
||||
stand = Stand()
|
||||
stand.attachments.fail.add("mark_ready")
|
||||
stand.attachments.fail.add("mark_queued")
|
||||
stand.storage.fail.add("delete")
|
||||
with pytest.raises(UnavailableError):
|
||||
run(stand.upload())
|
||||
@@ -241,12 +241,16 @@ def test_foreign_chat_is_404_before_reading_body() -> None:
|
||||
chat_id = uuid4()
|
||||
stand.chats.foreign.add(chat_id)
|
||||
with pytest.raises(NotFoundError):
|
||||
run(stand.service.upload(USER, chat_id, "a.png", "image/png", 10, chunks_of(b"")))
|
||||
run(
|
||||
stand.service.upload(
|
||||
USER, chat_id, "a.png", "image/png", 10, chunks_of(b"")
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_missing_variant_is_404() -> None:
|
||||
stand = Stand()
|
||||
attachment = run(stand.upload())
|
||||
attachment = run(stand.upload()).model_copy(update={"status": "ready"})
|
||||
|
||||
async def get_for_member(attachment_id, member_id):
|
||||
[key] = stand.storage.objects
|
||||
@@ -258,4 +262,6 @@ def test_missing_variant_is_404() -> None:
|
||||
)
|
||||
assert content.content_length == attachment.size_bytes
|
||||
with pytest.raises(NotFoundError):
|
||||
run(stand.service.open_content(USER, attachment.id, AttachmentVariant.THUMBNAIL))
|
||||
run(
|
||||
stand.service.open_content(USER, attachment.id, AttachmentVariant.THUMBNAIL)
|
||||
)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Восстановление после обрыва AMQP при объявлении топологии"""
|
||||
|
||||
import asyncio
|
||||
from datetime import UTC, datetime
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from aiormq import spec
|
||||
|
||||
import infrastructure.broker.rabbit as rabbit_module
|
||||
from domain.jobs import JobMessageSchema
|
||||
from infrastructure.broker import RabbitBrokerManager
|
||||
|
||||
|
||||
def connection(fail_bind: bool):
|
||||
bound = False
|
||||
|
||||
async def bind(*args, **kwargs):
|
||||
nonlocal bound
|
||||
if fail_bind:
|
||||
raise ConnectionError("connection lost during queue.bind")
|
||||
bound = True
|
||||
|
||||
async def publish(*args, **kwargs):
|
||||
if not bound:
|
||||
raise ConnectionError("mandatory message was unroutable")
|
||||
return spec.Basic.Ack()
|
||||
|
||||
exchange = SimpleNamespace(publish=AsyncMock(side_effect=publish))
|
||||
queue = SimpleNamespace(bind=AsyncMock(side_effect=bind))
|
||||
channel = SimpleNamespace(
|
||||
set_qos=AsyncMock(),
|
||||
declare_exchange=AsyncMock(return_value=exchange),
|
||||
declare_queue=AsyncMock(return_value=queue),
|
||||
)
|
||||
return SimpleNamespace(
|
||||
channel=AsyncMock(return_value=channel), ready=AsyncMock(), close=AsyncMock()
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reopen", [False, True])
|
||||
def test_publish_recovers_after_connection_loss_during_binding(
|
||||
tmp_path, monkeypatch, reopen
|
||||
):
|
||||
url_file = tmp_path / "broker_url"
|
||||
url_file.write_text("amqp://synthetic")
|
||||
first, second = connection(True), connection(False)
|
||||
connections = ([connection(False)] if reopen else []) + [first, second]
|
||||
connect = AsyncMock(side_effect=connections)
|
||||
monkeypatch.setattr(rabbit_module.aio_pika, "connect_robust", connect)
|
||||
message = JobMessageSchema(
|
||||
job_id=uuid4(), attachment_id=uuid4(), attempt=1, created_at=datetime.now(UTC)
|
||||
)
|
||||
|
||||
async def run():
|
||||
broker = RabbitBrokerManager(url_file, 2)
|
||||
try:
|
||||
if reopen:
|
||||
await broker.publish(message)
|
||||
await broker.close()
|
||||
with pytest.raises(ConnectionError, match="queue.bind"):
|
||||
await broker.publish(message)
|
||||
await broker.publish(message)
|
||||
assert connect.await_count == (3 if reopen else 2)
|
||||
first.close.assert_awaited_once()
|
||||
finally:
|
||||
await broker.close()
|
||||
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Проверка границ worker: checksum и остановка зависшего декодера"""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import os
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from fakes import FakeObjectStorage
|
||||
|
||||
import infrastructure.services.image_pipeline.pipeline as pipeline_module
|
||||
from domain.jobs import ClaimedJobSchema, JobMessageSchema, ProcessingError
|
||||
from infrastructure.services.image_pipeline import ImagePipeline
|
||||
|
||||
|
||||
def stand(data=b"source", checksum=None):
|
||||
storage = FakeObjectStorage()
|
||||
storage.objects["staging/source"] = (data, datetime.now(UTC))
|
||||
job = ClaimedJobSchema(
|
||||
message=JobMessageSchema(
|
||||
job_id=uuid4(),
|
||||
attachment_id=uuid4(),
|
||||
attempt=1,
|
||||
created_at=datetime.now(UTC),
|
||||
),
|
||||
lease_token=uuid4(),
|
||||
object_key="originals/final",
|
||||
staging_key="staging/source",
|
||||
size_bytes=len(data),
|
||||
sha256=checksum or hashlib.sha256(data).hexdigest(),
|
||||
content_type="image/png",
|
||||
)
|
||||
return ImagePipeline(None, storage, 1024, 40000000, 768, 60), storage, job
|
||||
|
||||
|
||||
def test_checksum_mismatch_cannot_publish_original():
|
||||
pipeline, storage, job = stand(checksum="0" * 64)
|
||||
with pytest.raises(ProcessingError, match="checksum_mismatch"):
|
||||
asyncio.run(pipeline.process(job))
|
||||
assert set(storage.objects) == {"staging/source"}
|
||||
|
||||
|
||||
def test_timeout_kills_child_and_leaves_no_effect(tmp_path, monkeypatch):
|
||||
pid_file = tmp_path / "pid"
|
||||
decoder = tmp_path / "decoder.py"
|
||||
decoder.write_text(
|
||||
f"import os, time\nfrom pathlib import Path\nPath({str(pid_file)!r}).write_text(str(os.getpid()))\ntime.sleep(30)\n"
|
||||
)
|
||||
monkeypatch.setattr(pipeline_module, "TRANSFORM_SCRIPT", decoder)
|
||||
pipeline, storage, job = stand()
|
||||
|
||||
async def run():
|
||||
async with asyncio.timeout(0.5):
|
||||
await pipeline.process(job)
|
||||
|
||||
with pytest.raises(TimeoutError):
|
||||
asyncio.run(run())
|
||||
pid = int(pid_file.read_text())
|
||||
with pytest.raises(ProcessLookupError):
|
||||
os.kill(pid, 0)
|
||||
assert set(storage.objects) == {"staging/source"}
|
||||
Reference in New Issue
Block a user