#!/usr/bin/env python3 import base64 import json import sys import threading import time import uuid from pathlib import Path import httpx BASE = "http://localhost:8080" ROOT = Path(__file__).resolve().parent.parent EVIDENCE = ROOT / "evidence" / "idempotency.json" def register_and_login(client): username = "idem_" + uuid.uuid4().hex[:10] password = "Test-password-" + uuid.uuid4().hex[:8] r = client.post( f"{BASE}/api/v1/users", json={"username": username, "display_name": "I", "password": password}, ) assert r.status_code == 201, r.text user = r.json() credential = base64.b64encode((username + ":" + password).encode()).decode() r = client.post( f"{BASE}/api/v1/auth/sessions", headers={"Authorization": "Basic " + credential}, ) assert r.status_code == 201, r.text return {"id": user["id"], "token": r.json()["token"]} def main(): with httpx.Client(timeout=10) as c: alice = register_and_login(c) bob = register_and_login(c) chat = c.post( f"{BASE}/api/v1/chats", json={"title": "idem", "member_ids": [alice["id"], bob["id"]]}, headers={"Authorization": "Bearer " + alice["token"]}, ).json() key = uuid.uuid4().hex text = "idempotency-test-" + uuid.uuid4().hex[:8] results = [] lock = threading.Lock() barrier = threading.Barrier(10) def worker(): try: with httpx.Client(timeout=10) as c: barrier.wait() r = c.post( f"{BASE}/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers={ "Authorization": "Bearer " + alice["token"], "Idempotency-Key": key, }, ) with lock: results.append((r.status_code, r.headers.get("x-instance-id"))) except Exception as e: with lock: results.append((0, str(e))) threads = [threading.Thread(target=worker) for _ in range(10)] for t in threads: t.start() for t in threads: t.join() time.sleep(1) with httpx.Client(timeout=10) as c: page = c.get( f"{BASE}/api/v1/chats/{chat['id']}/messages?limit=100", headers={"Authorization": "Bearer " + alice["token"]}, ).json() matching = [m for m in page["items"] if m["text"] == text] message_ids = {m["id"] for m in matching} instances_seen = list({r[1] for r in results if r[1] and r[0] > 0}) statuses = [r[0] for r in results] report = { "concurrent_requests": len(results), "statuses": statuses, "unique_instances": instances_seen, "messages_created": len(matching), "unique_message_ids": len(message_ids), "idempotency_ok": len(matching) == 1, "instances_count": len(instances_seen), } print(json.dumps(report, indent=2, ensure_ascii=False)) EVIDENCE.parent.mkdir(parents=True, exist_ok=True) EVIDENCE.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8") return 0 if __name__ == "__main__": sys.exit(main())