#!/usr/bin/env python3 """Prove that one session is served by at least two real API replicas via the LB.""" from __future__ import annotations import argparse from collections import Counter from common import HttpClient def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--base-url", default="http://localhost:8080") parser.add_argument("--requests", type=int, default=60) args = parser.parse_args() client = HttpClient(args.base_url) alice, alice_registration = client.register() bob, _bob_registration = client.register() alice_session = client.login(alice_registration) token = alice_session["token"] status, _headers, chat, _ = client.call( "POST", "/api/v1/chats", body={"title": "Replica spread", "member_ids": [alice["id"], bob["id"]]}, token=token, ) if status != 201: raise AssertionError(f"chat creation failed: HTTP {status}") instances: Counter[str] = Counter() for _ in range(args.requests): status, headers, me, _ = client.call("GET", "/api/v1/users/me", token=token) if status != 200 or me["id"] != alice["id"]: raise AssertionError("existing session did not work through the LB") instance = headers.get("X-Instance-Id", "") if not instance: raise AssertionError("missing X-Instance-Id on an API response") if not headers.get("X-Request-Id"): raise AssertionError("missing X-Request-Id on an API response") instances[instance] += 1 if len(instances) < 2: raise AssertionError( "fewer than two API instances observed; check LB discovery / replica count" ) # A write accepted by one replica must be visible from any other replica. for index, instance in enumerate(instances): status, headers, message, _ = client.call( "POST", "/api/v1/chats/" + chat["id"] + "/messages", body={"text": f"replica-write-{index}"}, token=token, headers={"Idempotency-Key": f"spread-{index}-{alice['id']}"}, ) if status != 201: raise AssertionError(f"message write failed through {instance}: HTTP {status}") status, _headers, page, _ = client.call( "GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100", token=token ) if status != 200 or not any(m["id"] == message["id"] for m in page["items"]): raise AssertionError("message written by one replica is not readable") print("instances:", ", ".join(f"{name}={count}" for name, count in sorted(instances.items()))) print("PASS: one session served by >=2 API replicas with a shared datastore") if __name__ == "__main__": main()