#!/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) 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()) 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())