Files
mtusi2026lab3/student-tests/level3.py
T

130 lines
4.8 KiB
Python

#!/usr/bin/env python3
"""Проверки lab3: разные реплики, идемпотентность через LB, гонка одного ключа."""
import json
import os
import sys
import threading
import time
import uuid
from collections import Counter
from pathlib import Path
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run
EVIDENCE = ROOT / "evidence"
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
def history(client, actor, chat):
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
result = []
seen = set()
for _ in range(1000):
page = client.call("GET", path, actor=actor, schema="MessagePage")["json"]
result.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return result
check(cursor not in seen, "cursor cycle")
seen.add(cursor)
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100&cursor=" + quote(cursor, safe="")
raise Failure("history pagination exceeded safety bound")
def test_instances(client, actor):
seen = []
for _ in range(40):
seen.append(client.call("GET", "/api/v1/users/me", actor=actor, schema="User")["headers"]["X-Instance-Id"])
unique = sorted(set(seen))
check(len(unique) >= 2, "less than two API instances observed: %s" % unique)
return {"unique_instance_ids": unique, "samples": len(seen), "counts": dict(Counter(seen))}
def test_idempotency(client, alice, bob, chat):
key = uuid.uuid4().hex
first = client.message(alice, chat, "Один ключ", key=key)
replay = client.message(alice, chat, "Один ключ", key=key)
check(first["json"] == replay["json"], "idempotent replay differs")
check(first["json"]["id"] == replay["json"]["id"], "idempotent replay allocated a new id")
conflict = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
409,
actor=alice,
body={"text": "другой body"},
headers={"Idempotency-Key": key},
)
check(conflict["json"]["error"]["code"] == "conflict", "wrong body code")
missing = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
400,
actor=alice,
body={"text": "без ключа"},
)
check(missing["json"]["error"]["code"] == "invalid_request", "missing key code")
other_user = client.message(bob, chat, "Один ключ", key=key)
check(other_user["json"]["id"] != first["json"]["id"], "key leaked across users")
return first["json"]["id"]
def test_concurrent_key(client, alice, chat):
key = uuid.uuid4().hex
text = "Гонка ключа " + key
barrier = threading.Barrier(12)
results = []
errors = []
lock = threading.Lock()
def worker():
local = Client(BASE, timeout=20)
try:
barrier.wait(20)
response = local.message(alice, chat, text, key=key)
with lock:
results.append((response["status"], response["json"]["id"], response["headers"]["X-Instance-Id"]))
except Exception as exc:
with lock:
errors.append("%s: %s" % (type(exc).__name__, exc))
threads = [threading.Thread(target=worker) for _ in range(12)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
check(not errors, "concurrent idempotent POST failed: " + "; ".join(errors[:5]))
check(len(results) == 12, "expected 12 successes, got %s" % len(results))
ids = {item[1] for item in results}
instances = sorted({item[2] for item in results})
check(len(ids) == 1, "concurrent key created %s messages" % len(ids))
listed = history(client, alice, chat)
matches = [item for item in listed if item["text"] == text]
check(len(matches) == 1, "history contains %s copies of the concurrent key" % len(matches))
return {"message_id": next(iter(ids)), "instances": instances, "successes": len(results)}
def main():
client = Client(BASE, timeout=10)
alice, bob, _eve, chat = client.bootstrap()
instances = test_instances(client, alice)
message_id = test_idempotency(client, alice, bob, chat)
race = test_concurrent_key(client, alice, chat)
EVIDENCE.mkdir(exist_ok=True)
report = {
"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"base_url": BASE,
"instances": instances,
"idempotent_message_id_present": bool(message_id),
"concurrent_key": race,
}
(EVIDENCE / "level3.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("PASS: level 3 replica routing and shared idempotency")
if __name__ == "__main__":
run(main)