146 lines
6.1 KiB
Python
146 lines
6.1 KiB
Python
#!/usr/bin/env python3
|
||
"""Демонстрация уровня 3: принятая работа переживает worker/API/broker restart.
|
||
|
||
Сценарии:
|
||
A. worker остановлен → upload 202 queued → content 409 → API restart →
|
||
тот же attachment остаётся queued → worker запущен → ready, варианты на месте.
|
||
B. worker остановлен → upload → durable сообщение в RabbitMQ → broker restart
|
||
с volume → worker запущен → ready.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import sys
|
||
import time
|
||
from datetime import datetime, timezone
|
||
from pathlib import Path
|
||
|
||
HERE = Path(__file__).resolve().parent
|
||
ROOT = HERE.parent
|
||
for candidate in (str(HERE), str(ROOT / "tests")):
|
||
if candidate not in sys.path:
|
||
sys.path.insert(0, candidate)
|
||
|
||
import job_control as jc # noqa: E402
|
||
from client import Client # noqa: E402
|
||
|
||
PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||
|
||
|
||
def now() -> str:
|
||
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
|
||
|
||
|
||
def wait_published(attachment_id: str, timeout: float = 60.0) -> dict:
|
||
deadline = time.monotonic() + timeout
|
||
report = jc.admin_json("show", "--attachment", attachment_id)
|
||
while time.monotonic() < deadline:
|
||
report = jc.admin_json("show", "--attachment", attachment_id)
|
||
if report.get("outbox") and all(row["published_at"] for row in report["outbox"]):
|
||
return report
|
||
time.sleep(0.25)
|
||
raise jc.ProbeError("outbox was not published: %s" % report)
|
||
|
||
|
||
def main() -> int:
|
||
api = jc.client(timeout=20)
|
||
api.call("GET", "/health/ready", schema="Health")
|
||
alice, bob, eve, chat = api.bootstrap()
|
||
started = now()
|
||
evidence: dict = {"started_at": started, "scenarios": []}
|
||
|
||
# A: worker остановлен; 202 и 409; API restart не теряет работу.
|
||
jc.scale("worker", 0)
|
||
jc.wait_service("worker", 0)
|
||
attachment = jc.upload(api, alice, chat, PNG)
|
||
queued = jc.wait_attachment(api, alice, attachment["id"], "queued", timeout=30)
|
||
api.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", 409, actor=bob)
|
||
content_status = 409
|
||
report_before = jc.admin_json("show", "--attachment", attachment["id"])
|
||
jc.restart("api")
|
||
jc.wait_ready(timeout=240)
|
||
api = jc.client(timeout=20)
|
||
after_restart = api.call(
|
||
"GET", "/api/v1/attachments/" + attachment["id"], actor=bob, schema="Attachment"
|
||
)["json"]
|
||
jc.scale("worker", 1)
|
||
jc.wait_service("worker", 1)
|
||
ready = jc.wait_attachment(api, bob, attachment["id"], "ready", timeout=120)
|
||
report_after = jc.admin_json("show", "--attachment", attachment["id"])
|
||
evidence["scenarios"].append(
|
||
{
|
||
"name": "worker_stopped_api_restart",
|
||
"attachment_id": attachment["id"],
|
||
"job_id": report_before["jobs"][0]["id"],
|
||
"upload_response_status": 202,
|
||
"status_before_restart": queued["status"],
|
||
"content_while_queued": content_status,
|
||
"outbox_after_upload": report_before["outbox"],
|
||
"status_after_api_restart": after_restart["status"],
|
||
"same_sha256": after_restart["sha256"] == attachment["sha256"],
|
||
"final_status": ready["status"],
|
||
"final_attempts": report_after["jobs"][0]["attempts"],
|
||
"final_variants": [item["name"] for item in report_after["attachment"]["variants"]],
|
||
"passed": (
|
||
queued["status"] == "queued"
|
||
and content_status == 409
|
||
and after_restart["status"] == "queued"
|
||
and ready["status"] == "ready"
|
||
and len(report_after["attachment"]["variants"]) == 3
|
||
),
|
||
}
|
||
)
|
||
|
||
# B: durable сообщение в broker; restart RabbitMQ с volume; затем worker.
|
||
jc.scale("worker", 0)
|
||
jc.wait_service("worker", 0)
|
||
time.sleep(5.0)
|
||
attachment_b = jc.upload(api, alice, chat, PNG)
|
||
published = wait_published(attachment_b["id"])
|
||
# Сообщение должно лежать именно в durable queue, а не быть уже забранным.
|
||
queue_before = jc.wait_queue_messages("attachment.jobs", 1, timeout=60)
|
||
jc.restart("rabbitmq")
|
||
jc.wait_broker(timeout=240)
|
||
queue_after = jc.queue_stats()
|
||
jc.scale("worker", 1)
|
||
jc.wait_service("worker", 1)
|
||
ready_b = jc.wait_attachment(api, bob, attachment_b["id"], "ready", timeout=150)
|
||
report_b = jc.admin_json("show", "--attachment", attachment_b["id"])
|
||
evidence["scenarios"].append(
|
||
{
|
||
"name": "broker_restart_with_volume",
|
||
"attachment_id": attachment_b["id"],
|
||
"job_id": published["jobs"][0]["id"],
|
||
"queue_before_restart": queue_before,
|
||
"queue_after_restart": queue_after,
|
||
"status_before_restart": "queued",
|
||
"final_status": ready_b["status"],
|
||
"final_attempts": report_b["jobs"][0]["attempts"],
|
||
"final_variants": [item["name"] for item in report_b["attachment"]["variants"]],
|
||
"passed": (
|
||
ready_b["status"] == "ready"
|
||
and len(report_b["attachment"]["variants"]) == 3
|
||
and any(
|
||
key == "attachment.jobs" and value["messages"] >= 1
|
||
for key, value in queue_before.items()
|
||
)
|
||
),
|
||
}
|
||
)
|
||
|
||
evidence["finished_at"] = now()
|
||
evidence["all_passed"] = all(item["passed"] for item in evidence["scenarios"])
|
||
evidence["note"] = (
|
||
"RabbitMQ quorum queue is durable; message was confirmed before restart. "
|
||
"Named volume lab5_rabbitmqdata was preserved. The same 202 attachment "
|
||
"and job id are used before and after restart."
|
||
)
|
||
output = ROOT / "evidence" / "worker-restart.json"
|
||
output.write_text(json.dumps(evidence, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
|
||
print(json.dumps(evidence, ensure_ascii=False, indent=2, sort_keys=True))
|
||
return 0 if evidence["all_passed"] else 1
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|