Files
mtusi2026lab2/student-tests/cache_stampede.py
T
Матвей 744e941d55
Skeleton contracts / contracts (pull_request) Canceled after 0s
add code for level 5
2026-10-08 19:48:18 +03:00

52 lines
1.7 KiB
Python

#!/usr/bin/env python3
"""Одновременное чтение холодной первой страницы истории."""
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import json
import sys
import threading
import time
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, check, run # noqa: E402
def main() -> None:
concurrency = 20
client = Client()
alice, _bob, _eve, chat = client.bootstrap()
created = client.message(alice, chat, "cold-cache message")["json"]
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=1"
barrier = threading.Barrier(concurrency)
def read_page(_worker: int) -> float:
local = Client()
barrier.wait()
started = time.monotonic()
response = local.call("GET", path, actor=alice, schema="MessagePage")["json"]
check(response["items"] == [created], "cold-page response differs")
return time.monotonic() - started
with ThreadPoolExecutor(max_workers=concurrency) as pool:
latencies = list(pool.map(read_page, range(concurrency)))
ordered = sorted(latencies)
print(
json.dumps(
{
"chat_id": chat["id"],
"concurrency": concurrency,
"successful_reads": len(latencies),
"latency_ms": {
"p50": round(1000 * ordered[(concurrency - 1) // 2], 3),
"p95": round(1000 * ordered[18], 3),
"max": round(1000 * ordered[-1], 3),
},
},
ensure_ascii=False,
)
)
if __name__ == "__main__":
run(main)