Реализовать лабораторную 3 на оценку 5 (трек 1)
This commit is contained in:
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Closed-loop POST benchmark for the lab3 scaling track.
|
||||
|
||||
Each worker keeps one HTTP/1.1 connection to the public LB, sends unique
|
||||
messages with unique Idempotency-Key values, and records successful latency.
|
||||
This is a comparative tool, not an open-loop capacity certificate: the client
|
||||
runs on the same host and closed-loop generators suffer coordinated omission.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import http.client
|
||||
import json
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from common import HttpClient
|
||||
|
||||
|
||||
def percentile(values: list[float], p: float) -> float | None:
|
||||
if not values:
|
||||
return None
|
||||
ordered = sorted(values)
|
||||
index = max(0, math.ceil(p * len(ordered)) - 1)
|
||||
return round(ordered[index] * 1000.0, 3)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--duration", type=float, default=20.0)
|
||||
parser.add_argument("--warmup", type=float, default=2.0)
|
||||
parser.add_argument("--concurrency", type=int, default=16)
|
||||
parser.add_argument("--label", default="run")
|
||||
parser.add_argument("--output", default=None)
|
||||
args = parser.parse_args()
|
||||
|
||||
base = urlsplit(args.base_url)
|
||||
host = base.hostname or "localhost"
|
||||
port = base.port or (443 if base.scheme == "https" else 80)
|
||||
secure = base.scheme == "https"
|
||||
|
||||
bootstrap = HttpClient(args.base_url)
|
||||
user, registration = bootstrap.register()
|
||||
session = bootstrap.login(registration)
|
||||
token = session["token"]
|
||||
status, _headers, chat, _raw = bootstrap.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
body={"title": "Track 1 bench", "member_ids": [user["id"]]},
|
||||
token=token,
|
||||
)
|
||||
if status != 201:
|
||||
raise AssertionError(f"chat creation failed: HTTP {status}")
|
||||
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
barrier = threading.Barrier(args.concurrency + 1)
|
||||
stop_at = time.monotonic() + args.warmup + args.duration
|
||||
measure_from = time.monotonic() + args.warmup
|
||||
lock = threading.Lock()
|
||||
latencies: list[float] = []
|
||||
errors = 0
|
||||
instances: Counter[str] = Counter()
|
||||
|
||||
def worker(worker_id: int) -> None:
|
||||
nonlocal errors
|
||||
connection = None
|
||||
if secure:
|
||||
import ssl
|
||||
|
||||
context = ssl.create_default_context()
|
||||
connection = http.client.HTTPSConnection(host, port, timeout=5, context=context)
|
||||
else:
|
||||
connection = http.client.HTTPConnection(host, port, timeout=5)
|
||||
barrier.wait()
|
||||
index = 0
|
||||
while time.monotonic() < stop_at:
|
||||
index += 1
|
||||
key = uuid.uuid4().hex
|
||||
body = json.dumps({"text": f"bench-{worker_id}-{index}"}).encode("utf-8")
|
||||
headers = {
|
||||
"Authorization": "Bearer " + token,
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"Idempotency-Key": key,
|
||||
"Connection": "keep-alive",
|
||||
}
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
connection.request("POST", path, body=body, headers=headers)
|
||||
response = connection.getresponse()
|
||||
payload = response.read()
|
||||
elapsed = time.perf_counter() - started
|
||||
if response.status == 201:
|
||||
if started >= measure_from:
|
||||
with lock:
|
||||
latencies.append(elapsed)
|
||||
instances[response.getheader("X-Instance-Id", "")] += 1
|
||||
else:
|
||||
with lock:
|
||||
errors += 1
|
||||
# Drain/close only on protocol trouble.
|
||||
if response.will_close:
|
||||
connection.close()
|
||||
connection = (
|
||||
http.client.HTTPSConnection(host, port, timeout=5)
|
||||
if secure
|
||||
else http.client.HTTPConnection(host, port, timeout=5)
|
||||
)
|
||||
except Exception:
|
||||
with lock:
|
||||
errors += 1
|
||||
try:
|
||||
connection.close()
|
||||
except Exception:
|
||||
pass
|
||||
connection = (
|
||||
http.client.HTTPSConnection(host, port, timeout=5)
|
||||
if secure
|
||||
else http.client.HTTPConnection(host, port, timeout=5)
|
||||
)
|
||||
|
||||
threads = [threading.Thread(target=worker, args=(i,), daemon=True) for i in range(args.concurrency)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
barrier.wait()
|
||||
while time.monotonic() < stop_at:
|
||||
time.sleep(0.05)
|
||||
for thread in threads:
|
||||
thread.join(timeout=5)
|
||||
|
||||
total = len(latencies) + errors
|
||||
report = {
|
||||
"label": args.label,
|
||||
"base_url": args.base_url,
|
||||
"concurrency": args.concurrency,
|
||||
"warmup_seconds": args.warmup,
|
||||
"duration_seconds": args.duration,
|
||||
"successful_requests": len(latencies),
|
||||
"failed_requests": errors,
|
||||
"error_ratio": round(errors / total, 6) if total else None,
|
||||
"successful_rps": round(len(latencies) / args.duration, 3),
|
||||
"successful_latency_ms": {
|
||||
"p50": percentile(latencies, 0.50),
|
||||
"p95": percentile(latencies, 0.95),
|
||||
"p99": percentile(latencies, 0.99),
|
||||
},
|
||||
"instances": dict(sorted(instances.items())),
|
||||
"note": (
|
||||
"closed-loop client on the same host; latency covers successes only; "
|
||||
"compare runs under the same client and host conditions"
|
||||
),
|
||||
}
|
||||
text = json.dumps(report, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
output = Path(args.output)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(text + "\n", encoding="utf-8")
|
||||
print(text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user