#!/usr/bin/env python3 """Stop the actual uploader, read via another process, and test LB's no-backend JSON.""" import json import os import subprocess import sys import time import urllib.error import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client # noqa: E402 - load the unchanged public helper after adding tests path. def main(): c = Client(os.getenv("BASE_URL", "http://127.0.0.1:8084")) alice, bob, _, chat = c.bootstrap() data = (ROOT / "tests/fixtures/sample.png").read_bytes() uploaded = c.call( "POST", f"/api/v1/chats/{chat['id']}/attachments?filename=failover.png", 201, actor=alice, raw=data, headers={"Content-Type": "image/png"}, schema="Attachment", ) target = uploaded["headers"]["X-Instance-Id"] started = time.monotonic() try: subprocess.run( [str(ROOT / "scripts/stop-one.sh")], cwd=ROOT, env={**os.environ, "TARGET_INSTANCE_ID": target}, check=True, capture_output=True, ) for _ in range(40): try: downloaded = c.call( "GET", f"/api/v1/attachments/{uploaded['json']['id']}/content", actor=bob ) if downloaded["headers"]["X-Instance-Id"] != target: break except AssertionError: pass time.sleep(0.2) else: raise AssertionError("Uploader failover timed out") assert downloaded["bytes"] == data result = { "uploader_instance": target, "download_instance": downloaded["headers"]["X-Instance-Id"], "same_original_bytes": True, "sha256": uploaded["json"]["sha256"], "elapsed_seconds": time.monotonic() - started, } finally: subprocess.run( ["docker", "compose", "up", "-d", "--wait", "--no-recreate"], cwd=ROOT, check=True, capture_output=True, ) subprocess.run(["docker", "compose", "stop", "api"], cwd=ROOT, check=True, capture_output=True) try: time.sleep(3) try: response = urllib.request.urlopen(c.base + "/api/v1/users/me", timeout=3) except urllib.error.HTTPError as exc: response = exc with response: body = json.loads(response.read()) assert response.code == 503 and body["error"]["code"] == "unavailable" assert response.headers["X-Request-Id"] == body["error"]["request_id"] assert not response.headers.get("X-Instance-Id") result["lb_no_backend"] = { "status": response.code, "request_id": response.headers["X-Request-Id"], "no_fake_instance": True, } finally: subprocess.run( ["docker", "compose", "up", "-d", "--wait", "--no-recreate"], cwd=ROOT, check=True, capture_output=True, ) c.call("GET", "/api/v1/users/me", actor=alice, schema="User") result["existing_session_recovers"] = True (ROOT / "evidence/attachment-failover.json").write_text( json.dumps(result, ensure_ascii=False, indent=2) + "\n" ) print(json.dumps(result, ensure_ascii=False)) if __name__ == "__main__": main()