Files
mtusi2026lab6/student-tests/traffic.py
T
2026-11-01 20:38:50 +03:00

74 lines
3.4 KiB
Python

"""lab6: фоновая нагрузка для инцидентов — несколько потоков пишут сообщения (и по желанию грузят картинки).
Нагрузка честная для наблюдения: ошибки не повторяются прозрачно, каждый ответ (код или таймаут)
считается. Токены живут только в памяти и не печатаются.
"""
import json
import threading
import time
import urllib.error
import urllib.request
import uuid
from collections import Counter
from helpers import ROOT, Client
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
class Traffic:
def __init__(self, api: Client, actor: dict, chat: dict, threads: int = 3, pause: float = 0.2,
uploads_every: float = 0.0, timeout: float = 15.0):
self.base, self.token, self.chat = api.base, actor["token"], chat["id"]
self.threads, self.pause, self.uploads_every, self.timeout = threads, pause, uploads_every, timeout
self.stop_event = threading.Event()
self.lock = threading.Lock()
self.codes = Counter()
self.uploads = [] # (attachment_id, X-Request-Id)
self._workers = []
def _request(self, method, path, data, headers):
headers = dict(headers, Authorization="Bearer " + self.token)
request = urllib.request.Request(self.base + path, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(request, timeout=self.timeout) as response:
return response.status, response.read(), response.headers
except urllib.error.HTTPError as exc:
return exc.code, exc.read(), exc.headers
except (urllib.error.URLError, TimeoutError, OSError):
return "timeout", b"", {}
def _loop(self, number):
last_upload = time.monotonic()
while not self.stop_event.is_set():
body = json.dumps({"text": f"нагрузка {number} {uuid.uuid4().hex[:6]}"}).encode()
status, _, _ = self._request("POST", f"/api/v1/chats/{self.chat}/messages", body,
{"Content-Type": "application/json", "Idempotency-Key": uuid.uuid4().hex})
with self.lock:
self.codes[str(status)] += 1
if number == 0 and self.uploads_every and time.monotonic() - last_upload >= self.uploads_every:
last_upload = time.monotonic()
status, raw, headers = self._request("POST", f"/api/v1/chats/{self.chat}/attachments?filename=load.png",
SAMPLE, {"Content-Type": "image/png"})
with self.lock:
self.codes["upload " + str(status)] += 1
if status == 202:
self.uploads.append((json.loads(raw)["id"], headers.get("X-Request-Id")))
self.stop_event.wait(self.pause)
def start(self):
for number in range(self.threads):
thread = threading.Thread(target=self._loop, args=(number,), daemon=True)
thread.start()
self._workers.append(thread)
return self
def stop(self):
self.stop_event.set()
for thread in self._workers:
thread.join(timeout=self.timeout + 5)
def snapshot(self) -> dict:
with self.lock:
return dict(self.codes)