Files
mtusi2026lab3/student-tests/idempotency_race.py
T

125 lines
4.8 KiB
Python

#!/usr/bin/env python3
"""Concurrent idempotency check through the public load balancer.
The same Idempotency-Key is sent from many threads at once; exactly one message
must be created and every successful response must carry the same Message. The
check also covers different-body conflict, missing/invalid key, and independent
scopes for another user and another chat.
"""
from __future__ import annotations
import argparse
import uuid
from concurrent.futures import ThreadPoolExecutor
from common import HttpClient, assert_status, error_code
def chat_for(client: HttpClient, token: str, members: list[str], title: str) -> dict:
status, _headers, chat, _raw = client.call(
"POST",
"/api/v1/chats",
body={"title": title, "member_ids": members},
token=token,
)
assert_status(status, 201, "create chat")
return chat
def message(client: HttpClient, token: str, chat_id: str, text: str, key: str | None):
headers = {"Idempotency-Key": key} if key is not None else {}
return client.call(
"POST",
f"/api/v1/chats/{chat_id}/messages",
body={"text": text},
token=token,
headers=headers,
)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--workers", type=int, default=24)
args = parser.parse_args()
client = HttpClient(args.base_url)
alice, alice_registration = client.register()
alice_session = client.login(alice_registration)
alice_token = alice_session["token"]
bob, bob_registration = client.register()
bob_session = client.login(bob_registration)
bob_token = bob_session["token"]
chat = chat_for(client, alice_token, [alice["id"], bob["id"]], "Idempotency race")
key = uuid.uuid4().hex
text = "concurrent replay " + uuid.uuid4().hex
def send(_index: int):
return message(client, alice_token, chat["id"], text, key)
with ThreadPoolExecutor(max_workers=args.workers) as executor:
results = list(executor.map(send, range(args.workers)))
statuses = [status for status, _headers, _payload, _raw in results]
if statuses != [201] * args.workers:
raise AssertionError(f"concurrent replay statuses: {statuses}")
ids = {payload["id"] for _status, _headers, payload, _raw in results}
if len(ids) != 1:
raise AssertionError(f"concurrent replay created {len(ids)} different messages")
instances = {headers.get("X-Instance-Id") for _status, headers, _payload, _raw in results}
if len(instances) < 2:
raise AssertionError("concurrent replay did not cross at least two replicas")
status, _headers, page, _raw = client.call(
"GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", token=bob_token
)
assert_status(status, 200, "history")
matching = [item for item in page["items"] if item["text"] == text]
if len(matching) != 1:
raise AssertionError(f"history contains {len(matching)} copies of the replayed message")
status, _headers, payload, _raw = message(
client, alice_token, chat["id"], "different body", key
)
if status != 409 or error_code(payload) != "conflict":
raise AssertionError(f"same key with another body: expected 409 conflict, got {status}")
status, _headers, payload, _raw = message(client, alice_token, chat["id"], "no key", None)
if status != 400 or error_code(payload) != "invalid_request":
raise AssertionError(f"missing key: expected 400 invalid_request, got {status}")
status, _headers, payload, _raw = message(
client, alice_token, chat["id"], "bad key", "bad key with spaces"
)
if status != 400 or error_code(payload) != "invalid_request":
raise AssertionError(f"invalid key: expected 400 invalid_request, got {status}")
# Same key, same body, different user: independent scope.
status, _headers, bob_message, _raw = message(
client, bob_token, chat["id"], text, key
)
if status != 201 or bob_message["id"] in ids or bob_message["sender_id"] != bob["id"]:
raise AssertionError("another user's identical key was not independent")
# Same key, same user, different chat: independent scope.
second_chat = chat_for(client, alice_token, [alice["id"], bob["id"]], "Second chat")
status, _headers, other_chat_message, _raw = message(
client, alice_token, second_chat["id"], text, key
)
if status != 201 or other_chat_message["id"] in ids:
raise AssertionError("same key in another chat was not independent")
print(
"OBSERVED: "
f"{args.workers} concurrent replays -> one message id; "
f"{len(instances)} replicas; 409 different body; 400 missing/invalid key"
)
print("PASS: shared idempotency is exactly-once across API replicas")
if __name__ == "__main__":
main()