Files
mtusi2026lab3/student-tests/traffic.py
T

136 lines
5.8 KiB
Python

"""Persistent HTTP/1.1 workers; closed-loop measurements include client overhead."""
from concurrent.futures import ThreadPoolExecutor
from collections import Counter
import http.client
import json
import math
import threading
import time
from urllib.parse import urlsplit
import uuid
def percentile(values, fraction):
return round(sorted(values)[max(0, math.ceil(len(values) * fraction) - 1)], 3) if values else None
def traffic(base_url, actor, chat, duration=10, concurrency=16, action=None, retry_uncertain=False, observer=None):
address = urlsplit(base_url)
barrier = threading.Barrier(concurrency + 1)
actions = []
action_error = []
observations = []
sample_stop = threading.Event()
started = 0
def worker(number):
connection = http.client.HTTPConnection(address.hostname, address.port, timeout=3)
records, confirmed = [], []
pending = None
index = number
barrier.wait()
deadline = started + duration
try:
while time.monotonic() < deadline:
operation = "write" if pending or index % 2 else "read"
headers = {"Authorization": "Bearer " + actor["token"], "Content-Type": "application/json"}
path = "/api/v1/chats/" + chat["id"] + "/messages"
payload = None
if operation == "write":
if pending is None:
pending = (uuid.uuid4().hex, uuid.uuid4().hex)
headers["Idempotency-Key"] = pending[0]
payload = json.dumps({"text": pending[1]}).encode()
else:
path += "?limit=50"
begin = time.monotonic()
status, instance, message_id = 0, "", None
try:
connection.request("POST" if operation == "write" else "GET", path, body=payload, headers=headers)
response = connection.getresponse()
status = response.status
instance = response.getheader("X-Instance-Id", "")
content = response.read()
if status == (201 if operation == "write" else 200):
if operation == "write":
message_id = json.loads(content)["id"]
confirmed.append((message_id, pending[1]))
pending = None
else:
connection.close()
except (OSError, http.client.HTTPException, ValueError):
connection.close()
status = 0
elapsed = (time.monotonic() - begin) * 1000
records.append((round(begin - started, 6), operation, status, round(elapsed, 4), instance))
if not retry_uncertain:
pending = None
index += 1
finally:
connection.close()
return records, confirmed
def run_action():
try:
time.sleep(2)
begin = time.monotonic()
result = action()
actions.append({"started_after_seconds": begin - started,
"finished_after_seconds": time.monotonic() - started, "result": result})
except Exception as error:
action_error.append(error)
def sample():
while not sample_stop.wait(2):
try:
observations.append({"offset_seconds": round(time.monotonic() - started, 3), "data": observer()})
except Exception as error:
observations.append({"error": type(error).__name__})
with ThreadPoolExecutor(max_workers=concurrency) as pool:
futures = [pool.submit(worker, n) for n in range(concurrency)]
started = time.monotonic()
barrier.wait()
sampler = threading.Thread(target=sample) if observer else None
if sampler:
sampler.start()
thread = threading.Thread(target=run_action) if action else None
if thread:
thread.start()
try:
outcomes = [future.result() for future in futures]
finally:
sample_stop.set()
if sampler:
sampler.join()
if thread:
thread.join()
ended = time.monotonic()
if action_error:
raise action_error[0]
samples = sorted([row for records, _ in outcomes for row in records])
successes = [row for row in samples if row[2] == (201 if row[1] == "write" else 200)]
failed = [row for row in samples if row[2] != (201 if row[1] == "write" else 200)]
latencies = [row[3] for row in successes]
report = {
"duration_seconds": round(ended - started, 4), "requested_seconds": duration,
"concurrency": concurrency, "successful_requests": len(successes), "failed_requests": len(failed),
"successful_rps": round(len(successes) / (ended - started), 3),
"error_ratio": round(len(failed) / len(samples), 6) if samples else None,
"successful_latency_ms": {name: percentile(latencies, fraction)
for name, fraction in (("p50", .5), ("p95", .95), ("p99", .99))},
"all_attempt_latency_ms": {name: percentile([row[3] for row in samples], fraction)
for name, fraction in (("p50", .5), ("p95", .95), ("p99", .99))},
"status_counts": dict(Counter(str(row[2]) for row in samples)),
"instance_counts": dict(Counter(row[4] for row in successes)),
"actions": actions,
"observations": observations,
"_samples": samples,
"_confirmed": [row for _, confirmations in outcomes for row in confirmations],
}
return report
def public_report(report):
return {key: value for key, value in report.items() if not key.startswith("_")}