#!/usr/bin/env python3 """LAB 6: генератор нагрузки для демо и защиты. Только stdlib. Создаёт пользователей и чаты, шлёт сообщения (Idempotency-Key обязателен по контракту lab3), опционально загружает вложения (202) и ждёт ready. Печатает сводку: запросы, коды ответов, RPS, p50/p95/p99. """ import argparse import base64 import json import threading import time import uuid import urllib.request import urllib.error from concurrent.futures import ThreadPoolExecutor PNG = base64.b64decode( "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJg==" ) _lock = threading.Lock() _lat = [] _codes = {} def call(base, method, path, token=None, basic=None, obj=None, raw=None, ctype=None, idem=None): headers = {} data = None if obj is not None: data = json.dumps(obj).encode() headers["Content-Type"] = "application/json" if raw is not None: data = raw headers["Content-Type"] = ctype or "application/octet-stream" if token: headers["Authorization"] = "Bearer " + token if basic: import base64 as b64 pair = f"{basic[0]}:{basic[1]}".encode() headers["Authorization"] = "Basic " + b64.b64encode(pair).decode() if idem: headers["Idempotency-Key"] = idem req = urllib.request.Request(base + path, data=data, headers=headers, method=method) t0 = time.perf_counter() try: with urllib.request.urlopen(req, timeout=30) as r: status, body = r.status, r.read() except urllib.error.HTTPError as e: status, body = e.code, e.read() dt = time.perf_counter() - t0 with _lock: _lat.append(dt) _codes[status] = _codes.get(status, 0) + 1 return status, body def jbody(b): try: return json.loads(b) except Exception: return {} def pct(v, p): if not v: return 0.0 v = sorted(v) k = max(0, min(len(v) - 1, int(round(p * (len(v) - 1))))) return v[k] def main(): ap = argparse.ArgumentParser() ap.add_argument("--base", default="http://localhost:8080") ap.add_argument("--users", type=int, default=2) ap.add_argument("--messages", type=int, default=30) ap.add_argument("--attachments", type=int, default=1) ap.add_argument("--concurrency", type=int, default=8) ap.add_argument("--poll-ready", action="store_true") a = ap.parse_args() t0 = time.perf_counter() jobs = [] for u in range(a.users): name = f"load{int(time.time())}-{u}" st, _ = call(a.base, "POST", "/api/v1/users", obj={"username": name, "display_name": name, "password": "load-pass-1"}) if st not in (201, 409): print(f"[skip] register {st}") continue st, b = call(a.base, "POST", "/api/v1/auth/sessions", basic=(name, "load-pass-1")) tok = jbody(b).get("token") if not tok: print(f"[skip] login {st}") continue st, b = call(a.base, "POST", "/api/v1/chats", token=tok, obj={"title": f"load chat {u}", "member_ids": []}) chat = jbody(b).get("id") if not chat: st, b = call(a.base, "POST", "/api/v1/chats", token=tok, obj={"title": f"load chat {u}"}) chat = jbody(b).get("id") if not chat: print(f"[skip] chat {st}") continue with ThreadPoolExecutor(a.concurrency) as ex: futs = [ex.submit(call, a.base, "POST", f"/api/v1/chats/{chat}/messages", token=tok, obj={"text": f"load msg {i}", "attachment_ids": []}, idem=str(uuid.uuid4())) for i in range(a.messages)] for f in futs: f.result() for _ in range(a.attachments): st, b = call(a.base, "POST", f"/api/v1/chats/{chat}/attachments", token=tok, raw=PNG, ctype="image/png") att = jbody(b).get("id") if att and a.poll_ready: jobs.append((tok, att)) def poll(job): tok, att = job deadline = time.time() + 60 while time.time() < deadline: st, b = call(a.base, "GET", f"/api/v1/attachments/{att}", token=tok) if jbody(b).get("status") == "ready": return True time.sleep(1) return False if jobs: with ThreadPoolExecutor(max(1, len(jobs))) as ex: oks = list(ex.map(poll, jobs)) print(f"attachments ready: {sum(oks)}/{len(jobs)}") dur = time.perf_counter() - t0 with _lock: lat, codes = list(_lat), dict(_codes) total = len(lat) print(f"requests={total} wall={dur:.1f}s rps={total / dur:.1f}") print("status_codes=", codes) print(f"latency_ms p50={pct(lat, .5) * 1000:.1f} p95={pct(lat, .95) * 1000:.1f} p99={pct(lat, .99) * 1000:.1f}") if __name__ == "__main__": main()