#!/usr/bin/env python3 """ Фоновая обработка (lab5): отказы, повторная доставка, outbox, retry/DLQ/replay, аренда. python student-tests/jobs.py --base-url http://localhost:8080 [--scenario NAME|all] Сценарии (каждый печатает ok/FAIL и итог): worker-down worker остановлен → 202 queued, content 409, сообщения работают; рестарт брокера и API с volumes; worker запущен → ready (уровень 3) broker-down брокер недоступен при upload → всё равно 202 (намерение в outbox), брокер вернулся → relay публикует → ready redelivery дубль сообщения уже ready-задачи → no-op, второго набора вариантов нет crash-s3 worker-fault падает ПОСЛЕ записи в S3, ДО COMMIT/ack → та же задача доходит до ready crash-ack worker-fault падает ПОСЛЕ COMMIT ready, ДО ack → повторная доставка = no-op outbox api-fault падает ПОСЛЕ COMMIT, ДО publish → relay публикует, ready без нового upload retry-replay временная ошибка на каждой попытке → backoff с jitter → failed retry_exhausted → явный replay → ready; повторный replay ready-задачи отклонён lease «долгая, но живая» задача (heartbeat) не перехватывается; «замёрзший» worker теряет аренду → reaper → другая попытка → ready, проснувшийся старый worker ничего не перезаписывает Docker-команды (по умолчанию) можно заменить файлом --hooks-file (JSON: имя → argv). Тест сам переключает worker ↔ worker-fault и в конце возвращает обычный worker. """ from __future__ import annotations import argparse import hashlib import json import subprocess import sys import time from pathlib import Path from common import Api, Report, upload ROOT = Path(__file__).resolve().parent.parent FIXTURE = (ROOT / "tests/fixtures/sample.png").read_bytes() # 320×200 C = ["docker", "compose", "--env-file", ".env"] F = C + ["--profile", "fault"] HOOKS = { "stop_worker": C + ["stop", "worker"], "start_worker": C + ["start", "worker"], "start_fault_worker": F + ["up", "-d", "worker-fault"], "stop_fault_worker": F + ["stop", "worker-fault"], "start_fault_api": F + ["up", "-d", "api-fault"], "restart_api": C + ["restart", "api"], "restart_broker": C + ["restart", "broker"], "stop_broker": C + ["stop", "broker"], "start_broker": C + ["start", "broker"], "tool": C + ["exec", "-T", "api", "python", "-m", "app.tools"], "replay": C + ["exec", "-T", "api", "python", "-m", "app.replay"], "redis": C + ["exec", "-T", "broker", "redis-cli"], } FAULT_BASE = "http://localhost:8082" def sh(name: str, *args: str, check: bool = True) -> str: out = subprocess.run(HOOKS[name] + list(args), cwd=ROOT, capture_output=True, text=True) if check and out.returncode != 0: raise RuntimeError(f"{name} {' '.join(args)}: {out.stderr.strip()[-300:]}") return out.stdout def tool(*args: str): out = sh("tool", *args) text = out.strip() try: return json.loads(text) except ValueError: return json.loads(text.splitlines()[-1]) def fault(*args: str) -> None: sh("redis", *args) class Ctx: def __init__(self, base: str): self.api = Api(base) self.r = Report() self.alice = self.api.new_user("jobs_a") st, chat, _ = self.api.call("POST", "/api/v1/chats", {"title": "jobs", "member_ids": [self.alice["id"]]}, token=self.alice["token"]) assert st == 201, st self.chat = chat def upload(self, data: bytes = FIXTURE, base: str | None = None, headers: dict | None = None): api = Api(base) if base else self.api return upload(api, self.alice["token"], self.chat["id"], data, "sample.png", headers=headers) def get(self, att_id: str) -> dict: st, att, _ = self.api.call("GET", f"/api/v1/attachments/{att_id}", token=self.alice["token"]) assert st == 200, st return att def wait(self, att_id: str, statuses=("ready",), seconds: float = 90) -> dict: deadline = time.monotonic() + seconds att = self.get(att_id) while time.monotonic() < deadline and att["status"] not in statuses: time.sleep(0.5) att = self.get(att_id) return att def content(self, att_id: str, variant: str = "original"): return self.api.raw("GET", f"/api/v1/attachments/{att_id}/content?variant={variant}", headers={"Authorization": "Bearer " + self.alice["token"]}) def check_ready_result(self, att: dict, label: str) -> None: r = self.r names = [v["name"] for v in att["variants"]] r.check(att["status"] == "ready" and att["error_code"] is None, f"{label}: status ready, error_code null") r.check(names == ["thumbnail", "crop", "optimized"], f"{label}: variants thumbnail+crop+optimized ({names})") st, body, rh = self.content(att["id"]) r.check(st == 200 and body == FIXTURE, f"{label}: original byte-for-byte") th = {v["name"]: v for v in att["variants"]}.get("thumbnail") st, tb, rh = self.content(att["id"], "thumbnail") r.check(st == 200 and th and (th["width"], th["height"]) == (256, 160) and hashlib.sha256(tb).hexdigest() == th["sha256"], f"{label}: thumbnail 256x160, sha256 matches") def job(self, att_id: str) -> dict: return tool("job", att_id) def use_fault_worker(self) -> None: sh("stop_worker") sh("start_fault_worker") time.sleep(3) def use_normal_worker(self) -> None: sh("stop_fault_worker", check=False) sh("start_worker") # ======================================================================== сценарии def worker_down(c: Ctx) -> None: r = c.r print("== worker остановлен: приём не зависит от обработки ==") sh("stop_worker") t0 = time.monotonic() st, att, _ = c.upload() took = time.monotonic() - t0 r.check(st == 202 and att["status"] == "queued" and att["variants"] == [], f"upload → 202 queued without worker ({took:.2f}s)") aid = att["id"] time.sleep(3) r.check(c.get(aid)["status"] == "queued", "still queued after 3 s: API did not resize synchronously") st, _, _ = c.content(aid) r.check(st == 409, f"content of queued attachment → 409 (got {st})") st, _, _ = c.content(aid, "thumbnail") r.check(st == 409, f"thumbnail of queued attachment → 409 (got {st})") st, msg, _ = c.api.call("POST", f"/api/v1/chats/{c.chat['id']}/messages", {"text": "", "attachment_ids": [aid]}, token=c.alice["token"]) r.check(st == 201, f"message with queued attachment → 201 (got {st})") st, _, _ = c.api.call("POST", f"/api/v1/chats/{c.chat['id']}/messages", {"text": "другие сообщения работают"}, token=c.alice["token"]) r.check(st == 201, "other messages keep working") q = tool("queue") r.check(q["stream_length"] >= 1 and q["outbox_unpublished"] == 0, f"job is in the broker stream (len={q['stream_length']}), outbox published") print("== рестарт брокера и API с сохранением volumes ==") sh("restart_broker") sh("restart_api") deadline = time.monotonic() + 60 while time.monotonic() < deadline: try: if c.api.raw("GET", "/health/ready")[0] == 200: break except OSError: pass time.sleep(1) q = tool("queue") r.check(q["stream_length"] >= 1, f"after broker restart the message is still there (len={q['stream_length']})") st, same, _ = c.api.call("GET", f"/api/v1/attachments/{aid}", token=c.alice["token"]) r.check(st == 200 and same["status"] == "queued", "same session, same attachment, still queued") print("== worker запущен ==") sh("start_worker") att = c.wait(aid, ("ready", "failed"), 60) c.check_ready_result(att, "after restart") time.sleep(3) j = c.job(aid) r.check(not j["staging_object_exists"] and not j["attachment"]["staging_present"], "staging removed after ready (original lives in originals/)") print(f" attachment {aid}, job {j['job']['job_id']}, events: {j['events']}") def broker_down(c: Ctx) -> None: r = c.r print("== брокер недоступен: приём не зависит от брокера (transactional outbox) ==") sh("stop_broker") try: r.check(c.api.raw("GET", "/health/ready")[0] == 200, "/health/ready = 200: broker is not critical for API") t0 = time.monotonic() st, att, _ = c.upload() r.check(st == 202 and att["status"] == "queued", f"upload → 202 queued while broker is down ({time.monotonic() - t0:.1f}s, publish timeout ≤ 2s)") aid = att["id"] j = c.job(aid) r.check(len(j["outbox"]) == 1 and not j["outbox"][0]["published"], "intent kept in outbox, not published yet") finally: sh("start_broker") att = c.wait(aid, ("ready", "failed"), 60) c.check_ready_result(att, "after broker is back") j = c.job(aid) r.check(j["outbox"][0]["published"], "relay published the outbox row when broker came back") def redelivery(c: Ctx) -> None: r = c.r print("== повторная доставка уже ready-задачи ==") st, att, _ = c.upload() att = c.wait(att["id"]) before = c.job(att["id"]) for _ in range(2): print(" ", sh("tool", "republish", att["id"]).strip()[:120]) time.sleep(4) after = c.job(att["id"]) same = c.get(att["id"]) r.check(same["status"] == "ready" and same["variants"] == att["variants"], "duplicates: status stays ready, variants unchanged (same sha256)") r.check(len(after["variant_rows"]) == 3 and after["variant_objects_in_s3"] == 3, f"no second set of variants: rows={len(after['variant_rows'])}, S3 objects={after['variant_objects_in_s3']}") r.check(sum("ready" in e.split()[1:2] for e in after["events"]) == 1 and after["job"]["attempt"] == before["job"]["attempt"], "job finished exactly once, attempt unchanged") q = tool("queue") r.check(all(g["pending"] == 0 for g in q["groups"]), "duplicates acked (no pending messages)") def crash_s3(c: Ctx) -> None: r = c.r print("== crash после записи в S3, до COMMIT и ack ==") c.use_fault_worker() try: fault("SET", "fault:crash-after-s3-write", "1") st, att, _ = c.upload() t0 = time.monotonic() att = c.wait(att["id"], ("ready", "failed"), 120) print(f" recovered in {time.monotonic() - t0:.1f}s (worker restart + lease expiry)") c.check_ready_result(att, "after crash before ack") j = c.job(att["id"]) r.check(any("lease_takeover" in e for e in j["events"]) and j["job"]["attempt"] == 1, "same attempt taken over after lease expiry (redelivery, not a new job)") r.check(len(j["variant_rows"]) == 3 and j["variant_objects_in_s3"] == 3, "S3 objects from the crashed attempt reused: still exactly 3 variants") print(f" events: {j['events']}") finally: fault("DEL", "fault:crash-after-s3-write") c.use_normal_worker() def crash_ack(c: Ctx) -> None: r = c.r print("== crash после COMMIT ready, до ack ==") c.use_fault_worker() try: fault("SET", "fault:crash-after-commit-before-ack", "1") st, att, _ = c.upload() att = c.wait(att["id"], ("ready", "failed"), 60) c.check_ready_result(att, "commit before crash") deadline = time.monotonic() + 40 while time.monotonic() < deadline: q = tool("queue") if all(g["pending"] == 0 for g in q["groups"]): break time.sleep(2) r.check(all(g["pending"] == 0 for g in q["groups"]), "unacked message redelivered after restart and acked as no-op") j = c.job(att["id"]) r.check(sum(e.split()[1] == "ready" for e in j["events"]) == 1 and len(j["variant_rows"]) == 3, "ready recorded once, 3 variants") finally: fault("DEL", "fault:crash-after-commit-before-ack") c.use_normal_worker() def outbox(c: Ctx) -> None: r = c.r print("== crash API между COMMIT и publish (transactional outbox) ==") sh("start_fault_api") deadline = time.monotonic() + 60 while time.monotonic() < deadline: try: if Api(FAULT_BASE).raw("GET", "/health/ready")[0] == 200: break except OSError: pass time.sleep(1) before = {a["id"] for a in tool("chat-attachments", c.chat["id"])} try: st, body, _ = c.upload(base=FAULT_BASE, headers={"X-Fault-Inject": "crash-after-commit-before-publish"}) except OSError as exc: st, body = None, str(exc) r.check(st != 202, f"client did NOT get 202: API died after COMMIT (got {st})") new = [a for a in tool("chat-attachments", c.chat["id"]) if a["id"] not in before] r.check(len(new) == 1, f"attachment and job were committed before the crash ({len(new)} new)") if new: aid = new[0]["id"] att = c.wait(aid, ("ready", "failed"), 60) c.check_ready_result(att, "relay-published job") j = c.job(aid) r.check(all(o["published"] for o in j["outbox"]) and len(j["outbox"]) == 1, "outbox row published by relay (no new job created)") def retry_replay(c: Ctx) -> None: r = c.r print("== временные ошибки → backoff+jitter → failed → replay ==") c.use_fault_worker() try: fault("SET", "fault:transient-error", "100") st, att, _ = c.upload() aid = att["id"] t0 = time.monotonic() att = c.wait(aid, ("failed", "ready"), 150) r.check(att["status"] == "failed" and att["error_code"] == "retry_exhausted" and att["variants"] == [], f"after {time.monotonic() - t0:.0f}s: failed, error_code=retry_exhausted") j = c.job(aid) delays = [float(e.split(" in ")[-1].rstrip("s")) for e in j["events"] if "retry_scheduled" in e] r.check(j["job"]["attempt"] == j["job"]["max_attempts"] == 5 and len(delays) == 4, f"bounded: 5 attempts, 4 scheduled retries, delays {delays}") base = [1, 2, 4, 8] r.check(all(b / 2 <= d <= b * 1.01 for b, d in zip(base, delays)), "backoff grows 2^n with jitter in [d/2, d] (JOB_BACKOFF_BASE_SECONDS=1)") st, _, _ = c.content(aid) r.check(st == 409, f"content of failed → 409 (got {st})") st, _, _ = c.api.call("POST", f"/api/v1/chats/{c.chat['id']}/messages", {"text": "x", "attachment_ids": [aid]}, token=c.alice["token"]) r.check(st == 409, f"failed attachment cannot be attached → 409 (got {st})") listed = sh("replay", "--list") r.check(aid in listed, "failed job is in the registry (python -m app.replay --list)") fault("DEL", "fault:transient-error") out = sh("replay", "--attachment", aid, "--actor", "jobs-test") r.check("replayed" in out, "explicit replay accepted") att = c.wait(aid, ("ready", "failed"), 60) c.check_ready_result(att, "after replay") j = c.job(aid) r.check(j["job"]["attempt"] == 6 and j["job"]["replays"] == 1, "same job_id, attempt 6, replays=1 (audit)") out = sh("replay", "--attachment", aid) r.check("refused" in out, "replay of a ready job is refused (no duplicate execution)") finally: fault("DEL", "fault:transient-error") c.use_normal_worker() def lease(c: Ctx) -> None: r = c.r print("== долгая, но живая задача: heartbeat продлевает аренду ==") c.use_fault_worker() try: fault("SET", "fault:slow-seconds", "30") t0 = time.monotonic() st, att, _ = c.upload() att = c.wait(att["id"], ("ready", "failed"), 90) took = time.monotonic() - t0 fault("DEL", "fault:slow-seconds") j = c.job(att["id"]) r.check(att["status"] == "ready" and took > 25 and j["job"]["attempt"] == 1 and not any("takeover" in e or "lease_expired" in e for e in j["events"]), f"job ran {took:.0f}s > lease 20s, no takeover, attempt 1") print("== замёрзший worker: аренда истекает, задачу забирают ==") fault("SET", "fault:freeze-after-claim", "1") st, att, _ = c.upload() aid = att["id"] time.sleep(3) r.check(c.get(aid)["status"] == "processing", "claimed by worker-fault, then it froze (processing)") sh("start_worker") # второй, здоровый worker t0 = time.monotonic() att = c.wait(aid, ("ready", "failed"), 120) print(f" recovered in {time.monotonic() - t0:.1f}s") c.check_ready_result(att, "after frozen worker") j = c.job(aid) r.check(j["job"]["attempt"] == 2 and any("lease_expired" in e for e in j["events"]), "reaper: lease expired → attempt 2 → ready") time.sleep(max(0, 65 - (time.monotonic() - t0))) # frozen worker wakes up (3×lease after claim) j2 = c.job(aid) r.check(sum(e.split()[1] == "ready" for e in j2["events"]) == 1 and len(j2["variant_rows"]) == 3 and c.get(aid)["variants"] == att["variants"], "woken stale worker could not commit (lease_token fencing), result unchanged") finally: fault("DEL", "fault:slow-seconds") fault("DEL", "fault:freeze-after-claim") c.use_normal_worker() SCENARIOS = {"worker-down": worker_down, "broker-down": broker_down, "redelivery": redelivery, "crash-s3": crash_s3, "crash-ack": crash_ack, "outbox": outbox, "retry-replay": retry_replay, "lease": lease} def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--base-url", default="http://localhost:8080") ap.add_argument("--scenario", default="all", choices=["all", *SCENARIOS]) ap.add_argument("--hooks-file", help="JSON {hook: argv} вместо docker compose") args = ap.parse_args() if args.hooks_file: HOOKS.update(json.loads(Path(args.hooks_file).read_text(encoding="utf-8"))) c = Ctx(args.base_url) names = list(SCENARIOS) if args.scenario == "all" else [args.scenario] for name in names: t0 = time.monotonic() try: SCENARIOS[name](c) except Exception as exc: # noqa: BLE001 c.r.check(False, f"{name}: crashed with {type(exc).__name__}: {exc}") print(f" [{name}: {time.monotonic() - t0:.0f}s]") c.r.finish() if __name__ == "__main__": sys.stdout.reconfigure(encoding="utf-8") main()