"""lab5, уровень 4: разрыв между PostgreSQL и брокером закрыт transactional outbox. make outbox-crash (= python student-tests/outbox_crash.py) Три окна отказа из contracts/attachment-states.md, в каждом процесс API падает по-настоящему (os._exit, как SIGKILL: без ответа, без finally) в точке отказа (src/messenger/faults.py): A. api_after_commit — вложение, задание и строка outbox закоммичены, ответ 202 ещё не отправлен. Клиент получает ошибку балансировщика (502), но работа принята: relay другой реплики (или этой после перезапуска) отправляет задание, worker его выполняет. Новое задание вручную не создаётся. B. relay_before_publish — relay взял строки outbox, но в брокер ничего не отправил. Транзакция откатывается вместе с упавшим процессом, строки остаются неотправленными, их отправляют позже. C. relay_after_publish — брокер подтвердил приём, но строка не отмечена отправленной. После перезапуска её отправляют ещё раз: worker получает дубль и подтверждает его без обработки. D. Брокер остановлен целиком: загрузка всё равно получает 202 (брокер не входит в readiness), строка outbox ждёт в PostgreSQL неотправленной; после запуска брокера relay её отправляет. Точка включается во всех репликах API: какая бы реплика ни взялась за строку, она упадёт. Docker сам перезапускает упавшие контейнеры (restart: unless-stopped); файл точки удаляется до падения, поэтому после перезапуска реплика работает нормально. В каждом сценарии проверяется: вложение стало ready, у задания одна попытка и один набор вариантов. """ import time import uuid import ops from filegen import SAMPLE_PNG, upload_when_ready, wait_status from helpers import Client, check, run from stand import lb_up_count, try_call def stand_ready(seconds=120): ops.wait_healthy("api", 2, seconds) deadline = time.monotonic() + seconds while True: try: if lb_up_count() >= 2: return except OSError: pass check(time.monotonic() < deadline, "HAProxy does not see 2 ready api replicas") time.sleep(0.5) def restart_counts(): return {c[:12]: ops.restarts(c) for c in ops.containers("api")} def finished(api, bob, attachment_id): meta = wait_status(api, bob, attachment_id, ("ready",), seconds=120) job = ops.job(attachment_id) check(job["job"]["attempt"] == 1, "the job must finish in its first attempt") check(len(job["variants"]) == 3, "exactly one set of variants expected") check(sum(e["event"] == "ready" for e in job["events"]) == 1, "the result must be committed once") return meta, job def show(job): outbox = "; ".join(f"row {o['id']} published {o['published_at']} by {o['published_by']}" for o in job["outbox"]) events = " -> ".join(f"{e['event']}" for e in job["events"]) return f"outbox: {outbox}\n events: {events}" def main(): api = Client(timeout=15) ops.wait_healthy("worker", 1) stand_ready() alice, bob, _eve, chat = api.bootstrap() # ---------- A ---------- before = restart_counts() ops.arm("api", "api_after_commit") name = f"outbox-a-{uuid.uuid4().hex[:8]}.png" reply = try_call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename={name}", raw=SAMPLE_PNG, token=alice["token"], headers={"Content-Type": "image/png"}, timeout=30) status = reply.status if reply else "no response" check(reply is None or reply.status >= 500, "the client must NOT get 202 when the API crashed after COMMIT") ops.disarm("api", "api_after_commit") # реплика, которая не упала, ещё «заряжена» attachment_id = ops.psql(f"SELECT id FROM attachments WHERE filename = '{name}'") check(bool(attachment_id), "the committed attachment row must exist") print(f"A. api_after_commit: the client got {status} instead of 202, but the attachment {attachment_id} " f"and its outbox row were committed before the crash") _meta, job = finished(api, bob, attachment_id) stand_ready() after = restart_counts() crashed = [c for c in after if after[c] > before.get(c, after[c])] print(f" ready without creating a new job by hand; api restarted by Docker: {crashed or 'see logs'}") print(" " + show(job)) # ---------- B ---------- before = restart_counts() ops.arm("api", "relay_before_publish") att = upload_when_ready(api, alice, chat, name="outbox-b.png")["json"] print(f"B. relay_before_publish: upload -> 202 ({att['id']}); every relay that takes the row crashes " f"before publishing") _meta, job = finished(api, bob, att["id"]) stand_ready() after = restart_counts() crashed = [c for c in after if after[c] > before.get(c, after[c])] check(crashed, "at least one relay must have crashed") check(not any(e["event"].startswith("duplicate") for e in job["events"]), "nothing was published twice here") print(f" crashed and restarted: {crashed}; after restart the row was published once -> ready") print(" " + show(job)) # ---------- C ---------- before = restart_counts() ops.arm("api", "relay_after_publish") att = upload_when_ready(api, alice, chat, name="outbox-c.png")["json"] print(f"C. relay_after_publish: upload -> 202 ({att['id']}); the broker confirms, the relay crashes before " f"marking the row") _meta, job = finished(api, bob, att["id"]) deadline = time.monotonic() + 60 while not any(e["event"].startswith("duplicate") for e in job["events"]): check(time.monotonic() < deadline, "the duplicate delivery was not observed") time.sleep(1) job = ops.job(att["id"]) stand_ready() after = restart_counts() crashed = [c for c in after if after[c] > before.get(c, after[c])] duplicates = [e for e in job["events"] if e["event"].startswith("duplicate")] print(f" crashed and restarted: {crashed}; the same message was delivered again " f"{len(duplicates)} time(s): " + ", ".join(e["event"] for e in duplicates)) print(" " + show(job)) keys = ops.objects(f"variants/{att['id']}/") check(len(keys) == 3, "duplicates must not create more objects") print(f" still one set of variants: {len(job['variants'])} rows, {len(keys)} objects") # ---------- D ---------- ops.stop("broker") try: att = upload_when_ready(api, alice, chat, name="outbox-d.png")["json"] time.sleep(5) job = ops.job(att["id"]) check(job["outbox"] and not job["outbox"][0]["published_at"], "the row must wait while the broker is down") meta = api.call("GET", f"/api/v1/attachments/{att['id']}", actor=bob, schema="Attachment")["json"] print(f"D. broker stopped: upload -> 202 ({att['id']}), after 5 s status {meta['status']}, outbox row " f"{job['outbox'][0]['id']} not published yet (it waits in PostgreSQL)") finally: ops.start("broker") ops.wait_healthy("broker", 1, 180) started = time.monotonic() _meta, job = finished(api, bob, att["id"]) print(f" broker started: the relay published the row, ready {time.monotonic() - started:.1f} s later") print(" " + show(job)) print("PASS: a crash between COMMIT and publish (A, B) loses nothing — the outbox row is published later and " "the job becomes ready without manual action; a crash after publish (C) only causes a duplicate " "delivery, which the worker acknowledges without a second set of variants; while the broker is down (D) " "uploads are still accepted and the jobs wait in the outbox") if __name__ == "__main__": run(main)