forked from mtusi2026/mtusi2026lab3
79 lines
2.1 KiB
Python
79 lines
2.1 KiB
Python
"""Concurrent Idempotency-Key test for lab 3."""
|
|
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import threading
|
|
import uuid
|
|
|
|
from client import Client, Failure, arguments, check, run
|
|
|
|
|
|
def main():
|
|
args = arguments("Concurrent idempotency test")
|
|
client = Client(args.base_url, args.ca_file)
|
|
|
|
alice, bob, eve, chat = client.bootstrap()
|
|
|
|
key = uuid.uuid4().hex
|
|
message_text = "concurrent-idempotency-" + uuid.uuid4().hex
|
|
path = f"/api/v1/chats/{chat['id']}/messages"
|
|
|
|
workers = 20
|
|
barrier = threading.Barrier(workers)
|
|
|
|
def send(_):
|
|
local = Client(args.base_url, args.ca_file, timeout=10)
|
|
barrier.wait()
|
|
|
|
response = local.message(
|
|
alice,
|
|
chat,
|
|
message_text,
|
|
key=key,
|
|
)
|
|
|
|
return {
|
|
"id": response["json"]["id"],
|
|
"instance": response["headers"].get("X-Instance-Id"),
|
|
"message": response["json"],
|
|
}
|
|
|
|
with ThreadPoolExecutor(max_workers=workers) as executor:
|
|
results = list(executor.map(send, range(workers)))
|
|
|
|
ids = {r["id"] for r in results}
|
|
instances = {r["instance"] for r in results if r["instance"]}
|
|
|
|
print(f"Concurrent requests: {workers}")
|
|
print(f"Unique message IDs: {len(ids)}")
|
|
print(f"Observed API instances: {len(instances)}")
|
|
print(f"Instance IDs: {sorted(instances)}")
|
|
|
|
check(len(ids) == 1, "duplicate messages were created")
|
|
check(
|
|
all(r["message"] == results[0]["message"] for r in results),
|
|
"idempotency responses differ",
|
|
)
|
|
check(len(instances) >= 2, "requests did not reach two API instances")
|
|
|
|
# Verify that the stored chat history contains exactly one copy.
|
|
history = client.call(
|
|
"GET",
|
|
path + "?limit=100",
|
|
actor=alice,
|
|
schema="MessagePage",
|
|
)["json"]
|
|
|
|
matches = [
|
|
item for item in history["items"]
|
|
if item["text"] == message_text
|
|
]
|
|
|
|
check(len(matches) == 1, "chat history contains duplicate messages")
|
|
check(matches[0]["id"] in ids, "stored message ID differs")
|
|
|
|
print("PASS: concurrent idempotency across API replicas")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run(main)
|