forked from mtusi2026/mtusi2026lab2
Исходная точка lab2: код из solution/bvt2302-bodanyuk лабы 1, коммит 472c1bd. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
135 lines
5.4 KiB
Python
135 lines
5.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Black-box race check against a RUNNING server (level 4 criterion).
|
|
|
|
10 clients (10 different users, one thread each) send 10 messages each into one
|
|
chat at the same moment. Then the whole history is read page by page through
|
|
the cursor. PASS requires: 100 confirmed writes, exactly 100 unique messages,
|
|
nothing lost, strict (created_at, id) order and per-client order preserved.
|
|
|
|
python student-tests/http_concurrency.py --base-url http://127.0.0.1:8080 \
|
|
--output evidence/concurrency.json
|
|
|
|
Standard library only (Python 3.9+). Creates synthetic users; run on a lab stand.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import sys
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
|
|
def call(base: str, method: str, path: str, body=None, user_id=None, expected=200):
|
|
data = None if body is None else json.dumps(body, ensure_ascii=False).encode("utf-8")
|
|
headers = {"Accept": "application/json"}
|
|
if data is not None:
|
|
headers["Content-Type"] = "application/json"
|
|
if user_id:
|
|
headers["X-User-Id"] = user_id
|
|
request = urllib.request.Request(base + path, data=data, headers=headers, method=method)
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=10) as response:
|
|
status, payload = response.status, response.read()
|
|
except urllib.error.HTTPError as error:
|
|
status, payload = error.code, error.read()
|
|
if status != expected:
|
|
raise AssertionError(f"{method} {path.split('?')[0]}: expected {expected}, got {status}")
|
|
return json.loads(payload)
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
parser.add_argument("--base-url", default="http://127.0.0.1:8080")
|
|
parser.add_argument("--clients", type=int, default=10)
|
|
parser.add_argument("--messages", type=int, default=10, help="messages per client")
|
|
parser.add_argument("--page-limit", type=int, default=7, help="small limit => many cursor pages")
|
|
parser.add_argument("--output", default=None, help="optional JSON summary (no secrets inside)")
|
|
args = parser.parse_args()
|
|
base = args.base_url.rstrip("/")
|
|
total = args.clients * args.messages
|
|
|
|
run = uuid.uuid4().hex[:8]
|
|
users = [call(base, "POST", "/api/v1/users", {"username": f"race_{run}_{i}", "display_name": f"Клиент {i}"}, expected=201)
|
|
for i in range(args.clients)]
|
|
chat = call(base, "POST", "/api/v1/chats", {"title": f"race {run}", "member_ids": [u["id"] for u in users]},
|
|
user_id=users[0]["id"], expected=201)
|
|
|
|
barrier = threading.Barrier(args.clients)
|
|
confirmed: list[dict] = []
|
|
errors: list[str] = []
|
|
lock = threading.Lock()
|
|
|
|
def client(index: int) -> None:
|
|
barrier.wait() # all clients start sending at the same moment
|
|
for j in range(args.messages):
|
|
try:
|
|
message = call(base, "POST", f"/api/v1/chats/{chat['id']}/messages",
|
|
{"text": f"c{index}-m{j} 🧵"}, user_id=users[index]["id"], expected=201)
|
|
with lock:
|
|
confirmed.append(message)
|
|
except Exception as exc: # noqa: BLE001 - reported below
|
|
with lock:
|
|
errors.append(f"client {index}: {exc}")
|
|
|
|
started = time.monotonic()
|
|
threads = [threading.Thread(target=client, args=(i,)) for i in range(args.clients)]
|
|
for t in threads:
|
|
t.start()
|
|
for t in threads:
|
|
t.join()
|
|
elapsed = time.monotonic() - started
|
|
|
|
history, pages, cursor = [], 0, None
|
|
while True:
|
|
query = f"?limit={args.page_limit}" + (f"&cursor={cursor}" if cursor else "")
|
|
page = call(base, "GET", f"/api/v1/chats/{chat['id']}/messages{query}", user_id=users[-1]["id"])
|
|
pages += 1
|
|
history.extend(page["items"])
|
|
cursor = page["next_cursor"]
|
|
if cursor is None or len(history) > 10 * total:
|
|
break
|
|
|
|
ids = [m["id"] for m in history]
|
|
keys = [(m["created_at"], uuid.UUID(m["id"]).int) for m in history]
|
|
per_client_ok = all(
|
|
[m["text"] for m in history if m["sender_id"] == u["id"]] == [f"c{i}-m{j} 🧵" for j in range(args.messages)]
|
|
for i, u in enumerate(users)
|
|
)
|
|
checks = {
|
|
"all_writes_confirmed_201": len(confirmed) == total and not errors,
|
|
"history_count_equals_sent": len(history) == total,
|
|
"ids_unique": len(set(ids)) == len(ids),
|
|
"no_confirmed_message_lost": {m["id"] for m in confirmed} <= set(ids),
|
|
"strict_created_at_id_order": all(a < b for a, b in zip(keys, keys[1:])),
|
|
"per_client_order_preserved": per_client_ok,
|
|
}
|
|
summary = {
|
|
"clients": args.clients,
|
|
"messages_per_client": args.messages,
|
|
"sent": total,
|
|
"confirmed_201": len(confirmed),
|
|
"errors": errors[:5],
|
|
"history_items": len(history),
|
|
"unique_ids": len(set(ids)),
|
|
"pages_read": pages,
|
|
"page_limit": args.page_limit,
|
|
"write_phase_seconds": round(elapsed, 3),
|
|
"checks": checks,
|
|
"result": "PASS" if all(checks.values()) else "FAIL",
|
|
}
|
|
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
|
print(text)
|
|
if args.output:
|
|
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
|
Path(args.output).write_text(text + "\n", encoding="utf-8")
|
|
return 0 if summary["result"] == "PASS" else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|