Files
mtusi2026lab6/tests/idempotency.py
T

117 lines
3.9 KiB
Python

#!/usr/bin/env python3
"""Конкурентная идемпотентность, область ключей и повторная авторизация."""
import json
import threading
import uuid
from concurrent.futures import ThreadPoolExecutor
from client import Client, arguments, check, run
def main():
args = arguments("Lab3 concurrency and idempotency")
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
path = "/api/v1/chats/" + chat["id"] + "/messages"
key = uuid.uuid4().hex
clients = [Client(args.base_url, args.ca_file) for _ in range(16)]
barrier = threading.Barrier(len(clients))
def send(local):
barrier.wait()
return local.message(alice, chat, "Одна отправка 👋", key=key)
with ThreadPoolExecutor(max_workers=len(clients)) as pool:
responses = list(pool.map(send, clients))
instances = {r["headers"]["X-Instance-Id"] for r in responses}
check(len(instances) >= 2, "Parallel repeats did not reach >=2 replicas")
original = responses[0]["json"]
check(all(r["json"] == original for r in responses), "Concurrent results differ")
messages = c.call("GET", path, actor=bob, schema="MessagePage")["json"]["items"]
check(messages == [original], "Concurrent retries duplicated message")
# Missing attachment_ids and [] are semantically equal; raw JSON ordering too.
replay = c.call(
"POST",
path,
201,
actor=alice,
raw=b'{"attachment_ids":[],"text":"' + "Одна отправка 👋".encode() + b'"}',
headers={"Idempotency-Key": key, "Content-Type": "application/json"},
schema="Message",
)
check(replay["json"] == original, "Equivalent JSON did not replay")
c.call(
"POST",
path,
409,
actor=alice,
body={"text": "Другой текст"},
headers={"Idempotency-Key": key},
)
other = c.message(bob, chat, "Другой отправитель", key=key)["json"]
check(other["id"] != original["id"], "Key incorrectly shared across users")
chat2 = c.call(
"POST",
"/api/v1/chats",
201,
actor=alice,
body={"title": "Другой чат", "member_ids": [alice["id"]]},
schema="Chat",
)["json"]
check(
c.message(alice, chat2, "Другой чат", key=key)["json"]["id"] != original["id"],
"Key scope includes wrong chat",
)
for invalid in [None, "", "bad key", "x" * 129, "bad/key"]:
c.call(
"POST",
path,
400,
actor=alice,
body={"text": "invalid"},
headers={} if invalid is None else {"Idempotency-Key": invalid},
)
# Validation/access failures must not consume a key.
retry_key = uuid.uuid4().hex
c.call(
"POST", path, 400, actor=alice, body={"text": ""}, headers={"Idempotency-Key": retry_key}
)
c.message(alice, chat, "После 400", key=retry_key)
c.call(
"POST",
path,
404,
actor=eve,
body={"text": original["text"]},
headers={"Idempotency-Key": key},
)
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
c.call(
"POST",
path,
401,
actor=alice,
body={"text": original["text"]},
headers={"Idempotency-Key": key},
)
for route in ["/health/live", "/health/ready", "/missing"]:
c.call("GET", route, 404 if route == "/missing" else 200)
print(
json.dumps(
{
"parallel_repeats": len(responses),
"instances": sorted(instances),
"messages_created": 1,
"checks": "normalization, conflict, key scope, invalid keys, access, logout, headers",
"result": "PASS",
},
ensure_ascii=False,
indent=2,
)
)
if __name__ == "__main__":
run(main)