+ скопировала все файлы проекта из л.р. 1
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 1 (оценка 5). Предел in-memory архитектуры.
|
||||
|
||||
Гипотеза: на больших историях список сообщений при чтении каждый раз
|
||||
копируется и сортируется под RLock, что ухудшает p95/p99 при росте
|
||||
истории. Убираем сортировку на чтении (append сохраняет порядок) и
|
||||
сравниваем "до/после" при тех же лимитах.
|
||||
|
||||
Эксперимент: >=3 размера истории (H) x >=3 уровня конкуренции (C).
|
||||
Метрики: successful RPS, доля ошибок, p50/p95/p99 только успешных
|
||||
запросов, RSS процесса API (читается через docker stats или /proc).
|
||||
|
||||
Скрипт не меняет API; использует те же публичные клиенты из tests/.
|
||||
Stdlib only, Python 3.9+.
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
|
||||
|
||||
# --- профиль эксперимента -------------------------------------------------
|
||||
HISTORY_SIZES = [100, 1000, 5000] # >=3 размера истории
|
||||
CONCURRENCY_LEVELS = [1, 4, 16] # >=3 уровня конкуренции
|
||||
DURATION_SECONDS = 10 # на каждую точку (H, C)
|
||||
API_CONTAINER = "mtusi-messenger-lab1" # имя контейнера для docker stats
|
||||
|
||||
|
||||
def rss_mb(container: str):
|
||||
"""RSS процесса API в МБ через docker stats --no-stream."""
|
||||
try:
|
||||
out = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", container],
|
||||
capture_output=True, text=True, timeout=10,
|
||||
)
|
||||
if out.returncode != 0:
|
||||
return None
|
||||
# Пример: "120.5MiB / 1GiB"
|
||||
used = out.stdout.strip().split("/")[0].strip()
|
||||
if used.endswith("MiB"):
|
||||
return round(float(used[:-3]), 2)
|
||||
if used.endswith("GiB"):
|
||||
return round(float(used[:-3]) * 1024, 2)
|
||||
if used.endswith("KiB"):
|
||||
return round(float(used[:-3]) / 1024, 2)
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def seed_history(c, actor, chat, count, workers=16):
|
||||
"""Заполняет историю до count сообщений параллельно."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
def one(i):
|
||||
local = Client(c.base, timeout=15)
|
||||
local.message(actor, chat, "seed-%06d-%s" % (i, uuid.uuid4().hex[:6]))
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
list(pool.map(one, range(count)))
|
||||
|
||||
|
||||
def measure_read_point(c, chat, actor, duration, concurrency):
|
||||
"""Закрытый контур: параллельно читаем GET /messages?limit=100."""
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
||||
barrier = threading.Barrier(concurrency)
|
||||
latencies, errors = [], 0
|
||||
errors_lock = threading.Lock()
|
||||
|
||||
def worker(_):
|
||||
nonlocal errors
|
||||
local = Client(c.base, timeout=15)
|
||||
barrier.wait()
|
||||
deadline = time.monotonic() + duration
|
||||
local_lat = []
|
||||
while time.monotonic() < deadline:
|
||||
start = time.monotonic()
|
||||
try:
|
||||
local.call("GET", path, actor=actor, schema="MessagePage")
|
||||
local_lat.append(time.monotonic() - start)
|
||||
except Failure:
|
||||
with errors_lock:
|
||||
errors += 1
|
||||
return local_lat
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
results = list(pool.map(worker, range(concurrency)))
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
for chunk in results:
|
||||
latencies.extend(chunk)
|
||||
latencies.sort()
|
||||
|
||||
def pct(p):
|
||||
if not latencies:
|
||||
return None
|
||||
return round(1000 * latencies[max(0, math.ceil(p * len(latencies)) - 1)], 3)
|
||||
|
||||
total = len(latencies) + errors
|
||||
return {
|
||||
"history_size": None, # заполнит вызывающий
|
||||
"concurrency": concurrency,
|
||||
"duration_s": round(elapsed, 3),
|
||||
"successful": len(latencies),
|
||||
"errors": errors,
|
||||
"error_ratio": round(errors / total, 6) if total else None,
|
||||
"rps": round(len(latencies) / elapsed, 3),
|
||||
"latency_ms": {"p50": pct(.50), "p95": pct(.95), "p99": pct(.99)},
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Трек 1: предел in-memory архитектуры")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
|
||||
report = {"lab": 1, "track": 1, "profile": {
|
||||
"history_sizes": HISTORY_SIZES,
|
||||
"concurrency_levels": CONCURRENCY_LEVELS,
|
||||
"duration_seconds": DURATION_SECONDS,
|
||||
"note": "closed-loop; клиент ограничивает throughput; RSS — docker stats",
|
||||
}, "points": []}
|
||||
|
||||
for h in HISTORY_SIZES:
|
||||
# Досеиваем историю до h (bootstrap уже создал часть).
|
||||
# Считаем число сообщений в истории.
|
||||
# Предыдущая версия: limit=1 - возвращает только одну страницу и далее считает её длину страницы за длину всей истории,
|
||||
# Текущая версия: limit=100 - делаем полный обход истории по курсору => реальное число сообщений
|
||||
have = 0
|
||||
cursor = None
|
||||
from urllib.parse import quote
|
||||
while True:
|
||||
q = path + "?limit=100"
|
||||
if cursor:
|
||||
q += "&cursor=" + quote(cursor, safe="")
|
||||
page = c.call("GET", q, actor=alice, schema="MessagePage")["json"]
|
||||
have += len(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
if have < h:
|
||||
seed_history(c, alice, chat, h - have)
|
||||
|
||||
for con in CONCURRENCY_LEVELS:
|
||||
point = measure_read_point(c, chat, alice, DURATION_SECONDS, con)
|
||||
point["history_size"] = h
|
||||
point["rss_mb"] = rss_mb(API_CONTAINER)
|
||||
report["points"].append(point)
|
||||
print(json.dumps(point, ensure_ascii=False))
|
||||
|
||||
out = Path("evidence/lab1_track1_load.json")
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
print("PASS: track1 load matrix saved to", out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Дополнительный CLI: --container для имени Docker-контейнера.
|
||||
import argparse
|
||||
p = argparse.ArgumentParser(add_help=False)
|
||||
p.add_argument("--container", default=API_CONTAINER)
|
||||
extra, _ = p.parse_known_args()
|
||||
# Прокидываем в namespace аргументов arguments() через env-подобный трюк.
|
||||
sys.argv = [a for a in sys.argv if not a.startswith("--container")]
|
||||
import os
|
||||
os.environ.setdefault("TRACK1_CONTAINER", extra.container)
|
||||
|
||||
def _bind_container(ns):
|
||||
ns.container = os.environ.get("TRACK1_CONTAINER", API_CONTAINER)
|
||||
return ns
|
||||
|
||||
# Патчим arguments, чтобы добавить --container.
|
||||
import client as _client # noqa: E402
|
||||
_orig_arguments = _client.arguments
|
||||
|
||||
def _arguments(description, configure=None):
|
||||
def cfg(parser):
|
||||
if configure:
|
||||
configure(parser)
|
||||
parser.add_argument("--container", default=API_CONTAINER)
|
||||
return _orig_arguments(description, cfg)
|
||||
|
||||
_client.arguments = _arguments
|
||||
run(main)
|
||||
Reference in New Issue
Block a user