forked from mtusi2026/mtusi2026lab3
54 lines
1.7 KiB
Python
54 lines
1.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Concurrent idempotency and replica-distribution checks."""
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import uuid
|
|
|
|
from client import Client, Failure, arguments, check, run
|
|
|
|
|
|
def main():
|
|
args = arguments("Concurrent shared-idempotency and API-replica check")
|
|
client = Client(args.base_url, args.ca_file, timeout=5)
|
|
alice, _, _, chat = client.bootstrap()
|
|
key = uuid.uuid4().hex
|
|
body = {"text": "parallel-idempotency-" + key}
|
|
|
|
def send(_):
|
|
return Client(args.base_url, args.ca_file, timeout=5).call(
|
|
"POST",
|
|
"/api/v1/chats/" + chat["id"] + "/messages",
|
|
201,
|
|
body=body,
|
|
actor=alice,
|
|
headers={"Idempotency-Key": key},
|
|
schema="Message",
|
|
)
|
|
|
|
with ThreadPoolExecutor(max_workers=12) as executor:
|
|
responses = list(executor.map(send, range(12)))
|
|
messages = [response["json"] for response in responses]
|
|
check(all(message == messages[0] for message in messages), "concurrent replay differed")
|
|
|
|
conflict = client.call(
|
|
"POST",
|
|
"/api/v1/chats/" + chat["id"] + "/messages",
|
|
409,
|
|
body={"text": "different body"},
|
|
actor=alice,
|
|
headers={"Idempotency-Key": key},
|
|
)
|
|
check(conflict["status"] == 409, "same key with a different body was accepted")
|
|
|
|
instances = {
|
|
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")["headers"][
|
|
"X-Instance-Id"
|
|
]
|
|
for _ in range(80)
|
|
}
|
|
check(len(instances) >= 2, "load balancer did not expose two API instances")
|
|
print("PASS: concurrent idempotency returned one message; observed %d API replicas" % len(instances))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run(main)
|