Files
mtusi2026lab3/student-tests/idempotency_probe.py
T
2026-11-06 18:09:01 +03:00

53 lines
1.7 KiB
Python

#!/usr/bin/env python3
"""Печатает обезличенную сводку конкурентного повтора одного Idempotency-Key."""
from __future__ import annotations
import json
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from uuid import uuid4
import harness
def main() -> int:
api = harness.client()
alice, bob, _, chat = api.bootstrap()
key = uuid4().hex
text = "probe-" + uuid4().hex
workers = 32
barrier = threading.Barrier(workers)
def worker(_: int) -> dict:
local = harness.client(10)
barrier.wait()
return local.message(alice, chat, text, key=key)
started = time.monotonic()
with ThreadPoolExecutor(max_workers=workers) as pool:
responses = list(pool.map(worker, range(workers)))
elapsed = time.monotonic() - started
bodies = [r["json"] for r in responses]
instances = sorted({r["headers"]["X-Instance-Id"] for r in responses})
messages = [m for m in harness.history(api, bob, chat["id"]) if m["text"] == text]
summary = {
"concurrent_requests": workers,
"elapsed_seconds": round(elapsed, 3),
"statuses": sorted({r["status"] for r in responses}),
"distinct_instances": instances,
"distinct_message_ids": len({b["id"] for b in bodies}),
"history_matches": len(messages),
"all_responses_identical": all(b == bodies[0] for b in bodies),
}
print(json.dumps(summary, ensure_ascii=False, indent=2))
return 0 if (
summary["statuses"] == [201]
and summary["distinct_message_ids"] == 1
and summary["history_matches"] == 1
and len(instances) >= 2
) else 1
if __name__ == "__main__":
raise SystemExit(main())