Files
mtusi2026lab3-fork/scripts/check_idempotency.py

66 lines
3.4 KiB
Python

import json
import sys
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from threading import Barrier
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, arguments, check, run
def main():
args = arguments(__doc__)
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
path = "/api/v1/chats/" + chat["id"] + "/messages"
observed = {
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")["headers"]["X-Instance-Id"]
for _ in range(40)
}
check(len(observed) >= 2, "same session did not reach two API replicas")
key = uuid.uuid4().hex
text = "Один ключ через разные реплики 👋"
concurrency = 24
start = Barrier(concurrency)
def send(_):
client = Client(args.base_url, args.ca_file)
start.wait(timeout=15)
return client.message(alice, chat, text, key=key)
with ThreadPoolExecutor(max_workers=concurrency) as pool:
replies = list(pool.map(send, range(concurrency)))
original = replies[0]["json"]
instances = {reply["headers"]["X-Instance-Id"] for reply in replies}
check(len(instances) >= 2, "concurrent POST did not reach different API replicas")
check(all(reply["json"] == original for reply in replies), "concurrent replay changed the response")
history = c.call("GET", path, actor=bob, schema="MessagePage")["json"]["items"]
check(history == [original], "concurrent POST created a duplicate")
check(c.message(alice, chat, text, key=key, attachments=[])["json"] == original, "empty attachment_ids changed replay")
reordered = c.call("POST", path, 201, actor=alice,
raw=json.dumps({"attachment_ids": [], "text": text}, ensure_ascii=False).encode(),
headers={"Content-Type": "application/json", "Idempotency-Key": key}, schema="Message")["json"]
check(reordered == original, "JSON key order changed replay")
c.call("POST", path, 409, actor=alice, body={"text": "другое тело"}, headers={"Idempotency-Key": key})
c.call("POST", path, 400, actor=alice, body={"text": text})
for invalid in ("bad key", "x" * 129, "invalid/key", ""):
c.call("POST", path, 400, actor=alice, body={"text": text}, headers={"Idempotency-Key": invalid})
c.call("POST", path, 400, actor=alice, body={"text": text, "extra": 1}, headers={"Idempotency-Key": key})
c.call("POST", path, 404, actor=eve, body={"text": text}, headers={"Idempotency-Key": key})
other_sender = c.message(bob, chat, text, key=key)["json"]
check(other_sender["id"] != original["id"], "key scope does not include sender")
other_chat = c.call("POST", "/api/v1/chats", 201, actor=alice,
body={"title": "Other scope", "member_ids": [alice["id"]]}, schema="Chat")["json"]
check(c.message(alice, other_chat, text, key=key)["json"]["id"] != original["id"], "key scope does not include chat")
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
c.call("POST", path, 401, actor=alice, body={"text": text}, headers={"Idempotency-Key": key})
print(json.dumps({"concurrent_requests": concurrency, "observed_instances": sorted(instances),
"messages_after_concurrent_repeat": len(history)}, ensure_ascii=False))
print("PASS: shared session, concurrent replay across replicas, key/body validation, independent scopes, reauthentication on replay")
if __name__ == "__main__":
run(main)