"""Exercise races, transaction rollback, expiry and dependency loss on a test stack.""" import argparse import secrets import subprocess import sys import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path from uuid import uuid4 ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client, Failure, check # noqa: E402 def compose(*args): subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, timeout=80) def await_ready(client): deadline = time.monotonic() + 35 while time.monotonic() < deadline: try: client.call("GET", "/health/ready", schema="Health") return except Failure: time.sleep(0.5) raise Failure("API did not recover") def main(): parser = argparse.ArgumentParser() parser.add_argument("--base-url", default="http://localhost:8080") parser.add_argument("--short-ttl-only", action="store_true", help="Use on a disposable stand with SESSION_TTL_SECONDS=2") parser.add_argument("--dependency-stops", action="store_true") args = parser.parse_args() client = Client(args.base_url) actor = client.user("atomic") if args.short_ttl_only: client.call("GET", "/api/v1/users/me", actor=actor, schema="User") time.sleep(2.3) client.call("GET", "/api/v1/users/me", 401, actor=actor) print("PASS: active session expires without being refreshed by GET") return registration = {"username": "race_" + uuid4().hex[:12], "display_name": "Race", "password": secrets.token_urlsafe(24)} def register(_): return Client(args.base_url).call("POST", "/api/v1/users", (201, 409), body=registration)["status"] with ThreadPoolExecutor(2) as pool: statuses = sorted(pool.map(register, range(2))) check(statuses == [201, 409], f"expected one successful registration: {statuses}") list_path = "/api/v1/chats" snapshot = client.call("GET", list_path, actor=actor, schema="ChatPage")["json"] rejected = {"title": "must roll back", "member_ids": [actor["id"], str(uuid4())]} client.call("POST", list_path, 400, actor=actor, body=rejected) check(snapshot == client.call("GET", list_path, actor=actor, schema="ChatPage")["json"], "a partial chat survived") print("PASS: concurrent registration and atomic rollback of chat membership") if args.dependency_stops: for service in ("cache", "db"): try: compose("stop", service) client.call("GET", "/health/live", schema="Health") client.call("GET", "/health/ready", 503) client.call("GET", "/api/v1/users/me", 503, actor=actor) print(f"PASS: {service} loss returns 503 without anonymous access") finally: compose("start", service) await_ready(client) client.call("GET", "/api/v1/users/me", actor=actor, schema="User") client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=actor) client.call("GET", "/api/v1/users/me", 401, actor=actor) print("PASS: logout revokes the session") if __name__ == "__main__": main()