ЛР 5 — БПИ2303 — Лазарев — на 4

Асинхронная обработка вложений: RabbitMQ 4.1 (quorum-очереди, publisher
confirms, manual ack, DLQ), transactional outbox, отдельный worker.

- upload: оригинал в staging S3, затем одной транзакцией queued + jobs +
  outbox -> 202; API к брокеру не подключается
- relay: публикация outbox с confirm, reaper истёкших аренд, redrive
- worker: claim по строке jobs, аренда с heartbeat и fencing по
  lease_token, transform в подпроцессе с RLIMIT_AS/RLIMIT_CPU/таймаутом,
  thumbnail 256, crop 128, WebP 1280 по детерминированным ключам
- retry с backoff и jitter, постоянные/временные ошибки, реестр failed,
  ops replay (ready не повторяется), DLQ для невалидных сообщений
- janitor: очистка staging и сирот; миграция 004 с backfill вложений lab4
- тесты отказов: окна COMMIT/publish, крахи worker до/после S3 и ack,
  заморозка worker, всплеск загрузок, права брокера; evidence/ и REPORT.md
This commit is contained in:
2026-11-13 16:28:18 +03:00
parent 276dbdad8a
commit 13bec4ab8b
86 changed files with 10257 additions and 25 deletions
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""Недоступность S3: stop (порт закрыт) и pause (S3 «завис», TCP не отвечает).
python3 student-tests/s3_outage.py [--output evidence/s3-outage.json]
Ожидания: upload и download — быстрый 503 unavailable c Retry-After (не 500 и не
таймаут LB), текстовые сообщения и /health/ready продолжают работать (S3 не входит в
readiness), после восстановления S3 загрузка снова 201 без перезапуска API.
"""
import argparse
import json
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client # noqa: E402
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
log = []
def probe(c, alice, chat, att):
out = {}
for name, args in (
("upload", ("POST", "/api/v1/chats/%s/attachments?filename=o.png" % chat["id"])),
("download", ("GET", "/api/v1/attachments/%s/content" % att["id"])),
("text_message", ("POST", "/api/v1/chats/%s/messages" % chat["id"])),
("ready", ("GET", "/health/ready"))):
kw = {}
if name == "upload":
kw = {"raw": PNG, "headers": {"Content-Type": "image/png"}}
if name == "text_message":
kw = {"body": {"text": "без S3"}, "headers": {"Idempotency-Key": uuid.uuid4().hex}}
t = time.monotonic()
r = c.call(*args, [200, 201, 503, 502, 504], actor=alice if name != "ready" else None, **kw)
out[name] = {"status": r["status"], "ms": round((time.monotonic() - t) * 1000),
"code": (r["json"] or {}).get("error", {}).get("code"),
"retry_after": r["headers"].get("Retry-After")}
return out
def phase(name, c, alice, chat, att):
entry = {"phase": name, "probe": probe(c, alice, chat, att)}
log.append(entry)
print(json.dumps(entry, ensure_ascii=False), flush=True)
return entry
def recover(c, alice, chat, started):
while time.monotonic() - started < 120:
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=r.png" % chat["id"], [201, 503], actor=alice,
raw=PNG, headers={"Content-Type": "image/png"})
if r["status"] == 201:
return round(time.monotonic() - started, 1)
time.sleep(0.5)
return None
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--base-url", default="http://localhost:8080")
ap.add_argument("--output")
args = ap.parse_args()
c = Client(args.base_url, timeout=30)
alice, _bob, _eve, chat = c.bootstrap()
att = c.call("POST", "/api/v1/chats/%s/attachments?filename=a.png" % chat["id"], 201, actor=alice, raw=PNG,
headers={"Content-Type": "image/png"}, schema="Attachment")["json"]
phase("baseline", c, alice, chat, att)
for action, undo in ((["stop", "s3"], ["start", "s3"]), (["pause", "s3"], ["unpause", "s3"])):
subprocess.run(["docker", "compose"] + action, cwd=ROOT, check=True, capture_output=True)
time.sleep(1)
phase("immediately after `%s` (S3Health not yet stale)" % " ".join(action), c, alice, chat, att)
time.sleep(4)
phase("S3 down for 5 s (`%s`)" % " ".join(action), c, alice, chat, att)
subprocess.run(["docker", "compose"] + undo, cwd=ROOT, check=True, capture_output=True)
t0 = time.monotonic()
rec = recover(c, alice, chat, t0)
log.append({"phase": "recovery after `%s`" % " ".join(undo), "upload_201_after_s": rec})
print(json.dumps(log[-1]), flush=True)
# Оставляем стенд рабочим: ждём, пока healthcheck S3 снова станет healthy (после pause
# он несколько проверок подряд был unhealthy, а `docker compose up api` при нездоровой
# зависимости не запускает реплики).
cid = subprocess.run(["docker", "compose", "ps", "-q", "s3"], cwd=ROOT, capture_output=True, text=True).stdout.strip()
t0 = time.monotonic()
while time.monotonic() - t0 < 120:
st = subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", cid], capture_output=True, text=True).stdout.strip()
if st == "healthy":
break
time.sleep(1)
log.append({"phase": "s3 healthcheck healthy again", "after_s": round(time.monotonic() - t0, 1), "status": st})
print(json.dumps(log[-1]), flush=True)
down = [e for e in log if e.get("phase", "").startswith("S3 down")]
ok = all(e["probe"]["upload"]["status"] == 503 and e["probe"]["download"]["status"] == 503
and e["probe"]["text_message"]["status"] == 201 and e["probe"]["ready"]["status"] == 200
for e in down) and all(e.get("upload_201_after_s") is not None for e in log if "upload_201_after_s" in e)
no5xx = all(p["status"] in (200, 201, 503) for e in log if "probe" in e for p in e["probe"].values())
ok = ok and st == "healthy"
print(json.dumps({"pass": ok and no5xx, "only_200_201_503": no5xx}))
if args.output:
Path(args.output).write_text(json.dumps({"pass": ok and no5xx, "phases": log}, ensure_ascii=False, indent=1))
return 0 if ok and no5xx else 1
if __name__ == "__main__":
sys.exit(main())