ЛР2 — БВТ2302 — Никитина — на 5 (трек 2)
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Yuliiiaaaa
2026-10-20 00:04:12 +03:00
parent 65003b6119
commit 7255878240
26 changed files with 1426 additions and 47 deletions
+7
View File
@@ -0,0 +1,7 @@
"""Shared path bootstrap so student tests can import tests/client.py."""
import sys
from pathlib import Path
TESTS_DIR = Path(__file__).resolve().parents[1] / "tests"
if str(TESTS_DIR) not in sys.path:
sys.path.insert(0, str(TESTS_DIR))
+264
View File
@@ -0,0 +1,264 @@
#!/usr/bin/env python3
"""Track 1: measure in-memory architecture limits.
Closed-loop workload with a mix of paginated reads (random cursor depth)
and writes. Iterates over history sizes and concurrency levels in one
process, so the server is seeded once per history size.
Requires the server to already run with the desired PAGINATION_MODE.
Use --docker-container to sample RSS via ``docker stats`` (Windows friendly).
"""
import argparse
import json
import math
import random
import subprocess
import sys
import threading
import time
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, Failure # noqa: E402
def pct(sorted_values, p):
if not sorted_values:
return None
idx = max(0, math.ceil(p * len(sorted_values)) - 1)
return round(1000 * sorted_values[idx], 3)
def read_rss_kb(pid):
try:
text = Path("/proc/%d/status" % pid).read_text()
except OSError:
return None
for line in text.splitlines():
if line.startswith("VmRSS:"):
return int(line.split()[1])
return None
def docker_rss_kb(container):
"""Return MiB/KiB value from `docker stats --no-stream` as KB."""
try:
out = subprocess.run(
["docker", "stats", "--no-stream",
"--format", "{{.MemUsage}}", container],
capture_output=True, text=True, timeout=15).stdout.strip()
except Exception:
return None
if not out or "/" not in out:
return None
used = out.split("/")[0].strip()
for suffix, factor in (("GiB", 1024 * 1024), ("MiB", 1024),
("KiB", 1), ("B", 1 / 1024)):
if used.endswith(suffix):
try:
return int(float(used[:-len(suffix)]) * factor)
except ValueError:
return None
return None
def sample_rss(args):
if args.server_pid:
return read_rss_kb(args.server_pid)
if args.docker_container:
return docker_rss_kb(args.docker_container)
return None
def prepopulate(client, actor, chat, count, existing, progress_every=2000):
if existing >= count:
return existing
t0 = time.monotonic()
for i in range(existing, count):
client.message(actor, chat, "seed-%08d" % i)
if progress_every and (i + 1) % progress_every == 0:
print(" seeded %d/%d (%.1fs)"
% (i + 1, count, time.monotonic() - t0),
file=sys.stderr)
return count
def collect_cursors(client, actor, chat, page_limit=50):
cursors = []
path = "/api/v1/chats/%s/messages?limit=%d" % (chat["id"], page_limit)
while True:
page = client.call("GET", path, actor=actor,
schema="MessagePage")["json"]
nxt = page["next_cursor"]
if nxt is None:
break
cursors.append(nxt)
path = "/api/v1/chats/%s/messages?limit=%d&cursor=%s" % (
chat["id"], page_limit, nxt)
return cursors
def op_once(client, actor, chat, cursors, rng, read_ratio):
if cursors and rng.random() < read_ratio:
cur = rng.choice(cursors)
start = time.monotonic()
client.call("GET",
"/api/v1/chats/%s/messages?limit=50&cursor=%s"
% (chat["id"], cur),
actor=actor, schema="MessagePage")
return "read", time.monotonic() - start
start = time.monotonic()
client.message(actor, chat, "load-" + uuid.uuid4().hex[:8])
return "write", time.monotonic() - start
def run_one(args, alice, chat, history, cursors, concurrency):
barrier = threading.Barrier(concurrency)
results = [None] * concurrency
def worker(wid):
local = Client(args.base_url, timeout=15)
rng = random.Random(0xC0FFEE + wid)
read_lat, write_lat = [], []
read_err = write_err = 0
w_deadline = time.monotonic() + args.warmup
while time.monotonic() < w_deadline:
try:
op_once(local, alice, chat, cursors, rng, args.read_ratio)
except Failure:
pass
barrier.wait()
deadline = time.monotonic() + args.duration
while time.monotonic() < deadline:
try:
kind, dt_s = op_once(local, alice, chat, cursors,
rng, args.read_ratio)
except Failure:
if rng.random() < args.read_ratio:
read_err += 1
else:
write_err += 1
continue
(read_lat if kind == "read" else write_lat).append(dt_s)
results[wid] = (read_lat, write_lat, read_err, write_err)
started = time.monotonic()
threads = [threading.Thread(target=worker, args=(i,))
for i in range(concurrency)]
for t in threads:
t.start()
for t in threads:
t.join()
elapsed = time.monotonic() - started
read_all, write_all = [], []
read_err_total = write_err_total = 0
for chunk in results:
r_lat, w_lat, r_err, w_err = chunk
read_all.extend(r_lat)
write_all.extend(w_lat)
read_err_total += r_err
write_err_total += w_err
read_all.sort()
write_all.sort()
return {
"history": history,
"concurrency": concurrency,
"duration_s": args.duration,
"elapsed_s": round(elapsed, 3),
"read_ratio": args.read_ratio,
"cursors": len(cursors),
"reads": {
"success": len(read_all),
"errors": read_err_total,
"rps": round(len(read_all) / elapsed, 2),
"p50_ms": pct(read_all, 0.50),
"p95_ms": pct(read_all, 0.95),
"p99_ms": pct(read_all, 0.99),
},
"writes": {
"success": len(write_all),
"errors": write_err_total,
"rps": round(len(write_all) / elapsed, 2),
"p50_ms": pct(write_all, 0.50),
"p95_ms": pct(write_all, 0.95),
"p99_ms": pct(write_all, 0.99),
},
"total_ops": len(read_all) + len(write_all) + read_err_total + write_err_total,
"error_ratio": round(
(read_err_total + write_err_total) /
max(1, len(read_all) + len(write_all) + read_err_total + write_err_total),
6),
}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--base-url", default="http://localhost:8080")
ap.add_argument("--history", default="1000,5000,20000",
help="comma-separated history sizes")
ap.add_argument("--concurrency", default="1,4,16",
help="comma-separated concurrency levels")
ap.add_argument("--duration", type=float, default=15.0)
ap.add_argument("--warmup", type=float, default=2.0)
ap.add_argument("--read-ratio", type=float, default=0.8)
ap.add_argument("--server-pid", type=int, default=None,
help="server PID for /proc RSS sampling (Linux)")
ap.add_argument("--docker-container", default=None,
help="container name for `docker stats` RSS sampling")
ap.add_argument("--mode", default=None, help="label: linear | index")
ap.add_argument("--output-dir", default="evidence")
args = ap.parse_args()
histories = [int(x) for x in args.history.split(",") if x.strip()]
concurrencies = [int(x) for x in args.concurrency.split(",") if x.strip()]
label = args.mode or "run"
c = Client(args.base_url)
alice, bob, eve, chat = c.bootstrap()
print("chat=%s" % chat["id"], file=sys.stderr)
out_dir = Path(args.output_dir)
out_dir.mkdir(parents=True, exist_ok=True)
seeded = 0
summaries = []
for history in histories:
print("== history=%d ==" % history, file=sys.stderr)
seeded = prepopulate(c, alice, chat, history, seeded)
cursors = collect_cursors(c, bob, chat)
rss_after_seed = sample_rss(args)
print(" cursors=%d rss_kb=%s"
% (len(cursors), rss_after_seed), file=sys.stderr)
for concurrency in concurrencies:
print(" -- concurrency=%d" % concurrency, file=sys.stderr)
r = run_one(args, alice, chat, history, cursors, concurrency)
r["rss_kb_after_seed"] = rss_after_seed
r["rss_kb_end"] = sample_rss(args)
r["mode"] = label
summaries.append(r)
out = out_dir / ("%s_h%d_c%d.json"
% (label, history, concurrency))
out.write_text(json.dumps(r, indent=2) + "\n")
print(json.dumps({
"mode": r["mode"], "history": r["history"],
"concurrency": r["concurrency"],
"read_rps": r["reads"]["rps"],
"read_p95_ms": r["reads"]["p95_ms"],
"read_p99_ms": r["reads"]["p99_ms"],
"write_rps": r["writes"]["rps"],
"write_p95_ms": r["writes"]["p95_ms"],
"write_p99_ms": r["writes"]["p99_ms"],
"err_ratio": r["error_ratio"],
"rss_kb_end": r["rss_kb_end"],
}))
combined = out_dir / ("%s_summary.json" % label)
combined.write_text(json.dumps(summaries, indent=2) + "\n")
print("combined summary: %s" % combined, file=sys.stderr)
if __name__ == "__main__":
main()
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
BASE_URL="${BASE_URL:-http://localhost:8080}"
PY="${PY:-python3}"
"$PY" student-tests/test_negative.py --base-url "$BASE_URL"
"$PY" student-tests/test_pagination.py --base-url "$BASE_URL"
"$PY" student-tests/test_concurrency.py --base-url "$BASE_URL"
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""100 parallel POSTs from 10 clients -> exactly 100 unique messages."""
import threading
from _bootstrap import TESTS_DIR # noqa: F401
from client import Client, arguments, check, run
def main():
args = arguments('Student concurrency test')
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id']
workers, per_worker = 10, 10
barrier = threading.Barrier(workers)
ids_per_worker = [None] * workers
errors = [None] * workers
def worker(wid):
local = Client(args.base_url, args.ca_file, timeout=20)
barrier.wait()
collected = []
try:
for i in range(per_worker):
m = local.message(alice, chat, 'w%02d-%02d' % (wid, i))['json']
collected.append(m['id'])
except Exception as exc: # noqa: BLE001
errors[wid] = repr(exc)
ids_per_worker[wid] = collected
threads = [threading.Thread(target=worker, args=(i,)) for i in range(workers)]
for t in threads:
t.start()
for t in threads:
t.join()
failures = [e for e in errors if e]
check(not failures, 'worker errors: ' + '; '.join(failures))
all_ids = [mid for chunk in ids_per_worker for mid in chunk]
check(len(all_ids) == workers * per_worker,
'expected %d writes, got %d' % (workers * per_worker, len(all_ids)))
check(len(set(all_ids)) == len(all_ids), 'duplicate message ids returned')
# Read back the entire history
seen = set()
cursor = None
pages = 0
while True:
q = path + '/messages?limit=100'
if cursor:
q += '&cursor=' + cursor
page = c.call('GET', q, actor=bob, schema='MessagePage')['json']
for item in page['items']:
seen.add(item['id'])
pages += 1
if page['next_cursor'] is None or pages > 50:
break
cursor = page['next_cursor']
missing = [mid for mid in all_ids if mid not in seen]
check(not missing, 'history lost %d messages' % len(missing))
print('PASS: 100 messages from 10 clients, all unique and readable')
if __name__ == '__main__':
run(main)
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Negative-path checks: bad JSON, empty/oversized text, foreign chat,
duplicate username, bad auth, invalid limit, extra fields."""
from _bootstrap import TESTS_DIR # noqa: F401 (adds tests/ to sys.path)
import uuid
from client import Client, arguments, run
def main():
args = arguments('Student negative tests')
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id']
# 1. Malformed JSON: the client asserts the server must answer 400.
c.call('POST', '/api/v1/users', 400,
raw=b'{not json',
headers={'Content-Type': 'application/json'})
c.call('POST', path + '/messages', 400, actor=alice,
raw=b'{"text":',
headers={'Content-Type': 'application/json'})
# 2. Empty / whitespace / oversized text.
c.call('POST', path + '/messages', 400, actor=alice, body={'text': ''})
c.call('POST', path + '/messages', 400, actor=alice, body={'text': ' '})
c.call('POST', path + '/messages', 400, actor=alice,
body={'text': 'x' * 4001})
# 3. Foreign chat: eve is not a member.
c.call('GET', path, 404, actor=eve)
c.call('POST', path + '/messages', 404, actor=eve, body={'text': 'hack'})
# 4. Duplicate username.
dup = {'username': 'uniq_' + uuid.uuid4().hex[:8], 'display_name': 'Dup'}
c.call('POST', '/api/v1/users', 201, body=dup)
c.call('POST', '/api/v1/users', 409, body=dup)
# 5. Authentication edge cases.
c.call('GET', '/api/v1/users/me', 401,
headers={'X-User-Id': str(uuid.uuid4())})
c.call('GET', '/api/v1/users/me', 401)
c.call('GET', '/api/v1/users/me', 401,
headers={'X-User-Id': 'not-a-uuid'})
# 6. Invalid limits.
c.call('GET', path + '/messages?limit=0', 400, actor=alice)
c.call('GET', path + '/messages?limit=101', 400, actor=alice)
c.call('GET', path + '/messages?limit=abc', 400, actor=alice)
c.call('GET', path + '/messages?limit=', 400, actor=alice)
# 7. Invalid chat id in path.
c.call('GET', '/api/v1/chats/not-a-uuid', 400, actor=alice)
# 8. Extra fields are rejected (additionalProperties: false).
c.call('POST', '/api/v1/users', 400,
body={'username': 'extra_' + uuid.uuid4().hex[:6],
'display_name': 'X',
'password': 'p'})
c.call('POST', path + '/messages', 400, actor=alice,
body={'text': 'hi', 'sender_id': alice['id']})
print('PASS: student negative tests')
if __name__ == '__main__':
run(main)
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Walk multi-page history, verify no loss/dup/reorder, and limit change."""
import uuid
from _bootstrap import TESTS_DIR # noqa: F401
from client import Client, arguments, check, run, timestamp
def main():
args = arguments('Student pagination tests')
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id']
# Create 25 messages with different Unicode payloads.
created = []
for i in range(25):
created.append(c.message(alice, chat,
'строка-%02d-😀' % i)['json'])
created.sort(key=lambda m: (timestamp(m['created_at']), uuid.UUID(m['id']).int))
# Walk with limit=7
items = []
cursor = None
pages = 0
while True:
q = path + '/messages?limit=7'
if cursor:
from urllib.parse import quote
q += '&cursor=' + quote(cursor, safe='')
page = c.call('GET', q, actor=bob, schema='MessagePage')['json']
items.extend(page['items'])
pages += 1
if page['next_cursor'] is None:
break
cursor = page['next_cursor']
check(pages < 20, 'too many pages')
check(items == created,
'pagination lost/duplicated/reordered messages')
check(pages == 4, 'expected 4 pages, got %d' % pages)
# Change limit on continuation
first = c.call('GET', path + '/messages?limit=3', actor=alice,
schema='MessagePage')['json']
from urllib.parse import quote
second = c.call('GET',
path + '/messages?limit=10&cursor=' + quote(first['next_cursor'], safe=''),
actor=alice, schema='MessagePage')['json']
combined = first['items'] + second['items']
check(combined == created[:13], 'limit change broke the cursor')
# Cursor from another chat must be rejected with 400
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Second', 'member_ids': [alice['id']]},
schema='Chat')['json']
c.call('GET', '/api/v1/chats/%s/messages?limit=1' % other['id'],
actor=alice, schema='MessagePage')
# Take a cursor from the original chat and try it on `other`
fake = c.call('GET', path + '/messages?limit=1', actor=alice,
schema='MessagePage')['json']['next_cursor']
c.call('GET',
'/api/v1/chats/%s/messages?limit=1&cursor=%s' % (other['id'], fake),
400, actor=alice)
print('PASS: student pagination tests (4 pages, no loss, cursor scoped)')
if __name__ == '__main__':
run(main)
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""SIGTERM must stop the container in <= 10s and refuse new requests."""
import argparse
import os
import subprocess
import sys
import time
import urllib.error
import urllib.request
def _http_ok(url):
try:
with urllib.request.urlopen(url, timeout=2) as resp:
return 200 <= resp.status < 300
except Exception: # noqa: BLE001
return False
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--container', default=os.environ.get('CONTAINER', 'mtusi-messenger-lab1'))
ap.add_argument('--base-url', default=os.environ.get('BASE_URL', 'http://localhost:8080'))
args = ap.parse_args()
if not _http_ok(args.base_url + '/health/live'):
print('FAIL: server is not alive before SIGTERM')
return 1
start = time.monotonic()
subprocess.run(['docker', 'kill', '--signal', 'SIGTERM', args.container],
check=True)
deadline = start + 12
while time.monotonic() < deadline:
state = subprocess.run(
['docker', 'inspect', '-f', '{{.State.Running}}', args.container],
capture_output=True, text=True).stdout.strip()
if state == 'false':
break
time.sleep(0.15)
else:
print('FAIL: container did not stop within 12 s')
return 1
elapsed = time.monotonic() - start
if elapsed > 10.0:
print('FAIL: SIGTERM took %.2f s (>10)' % elapsed)
return 1
if _http_ok(args.base_url + '/health/live'):
print('FAIL: server still accepts requests after SIGTERM')
return 1
print('PASS: SIGTERM stopped container in %.2f s; port refused afterwards'
% elapsed)
return 0
if __name__ == '__main__':
sys.exit(main())
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env python3
"""Verify that user, session and message survive a full service restart."""
import os
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
import urllib.request
import urllib.error
import json
import base64
def http(method, url, body=None, headers=None, expect=None):
h = {"Accept": "application/json"}
if headers:
h.update(headers)
raw = None
if body is not None:
raw = json.dumps(body, ensure_ascii=False).encode("utf-8")
h["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=raw, headers=h, method=method)
try:
resp = urllib.request.urlopen(req, timeout=10)
except urllib.error.HTTPError as e:
resp = e
data = resp.read()
if expect is not None:
assert resp.status == expect, f"{method} {url}: got {resp.status}, want {expect}"
return resp.status, json.loads(data) if data else None
def wait_ready(base, timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
s, _ = http("GET", base + "/health/ready")
if s == 200:
return
except Exception:
pass
time.sleep(1)
raise SystemExit("ready timeout")
def main():
base = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
action = os.environ.get("ACTION_SCRIPT")
if not action:
print("FAIL: ACTION_SCRIPT not set")
sys.exit(1)
u = "persist_" + uuid.uuid4().hex[:8]
pwd = "SuperSecretPassword123"
s, user = http("POST", base + "/api/v1/users",
body={"username": u, "display_name": "P", "password": pwd},
expect=201)
alice_id = user["id"]
cred = base64.b64encode(f"{u}:{pwd}".encode()).decode()
s, sess = http("POST", base + "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + cred}, expect=201)
token = sess["token"]
s, chat = http("POST", base + "/api/v1/chats",
body={"title": "P", "member_ids": [alice_id]},
headers={"Authorization": "Bearer " + token}, expect=201)
s, msg = http("POST", base + f"/api/v1/chats/{chat['id']}/messages",
body={"text": "persist"},
headers={"Authorization": "Bearer " + token}, expect=201)
print(f"created user={alice_id} msg={msg['id']}", file=sys.stderr)
print(f"running action: {action}", file=sys.stderr)
subprocess.run(action, shell=True, check=True)
wait_ready(base)
s, me = http("GET", base + "/api/v1/users/me",
headers={"Authorization": "Bearer " + token}, expect=200)
assert me["id"] == alice_id, "user id changed"
s, hist = http("GET", base + f"/api/v1/chats/{chat['id']}/messages?limit=10",
headers={"Authorization": "Bearer " + token}, expect=200)
assert any(m["id"] == msg["id"] for m in hist["items"]), "message lost"
print("PASS: persistence verified")
if __name__ == "__main__":
main()