#!/usr/bin/env python3 """Сценарий защиты lab5 (README, шаги 1–3) с протоколом действий: время, действие, HTTP-коды, статус, ID вложения/работы и состояние контейнеров (StartedAt/PID). Токены и пароли не печатаются. 1. make test проходит отдельно (smoke). 2. worker остановлен → upload 202 → GET queued → content 409 → другие сообщения работают. 3. перезапуск API и брокера с сохранением volumes → запуск worker → та же запись ready, thumbnail доступен. python3 student-tests/defense_demo.py # нужен docker compose в PATH и работающий стенд """ import datetime as dt import hashlib import shlex import subprocess import sys import time import uuid from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) from image_probe import jpeg_size # noqa: E402 from common import BASE_URL, DC, ROOT, Client, Failure, check, jobs_cli, login, make_png, new_user, sh, upload # noqa: E402 c = Client(BASE_URL, timeout=30) def log(step, msg): print("%s %-6s %s" % (dt.datetime.now(dt.timezone.utc).strftime("%H:%M:%S.%f")[:-3], step, msg), flush=True) def containers(services=("api", "worker", "nats")): out = [] for svc in services: ids = subprocess.run(shlex.split(DC) + ["ps", "-a", "-q", svc], cwd=ROOT, capture_output=True, text=True).stdout.split() for i in ids: out.append(subprocess.run(["docker", "inspect", "-f", "{{.Name}} {{.State.Status}} started={{.State.StartedAt}}" " pid={{.State.Pid}}", i], capture_output=True, text=True).stdout.strip().lstrip("/")) return out def wait(probe, timeout, interval=0.5): deadline = time.monotonic() + timeout while time.monotonic() < deadline: try: v = probe() except Failure: # пока реплики перезапускаются, LB отвечает сам (503 без X-Instance-Id) v = None if v: return v time.sleep(interval) raise SystemExit("timeout") alice = new_user(c, "demo"); login(c, alice) bob = new_user(c, "demob"); login(c, bob) chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", body={"title": "defense", "member_ids": [alice["id"], bob["id"]]})["json"] log("0", "chat %s, users alice/bob (tokens not shown)" % chat["id"]) for line in containers(): log("0", " " + line) log("2", "stop worker: " + DC + " stop worker") sh("stop_worker", timeout=120) for line in containers(("worker",)): log("2", " " + line) data = make_png(320, 200) att, _ = upload(c, alice, chat, data, filename="defense.png") log("2", "POST /chats/%s/attachments → 202, attachment_id=%s status=%s" % (chat["id"], att["id"], att["status"])) job = jobs_cli("status", att["id"])["jobs"][0] log("2", "job_id=%s pipeline_version=%s attempt=%s status=%s" % (job["job_id"], job["pipeline_version"], job["attempt"], job["status"])) r = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob) log("2", "GET /attachments/%s/content → %d (%s)" % (att["id"], r["status"], r["json"]["error"]["code"])) m = c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=alice, schema="Message", body={"text": "фото во вложении", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex}) log("2", "POST message with queued attachment → 201, message_id=%s" % m["json"]["id"]) m = c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=bob, schema="Message", body={"text": "обычное сообщение"}, headers={"Idempotency-Key": uuid.uuid4().hex}) log("2", "POST plain message (bob) → 201, message_id=%s; history works while worker is down" % m["json"]["id"]) ev = wait(lambda: [e for e in jobs_cli("status", att["id"])["events"] if e["event"] == "published"], 30) log("2", "job published to JetStream: stream_seq=%s (outbox → relay → publish ack)" % ev[0]["detail"]["stream_seq"]) log("3", "restart broker (volume natsdata kept) and API replicas: restart nats; restart api") sh("restart_broker", timeout=120) sh("restart_api", timeout=180) wait(lambda: c.call("GET", "/health/ready", [200, 502, 503])["status"] == 200, 90) for line in containers(("api", "nats")): log("3", " " + line) meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"] log("3", "after restart: attachment %s status=%s (job survived in PostgreSQL + JetStream)" % (att["id"], meta["status"])) log("3", "start worker: " + DC + " start worker") sh("start_worker", timeout=120) t = time.monotonic() meta = wait(lambda: (lambda x: x if x["status"] in ("ready", "failed") else None)( c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"]), 60) check(meta["status"] == "ready", "not ready") log("3", "attachment %s status=ready %.1fs after worker start; variants=%s" % ( att["id"], time.monotonic() - t, ["%s %dx%d" % (v["name"], v["width"], v["height"]) for v in meta["variants"]])) orig = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)["bytes"] thumb = c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], actor=bob)["bytes"] check(orig == data, "original differs") log("3", "original sha256=%s… (= uploaded), thumbnail JPEG %s" % (hashlib.sha256(orig).hexdigest()[:16], jpeg_size(thumb))) for e in jobs_cli("status", att["id"])["events"]: log("log", "%s %-24s attempt=%s token=%s %s" % (str(e["created_at"])[11:23], e["event"], e["attempt"], e["lease_token"], e["detail"] or "")) print("PASS: defense scenario (worker down → 202 → 409 → restart API+broker → worker → ready)")