forked from mtusi2026/mtusi2026lab3
Implement lab3 load balancing and idempotent messaging
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab3 own test: 30 requests using identical actor/chat/key/body across both replicas."""
|
||||
import concurrent.futures
|
||||
import sys
|
||||
import uuid
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Check atomic idempotency across API replicas")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
body = {"text": "Concurrent replay " + key}
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
def worker(_):
|
||||
# Independent request client; one shared bearer token and idempotency key.
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
return client.call("POST", path, expected=201, actor=alice, body=body,
|
||||
headers={"Idempotency-Key": key}, schema="Message")
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as executor:
|
||||
results = list(executor.map(worker, range(30)))
|
||||
ids = {result["json"]["id"] for result in results}
|
||||
instances = {result["headers"]["X-Instance-Id"] for result in results}
|
||||
check(len(ids) == 1, "parallel replay created different messages")
|
||||
check(len(instances) >= 2, "LB did not serve requests via both API replicas")
|
||||
check(all(r["json"] == results[0]["json"] for r in results), "replay returned altered result")
|
||||
c.call("POST", path, 409, actor=alice, body={"text": "different body"}, headers={"Idempotency-Key": key})
|
||||
c.call("POST", path, 201, actor=bob, body=body, headers={"Idempotency-Key": key}, schema="Message")
|
||||
history = c.call("GET", path + "?limit=100", actor=bob, schema="MessagePage")["json"]["items"]
|
||||
check(sum(x["id"] in ids for x in history) == 1, "message duplicated in history")
|
||||
print("PASS: parallel idempotency across", len(instances), "replicas; one message, replay 201, conflicting body 409")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fast non-Docker checks for input contracts and cursor scoping."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from app.core import make_cursor, read_cursor, parse_limit, APIError
|
||||
from app.models import CreateUser, CreateChat, CreateMessage
|
||||
from pydantic import ValidationError
|
||||
|
||||
|
||||
def reject(fn):
|
||||
try:
|
||||
fn()
|
||||
except (APIError, ValidationError, ValueError):
|
||||
return
|
||||
raise AssertionError("Expected invalid input")
|
||||
|
||||
|
||||
def main():
|
||||
token = str(uuid.uuid4())
|
||||
dt = datetime.now(timezone.utc)
|
||||
cursor = make_cursor("messages", token, dt, str(uuid.uuid4()))
|
||||
assert read_cursor(cursor, "messages", token)[0] == dt
|
||||
reject(lambda: read_cursor(cursor, "messages", str(uuid.uuid4())))
|
||||
reject(lambda: read_cursor(cursor, "chats", token))
|
||||
assert parse_limit(None) == 50
|
||||
reject(lambda: parse_limit("0"))
|
||||
reject(lambda: parse_limit("101"))
|
||||
reject(lambda: CreateUser(username="user_name", display_name=" \t", password="Long-enough-secret"))
|
||||
reject(lambda: CreateUser(username="user_name", display_name="Test", password=" " * 3))
|
||||
assert CreateMessage(text="A\u0000B").text == "A\u0000B"
|
||||
reject(lambda: CreateMessage(text=" \t"))
|
||||
reject(lambda: CreateChat(title="title", member_ids=[token] * 2))
|
||||
reject(lambda: CreateChat(title="title", member_ids=[token] * 101))
|
||||
print("PASS: models, cursor scoping, limits, Unicode U+0000")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user