#!/usr/bin/env python3 """Test shared idempotency: N parallel POST requests with the same Idempotency-Key must create exactly one message and return identical responses.""" import argparse import base64 import concurrent.futures import json import sys import urllib.error import urllib.request import uuid def main(): p = argparse.ArgumentParser() p.add_argument("--base-url", default="http://localhost:8080") p.add_argument("--concurrency", type=int, default=8) args = p.parse_args() base = args.base_url.rstrip("/") def api(method, path, body=None, headers=None): h = {"Accept": "application/json"} h.update(headers or {}) data = None if body is not None: data = json.dumps(body).encode() h["Content-Type"] = "application/json" req = urllib.request.Request(base + path, data=data, headers=h, method=method) try: resp = urllib.request.urlopen(req, timeout=10) except urllib.error.HTTPError as e: resp = e return resp.code, json.loads(resp.read()) pw = "TestPassword-" + uuid.uuid4().hex[:8] u1 = "u_idem_" + uuid.uuid4().hex[:8] u2 = "u_idem_" + uuid.uuid4().hex[:8] _, alice = api("POST", "/api/v1/users", {"username": u1, "display_name": "Alice", "password": pw}) _, bob = api("POST", "/api/v1/users", {"username": u2, "display_name": "Bob", "password": pw}) cred = base64.b64encode((u1 + ":" + pw).encode()).decode() _, sess = api("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred}) token = sess["token"] _, chat = api("POST", "/api/v1/chats", {"title": "Idempotency test", "member_ids": [alice["id"], bob["id"]]}, headers={"Authorization": "Bearer " + token}) idem_key = uuid.uuid4().hex text = "Parallel idempotency test " + idem_key path = "/api/v1/chats/" + chat["id"] + "/messages" def send(_): h = {"Authorization": "Bearer " + token, "Idempotency-Key": idem_key, "Content-Type": "application/json", "Accept": "application/json"} data = json.dumps({"text": text}).encode() req = urllib.request.Request(base + path, data=data, headers=h, method="POST") try: resp = urllib.request.urlopen(req, timeout=10) except urllib.error.HTTPError as e: resp = e body = json.loads(resp.read()) return resp.code, body, resp.headers.get("X-Instance-Id", "") with concurrent.futures.ThreadPoolExecutor(max_workers=args.concurrency) as pool: results = list(pool.map(send, range(args.concurrency))) codes = [r[0] for r in results] bodies = [r[1] for r in results] instances = set(r[2] for r in results) assert all(c == 201 for c in codes), "not all responses are 201: %s" % codes message_ids = set(b["id"] for b in bodies) assert len(message_ids) == 1, "expected exactly 1 message, got %d different IDs" % len(message_ids) first = bodies[0] for b in bodies[1:]: assert b == first, "response mismatch: %s vs %s" % (first, b) print("PASS: %d parallel requests, 1 message created, %d distinct replicas observed: %s" % (args.concurrency, len(instances), sorted(instances))) # Verify different body with same key gives 409 h = {"Authorization": "Bearer " + token, "Idempotency-Key": idem_key, "Content-Type": "application/json", "Accept": "application/json"} data = json.dumps({"text": "different body"}).encode() req = urllib.request.Request(base + path, data=data, headers=h, method="POST") try: resp = urllib.request.urlopen(req, timeout=10) code = resp.code except urllib.error.HTTPError as e: code = e.code assert code == 409, "expected 409 for different body with same key, got %d" % code print("PASS: same key + different body → 409") if __name__ == "__main__": main()