"""Check shared sessions and concurrent idempotency through the public LB only. Creates synthetic data; never prints credentials or tokens. """ import base64 import concurrent.futures import json import urllib.error import urllib.request import uuid BASE = "http://127.0.0.1:8083" def request(method, path, body=None, token=None, key=None, basic=None): headers = {"Content-Type": "application/json"} if token: headers["Authorization"] = "Bearer " + token if basic: headers["Authorization"] = "Basic " + base64.b64encode(basic.encode()).decode() if key is not None: headers["Idempotency-Key"] = key raw = None if body is None else json.dumps(body).encode() req = urllib.request.Request(BASE + path, data=raw, headers=headers, method=method) try: response = urllib.request.urlopen(req, timeout=15) except urllib.error.HTTPError as error: response = error with response: return response.status, json.load(response), response.headers.get("X-Instance-Id") def main(): username = "r_" + uuid.uuid4().hex[:20] password = uuid.uuid4().hex status, user, _ = request("POST", "/api/v1/users", { "username": username, "display_name": "Replica test", "password": password, }) assert status == 201, status status, session, _ = request("POST", "/api/v1/auth/sessions", basic=username + ":" + password) assert status == 201, status token = session["token"] instances = set() for _ in range(20): status, current, instance = request("GET", "/api/v1/users/me", token=token) assert status == 200 and current["id"] == user["id"] assert instance instances.add(instance) assert len(instances) >= 2, "Fewer than two API instances observed" print("PASS: one session accepted by", len(instances), "API instances") status, chat, _ = request("POST", "/api/v1/chats", { "title": "Concurrent retries", "member_ids": [user["id"]], }, token=token) assert status == 201, status path = "/api/v1/chats/" + chat["id"] + "/messages" key = uuid.uuid4().hex with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: results = list(pool.map(lambda _: request("POST", path, {"text": "hello"}, token, key), range(16))) original = results[0][1] assert all(status == 201 and body == original for status, body, _ in results) assert len({instance for _, _, instance in results}) >= 2 assert request("POST", path, {"text": "different"}, token, key)[0] == 409 assert request("POST", path, {"text": "hello"}, token)[0] == 400 status, history, _ = request("GET", path, token=token) assert status == 200 and history["items"] == [original] print("PASS: 16 parallel retries across replicas returned the same Message; history has one item") print("PASS: changed text -> 409; missing key -> 400") if __name__ == "__main__": main()