from __future__ import annotations import base64 import hashlib import io import json from pathlib import Path import secrets import subprocess import time import urllib.error import urllib.request from uuid import uuid4 from PIL import Image ROOT = Path(__file__).resolve().parent.parent BASE = "http://127.0.0.1:18085" DC = str(ROOT / "scripts/dc") EVIDENCE = ROOT / "evidence" / "queued_restart.json" def dc(*args, timeout=150): result = subprocess.run( [DC, *args], cwd=ROOT, capture_output=True, text=True, timeout=timeout, ) if result.returncode: details = "\n".join( part.strip() for part in (result.stdout, result.stderr) if part.strip() ) raise RuntimeError( "Compose command failed: " + " ".join(args) + f" (exit={result.returncode})" + "\n" + details[-6000:] ) return result.stdout.strip() def http(method, path, *, token=None, payload=None, data=None, headers=None): request_headers = dict(headers or {}) if token: request_headers["Authorization"] = "Bearer " + token if payload is not None: data = json.dumps(payload).encode() request_headers["Content-Type"] = "application/json" request = urllib.request.Request( BASE + path, data=data, headers=request_headers, method=method, ) try: response = urllib.request.urlopen(request, timeout=15) except urllib.error.HTTPError as exc: response = exc with response: return response.status, response.read() def api(method, path, expected, **kwargs): status, body = http(method, path, **kwargs) if status != expected: raise AssertionError( f"{method} {path}: expected {expected}, got {status}" ) return json.loads(body) if body else None def wait_ready(timeout=90): deadline = time.monotonic() + timeout while time.monotonic() < deadline: try: if http("GET", "/health/ready")[0] == 200: return except (OSError, TimeoutError): pass time.sleep(1) raise AssertionError("API readiness timeout") def container_starts(): result = {} for service in ("api", "broker"): ids = dc("ps", "-q", service).split() if not ids: raise AssertionError(f"No running containers for {service}") for container_id in ids: inspected = subprocess.run( [ "docker", "inspect", "--format", "{{.State.StartedAt}}", container_id, ], check=True, capture_output=True, text=True, ) result[container_id] = inspected.stdout.strip() return result def job_snapshot(attachment_id): code = """ import json import sys from uuid import UUID from app.job_db import connect_db with connect_db() as db: row = db.execute( ''' SELECT j.status, j.attempt, EXISTS ( SELECT 1 FROM attachment_outbox o WHERE o.job_id = j.id AND o.attempt = j.attempt AND o.published_at IS NOT NULL ) AS published FROM attachment_jobs j WHERE j.attachment_id = %s AND j.pipeline_version = 1 ''', (UUID(sys.argv[1]),), ).fetchone() print(json.dumps(row)) """ return json.loads( dc("exec", "-T", "publisher", "python", "-c", code, attachment_id) ) def queue_snapshot(timeout=90): deadline = time.monotonic() + timeout while time.monotonic() < deadline: try: output = dc( "exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", "durable", "messages_ready", timeout=20, ) for line in output.splitlines(): fields = line.split() if len(fields) == 3 and fields[0] == "attachment.process.v1": return { "name": fields[0], "durable": fields[1].lower() == "true", "messages_ready": int(fields[2]), } except (RuntimeError, subprocess.TimeoutExpired): pass time.sleep(2) raise AssertionError("Queue inspection timeout") def main(): evidence = {"scenario": "queued upload survives API and broker restart"} stopped = False try: wait_ready() if not dc("ps", "--status", "running", "-q", "worker"): raise AssertionError("Start worker before running this test") username = "lab5_" + uuid4().hex[:16] password = secrets.token_hex(16) user = api( "POST", "/api/v1/users", 201, payload={ "username": username, "display_name": "Queue restart test", "password": password, }, ) basic = base64.b64encode( f"{username}:{password}".encode() ).decode() session = api( "POST", "/api/v1/auth/sessions", 201, headers={"Authorization": "Basic " + basic}, ) token = session["token"] chat = api( "POST", "/api/v1/chats", 201, token=token, payload={ "title": "Queued restart", "member_ids": [user["id"]], }, ) dc("stop", "worker") stopped = True if dc("ps", "--status", "running", "-q", "worker"): raise AssertionError("Worker is still running") print("Worker stopped") original = (ROOT / "tests/fixtures/sample.png").read_bytes() attachment = api( "POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", 202, token=token, data=original, headers={"Content-Type": "image/png"}, ) attachment_id = attachment["id"] path = f"/api/v1/attachments/{attachment_id}" assert attachment["status"] == "queued" evidence["attachment_id"] = attachment_id print(f"Upload accepted: {attachment_id}, status=queued") api("GET", path + "/content", 409, token=token) message = api( "POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=token, payload={"text": "", "attachment_ids": [attachment_id]}, headers={"Idempotency-Key": str(uuid4())}, ) evidence["message_id"] = message["id"] deadline = time.monotonic() + 30 while time.monotonic() < deadline: snapshot = job_snapshot(attachment_id) if snapshot and snapshot["published"]: break time.sleep(1) else: raise AssertionError("Outbox was not confirmed as published") evidence["job_before_restart"] = snapshot before_queue = queue_snapshot() assert before_queue["durable"] assert before_queue["messages_ready"] >= 1 evidence["queue_before_restart"] = before_queue before = container_starts() dc("restart", "api", "broker") wait_ready() after_queue = queue_snapshot() after = container_starts() assert set(before) == set(after) assert all(before[key] != after[key] for key in before) assert after_queue["durable"] assert after_queue["messages_ready"] >= 1 evidence["container_starts_before"] = before evidence["container_starts_after"] = after evidence["queue_after_restart"] = after_queue print("API and broker restarted; queued message remains in broker") current = api("GET", path, 200, token=token) assert current["status"] == "queued" api("GET", path + "/content", 409, token=token) history = api( "GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", 200, token=token, ) assert any(item["id"] == message["id"] for item in history["items"]) dc("start", "worker") started = time.monotonic() deadline = started + 90 while time.monotonic() < deadline: current = api("GET", path, 200, token=token) if current["status"] == "ready": break if current["status"] == "failed": raise AssertionError( "Attachment failed: " + str(current["error_code"]) ) time.sleep(0.5) else: raise AssertionError("Attachment did not become ready") status, downloaded = http("GET", path + "/content", token=token) assert status == 200 and downloaded == original variants = {item["name"]: item for item in current["variants"]} assert set(variants) == {"thumbnail", "crop", "optimized"} for name, fmt in ( ("thumbnail", "JPEG"), ("crop", "JPEG"), ("optimized", "WEBP"), ): status, body = http( "GET", path + "/content?variant=" + name, token=token, ) assert status == 200 metadata = variants[name] assert len(body) == metadata["size_bytes"] assert hashlib.sha256(body).hexdigest() == metadata["sha256"] with Image.open(io.BytesIO(body)) as image: image.load() assert image.format == fmt assert image.size == (metadata["width"], metadata["height"]) evidence["ready_after_worker_start_s"] = round( time.monotonic() - started, 3 ) evidence["original_sha256"] = hashlib.sha256(original).hexdigest() evidence["variants"] = list(variants) evidence["result"] = "PASS" except BaseException as exc: evidence["result"] = "FAIL" evidence["error_type"] = type(exc).__name__ raise finally: try: if stopped: dc("start", "worker") finally: EVIDENCE.parent.mkdir(exist_ok=True) EVIDENCE.write_text( json.dumps(evidence, ensure_ascii=False, indent=2) + "\n" ) print("PASS: queued task survived API/broker restart; original and variants verified") if __name__ == "__main__": main()