+ скопировала все файлы проекта из л.р. 1
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Единая команда запуска собственных тестов.
|
||||
Запускает: test_negative.py, test_concurrency.py.
|
||||
Публичный smoke запускается отдельно."""
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def run_one(script, base_url):
|
||||
print("=== %s ===" % script.name)
|
||||
proc = subprocess.run(
|
||||
[sys.executable, str(script), "--base-url", base_url],
|
||||
cwd=str(HERE),
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
print("FAIL: %s" % script.name)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
p = argparse.ArgumentParser(description="Lab1 student tests (level 4)")
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = p.parse_args()
|
||||
|
||||
ok = True
|
||||
for script in ("test_negative.py", "test_concurrency.py"):
|
||||
if not run_one(HERE / script, args.base_url):
|
||||
ok = False
|
||||
if not ok:
|
||||
raise SystemExit(1)
|
||||
print("PASS: all student tests (level 4) passed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Конкурентный тест: 100 сообщений от 10 клиентов -> ровно 100 уникальных.
|
||||
Проверяет защиту in-memory структур от гонок (RLock)."""
|
||||
import sys
|
||||
import threading
|
||||
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, arguments, check, run # noqa: E402
|
||||
|
||||
TOTAL_MESSAGES = 100
|
||||
CLIENTS = 10
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Lab1 concurrency safety")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"]
|
||||
|
||||
# Каждый «клиент» — свой actor (alice/bob) для реалистичной конкуренции
|
||||
actors = [alice, bob]
|
||||
barrier = threading.Barrier(CLIENTS)
|
||||
|
||||
def worker(worker_id):
|
||||
local = Client(args.base_url, args.ca_file, timeout=15)
|
||||
actor = actors[worker_id % len(actors)]
|
||||
barrier.wait() # синхронный старт всех потоков
|
||||
produced = []
|
||||
for i in range(TOTAL_MESSAGES // CLIENTS):
|
||||
text = "c-%02d-%02d-%s" % (worker_id, i, uuid.uuid4().hex[:8])
|
||||
msg = local.message(actor, chat, text)["json"]
|
||||
produced.append(msg)
|
||||
return produced
|
||||
|
||||
with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
|
||||
results = list(pool.map(worker, range(CLIENTS)))
|
||||
|
||||
all_ids = [m["id"] for chunk in results for m in chunk]
|
||||
check(len(all_ids) == TOTAL_MESSAGES,
|
||||
"expected %d message ids, got %d" % (TOTAL_MESSAGES, len(all_ids)))
|
||||
check(len(set(all_ids)) == TOTAL_MESSAGES,
|
||||
"duplicate message ids under concurrency: %d unique" % len(set(all_ids)))
|
||||
|
||||
# Читаем всю историю через пагинацию
|
||||
collected = []
|
||||
cursor = None
|
||||
from urllib.parse import quote
|
||||
for _ in range(50):
|
||||
q = path + "/messages?limit=100"
|
||||
if cursor:
|
||||
q += "&cursor=" + quote(cursor, safe="")
|
||||
page = c.call("GET", q, actor=alice, schema="MessagePage")["json"]
|
||||
collected.extend(m["id"] for m in page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
check(len(collected) == TOTAL_MESSAGES,
|
||||
"stored messages: %d, expected %d" % (len(collected), TOTAL_MESSAGES))
|
||||
check(len(set(collected)) == TOTAL_MESSAGES,
|
||||
"stored messages contain duplicates: %d unique" % len(set(collected)))
|
||||
|
||||
print("PASS: lab1 concurrency: %d messages from %d clients, "
|
||||
"%d unique stored and readable" % (TOTAL_MESSAGES, CLIENTS, len(set(collected))))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Негативные сценарии lab1: неверный JSON, чужой чат, пустое сообщение,
|
||||
дубликат username, обход нескольких страниц. Stdlib only, Python 3.9+."""
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
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
|
||||
|
||||
|
||||
def _raw_call(base_url, method, path, body=None, headers=None):
|
||||
"""Сырой запрос для проверки malformed JSON (client.py всегда сериализует)."""
|
||||
url = base_url.rstrip("/") + path
|
||||
data = body if isinstance(body, (bytes, type(None))) else body.encode("utf-8")
|
||||
req = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
return resp.status, resp.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read()
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Lab1 negative scenarios")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"]
|
||||
|
||||
# 1. Дубликат username -> 409
|
||||
c.call("POST", "/api/v1/users", 409, body=alice["registration"])
|
||||
|
||||
# 2. Неверный JSON (malformed) -> 400
|
||||
status, _ = _raw_call(
|
||||
c.base,
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
body=b"{not json at all",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
check(status == 400, "malformed JSON must be 400, got %s" % status)
|
||||
|
||||
# 3. Лишние поля -> 400
|
||||
c.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
400,
|
||||
body={"username": "extra_user_x", "display_name": "X", "unexpected": True},
|
||||
)
|
||||
|
||||
# 4. Неверный тип -> 400
|
||||
c.call("POST", "/api/v1/users", 400, body={"username": 123, "display_name": "X"})
|
||||
|
||||
# 5. Пустое / пробельное сообщение -> 400
|
||||
c.call("POST", path + "/messages", 400, actor=alice, body={"text": ""})
|
||||
c.call("POST", path + "/messages", 400, actor=alice, body={"text": " "})
|
||||
|
||||
# 6. Чужой чат -> 404 (не 403)
|
||||
c.call("GET", path, 404, actor=eve)
|
||||
c.call("GET", path + "/messages", 404, actor=eve)
|
||||
c.call("POST", path + "/messages", 404, actor=eve, body={"text": "чужое"})
|
||||
|
||||
# 7. Пагинация: обход нескольких страниц без потерь и дублей
|
||||
texts = ["p-%02d" % i for i in range(7)]
|
||||
for t in texts:
|
||||
c.message(alice, chat, t)
|
||||
collected = []
|
||||
cursor = None
|
||||
seen_cursors = set()
|
||||
for _ in range(20): # предохранитель от бесконечного цикла
|
||||
q = path + "/messages?limit=2"
|
||||
if cursor:
|
||||
from urllib.parse import quote
|
||||
q += "&cursor=" + quote(cursor, safe="")
|
||||
page = c.call("GET", q, actor=bob, schema="MessagePage")["json"]
|
||||
collected.extend(m["text"] for m in page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
check(cursor not in seen_cursors, "cursor loop detected")
|
||||
seen_cursors.add(cursor)
|
||||
check(len(collected) == len(texts), "pagination lost messages: %d != %d" % (len(collected), len(texts)))
|
||||
check(len(set(collected)) == len(collected), "pagination duplicated messages")
|
||||
check(collected == texts, "pagination order/contents mismatch")
|
||||
|
||||
# 8. Некорректный limit -> 400
|
||||
c.call("GET", path + "/messages?limit=0", 400, actor=alice)
|
||||
c.call("GET", path + "/messages?limit=101", 400, actor=alice)
|
||||
|
||||
# 9. Неизвестный X-User-Id -> 401
|
||||
c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": str(uuid.uuid4())})
|
||||
|
||||
print("PASS: lab1 negative scenarios (dup, malformed JSON, extra fields, "
|
||||
"wrong type, empty text, foreign chat, pagination, bad limit, unknown user)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user