Files
mtusi2026lab5/student-tests/lab5/checks.py
T

280 lines
12 KiB
Python

"""Shared assertions and safe evidence for Lab 5 acceptance."""
import base64
from collections import Counter
import concurrent.futures
import http.client
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import math
from pathlib import Path
import ssl
import sys
import threading
import time
from urllib.parse import urlsplit
import uuid
sys.dont_write_bytecode = True
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check
from resilience import history
IO_ERRORS = (OSError, http.client.HTTPException)
class Pending(Exception):
"""A scenario has no configured infrastructure; exit status is not zero."""
class Evidence:
def __init__(self, path):
self.started = time.monotonic()
self.lock = threading.Lock()
self.phase = "setup"
self.file = Path(path).open("x", encoding="utf-8", buffering=1)
def event(self, event, **fields):
with self.lock:
line = {"event": event, "t_s": round(time.monotonic() - self.started, 6),
"phase": self.phase, **fields}
self.file.write(json.dumps(line, ensure_ascii=False) + "\n")
return line
def case(self, name, fn):
self.phase = name
print(f"RUN: {name}", flush=True)
try:
fn()
except Pending as exc:
status, note = "PENDING", str(exc)
except (Failure, ValueError, OSError, http.client.HTTPException) as exc:
status, note = "FAIL", str(exc) if isinstance(exc, Failure) else type(exc).__name__
else:
status, note = "PASS", ""
self.event("result", status=status, note=note)
print(f"{status}: {name}" + (f" — {note}" if note else ""), flush=True)
return status
class ObservedOpener:
def __init__(self, opener, capture):
self.opener = opener
self.capture = capture
def open(self, request, **kwargs):
from urllib.error import HTTPError
try:
response = self.opener.open(request, **kwargs)
except HTTPError as response:
self.capture(response)
raise
self.capture(response)
return response
class Probe(Client):
def __init__(self, base, ca, timeout, evidence):
super().__init__(base, ca, timeout=timeout)
self.ca = ca
self.evidence = evidence
self.local = threading.local()
self.opener = ObservedOpener(self.opener, self.capture)
def capture(self, response):
self.local.status = response.code
self.local.instance = response.headers.get("X-Instance-Id")
self.local.request_id = response.headers.get("X-Request-Id")
def call(self, method, path, *args, **kwargs):
self.local.status = self.local.instance = self.local.request_id = None
started = time.monotonic()
result = None
try:
result = super().call(method, path, *args, **kwargs)
return result
except IO_ERRORS as exc:
raise Failure(f"{method}: {type(exc).__name__} while reading response") from None
finally:
self.evidence.event("http", method=method, path=path.split("?")[0],
status=self.local.status, instance=self.local.instance,
request_id=self.local.request_id, ok=result is not None,
elapsed_s=time.monotonic() - started)
def key():
return uuid.uuid4().hex
def message_path(chat):
return f"/api/v1/chats/{chat['id']}/messages"
def post(c, actor, chat, k, text, *, status=201, body=None, code=None):
r = c.call("POST", message_path(chat), status, actor=actor,
headers={} if k is None else {"Idempotency-Key": k},
body={"text": text} if body is None else body, schema="Message")
if status == 201:
m = r["json"]
check((m["chat_id"], m["sender_id"], m["text"], m["attachment_ids"]) ==
(chat["id"], actor["id"], text, (body or {}).get("attachment_ids", [])),
"Message fields differ from POST")
elif code:
check(r["json"]["error"]["code"] == code, f"expected error code {code}")
if status == 401:
check(r["headers"].get("WWW-Authenticate") == 'Bearer realm="messenger"',
"incorrect Bearer challenge")
return r
def health(c):
for endpoint in ("live", "ready"):
r = c.call("GET", f"/health/{endpoint}", schema="Health")
check(r["json"] == {"status": "ok"}, f"/health/{endpoint}: unexpected payload")
def assert_history(c, actor, chat, expected):
actual = history(c, actor, chat)
check(len(actual) == len(expected) and {m["id"]: m for m in actual} ==
{m["id"]: m for m in expected}, "history has a missing, changed or extra Message")
def idempotency(c, workers, known_instances=None):
alice, bob, eve, chat = c.bootstrap()
other = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "Independent key scope", "member_ids": [alice["id"]]})["json"]
for bad in (None, "", "a" * 129, "a b", "a/b", "a@b", "nonASCII-é"):
post(c, alice, chat, bad, "must not persist", status=400, code="invalid_request")
assert_history(c, bob, chat, [])
k, upper = "A", ("AZaz09._:-" * 13)[:128]
check(len(upper) == 128, "length-128 fixture")
first = post(c, alice, chat, k, "Сообщение")["json"]
for body in (None, {"attachment_ids": [], "text": "Сообщение"},
{"text": "Сообщение", "attachment_ids": []}):
check(post(c, alice, chat, k, "Сообщение", body=body)["json"] == first,
"same semantic JSON must return the same 201 Message")
post(c, alice, chat, k, "different text", status=409, code="conflict")
assert_history(c, bob, chat, [first])
boundary = post(c, alice, chat, upper, "128-byte key")["json"]
check(post(c, alice, chat, upper, "128-byte key")["json"] == boundary, "max-key replay changed")
user_scope = post(c, bob, chat, k, "another user")["json"]
chat_scope = post(c, alice, other, k, "another chat")["json"]
check(len({first["id"], user_scope["id"], chat_scope["id"]}) == 3, "key leaked across scopes")
assert_history(c, alice, other, [chat_scope])
post(c, eve, chat, k, "Сообщение", status=404, code="not_found")
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
post(c, alice, chat, k, "Сообщение", status=401, code="unauthorized")
reg = alice["registration"]
basic = base64.b64encode(f'{reg["username"]}:{reg["password"]}'.encode()).decode()
session = c.call("POST", "/api/v1/auth/sessions", 201, schema="Session",
headers={"Authorization": "Basic " + basic})["json"]
alice = {**alice, "token": session["token"]}
check(post(c, alice, chat, k, "Сообщение")["json"] == first, "key unexpectedly scoped to session")
concurrent_key = key()
barrier = threading.Barrier(workers, timeout=10)
def race(_):
barrier.wait()
return post(c, alice, chat, concurrent_key, "same concurrent request")
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
responses = list(pool.map(race, range(workers)))
m = responses[0]["json"]
check(all(r["json"] == m for r in responses), "concurrent requests returned different Messages")
instances = {r["headers"]["X-Instance-Id"] for r in responses}
c.evidence.event("concurrent_posts", attempts=workers, instances=sorted(instances), message=m["id"])
assert_history(c, bob, chat, [first, boundary, user_scope, m])
lost_key, lost_text = key(), "commit with response unobserved by sender"
recorded = timeout_after_commit(c, alice, bob, chat, lost_key, lost_text)
check(post(c, alice, chat, lost_key, lost_text)["json"] == recorded,
"retry after loss of response changed Message")
assert_history(c, bob, chat, [first, boundary, user_scope, m, recorded])
if known_instances is not None:
check(len(instances) >= 2 and instances <= known_instances,
"concurrent POSTs did not reach two API replicas of this project")
def timeout_after_commit(c, actor, reader, chat, k, text):
# One shot loopback relay. The caller times out waiting for a response
# which the relay intentionally withholds after forwarding through the LB.
target = urlsplit(c.base)
cls = http.client.HTTPConnection if target.scheme == "http" else http.client.HTTPSConnection
opts = {} if target.scheme == "http" else {"context": ssl.create_default_context(cafile=c.ca)}
received = {}
finished, release = threading.Event(), threading.Event()
class DropResponse(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_POST(self):
upstream = cls(target.hostname, target.port, timeout=c.timeout, **opts)
try:
payload = self.rfile.read(int(self.headers["Content-Length"]))
headers = {h: self.headers[h] for h in ("Content-Type", "Idempotency-Key", "Authorization")}
upstream.request("POST", self.path, body=payload, headers=headers)
with upstream.getresponse() as response:
received["status"] = response.status
received["instance"] = response.getheader("X-Instance-Id")
if response.status == 201:
received["message"] = json.loads(response.read(1024 * 1024))
except (ValueError, OSError, http.client.HTTPException):
received["error"] = "upstream connection or invalid response"
finally:
upstream.close()
finished.set()
release.wait(8)
with HTTPServer(("127.0.0.1", 0), DropResponse) as relay:
relay.timeout = 3
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as jobs:
served = jobs.submit(relay.handle_request)
downstream = http.client.HTTPConnection(*relay.server_address, timeout=0.5)
timed_out = False
try:
downstream.request("POST", message_path(chat), body=json.dumps({"text": text}),
headers={"Content-Type": "application/json",
"Idempotency-Key": k, "Authorization": "Bearer " + actor["token"]})
try:
downstream.getresponse().close()
except TimeoutError:
timed_out = True
check(timed_out, "client did not actually time out on the dropped response")
check(finished.wait(6) and received.get("status") == 201 and received.get("instance"),
"relay did not observe committed upstream 201")
outcome = received["message"]
check(outcome in history(c, reader, chat), "original timed-out invocation did not durably commit")
c.evidence.event("lost_response", downstream="TimeoutError", upstream_status=201,
instance=received["instance"], message=outcome["id"])
return outcome
finally:
release.set()
downstream.close()
served.result(timeout=10)
def wait(fn, seconds, label):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
value = fn()
except Failure:
value = None
if value and time.monotonic() <= deadline:
return value
time.sleep(0.1)
raise Failure(label)
def summarize(evidence, records, elapsed, window="full"):
times = sorted(r["elapsed_s"] for r in records if r["ok"])
percentiles = {f"p{p}_ms": round(times[math.ceil(len(times)*p/100)-1]*1000, 3) if times else None
for p in (50, 95, 99)}
evidence.event("load_summary", window=window, elapsed_s=elapsed, attempts=len(records), successes=len(times),
successful_rps=len(times) / elapsed, failures=len(records)-len(times),
error_ratio=(len(records)-len(times))/len(records) if records else None,
statuses=dict(Counter(str(r["status"]) for r in records)), **percentiles)