lab3: выполнение и доказательтсва

This commit is contained in:
kalibr456
2026-10-14 20:29:41 +03:00
parent 0ab3a341aa
commit 3410871c41
66 changed files with 4266 additions and 17 deletions
+72
View File
@@ -0,0 +1,72 @@
import json
import platform
import sys
from common import call, check, compose_output, docker, new_user, seen_instances
def main():
info = json.loads(docker("info", "--format", "{{json .}}"))
print(f"host: {platform.system()} {platform.release()}, {platform.processor() or platform.machine()}; "
f"client Python {platform.python_version()}")
print(f"Docker {docker('version', '--format', '{{.Server.Version}}')}, "
f"{compose_output('version').strip()}; Docker VM: {info.get('NCPU')} CPU, "
f"{int(info.get('MemTotal', 0)) / 2**30:.1f} GiB RAM, {info.get('OperatingSystem')}")
print()
print(compose_output("ps", "-a", "--format", "table {{.Service}}\t{{.ID}}\t{{.Status}}\t{{.Ports}}").strip())
migrate = compose_output("ps", "-a", "--format", "{{.Status}}", "migrate").strip()
check(migrate.startswith("Exited (0)"), "migrate service must finish with exit code 0")
config = json.loads(compose_output("config", "--format", "json"))
services = config["services"]
containers = compose_output("ps", "-q").split()
rows = [json.loads(line) for line in docker("inspect", "--format", "{{json .}}", *containers).splitlines()]
print()
print("container image cpus memory host ports networks")
api_count = 0
for row in sorted(rows, key=lambda r: r["Name"]):
labels = row["Config"]["Labels"]
service = labels.get("com.docker.compose.service")
limits = row["HostConfig"]
cpus = limits.get("NanoCpus", 0) / 1e9
memory = limits.get("Memory", 0) // 2**20
ports = sorted({f"{b['HostIp']}:{b['HostPort']}" for bindings in (row["NetworkSettings"]["Ports"] or {}).values()
for b in (bindings or [])})
networks = sorted(name.split("_", 1)[-1] for name in row["NetworkSettings"]["Networks"])
print(f"{row['Name'].lstrip('/'):<28} {row['Config']['Image']:<24} {cpus:>4.2f} {memory:>4} MiB "
f"{','.join(ports) or '-':<23} {','.join(networks)}")
check(cpus > 0 and memory > 0, f"{service}: no CPU/RAM limit")
if service == "api":
api_count += 1
check(not ports, "api must not publish ports: everything goes through the balancer")
if service == "lb":
check(ports and all(p.startswith("127.0.0.1:") for p in ports), "lb must listen on 127.0.0.1 only")
if service in ("postgres", "redis"):
check(not ports and networks == ["data"], f"{service} must be only in the internal data network")
check(api_count >= 2, "need at least 2 api replicas")
check(all("container_name" not in s for s in services.values()), "container_name prevents scaling")
check(config["networks"]["data"].get("internal") is True, "data network must be internal")
check("data" not in services["lb"]["networks"], "lb must not reach postgres/redis")
print()
for name, service in sorted(services.items()):
secrets = sorted(s["source"] for s in service.get("secrets", []))
print(f"secrets of {name}: {secrets or '-'}")
check(not services["lb"].get("secrets"), "lb gets no secrets")
check(sorted(s["source"] for s in services["migrate"]["secrets"]) == ["database_url"], "migrate needs only database_url")
user = new_user("stack")
served = seen_instances(user["token"])
print()
print(f"through http://127.0.0.1:8080 one session is served by {len(served)} replicas: {sorted(served)}")
check(len(served) >= 2, "requests are not balanced")
health = call("GET", "/health/ready", 200)
print(f"/health/ready -> {health.status} from {health.instance}")
print(f"PASS: {api_count} api replicas behind one entry point, no direct API ports, limits on every "
f"container, internal data network, secrets only where needed")
if __name__ == "__main__":
sys.exit(main())
+243
View File
@@ -0,0 +1,243 @@
import json
import os
import platform
import re
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / "evidence"
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
PY = sys.executable
STEPS = [
("check", "offline contract check (make check)", [PY, "scripts/check_contract.py"]),
("stack", "stand layout: replicas, ports, limits, networks, secrets", [PY, "student-tests/check_stack.py"]),
("smoke", "public smoke via the balancer (make test)", [PY, "tests/smoke.py", "--base-url", BASE_URL]),
("balancing", "balancing, shared sessions and data, X-Instance-Id", [PY, "student-tests/test_balancing.py"]),
("idempotency", "Idempotency-Key, parallel same key via replicas", [PY, "student-tests/test_idempotency.py"]),
("student-tests", "lab1/lab2 API tests via the balancer", [PY, "student-tests/test_api.py"]),
("race", "lab2 races via the balancer", [PY, "student-tests/test_race.py"]),
("db", "PostgreSQL: rollback, FK, Argon2id, unique keys, migrations", [PY, "student-tests/test_db.py"]),
("redis", "Redis as the session store", [PY, "student-tests/redis_info.py"]),
("explain", "EXPLAIN of the history page (full plans: explain-history.txt)", [PY, "student-tests/explain.py"]),
("failover", "public failover test for every replica (make test-failover)", [PY, "student-tests/run_failover.py"]),
("failover-metrics", "stop/kill every replica under load, metrics", [PY, "student-tests/failover_metrics.py"]),
("load", "public load generator, 30 s, concurrency 4", [PY, "tests/load.py", "--base-url", BASE_URL,
"--duration", "30", "--concurrency", "4",
"--output", "evidence/load.json"]),
("expiry", "session TTL=2 s, then normal TTL", [PY, "student-tests/test_expiry.py"]),
("failures", "Redis and PostgreSQL outages via the balancer", [PY, "student-tests/test_failures.py"]),
("persistence", "public persistence test + proof of real restarts (make test-persistence)",
[PY, "student-tests/run_persistence.py"]),
("rolling-update", "rolling update under load", [PY, "student-tests/rolling_update.py"]),
]
def git(*args):
try:
return subprocess.run(["git", *args], cwd=ROOT, capture_output=True, text=True, check=True).stdout.strip()
except (OSError, subprocess.CalledProcessError):
return ""
def commit():
head = git("rev-parse", "--short", "HEAD") or "unknown"
changed = [line for line in git("status", "--porcelain").splitlines()
if not line[3:].startswith(("evidence/", "REPORT.md"))]
return head + (" + uncommitted changes" if changed else "")
def run_step(name, description, command):
env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8", BASE_URL=BASE_URL)
print(f"=== {name}: {description}", flush=True)
started = time.monotonic()
result = subprocess.run(command, cwd=ROOT, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
seconds = time.monotonic() - started
output = result.stdout.decode("utf-8", "replace").replace("\r\n", "\n")
shown = " ".join(Path(part).name if part == PY else part for part in command)
header = (f"# {name}: {description}\n# date: {time.strftime('%Y-%m-%d %H:%M:%S')}, commit: {commit()}\n"
f"# command: {shown}\n# exit code: {result.returncode}, {seconds:.1f} s\n\n")
(EVIDENCE / f"{name}.txt").write_text(header + output, encoding="utf-8")
tail = [line for line in output.splitlines() if line.strip()][-3:]
for line in tail:
print(" " + line)
print(f" -> {'PASS' if result.returncode == 0 else 'FAIL'} ({seconds:.0f} s), evidence/{name}.txt", flush=True)
return result.returncode == 0, seconds
def load_json(name):
path = EVIDENCE / name
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else None
def measurements():
"""Markdown-таблицы замеров из evidence/*.json и evidence/*.txt (для REPORT.md и summary.md)."""
lines = []
try:
info = json.loads(subprocess.run(["docker", "info", "--format", "{{json .}}"], capture_output=True,
text=True, check=True).stdout)
docker_vm = f"{info.get('NCPU')} CPU, {int(info.get('MemTotal', 0)) / 2**30:.1f} GiB RAM"
except (OSError, ValueError, subprocess.CalledProcessError):
docker_vm = "unknown"
lines.append(f"Машина: {platform.system()} {platform.release()}, {platform.processor() or platform.machine()}; "
f"Docker VM: {docker_vm}; клиент Python {platform.python_version()}; дата прогона "
f"{time.strftime('%Y-%m-%d')}, commit {commit()}. Лимиты контейнеров: api 1 CPU / 512 MiB "
f"каждая, postgres 1 CPU / 512 MiB, redis и lb по 0,5 CPU / 128 MiB.")
lines.append("")
failover = EVIDENCE / "failover.txt"
results = []
if failover.exists():
text = failover.read_text(encoding="utf-8")
stopped = re.findall(r"the hook stopped (\w+)", text)
results = [json.loads(m) for m in re.findall(r"^(\{\"observed_instances_before\".*\})$", text, re.M)]
if results:
lines.append("Публичный тест отказа (`make test-failover`, 15 с записи во время остановки реплики):")
lines.append("")
lines.append("| Прогон | Остановлена реплика | Реплик до отказа | Успешных записей | Неудачных попыток "
"(повторены с тем же ключом) | Первая запись после hook, с |")
lines.append("| --- | --- | --- | --- | --- | --- |")
for number, (result, container) in enumerate(zip(results, stopped), start=1):
lines.append(f"| {number} | {container} | {result['observed_instances_before']} | "
f"{result['successful_writes']} | {result['failed_attempts']} | "
f"{result['first_recovery_seconds']} |")
lines.append("")
metrics = load_json("failover-metrics.json")
if metrics:
lines.append("Остановка каждой реплики под нагрузкой (`student-tests/failover_metrics.py`: 4 потока записи "
"без пауз + 1 поток чтения, timeout клиента 2 с, 3 с до и 10 с после отказа):")
lines.append("")
lines.append("| Реплика | Как остановлена | Команда, с | HAProxy вывел из балансировки через, с | Ошибок "
"(коды) | Ошибки прекратились через, с | Записей/с до | Записей/с после | p95 после, мс | "
"Вернулась в балансировку после docker start, с |")
lines.append("| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |")
for r in metrics["runs"]:
how = "docker stop (SIGTERM)" if r["mode"] == "stop" else "docker kill (SIGKILL)"
codes = ", ".join(f"{k}: {v}" for k, v in r["error_codes"].items()) or "-"
lines.append(f"| {r['replica']} | {how} | {r['command_seconds']} | {r['lb_excluded_after_seconds']} | "
f"{r['errors']} ({codes}) | {r['errors_stopped_after_seconds']} | {r['before']['write_rps']} | "
f"{r['after']['write_rps']} | {r['after']['write_p95_ms']} | {r['rejoin_seconds']} |")
lines.append("")
lines.append("Во всех прогонах: потерянных подтверждённых сообщений 0, дублей 0, остановленная реплика "
"после остановки не ответила ни разу.")
lines.append("")
rolling = load_json("rolling-update.json")
if rolling:
during = rolling["during"]
codes = ", ".join(f"{k}: {v}" for k, v in during["error_codes"].items()) or "-"
lines.append(f"Rolling update (`student-tests/rolling_update.py`): версия {rolling['from_version']} -> "
f"{rolling['to_version']}, {rolling['replicas']} реплики заменены по одной за "
f"{rolling['update_seconds']} с под той же нагрузкой. Записей/с до: {rolling['before']['write_rps']}, "
f"во время замены: {during['write_rps']}; ошибок: {during['errors']} ({codes}); "
f"p95 {during['write_p95_ms']} мс, максимум {during['write_max_ms']} мс; подтверждено "
f"{rolling['integrity']['confirmed_writes']} сообщений, потерь и дублей нет.")
lines.append("")
load = load_json("load.json")
if load:
latency = load["successful_latency_ms"]
lines.append(f"Публичный генератор нагрузки (`tests/load.py`, closed loop, concurrency {load['concurrency']}, "
f"{load['requested_duration_seconds']:.0f} с, 2 реплики): {load['successful_rps']} успешных "
f"POST/с, ошибок {load['failed_requests']} (доля {load['error_ratio']}), задержка успешных "
f"p50 {latency['p50']} мс, p95 {latency['p95']} мс, p99 {latency['p99']} мс.")
lines.append("")
persistence = EVIDENCE / "persistence.txt"
restart_seconds = None
if persistence.exists():
found = re.search(r"took ([\d.]+) s", persistence.read_text(encoding="utf-8"))
restart_seconds = found.group(1) if found else None
impacts = []
if metrics:
for mode, what, expected in (
("stop", "`docker stop` реплики (SIGTERM) под нагрузкой",
"ошибок нет: реплика сначала уходит из балансировки (readiness 503), потом закрывает приём"),
("kill", "`docker kill` реплики (SIGKILL, авария) под нагрузкой",
"единицы 502 на запросы, начатые на убитой реплике; клиент повторяет их с тем же ключом")):
runs = [r for r in metrics["runs"] if r["mode"] == mode]
if runs:
impacts.append(
f"| {what} | {expected} | ошибок: {', '.join(str(r['errors']) for r in runs)} (по репликам); "
f"HAProxy вывел реплику через {', '.join(str(r['lb_excluded_after_seconds']) for r in runs)} с | "
f"ошибки прекратились через {max(r['errors_stopped_after_seconds'] for r in runs)} с; "
f"потерь 0, дублей 0; реплика вернулась через "
f"{max(r['rejoin_seconds'] for r in runs)} с после `docker start` |")
if failover.exists() and results:
impacts.append(
f"| публичный `make test-failover` для каждой реплики | запись продолжается не позже 10 с, "
f"подтверждённые сообщения на месте, дублей нет | PASS {len(results)} раз(а), неудачных попыток: "
f"{', '.join(str(r['failed_attempts']) for r in results)} | первая запись после hook через "
f"{', '.join(str(r['first_recovery_seconds']) for r in results)} с (hook ждёт остановки ~4 с); потерь нет |")
if rolling:
impacts.append(
f"| rolling update под нагрузкой | ошибок нет, реплик всё время не меньше {rolling['replicas']} | "
f"ошибок: {rolling['during']['errors']}, замена заняла {rolling['update_seconds']} с | потерь 0, дублей 0 |")
if restart_seconds:
impacts.append(
f"| перезапуск всего стенда (`restart` hook: postgres, redis, api, lb) | данные и прежний токен живы | "
f"PASS, те же контейнеры с новым временем старта | {restart_seconds} с до готовности; потерь нет |")
if impacts:
lines.append("| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |")
lines.append("| --- | --- | --- | --- |")
lines.extend(impacts)
lines.append("")
return "\n".join(lines).strip()
def update_report(block):
report = ROOT / "REPORT.md"
text = report.read_text(encoding="utf-8")
begin, end = "<!-- measurements:begin -->", "<!-- measurements:end -->"
if begin not in text or end not in text:
print("REPORT.md has no measurement markers, only evidence/summary.md was written")
return
head, rest = text.split(begin, 1)
_, tail = rest.split(end, 1)
report.write_text(f"{head}{begin}\n{block}\n{end}{tail}", encoding="utf-8")
print("REPORT.md: measurement tables updated")
def main():
args = sys.argv[1:]
names = [name for name, _, _ in STEPS]
if args[:1] == ["--from"]:
if len(args) < 2 or args[1] not in names:
raise SystemExit("usage: --from <step>; steps: " + ", ".join(names))
selected = names[names.index(args[1]):]
else:
unknown = [a for a in args if a not in names]
if unknown:
raise SystemExit(f"unknown steps {unknown}; steps: " + ", ".join(names))
selected = args or names
EVIDENCE.mkdir(exist_ok=True)
results = []
for name, description, command in STEPS:
if name not in selected:
continue
ok, seconds = run_step(name, description, command)
results.append((name, description, ok, seconds))
if not ok:
print(f"\nSTOP: step '{name}' failed, see evidence/{name}.txt.")
print(f"After fixing: python student-tests/collect_evidence.py --from {name}")
break
block = measurements()
summary = ["# Сводка проверок", "", "| Шаг | Что проверяет | Результат | Время, с | Файл |",
"| --- | --- | --- | --- | --- |"]
summary += [f"| {n} | {d} | {'PASS' if ok else 'FAIL'} | {s:.0f} | evidence/{n}.txt |" for n, d, ok, s in results]
(EVIDENCE / "summary.md").write_text("\n".join(summary) + "\n\n# Замеры\n\n" + block + "\n", encoding="utf-8")
print("evidence/summary.md written")
passed = all(ok for _, _, ok, _ in results)
if passed:
update_report(block) # таблицы строятся из всех файлов evidence/, в том числе от прошлых запусков
raise SystemExit(0 if passed else 1)
if __name__ == "__main__":
main()
+273
View File
@@ -0,0 +1,273 @@
import base64
import csv
import hashlib
import io
import json
import os
import subprocess
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
LB_STATS_URL = os.environ.get("LB_STATS_URL", "http://127.0.0.1:8404/stats;csv")
PASSWORD = "Test-password-123"
class Response:
def __init__(self, status, headers, data):
self.status = status
self.headers = {name.lower(): value for name, value in headers.items()}
self.data = data
try:
self.json = json.loads(data.decode("utf-8")) if data else None
except ValueError:
self.json = None
@property
def instance(self):
"""X-Instance-Id: какая реплика API ответила (ID её контейнера)."""
return self.headers.get("x-instance-id")
def check(condition, message):
if not condition:
raise AssertionError(message)
def call(method, path, expected=200, *, body=None, raw=None, token=None, headers=None, timeout=30):
"""HTTP-запрос к API. expected — код или кортеж кодов, иначе AssertionError.
Заодно проверяет то, что контракт требует от любого ответа:
X-Request-Id, X-Instance-Id (с lab3), единый формат ошибки, WWW-Authenticate у 401.
"""
all_headers = dict(headers or {})
data = raw
if body is not None:
data = json.dumps(body).encode("utf-8")
if data is not None:
all_headers.setdefault("Content-Type", "application/json")
if token is not None:
all_headers["Authorization"] = "Bearer " + token
request = urllib.request.Request(BASE_URL + path, data=data, method=method, headers=all_headers)
try:
with urllib.request.urlopen(request, timeout=timeout) as reply:
response = Response(reply.status, reply.headers, reply.read())
except urllib.error.HTTPError as error:
response = Response(error.code, error.headers, error.read())
expected = expected if isinstance(expected, tuple) else (expected,)
check(response.status in expected,
f"{method} {path}: expected {expected}, got {response.status} {response.data[:200]!r}")
request_id = response.headers.get("x-request-id")
check(request_id, f"{method} {path}: no X-Request-Id header")
check(response.instance, f"{method} {path}: no X-Instance-Id header")
if response.status >= 400:
error = (response.json or {}).get("error") or {}
check(error.get("code") and error.get("message"), f"{method} {path}: wrong error format")
check(error.get("request_id") == request_id, f"{method} {path}: request_id differs from header")
if response.status == 401:
check(response.headers.get("www-authenticate"), f"{method} {path}: 401 without WWW-Authenticate")
return response
def try_call(method, path, *, body=None, token=None, headers=None, timeout=2):
"""Запрос без проверок и без исключений — для нагрузки во время отказа.
Возвращает Response или None, если соединение оборвалось / вышел timeout.
"""
all_headers = dict(headers or {})
data = None
if body is not None:
data = json.dumps(body).encode("utf-8")
all_headers["Content-Type"] = "application/json"
if token is not None:
all_headers["Authorization"] = "Bearer " + token
request = urllib.request.Request(BASE_URL + path, data=data, method=method, headers=all_headers)
try:
with urllib.request.urlopen(request, timeout=timeout) as reply:
return Response(reply.status, reply.headers, reply.read())
except urllib.error.HTTPError as error:
try:
return Response(error.code, error.headers, error.read())
except OSError:
return None
except (urllib.error.URLError, OSError):
return None
def basic(username, password):
"""Значение заголовка Authorization: Basic base64(username:password), пароль в UTF-8."""
return "Basic " + base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
def login(username, password, expected=201):
return call("POST", "/api/v1/auth/sessions", expected, headers={"Authorization": basic(username, password)})
def new_user(prefix="user", password=PASSWORD):
"""Регистрирует пользователя и входит. Возвращает dict: id, username, password, token."""
username = f"{prefix}_{uuid.uuid4().hex[:10]}"
user = call("POST", "/api/v1/users", 201,
body={"username": username, "display_name": prefix.title(), "password": password}).json
session = login(username, password).json
return {**user, "password": password, "token": session["token"]}
def new_chat(owner, *others, title="Test chat"):
member_ids = [owner["id"]] + [user["id"] for user in others]
return call("POST", "/api/v1/chats", 201, token=owner["token"],
body={"title": title, "member_ids": member_ids}).json
def new_key():
return uuid.uuid4().hex
def send(user, chat_id, text, expected=201, key=None):
"""POST сообщения. С lab3 Idempotency-Key обязателен: если не задан, берём новый случайный."""
return call("POST", f"/api/v1/chats/{chat_id}/messages", expected, token=user["token"],
body={"text": text}, headers={"Idempotency-Key": key or new_key()})
def read_history(user, chat_id, limit=100):
"""Вся история чата по страницам. Возвращает (сообщения, число_страниц)."""
items, pages, cursor = [], 0, None
while True:
query = f"?limit={limit}" + (f"&cursor={urllib.parse.quote(cursor, safe='')}" if cursor else "")
page = call("GET", f"/api/v1/chats/{chat_id}/messages{query}", 200, token=user["token"]).json
items += page["items"]
pages += 1
cursor = page["next_cursor"]
if cursor is None:
return items, pages
def wait_ready(seconds=90):
deadline = time.monotonic() + seconds
while True:
try:
with urllib.request.urlopen(BASE_URL + "/health/ready", timeout=3) as reply:
if reply.status == 200:
return
except (urllib.error.URLError, OSError):
pass
check(time.monotonic() < deadline, f"API is not ready after {seconds} s")
time.sleep(0.5)
def compose(*args, env=None):
"""docker compose <args> в корне репозитория. Вывод скрыт: в нём могут быть пути к секретам."""
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def compose_output(*args, env=None):
"""docker compose <args> и его вывод (для logs, ps)."""
result = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, check=True, env=env)
return result.stdout.decode("utf-8", "replace") + result.stderr.decode("utf-8", "replace")
def docker(*args, check_exit=True):
"""docker <args>, возвращает stdout."""
result = subprocess.run(["docker", *args], cwd=ROOT, capture_output=True, check=check_exit)
return result.stdout.decode("utf-8", "replace").strip()
def api_containers(include_stopped=False):
"""Полные ID контейнеров сервиса api (по умолчанию только запущенные)."""
args = ["ps", "-q", "-a", "api"] if include_stopped else ["ps", "-q", "api"]
return sorted(compose_output(*args).split())
def health(container):
"""Статус Docker healthcheck контейнера: starting / healthy / unhealthy / ''."""
return docker("inspect", "-f", "{{if .State.Health}}{{.State.Health.Status}}{{end}}", container,
check_exit=False)
def lb_servers():
"""Состояние слотов backend api в HAProxy (страница статистики, CSV): {имя: статус}."""
with urllib.request.urlopen(LB_STATS_URL, timeout=2) as reply:
rows = list(csv.reader(io.StringIO(reply.read().decode("utf-8", "replace"))))
header = [name.lstrip("# ") for name in rows[0]]
servers = {}
for row in rows[1:]:
item = dict(zip(header, row))
if item.get("pxname") == "api" and item.get("svname") not in ("FRONTEND", "BACKEND"):
servers[item["svname"]] = item.get("status", "")
return servers
def lb_up_count():
"""Сколько основных слотов (api1..api6, не аварийных) HAProxy считает готовыми (UP)."""
return sum(1 for name, status in lb_servers().items() if name.startswith("api") and status.startswith("UP"))
def seen_instances(token, requests=20):
"""Какие реплики отвечают через балансировщик: X-Instance-Id у серии GET /users/me."""
return {call("GET", "/api/v1/users/me", 200, token=token).instance for _ in range(requests)}
def wait_balanced(replicas, seconds=60):
"""Ждёт, пока все replicas контейнеров api healthy и HAProxy держит их в балансировке."""
deadline = time.monotonic() + seconds
while True:
running = api_containers()
healthy = [container for container in running if health(container) == "healthy"]
try:
up = lb_up_count()
except OSError:
up = 0
if len(healthy) >= replicas and up >= replicas:
return running
check(time.monotonic() < deadline,
f"after {seconds} s: {len(healthy)} healthy api containers, {up} UP in HAProxy, need {replicas}")
time.sleep(0.5)
def redis_cli(*args):
"""redis-cli внутри контейнера redis. Пароль читается там же из секрета и не попадает в вывод."""
command = "REDISCLI_AUTH=\"$(sed -n 's/^requirepass //p' /run/secrets/redis_auth)\" redis-cli " + " ".join(args)
result = subprocess.run(["docker", "compose", "exec", "-T", "redis", "sh", "-c", command],
cwd=ROOT, capture_output=True, check=True)
return result.stdout.decode("utf-8", "replace").strip()
def session_key(token):
"""Ключ сессии в Redis, как его считает auth.py: session:<SHA-256 токена>."""
return "session:" + hashlib.sha256(token.encode("utf-8")).hexdigest()
def psql(sql):
"""Выполняет SQL в контейнере postgres. Возвращает (код выхода, вывод, текст ошибки).
Значения в SQL тестов — только сгенерированные самим тестом (uuid), не ввод пользователя.
"""
result = subprocess.run(
["docker", "compose", "exec", "-T", "postgres",
"psql", "-U", "messenger", "-d", "messenger", "-X", "-A", "-t", "-v", "ON_ERROR_STOP=1", "-c", sql],
cwd=ROOT, capture_output=True, check=False,
)
output = result.stdout.decode("utf-8", "replace").strip()
error = result.stderr.decode("utf-8", "replace").strip()
return result.returncode, output, error
def run_tests(tests):
"""Запускает функции-тесты по очереди. Код выхода 1, если хоть один упал."""
failed = 0
for test in tests:
try:
test()
except Exception as exc: # noqa: BLE001 — нужно напечатать любую ошибку теста
failed += 1
print(f"FAIL: {test.__name__}: {exc}")
print(f"{len(tests) - failed} passed, {failed} failed")
raise SystemExit(1 if failed else 0)
+16
View File
@@ -0,0 +1,16 @@
from common import call, compose_output, new_user
def main():
user = new_user("demo")
print(f"logged in once as {user['username']}; 8 requests with the same Bearer token:")
for number in range(1, 9):
reply = call("GET", "/api/v1/users/me", 200, token=user["token"])
print(f" {number}. GET /api/v1/users/me -> {reply.status}, X-Instance-Id: {reply.instance}")
print()
print(compose_output("ps", "--format", "table {{.Service}}\t{{.ID}}\t{{.Status}}", "api").strip())
if __name__ == "__main__":
main()
+28
View File
@@ -0,0 +1,28 @@
import subprocess
from common import ROOT
OUTPUT = ROOT / "evidence" / "explain-history.txt"
def main():
sql = (ROOT / "student-tests" / "explain.sql").read_bytes()
result = subprocess.run(
["docker", "compose", "exec", "-T", "postgres",
"psql", "-U", "messenger", "-d", "messenger", "-X", "-q", "-v", "ON_ERROR_STOP=1"],
cwd=ROOT, input=sql, capture_output=True, check=False,
)
OUTPUT.parent.mkdir(exist_ok=True)
OUTPUT.write_bytes(result.stdout + result.stderr)
if result.returncode != 0:
print(result.stderr.decode("utf-8", "replace"))
raise SystemExit("FAIL: psql returned an error, see output above")
for line in result.stdout.decode("utf-8", "replace").splitlines():
if line.startswith("===") or "Buffers" in line or "Execution Time" in line or " Scan " in line:
print(line)
print(f"PASS: full plans saved to {OUTPUT.relative_to(ROOT)}")
if __name__ == "__main__":
main()
+66
View File
@@ -0,0 +1,66 @@
\pset footer off
BEGIN;
CREATE TEMP TABLE seed_chats AS
SELECT gen_random_uuid() AS id, n, CASE WHEN n = 0 THEN 15000 ELSE 100 END AS size
FROM generate_series(0, 50) AS n;
CREATE TEMP TABLE seed_user AS SELECT gen_random_uuid() AS id;
INSERT INTO users (id, username, display_name, password_hash)
SELECT id, 'explain_' || substr(md5(random()::text), 1, 10), convert_to('Explain', 'UTF8'), 'not-a-real-hash'
FROM seed_user;
INSERT INTO chats (id, title) SELECT id, convert_to('explain ' || n, 'UTF8') FROM seed_chats;
INSERT INTO chat_members (chat_id, user_id) SELECT c.id, u.id FROM seed_chats c, seed_user u;
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), c.id, u.id, convert_to('message ' || g, 'UTF8'),
timestamptz '2026-09-01 00:00:00+00' + g * interval '1 second'
FROM seed_chats c, seed_user u, generate_series(1, c.size) AS g;
ANALYZE messages;
SELECT id AS big_chat FROM seed_chats WHERE n = 0 \gset
SELECT created_at AS cursor_time, id AS cursor_id FROM messages
WHERE chat_id = :'big_chat' ORDER BY created_at, id OFFSET 9999 LIMIT 1 \gset
\echo '=== Data volume'
SELECT count(*) AS messages_total,
count(*) FILTER (WHERE chat_id = :'big_chat') AS messages_in_big_chat
FROM messages;
\echo ''
\echo '=== History index'
SELECT indexdef FROM pg_indexes WHERE indexname = 'messages_history';
\echo ''
\echo '=== 1. First page: limit=50, the app asks for 51 rows to know if there is a next page'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat'
ORDER BY created_at, id LIMIT 51;
\echo ''
\echo '=== 2. Page after the 10000th message by keyset cursor (this is what the app does)'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat' AND (created_at, id) > (:'cursor_time'::timestamptz, :'cursor_id'::uuid)
ORDER BY created_at, id LIMIT 51;
\echo ''
\echo '=== 3. The same page with OFFSET 10000 (the app does NOT do this)'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat'
ORDER BY created_at, id OFFSET 10000 LIMIT 51;
\echo ''
\echo '=== 4. Query 2 without the index (index is dropped only inside this transaction)'
DROP INDEX messages_history;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat' AND (created_at, id) > (:'cursor_time'::timestamptz, :'cursor_id'::uuid)
ORDER BY created_at, id LIMIT 51;
ROLLBACK;
\echo ''
\echo '=== ROLLBACK: test data removed, index is back'
SELECT count(*) AS explain_users_left FROM users WHERE username LIKE 'explain\_%';
+129
View File
@@ -0,0 +1,129 @@
import json
import platform
import sys
import threading
import time
from common import ROOT, api_containers, check, docker, lb_up_count, wait_balanced
from loadgen import Load, summary
WARMUP_SECONDS = 3
AFTER_SECONDS = 10
OUTPUT = ROOT / "evidence" / "failover-metrics.json"
class LbWatch:
"""Раз в 0,1 с спрашивает у HAProxy, сколько реплик в балансировке (UP)."""
def __init__(self):
self.points, self.stopping = [], threading.Event()
self.thread = threading.Thread(target=self._run, daemon=True)
def _run(self):
while not self.stopping.is_set():
try:
self.points.append((time.monotonic(), lb_up_count()))
except OSError:
pass
time.sleep(0.1)
def start(self):
self.thread.start()
def stop(self):
self.stopping.set()
self.thread.join(timeout=3)
def first_drop(self, after, replicas):
return next((t for t, up in self.points if t >= after and up < replicas), None)
def measure(container, mode, replicas):
wait_balanced(replicas)
load, watch = Load(), LbWatch()
watch.start()
load.start()
time.sleep(WARMUP_SECONDS)
t0 = time.monotonic()
if mode == "stop":
docker("stop", "--time", "8", container)
else:
docker("kill", container)
command_seconds = time.monotonic() - t0
time.sleep(max(0.0, AFTER_SECONDS - command_seconds))
end = t0 + AFTER_SECONDS
load.stop()
watch.stop()
errors = [e for e in load.window(t0 - WARMUP_SECONDS, end) if not e[2]]
errors_end = max((e[0] + e[5] for e in errors), default=None)
drop = watch.first_drop(t0, replicas)
served_after = [e[4] for e in load.window(t0 + command_seconds, end) if e[2]]
target_hits = sum(1 for instance in served_after if instance and container.startswith(instance))
integrity = load.verify()
started = time.monotonic()
docker("start", container)
wait_balanced(replicas)
rejoin_seconds = time.monotonic() - started
return {
"replica": container[:12],
"mode": mode,
"command_seconds": round(command_seconds, 2),
"lb_excluded_after_seconds": round(drop - t0, 2) if drop else None,
"errors": len(errors),
"error_codes": summary(load, t0 - WARMUP_SECONDS, end)["error_codes"],
"errors_stopped_after_seconds": round(errors_end - t0, 2) if errors_end else 0.0,
"before": summary(load, t0 - WARMUP_SECONDS, t0),
"after": summary(load, t0, end),
"stopped_replica_answers_after_stop": target_hits,
"integrity": integrity,
"rejoin_seconds": round(rejoin_seconds, 2),
}
def main():
modes = sys.argv[1:] or ["stop", "kill"]
check(set(modes) <= {"stop", "kill"}, "usage: python student-tests/failover_metrics.py [stop] [kill]")
containers = api_containers()
replicas = len(containers)
check(replicas >= 2, "need at least 2 running api replicas")
print(f"api replicas: {[c[:12] for c in containers]}; load: 4 writers without pauses + 1 reader, "
f"client timeout 2 s, retry with the same Idempotency-Key; {WARMUP_SECONDS} s before and "
f"{AFTER_SECONDS} s after the failure")
runs = []
for container in containers:
for mode in modes:
print(f"--- {mode} {container[:12]} ...")
run = measure(container, mode, replicas)
runs.append(run)
print(f" docker {mode}: {run['command_seconds']} s; HAProxy excluded it after "
f"{run['lb_excluded_after_seconds']} s; errors: {run['errors']} {run['error_codes']}, "
f"stopped after {run['errors_stopped_after_seconds']} s")
print(f" write RPS before {run['before']['write_rps']} -> after {run['after']['write_rps']}; "
f"p95 after {run['after']['write_p95_ms']} ms, max {run['after']['write_max_ms']} ms; "
f"answers from the stopped replica after stop: {run['stopped_replica_answers_after_stop']}")
print(f" confirmed {run['integrity']['confirmed_writes']}, in history "
f"{run['integrity']['messages_in_history']}, lost 0, duplicates 0; "
f"back in the balancer {run['rejoin_seconds']} s after docker start")
check(run["stopped_replica_answers_after_stop"] == 0, "the stopped replica still answered")
check(run["after"]["write_rps"] > 0, "no successful writes after the failure")
print()
print("replica mode cmd,s lb_out,s errors errors_end,s rps_before rps_after p95_after,ms rejoin,s")
for r in runs:
print(f"{r['replica']} {r['mode']:<4} {r['command_seconds']:>5} {str(r['lb_excluded_after_seconds']):>8} "
f"{r['errors']:>6} {r['errors_stopped_after_seconds']:>12} {r['before']['write_rps']:>10} "
f"{r['after']['write_rps']:>9} {str(r['after']['write_p95_ms']):>12} {r['rejoin_seconds']:>8}")
OUTPUT.parent.mkdir(exist_ok=True)
OUTPUT.write_text(json.dumps({
"profile": {"writers": 4, "readers": 1, "client_timeout_seconds": 2, "warmup_seconds": WARMUP_SECONDS,
"after_seconds": AFTER_SECONDS, "replicas": replicas, "client_python": platform.python_version()},
"runs": runs,
}, indent=2) + "\n", encoding="utf-8")
print(f"PASS: every replica was stopped ({', '.join(modes)}) and restored; no lost or duplicated messages; "
f"saved {OUTPUT.relative_to(ROOT)}")
if __name__ == "__main__":
main()
+102
View File
@@ -0,0 +1,102 @@
import math
import threading
import time
from common import check, new_chat, new_key, new_user, read_history, try_call
class Load:
def __init__(self, writers=4, timeout=2):
self.alice, self.bob = new_user("load_a"), new_user("load_b")
self.chat = new_chat(self.alice, self.bob, title="load")
self.writers, self.timeout = writers, timeout
self.events = [] # (время, "write"/"read", ok, код или "conn", реплика, задержка в с)
self.confirmed = [] # сообщения, на которые пришёл 201
self.lock = threading.Lock()
self.stopping = threading.Event()
self.threads = []
def _record(self, kind, started, reply, ok):
code = reply.status if reply is not None else "conn"
instance = reply.instance if reply is not None else None
with self.lock:
self.events.append((started, kind, ok, code, instance, time.monotonic() - started))
def _writer(self, number):
path = f"/api/v1/chats/{self.chat['id']}/messages"
sent = 0
key, text = new_key(), f"load-{number}-{sent}"
while not self.stopping.is_set():
started = time.monotonic()
reply = try_call("POST", path, body={"text": text}, token=self.alice["token"],
headers={"Idempotency-Key": key}, timeout=self.timeout)
ok = reply is not None and reply.status == 201
self._record("write", started, reply, ok)
if ok:
with self.lock:
self.confirmed.append(reply.json)
sent += 1
key, text = new_key(), f"load-{number}-{sent}"
else:
time.sleep(0.05) # и повторить тот же text с тем же ключом
def _reader(self):
path = f"/api/v1/chats/{self.chat['id']}/messages?limit=20"
while not self.stopping.is_set():
started = time.monotonic()
reply = try_call("GET", path, token=self.bob["token"], timeout=self.timeout)
self._record("read", started, reply, reply is not None and reply.status == 200)
time.sleep(0.05)
def start(self):
self.threads = [threading.Thread(target=self._writer, args=(n,), daemon=True) for n in range(self.writers)]
self.threads.append(threading.Thread(target=self._reader, daemon=True))
for thread in self.threads:
thread.start()
def stop(self):
self.stopping.set()
for thread in self.threads:
thread.join(timeout=self.timeout + 5)
def window(self, start, end, kind=None):
with self.lock:
return [e for e in self.events if start <= e[0] < end and (kind is None or e[1] == kind)]
def verify(self):
"""Все подтверждённые сообщения есть в истории, id и тексты не повторяются."""
history, _ = read_history(self.bob, self.chat["id"])
ids = [message["id"] for message in history]
texts = [message["text"] for message in history]
by_id = {message["id"]: message for message in history}
check(len(ids) == len(set(ids)), "duplicated message ids in history")
check(len(texts) == len(set(texts)), "a retried request created a duplicate message")
lost = [m for m in self.confirmed if by_id.get(m["id"]) != m]
check(not lost, f"{len(lost)} confirmed messages are lost or changed")
return {"confirmed_writes": len(self.confirmed), "messages_in_history": len(history), "duplicates": 0, "lost": 0}
def summary(load, start, end):
"""Успешные RPS, ошибки и задержки на отрезке [start, end)."""
events = load.window(start, end)
writes = [e for e in events if e[1] == "write"]
ok_writes = sorted(e[5] for e in writes if e[2])
errors = [e for e in events if not e[2]]
seconds = max(end - start, 1e-6)
def percentile(p):
return round(1000 * ok_writes[max(0, math.ceil(p * len(ok_writes)) - 1)], 1) if ok_writes else None
codes = {}
for e in errors:
codes[str(e[3])] = codes.get(str(e[3]), 0) + 1
return {
"seconds": round(seconds, 2),
"write_rps": round(len(ok_writes) / seconds, 1),
"reads": len([e for e in events if e[1] == "read"]),
"errors": len(errors),
"error_codes": codes,
"write_p50_ms": percentile(0.50),
"write_p95_ms": percentile(0.95),
"write_max_ms": round(1000 * ok_writes[-1], 1) if ok_writes else None,
}
+29
View File
@@ -0,0 +1,29 @@
import subprocess
from common import ROOT, login, new_user, redis_cli, session_key
def without_password():
result = subprocess.run(["docker", "compose", "exec", "-T", "redis", "redis-cli", "get", "anything"],
cwd=ROOT, capture_output=True, check=False)
return (result.stdout + result.stderr).decode("utf-8", "replace").strip()
def main():
user = new_user("info")
token = login(user["username"], user["password"]).json["token"]
key = session_key(token)
print(f"session key: {key[:24]}...; value is the user id: {redis_cli('get', key) == user['id']}")
print(f"TTL of the key, seconds: {redis_cli('ttl', key)}")
keys = redis_cli("--scan", "--pattern", "'session:*'").splitlines()
print(f"sessions in Redis: {len(keys)}")
for name in ("appendonly", "appendfsync", "maxmemory-policy"):
print("config", " = ".join(redis_cli("config", "get", name).split()))
for line in redis_cli("info", "persistence").splitlines():
if line.startswith(("aof_enabled", "aof_last_write_status")):
print(line)
print(f"without password: {without_password()}")
if __name__ == "__main__":
main()
+88
View File
@@ -0,0 +1,88 @@
import json
import os
import time
from common import ROOT, api_containers, check, compose, compose_output, docker, health, lb_up_count, wait_balanced
from loadgen import Load, summary
OUTPUT = ROOT / "evidence" / "rolling-update.json"
def env_of(container):
lines = docker("inspect", "-f", "{{range .Config.Env}}{{println .}}{{end}}", container).splitlines()
return dict(line.split("=", 1) for line in lines if "=" in line)
def wait_new_replica(container, up_needed, seconds=90):
deadline = time.monotonic() + seconds
while health(container) != "healthy" or lb_up_count() < up_needed:
check(time.monotonic() < deadline, f"new replica {container[:12]} is not in the balancer after {seconds} s")
time.sleep(0.2)
def main():
old = api_containers()
replicas = len(old)
check(replicas >= 2, "need at least 2 running api replicas")
wait_balanced(replicas)
old_version = env_of(old[0]).get("APP_VERSION")
version = time.strftime("rolling-%Y%m%d-%H%M%S")
env = dict(os.environ, APP_VERSION=version)
print(f"old replicas {[c[:12] for c in old]}, version {old_version}; building version {version}")
started = time.monotonic()
compose("build", "api", "migrate", env=env)
print(f"image built in {time.monotonic() - started:.1f} s")
migrate_log = compose_output("run", "--rm", "--no-deps", "-T", "migrate", env=env)
print("migrations: " + [line for line in migrate_log.splitlines() if "Migrations applied" in line][-1]
.split("messenger.db: ")[-1])
load = Load()
load.start()
time.sleep(3)
t0 = time.monotonic()
steps = []
for container in old:
step_start = time.monotonic()
before = set(api_containers())
compose("up", "-d", "--no-deps", "--no-recreate", "--scale", f"api={len(before) + 1}", "api", env=env)
new = sorted(set(api_containers()) - before)
check(len(new) == 1, f"expected one new container, got {len(new)}")
wait_new_replica(new[0], replicas + 1)
ready = time.monotonic() - step_start
docker("stop", "--time", "15", container)
docker("rm", container)
steps.append({"old": container[:12], "new": new[0][:12], "new_ready_seconds": round(ready, 2),
"step_seconds": round(time.monotonic() - step_start, 2)})
print(f"replaced {container[:12]} -> {new[0][:12]}: new replica ready and in HAProxy after {ready:.1f} s, "
f"step {steps[-1]['step_seconds']} s")
t1 = time.monotonic()
time.sleep(3)
load.stop()
final = api_containers()
versions = sorted({env_of(c).get("APP_VERSION") for c in final})
integrity = load.verify()
during = summary(load, t0, t1)
before_stats = summary(load, t0 - 3, t0)
print(f"now: replicas {[c[:12] for c in final]}, versions {versions}")
print(f"under load: write RPS before {before_stats['write_rps']}, during the update {during['write_rps']}; "
f"errors {during['errors']} {during['error_codes']}; p95 {during['write_p95_ms']} ms, "
f"max {during['write_max_ms']} ms; update took {t1 - t0:.1f} s")
print(f"confirmed {integrity['confirmed_writes']}, in history {integrity['messages_in_history']}, "
f"lost 0, duplicates 0")
check(len(final) == replicas and not set(final) & set(old), "old replicas are still running")
check(versions == [version], "not every replica runs the new version")
OUTPUT.parent.mkdir(exist_ok=True)
OUTPUT.write_text(json.dumps({
"from_version": old_version, "to_version": version, "replicas": replicas,
"profile": {"writers": 4, "readers": 1, "client_timeout_seconds": 2},
"steps": steps, "update_seconds": round(t1 - t0, 2),
"before": before_stats, "during": during, "integrity": integrity,
}, indent=2) + "\n", encoding="utf-8")
print(f"PASS: all {replicas} replicas replaced one by one under load, "
f"{during['errors']} errors, no lost or duplicated messages; saved {OUTPUT.relative_to(ROOT)}")
if __name__ == "__main__":
main()
+55
View File
@@ -0,0 +1,55 @@
import os
import subprocess
import sys
from common import BASE_URL, ROOT, api_containers, call, check, compose_output, docker, wait_balanced
HOOK = ROOT / "scripts" / ("stop-one.cmd" if os.name == "nt" else "stop-one.sh")
def ps():
return compose_output("ps", "-a", "--format", "table {{.Service}}\t{{.ID}}\t{{.Status}}", "api").strip()
def aim(wanted):
"""Для 2 реплик: последним перед тестом должна ответить реплика из wanted."""
probe = call("GET", "/health/live", 200).instance
if not any(container.startswith(probe) for container in wanted):
call("GET", "/health/live", 200) # теперь последней ответила другая реплика
def main():
containers = api_containers()
check(len(containers) >= 2, "need at least 2 running api replicas")
print(f"hook: {HOOK.relative_to(ROOT)}; api replicas: {[c[:12] for c in containers]}")
stopped_once = set()
for attempt in range(1, 7):
wait_balanced(len(containers))
if len(containers) == 2:
aim(set(containers) - stopped_once)
print(f"=== run {attempt}: api containers before")
print(ps())
env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8")
result = subprocess.run([sys.executable, "tests/resilience.py", "--mode", "failover",
"--action-script", str(HOOK), "--base-url", BASE_URL],
cwd=ROOT, capture_output=True, env=env)
print((result.stdout + result.stderr).decode("utf-8", "replace").strip())
check(result.returncode == 0, "public failover test failed")
print("api containers after")
print(ps())
stopped = [container for container in containers if container not in api_containers()]
check(len(stopped) == 1, f"expected exactly one stopped api container, got {len(stopped)}")
print(f"the hook stopped {stopped[0][:12]} (X-Instance-Id of that replica = container ID); "
f"other api containers kept running, postgres/redis/lb were not touched")
stopped_once.add(stopped[0])
docker("start", stopped[0])
wait_balanced(len(containers))
print(f"restored: docker start {stopped[0][:12]} -> healthy and back in HAProxy")
if stopped_once == set(containers):
break
check(stopped_once == set(containers), "not every replica was stopped by the public test")
print(f"PASS: public failover test passed {attempt} times; every api replica was stopped once and restored")
if __name__ == "__main__":
main()
+47
View File
@@ -0,0 +1,47 @@
import os
import subprocess
import sys
import time
from common import BASE_URL, ROOT, check, compose_output, docker
HOOK = ROOT / "scripts" / ("restart.cmd" if os.name == "nt" else "restart.sh")
def started():
containers = compose_output("ps", "-q").split()
lines = docker("inspect", "-f", "{{.Name}} {{.Id}} {{.State.StartedAt}}", *containers).splitlines()
return {name.lstrip("/"): (cid, at) for name, cid, at in (line.split() for line in lines)}
def main():
before = started()
print("before: container, ID, started at")
for name, (cid, at) in sorted(before.items()):
print(f" {name:<28} {cid[:12]} {at}")
env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8")
begin = time.monotonic()
result = subprocess.run([sys.executable, "tests/resilience.py", "--mode", "persistence",
"--action-script", str(HOOK), "--base-url", BASE_URL],
cwd=ROOT, capture_output=True, env=env)
seconds = time.monotonic() - begin
print((result.stdout + result.stderr).decode("utf-8", "replace").strip())
check(result.returncode == 0, "public persistence test failed")
after = started()
print(f"after (hook + waiting for readiness took {seconds:.1f} s): container, ID, started at, restarted?")
restarted = []
for name, (cid, at) in sorted(after.items()):
same_id = before.get(name, ("", ""))[0] == cid
new_start = before.get(name, ("", ""))[1] != at
print(f" {name:<28} {cid[:12]} {at} same container: {same_id}, restarted: {new_start}")
check(same_id, f"{name}: container was recreated, volumes/IDs must stay")
if new_start:
restarted.append(name.split("-")[-2])
for service in ("postgres", "redis", "api", "lb"):
check(service in restarted, f"{service} was not restarted by the hook")
print("PASS: the hook restarted postgres, redis, all api replicas and lb (same containers, new start time); "
"data and the old token survived")
if __name__ == "__main__":
main()
+246
View File
@@ -0,0 +1,246 @@
import base64
import datetime as dt
import uuid
from common import PASSWORD, basic, call, check, login, new_chat, new_key, new_user, read_history, run_tests, send
def parse_time(value):
return dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
def test_duplicate_username():
body = {"username": "dup_" + uuid.uuid4().hex[:10], "display_name": "First user", "password": PASSWORD}
call("POST", "/api/v1/users", 201, body=body)
call("POST", "/api/v1/users", 409, body=dict(body, display_name="Second user"))
print("PASS: duplicate username returns 409")
def test_invalid_json():
alice = new_user("alice")
chat = new_chat(alice)
call("POST", "/api/v1/users", 400, raw=b'{"username":')
call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=alice["token"], raw=b"not json",
headers={"Idempotency-Key": new_key()})
print("PASS: invalid JSON returns 400")
def test_wrong_fields():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
call("POST", "/api/v1/users", 400, body={"username": "Bad Name!", "display_name": "x", "password": PASSWORD})
call("POST", "/api/v1/users", 400,
body={"username": "valid_" + uuid.uuid4().hex[:8], "display_name": "x", "password": PASSWORD, "is_admin": True})
# Отправителя нельзя подставить: он берётся из сессии.
call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=alice["token"],
body={"text": "hi", "sender_id": bob["id"]}, headers={"Idempotency-Key": new_key()})
print("PASS: wrong and extra fields return 400")
def test_foreign_chat():
alice, bob, eve = new_user("alice"), new_user("bob"), new_user("eve")
chat = new_chat(alice, bob)
call("GET", f"/api/v1/chats/{chat['id']}", 404, token=eve["token"])
call("GET", f"/api/v1/chats/{chat['id']}/messages", 404, token=eve["token"])
send(eve, chat["id"], "not my chat", expected=404)
# Несуществующий чат выглядит так же, как чужой.
call("GET", f"/api/v1/chats/{uuid.uuid4()}", 404, token=eve["token"])
print("PASS: foreign chat returns 404")
def test_empty_message():
alice = new_user("alice")
chat = new_chat(alice)
for text in ("", " ", "\n\t"):
send(alice, chat["id"], text, expected=400)
send(alice, chat["id"], "я" * 4001, expected=400)
send(alice, chat["id"], "я" * 4000)
print("PASS: empty and too long messages return 400, 4000 chars is ok")
def test_pagination():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
sent = [send(alice, chat["id"], f"Message {i}").json["id"] for i in range(7)]
history, pages = read_history(bob, chat["id"], limit=2)
check(pages == 4, f"expected 4 pages, got {pages}")
check([m["id"] for m in history] == sent, "pages overlap, lose or reorder messages")
other = new_chat(alice)
for i in range(3):
send(alice, other["id"], f"Other {i}")
first = call("GET", f"/api/v1/chats/{other['id']}/messages?limit=1", token=alice["token"]).json
call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor={first['next_cursor']}", 400, token=alice["token"])
call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor=broken", 400, token=alice["token"])
print("PASS: pagination works across multiple pages, foreign cursor returns 400")
def test_chat_list_pagination():
alice, bob = new_user("alice"), new_user("bob")
created = [new_chat(alice, bob, title=f"Chat {i}")["id"] for i in range(3)]
seen, cursor = [], None
while True:
query = "?limit=1" + (f"&cursor={cursor}" if cursor else "")
page = call("GET", "/api/v1/chats" + query, token=bob["token"]).json
seen += [chat["id"] for chat in page["items"]]
cursor = page["next_cursor"]
if cursor is None:
break
check(seen == created, "chat list pages are wrong")
print("PASS: chat list pagination")
def test_unicode():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob, title="Чат 👋")
text = "Привет 👋 你好"
check(send(alice, chat["id"], text).json["text"] == text, "text changed on write")
history, _ = read_history(bob, chat["id"])
check(history[-1]["text"] == text, "text changed on read")
print("PASS: unicode text is stored as is")
def test_nul_character_is_stored():
name, title, text = "A\u0000B", "Chat\u0000title", "hello\u0000world"
body = {"username": "nul_" + uuid.uuid4().hex[:10], "display_name": name, "password": "pass\u0000word-123"}
user = call("POST", "/api/v1/users", 201, body=body).json
check(user["display_name"] == name, "display_name with U+0000 changed")
token = login(body["username"], body["password"]).json["token"]
check(call("GET", "/api/v1/users/me", token=token).json["display_name"] == name, "display_name changed on read")
chat = call("POST", "/api/v1/chats", 201, token=token, body={"title": title, "member_ids": [user["id"]]}).json
check(chat["title"] == title, "title with U+0000 changed")
check(call("GET", f"/api/v1/chats/{chat['id']}", token=token).json["title"] == title, "title changed on read")
sent = call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=token, body={"text": text},
headers={"Idempotency-Key": new_key()}).json
history = call("GET", f"/api/v1/chats/{chat['id']}/messages", token=token).json["items"]
check(sent["text"] == text and history[-1]["text"] == text, "text with U+0000 changed")
login("nul\u0000user", PASSWORD, expected=401)
print("PASS: strings with U+0000 are stored and returned as is")
def test_user_has_no_password():
body = {"username": "np_" + uuid.uuid4().hex[:10], "display_name": "No password", "password": PASSWORD}
user = call("POST", "/api/v1/users", 201, body=body).json
check(set(user) == {"id", "username", "display_name", "created_at"}, f"unexpected fields: {set(user)}")
print("PASS: user response has no password or hash")
def test_password_rules():
def register(password, expected):
body = {"username": "pw_" + uuid.uuid4().hex[:10], "display_name": "Password", "password": password}
call("POST", "/api/v1/users", expected, body=body)
register("x" * 11, 400)
register("x" * 129, 400)
register(" " * 12, 400)
register("x" * 12, 201)
register("я" * 128, 201)
print("PASS: password length 12..128, blank password is rejected")
def test_login_gives_token():
username = "lg_" + uuid.uuid4().hex[:10]
user = call("POST", "/api/v1/users", 201,
body={"username": username, "display_name": "Login", "password": PASSWORD}).json
reply = login(username, PASSWORD)
session = reply.json
check(session["token_type"] == "Bearer", "token_type must be Bearer")
check(session["user"] == user, "session user differs from registered user")
check(len(session["token"]) >= 43, "token is too short")
check(username not in session["token"] and user["id"] not in session["token"], "token is not opaque")
check(reply.headers.get("cache-control") == "no-store", "response with token must not be cached")
left = (parse_time(session["expires_at"]) - dt.datetime.now(dt.timezone.utc)).total_seconds()
check(290 < left <= 3600 + 5, f"unexpected session lifetime: {left:.0f} s")
me = call("GET", "/api/v1/users/me", token=session["token"]).json
check(me == user, "/users/me returned another user")
print("PASS: Basic login returns opaque Bearer token with expiry")
def test_wrong_password():
user = new_user("wp")
wrong = login(user["username"], "Wrong-password-000", expected=401)
unknown = login("nobody_" + uuid.uuid4().hex[:8], PASSWORD, expected=401)
check(wrong.headers["www-authenticate"].lower().startswith("basic"), "login 401 must ask for Basic")
check(wrong.json["error"]["message"] == unknown.json["error"]["message"], "different answers leak usernames")
print("PASS: wrong password and unknown user both return the same 401")
def test_malformed_basic():
no_colon = base64.b64encode(b"just_username").decode()
for header in (None, "Basic", "Basic !!!", "Basic " + no_colon, "Bearer something"):
headers = {} if header is None else {"Authorization": header}
call("POST", "/api/v1/auth/sessions", 401, headers=headers)
print("PASS: malformed Basic header returns 401")
def test_password_with_colon_and_unicode():
password = "пароль:с:двоеточием 👋"
user = new_user("colon", password=password)
call("GET", "/api/v1/users/me", token=user["token"])
print("PASS: password with colon and unicode works")
def test_bearer_required():
user = new_user("br")
for headers in ({}, {"Authorization": basic(user["username"], user["password"])},
{"X-User-Id": user["id"]}, {"Authorization": "Bearer " + "A" * 43},
{"Authorization": "Bearer"}, {"Authorization": "Token " + user["token"]}):
reply = call("GET", "/api/v1/users/me", 401, headers=headers)
check(reply.headers["www-authenticate"].lower().startswith("bearer"), "401 must ask for Bearer")
call("GET", "/api/v1/users/me", 200, headers={"Authorization": "bearer " + user["token"]})
print("PASS: business endpoints need Bearer; Basic and X-User-Id give 401")
def test_x_user_id_ignored():
alice, bob = new_user("alice"), new_user("bob")
me = call("GET", "/api/v1/users/me", token=alice["token"], headers={"X-User-Id": bob["id"]}).json
check(me["id"] == alice["id"], "X-User-Id changed the current user")
print("PASS: X-User-Id does not change the current user")
def test_auth_before_body():
alice = new_user("alice")
chat = new_chat(alice)
call("POST", f"/api/v1/chats/{chat['id']}/messages", 401, raw=b"not json")
call("GET", f"/api/v1/chats/{uuid.uuid4()}", 401)
print("PASS: 401 comes before 400 and 404")
def test_logout():
user = new_user("lo")
second = login(user["username"], user["password"]).json["token"]
call("DELETE", "/api/v1/auth/sessions/current", 204, token=user["token"])
call("GET", "/api/v1/users/me", 401, token=user["token"])
call("DELETE", "/api/v1/auth/sessions/current", 401, token=user["token"])
call("GET", "/api/v1/users/me", 200, token=second) # другая сессия того же пользователя жива
again = login(user["username"], user["password"]).json["token"]
check(again != user["token"], "new login must give a new token")
call("GET", "/api/v1/users/me", 200, token=again)
print("PASS: logout revokes only the current session")
if __name__ == "__main__":
run_tests([
test_duplicate_username,
test_invalid_json,
test_wrong_fields,
test_foreign_chat,
test_empty_message,
test_pagination,
test_chat_list_pagination,
test_unicode,
test_nul_character_is_stored,
test_user_has_no_password,
test_password_rules,
test_login_gives_token,
test_wrong_password,
test_malformed_basic,
test_password_with_colon_and_unicode,
test_bearer_required,
test_x_user_id_ignored,
test_auth_before_body,
test_logout,
])
+86
View File
@@ -0,0 +1,86 @@
from collections import Counter
from common import api_containers, call, check, new_chat, new_key, new_user, run_tests, send
def test_requests_spread_over_replicas():
alice = new_user("alice")
replies = [call("GET", "/api/v1/users/me", 200, token=alice["token"]) for _ in range(20)]
served = Counter(reply.instance for reply in replies)
print(f"20 x GET /users/me with one token -> replicas: {dict(served)}")
check(all(reply.json["id"] == alice["id"] for reply in replies), "another user returned")
check(len(served) >= 2, "all requests went to one replica: balancing does not work")
print("PASS: one session works on every replica, no second login (sessions are shared in Redis)")
def test_write_on_one_read_on_other():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
sent = send(alice, chat["id"], "written on one replica")
readers = set()
for _ in range(6):
reply = call("GET", f"/api/v1/chats/{chat['id']}/messages", 200, token=bob["token"])
check(sent.json in reply.json["items"], "confirmed message is not visible on another replica")
readers.add(reply.instance)
print(f"message written by {sent.instance}; read back by {sorted(readers)}")
check(readers - {sent.instance}, "no read went to another replica")
print("PASS: a message written via one replica is read right away via another (shared PostgreSQL)")
def test_logout_seen_by_all_replicas():
user = new_user("logout")
out = call("DELETE", "/api/v1/auth/sessions/current", 204, token=user["token"])
after = [call("GET", "/api/v1/users/me", 401, token=user["token"]).instance for _ in range(10)]
print(f"logout on {out.instance}; old token then rejected by {sorted(set(after))}")
check(len(set(after)) >= 2, "only one replica answered")
print("PASS: logout on one replica revokes the session on all of them")
def test_idempotent_retry_on_other_replica():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
key = new_key()
first = send(alice, chat["id"], "retry me", key=key)
for _ in range(10): # round robin: следующий запрос уйдёт на другую реплику
retry = send(alice, chat["id"], "retry me", key=key)
if retry.instance != first.instance:
break
print(f"first POST on {first.instance} -> 201 {first.json['id']}; "
f"same key on {retry.instance} -> {retry.status} {retry.json['id']}")
check(retry.instance != first.instance, "retry never reached another replica")
check(retry.json == first.json, "retry on another replica returned a different message")
items = call("GET", f"/api/v1/chats/{chat['id']}/messages", 200, token=bob["token"]).json["items"]
check([m["text"] for m in items].count("retry me") == 1, "retry created a duplicate")
print("PASS: Idempotency-Key is shared: a retry through another replica returns the same message")
def test_instance_header_everywhere():
containers = api_containers()
alice, eve = new_user("alice"), new_user("eve")
chat = new_chat(alice)
replies = [
call("GET", "/health/live", 200),
call("GET", "/health/ready", 200),
send(alice, chat["id"], "hello"),
call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=alice["token"], body={"text": "no key"}),
call("GET", "/api/v1/users/me", 401),
call("GET", f"/api/v1/chats/{chat['id']}", 404, token=eve["token"]),
call("POST", "/api/v1/users", 409,
body={"username": alice["username"], "display_name": "x", "password": alice["password"]}),
]
for reply in replies: # call() уже проверил, что заголовок есть; здесь — что это настоящий контейнер
check(any(container.startswith(reply.instance) for container in containers),
f"X-Instance-Id {reply.instance} is not a running api container")
print(f"statuses {[r.status for r in replies]}: every answer has X-Instance-Id of a running container "
f"{sorted({r.instance for r in replies})}; api containers: {[c[:12] for c in containers]}")
print("PASS: X-Instance-Id is in every response and points to a real container")
if __name__ == "__main__":
run_tests([
test_requests_spread_over_replicas,
test_write_on_one_read_on_other,
test_logout_seen_by_all_replicas,
test_idempotent_retry_on_other_replica,
test_instance_header_everywhere,
])
+101
View File
@@ -0,0 +1,101 @@
import time
import uuid
from common import call, check, compose_output, new_user, psql, run_tests
def sql_value(sql):
code, output, error = psql(sql)
check(code == 0, f"psql failed: {error}")
return output
def test_create_chat_rolls_back():
alice = new_user("rollback")
title = "rollback-" + uuid.uuid4().hex[:8]
inserted_before = int(sql_value("SELECT n_tup_ins FROM pg_stat_user_tables WHERE relname = 'chats'"))
call("POST", "/api/v1/chats", 400, token=alice["token"],
body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]})
left = sql_value(f"SELECT count(*) FROM chats WHERE title = '{title}'")
orphans = sql_value("SELECT count(*) FROM chats c WHERE NOT EXISTS "
"(SELECT 1 FROM chat_members m WHERE m.chat_id = c.id)")
inserted_after = inserted_before
deadline = time.monotonic() + 15
while inserted_after == inserted_before and time.monotonic() < deadline:
time.sleep(0.5)
inserted_after = int(sql_value("SELECT n_tup_ins FROM pg_stat_user_tables WHERE relname = 'chats'"))
print(f"chat with unknown member -> 400; rows with this title: {left}; chats without members: {orphans}; "
f"chats insert counter: {inserted_before} -> {inserted_after}")
check(left == "0" and orphans == "0", "chat row survived the failed transaction")
check(inserted_after > inserted_before, "the chat row was never inserted, rollback is not shown")
print("PASS: chat row was inserted and then rolled back together with members")
def test_message_needs_membership_in_db():
code, _, error = psql("INSERT INTO messages (id, chat_id, sender_id, text) "
f"VALUES ('{uuid.uuid4()}', '{uuid.uuid4()}', '{uuid.uuid4()}', convert_to('direct insert', 'UTF8'))")
print(f"direct INSERT of a message from a non-member -> exit code {code}: {error.splitlines()[0] if error else ''}")
check(code != 0 and "foreign key" in error, "database accepted a message from a non-member")
print("PASS: the database itself rejects a message from a non-member")
def test_password_is_argon2id():
user = new_user("hash")
stored = sql_value(f"SELECT password_hash FROM users WHERE username = '{user['username']}'")
print(f"stored password: {stored[:31]}... (length {len(stored)})")
check(stored.startswith("$argon2id$") and user["password"] not in stored, "password is not an Argon2id hash")
print("PASS: password is stored as Argon2id hash")
def test_unique_username_constraint():
constraint = sql_value("SELECT pg_get_constraintdef(oid) FROM pg_constraint "
"WHERE conrelid = 'users'::regclass AND contype = 'u'")
print(f"unique constraint on users: {constraint}")
check(constraint == "UNIQUE (username)", "no unique constraint on username")
print("PASS: username is unique in the database")
def test_migrations_are_not_repeated():
versions = sql_value("SELECT string_agg(version, ',' ORDER BY version) FROM schema_migrations")
print(f"applied migrations: {versions}; running the migrate service once more")
output = compose_output("run", "--rm", "--no-deps", "-T", "migrate")
again = sql_value("SELECT string_agg(version, ',' ORDER BY version) FROM schema_migrations")
last_log = [line for line in output.splitlines() if "Migrations applied" in line][-1]
print(f"after the second run: {again}; log: {last_log.split('messenger.db: ')[-1]}")
check(again == versions and "none" in last_log, "migrations were applied again")
print("PASS: migrations are applied once, a repeated run does nothing")
def test_replicas_do_not_migrate():
"""lab3: миграции применяет только сервис migrate, API-реплики лишь проверяют схему."""
logs = compose_output("logs", "api").splitlines()
checked = [line for line in logs if "Schema is up to date" in line]
migrated = [line for line in logs if "Migrations applied" in line]
migrate_exit = compose_output("ps", "-a", "--format", "{{.Status}}", "migrate").strip()
print(f"api replicas that checked the schema at start: {len(checked)}; api log lines 'Migrations applied': "
f"{len(migrated)}; migrate service: {migrate_exit}")
check(checked and not migrated, "api replicas must not apply migrations")
check(migrate_exit.startswith("Exited (0)"), "migrate service must finish with exit code 0")
print("PASS: only the migrate service applies migrations, replicas wait for the schema")
def test_idempotency_key_is_unique_in_db():
constraint = sql_value("SELECT pg_get_constraintdef(oid) FROM pg_constraint "
"WHERE conname = 'messages_idempotency_key'")
print(f"unique constraint for Idempotency-Key: {constraint}")
check(constraint == "UNIQUE (chat_id, sender_id, idempotency_key)", "no unique constraint for idempotency keys")
print("PASS: one message per (chat, sender, Idempotency-Key) is enforced by the database")
if __name__ == "__main__":
run_tests([
test_create_chat_rolls_back,
test_message_needs_membership_in_db,
test_password_is_argon2id,
test_unique_username_constraint,
test_migrations_are_not_repeated,
test_replicas_do_not_migrate,
test_idempotency_key_is_unique_in_db,
])
+57
View File
@@ -0,0 +1,57 @@
import datetime as dt
import os
import time
from common import call, check, compose, login, new_user, redis_cli, run_tests, session_key, wait_ready
SHORT_TTL = 2
def restart_api(ttl=None):
env = dict(os.environ)
if ttl is None:
env.pop("SESSION_TTL_SECONDS", None) # значение снова из .env
else:
env["SESSION_TTL_SECONDS"] = str(ttl)
compose("up", "-d", "--no-deps", "--wait", "api", env=env)
wait_ready()
def seconds_left(expires_at):
moment = dt.datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
return (moment - dt.datetime.now(dt.timezone.utc)).total_seconds()
def test_session_expires():
print(f"recreating api with SESSION_TTL_SECONDS={SHORT_TTL}")
restart_api(SHORT_TTL)
try:
user = new_user("ttl")
session = login(user["username"], user["password"]).json
token = session["token"]
left = seconds_left(session["expires_at"])
print(f"session issued, expires in {left:.2f} s; Redis TTL of the key: "
f"{redis_cli('pttl', session_key(token))} ms")
check(0 < left <= SHORT_TTL + 0.5, "short TTL instance must issue ~2 second sessions")
call("GET", "/api/v1/users/me", 200, token=token)
print("before expiry: GET /users/me -> 200")
time.sleep(max(0.0, seconds_left(session["expires_at"])) + 1.0)
call("GET", "/api/v1/users/me", 401, token=token)
exists = redis_cli("exists", session_key(token))
print(f"after expiry: GET /users/me -> 401; key exists in Redis: {exists}")
check(exists == "0", "Redis must delete the expired session key")
finally:
print("recreating api with SESSION_TTL_SECONDS from .env")
restart_api()
user = new_user("ttl_back")
left = seconds_left(login(user["username"], user["password"]).json["expires_at"])
print(f"normal API again: new session expires in {left:.0f} s")
check(left > 300, "normal TTL was not restored")
print("PASS: session expires after SESSION_TTL_SECONDS and is rejected with 401")
if __name__ == "__main__":
run_tests([test_session_expires])
+110
View File
@@ -0,0 +1,110 @@
import sys
import time
import uuid
from common import PASSWORD, basic, call, check, compose, new_chat, new_key, new_user, read_history, run_tests, send, wait_ready
FAKE_TOKEN = "A" * 43
def timed(method, path, expected, **kwargs):
started = time.monotonic()
reply = call(method, path, expected, **kwargs)
return reply, (time.monotonic() - started) * 1000
def prepare():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
before = send(alice, chat["id"], "confirmed before outage").json
return alice, bob, chat, before
def recovered(alice, chat, before):
wait_ready()
history, _ = read_history(alice, chat["id"])
check(before in history, "message confirmed before the outage is lost or changed")
call("GET", "/api/v1/users/me", 200, token=alice["token"])
print("after start: the old token works, confirmed messages are in place")
def test_redis_down():
alice, bob, chat, before = prepare()
print("stopping redis")
compose("stop", "redis")
try:
call("GET", "/health/live", 200)
_, ms = timed("GET", "/health/ready", 503)
print(f"/health/live -> 200, /health/ready -> 503 ({ms:.0f} ms)")
reply, ms = timed("GET", "/api/v1/users/me", 503, token=alice["token"])
check(reply.json["error"]["code"] == "unavailable", "expected code unavailable")
print(f"valid token: GET /users/me -> 503 unavailable ({ms:.0f} ms), session cannot be checked")
call("GET", "/api/v1/chats", 503, token=FAKE_TOKEN)
print("unknown token -> 503, not 200: nobody is trusted without a check")
call("GET", "/api/v1/chats", 401)
print("no token -> 401")
call("POST", "/api/v1/auth/sessions", 503, headers={"Authorization": basic(alice["username"], PASSWORD)})
print("login -> 503: there is nowhere to store the session")
call("POST", "/api/v1/users", 201,
body={"username": "rd_" + uuid.uuid4().hex[:10], "display_name": "x", "password": PASSWORD})
print("registration -> 201: it needs only PostgreSQL")
finally:
print("starting redis")
compose("start", "redis")
recovered(alice, chat, before)
print("PASS: Redis outage gives 503 and does not let anyone in without a session check")
def test_redis_crash():
alice = new_user("crash")
print("killing redis with SIGKILL (docker compose kill redis): no graceful shutdown")
compose("kill", "redis")
try:
# Обычно 503; 200 возможен, если Docker уже успел поднять Redis по restart policy.
status = call("GET", "/api/v1/users/me", (503, 200), token=alice["token"]).status
print(f"right after the crash: GET /users/me -> {status}")
finally:
print("starting redis")
compose("start", "redis")
wait_ready()
call("GET", "/api/v1/users/me", 200, token=alice["token"])
print("after start: the session issued before the crash still works (AOF, appendfsync always)")
print("PASS: sessions survive a Redis crash, not only a clean restart")
def test_postgres_down():
alice, bob, chat, before = prepare()
print("stopping postgres")
compose("stop", "postgres")
try:
call("GET", "/health/live", 200)
_, ms = timed("GET", "/health/ready", 503)
print(f"/health/live -> 200, /health/ready -> 503 ({ms:.0f} ms)")
for method, path, body in (("GET", "/api/v1/users/me", None),
("GET", "/api/v1/chats", None),
("GET", f"/api/v1/chats/{chat['id']}/messages", None),
("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": "will not be saved"})):
reply = call(method, path, 503, token=alice["token"], body=body, headers={"Idempotency-Key": new_key()})
check(reply.json["error"]["code"] == "unavailable", "expected code unavailable")
check("postgres" not in reply.data.decode().lower(), "error must not show database details")
print("valid token: users/me, chats, history, new message -> 503 unavailable, no details")
call("GET", "/api/v1/chats", 401)
call("GET", "/api/v1/chats", 401, token=FAKE_TOKEN)
print("no token -> 401, unknown token -> 401: anonymous users are not let in")
call("POST", "/api/v1/auth/sessions", 503, headers={"Authorization": basic(alice["username"], PASSWORD)})
call("POST", "/api/v1/users", 503,
body={"username": "pd_" + uuid.uuid4().hex[:10], "display_name": "x", "password": PASSWORD})
print("login -> 503, registration -> 503")
finally:
print("starting postgres")
compose("start", "postgres")
recovered(alice, chat, before)
print("PASS: PostgreSQL outage gives limited 503 errors and keeps anonymous users out")
if __name__ == "__main__":
target = sys.argv[1] if len(sys.argv) > 1 else "all"
tests = {"redis": [test_redis_down, test_redis_crash], "postgres": [test_postgres_down],
"all": [test_redis_down, test_redis_crash, test_postgres_down]}
check(target in tests, "usage: python student-tests/test_failures.py [redis|postgres]")
run_tests(tests[target])
+174
View File
@@ -0,0 +1,174 @@
import json
import socket
import threading
import time
import urllib.parse
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from common import BASE_URL, call, check, new_chat, new_key, new_user, read_history, run_tests, send
PARALLEL = 20
def post_raw(user, chat_id, raw, key):
"""POST с телом «как есть» (bytes) — чтобы проверить другой порядок ключей и пробелы."""
return call("POST", f"/api/v1/chats/{chat_id}/messages", (201, 409, 400), token=user["token"],
raw=raw, headers={"Idempotency-Key": key})
def texts_in(user, chat_id):
history, _ = read_history(user, chat_id)
return [message["text"] for message in history]
def test_replay_returns_same_message():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
key = new_key()
first = send(alice, chat["id"], "Привет 👋", key=key)
# То же JSON-значение, записанное иначе: пробелы и \u-экранирование.
same = post_raw(alice, chat["id"], b'{ "text" : "\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442 \\ud83d\\udc4b" }', key)
again = send(alice, chat["id"], "Привет 👋", key=key)
print(f"first -> {first.status}; same JSON written differently -> {same.status}; plain retry -> {again.status}")
check(same.status == 201 and same.json == first.json and again.json == first.json,
"retry must return the original 201 and the same message")
check(texts_in(bob, chat["id"]).count("Привет 👋") == 1, "retry created a duplicate")
print("PASS: a retry with the same key returns the original 201 and message, no duplicate")
def test_same_key_parallel_through_replicas():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
key = new_key()
barrier = threading.Barrier(PARALLEL)
def post(_):
barrier.wait() # все запросы стартуют одновременно
return send(alice, chat["id"], "one message for 20 requests", key=key)
with ThreadPoolExecutor(max_workers=PARALLEL) as pool:
replies = list(pool.map(post, range(PARALLEL)))
bodies = {json.dumps(reply.json, sort_keys=True) for reply in replies}
served = Counter(reply.instance for reply in replies)
count = texts_in(bob, chat["id"]).count("one message for 20 requests")
print(f"{PARALLEL} parallel POSTs with one key: statuses {dict(Counter(r.status for r in replies))}, "
f"replicas {dict(served)}, different bodies in answers: {len(bodies)}, messages in history: {count}")
check(len(served) >= 2, "requests did not go through different replicas")
check(len(bodies) == 1 and count == 1, "parallel retries created more than one message")
print("PASS: parallel requests with one key through different replicas create exactly one message")
def test_same_key_different_bodies_parallel():
alice = new_user("alice")
chat = new_chat(alice)
key = new_key()
barrier = threading.Barrier(PARALLEL)
def post(index):
text = "body A" if index % 2 == 0 else "body B"
barrier.wait()
reply = call("POST", f"/api/v1/chats/{chat['id']}/messages", (201, 409), token=alice["token"],
body={"text": text}, headers={"Idempotency-Key": key})
return text, reply
with ThreadPoolExecutor(max_workers=PARALLEL) as pool:
results = list(pool.map(post, range(PARALLEL)))
texts = texts_in(alice, chat["id"])
winner = [t for t in texts if t in ("body A", "body B")]
print(f"{PARALLEL} parallel POSTs, one key, two different bodies: "
f"{dict(Counter((t, r.status) for t, r in results))}; saved: {winner}")
check(len(winner) == 1, "exactly one message must be created")
for text, reply in results:
expected = 201 if text == winner[0] else 409
check(reply.status == expected, f"{text}: expected {expected}, got {reply.status}")
print("PASS: the first body wins, the same body gets 201, the other body gets 409")
def test_key_scope():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
other = new_chat(alice, bob)
key = new_key()
a1 = send(alice, chat["id"], "scope", key=key).json
b1 = send(bob, chat["id"], "scope", key=key).json
a2 = send(alice, other["id"], "scope", key=key).json
print(f"one key: alice in chat 1, bob in chat 1, alice in chat 2 -> {len({a1['id'], b1['id'], a2['id']})} messages")
check(len({a1["id"], b1["id"], a2["id"]}) == 3, "a key must be scoped to user + chat")
call("POST", f"/api/v1/chats/{chat['id']}/messages", 409, token=alice["token"],
body={"text": "other text"}, headers={"Idempotency-Key": key})
print("PASS: the key is scoped to the current user and chat; another body with a used key -> 409")
def test_key_validation():
alice = new_user("alice")
chat = new_chat(alice)
path = f"/api/v1/chats/{chat['id']}/messages"
call("POST", path, 400, token=alice["token"], body={"text": "no key"})
for bad in ("", "a" * 129, "has space", "slash/inside", "ключ", "quote\"", "a+b"):
call("POST", path, 400, token=alice["token"], body={"text": "bad key"},
headers={"Idempotency-Key": bad.encode("utf-8").decode("latin-1")}) # как есть, байтами UTF-8
longest = ("Az09._:-" * 16)[:128]
call("POST", path, 201, token=alice["token"], body={"text": "longest key"}, headers={"Idempotency-Key": longest})
print("missing, empty, 129 chars, space, '/', non-ASCII, '\"', '+' -> 400; 128 chars of A-Z a-z 0-9 . _ : - -> 201")
print("PASS: Idempotency-Key is required and checked: [A-Za-z0-9._:-]{1,128}")
def test_failed_request_does_not_burn_key():
alice, eve = new_user("alice"), new_user("eve")
chat = new_chat(alice)
key = new_key()
path = f"/api/v1/chats/{chat['id']}/messages"
call("POST", path, 400, token=alice["token"], body={"text": " "}, headers={"Idempotency-Key": key})
call("POST", path, 404, token=eve["token"], body={"text": "not my chat"}, headers={"Idempotency-Key": key})
created = call("POST", path, 201, token=alice["token"], body={"text": "valid now"}, headers={"Idempotency-Key": key})
print(f"key used by a 400 and by a 404 first, then valid request -> {created.status}")
print("PASS: rejected requests (400, 404) do not store a result for the key")
def test_replay_checks_session_and_access():
alice, eve = new_user("alice"), new_user("eve")
chat = new_chat(alice)
key = new_key()
send(alice, chat["id"], "private", key=key)
stolen = call("POST", f"/api/v1/chats/{chat['id']}/messages", 404, token=eve["token"],
body={"text": "private"}, headers={"Idempotency-Key": key})
call("DELETE", "/api/v1/auth/sessions/current", 204, token=alice["token"])
revoked = call("POST", f"/api/v1/chats/{chat['id']}/messages", 401, token=alice["token"],
body={"text": "private"}, headers={"Idempotency-Key": key})
print(f"same key and body by an outsider -> {stolen.status}; by alice after logout -> {revoked.status}")
print("PASS: a retry checks the session and chat access again, the saved answer is not leaked")
def test_lost_response_then_retry():
"""Клиент отправил POST и не дождался ответа (оборвал соединение). Повтор с тем же ключом безопасен."""
alice = new_user("alice")
chat = new_chat(alice)
key = new_key()
body = json.dumps({"text": "answer was lost"}).encode("utf-8")
url = urllib.parse.urlsplit(BASE_URL)
request = (f"POST /api/v1/chats/{chat['id']}/messages HTTP/1.1\r\nHost: {url.netloc}\r\n"
f"Authorization: Bearer {alice['token']}\r\nIdempotency-Key: {key}\r\n"
f"Content-Type: application/json\r\nContent-Length: {len(body)}\r\nConnection: close\r\n\r\n").encode()
with socket.create_connection((url.hostname, url.port or 80), timeout=5) as connection:
connection.sendall(request + body) # и сразу закрываем, ответ не читаем
time.sleep(1)
retry = call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=alice["token"],
body={"text": "answer was lost"}, headers={"Idempotency-Key": key})
count = texts_in(alice, chat["id"]).count("answer was lost")
print(f"POST sent, connection closed without reading the answer; retry -> {retry.status}; messages: {count}")
check(count == 1, "the retry after a lost answer created a duplicate")
print("PASS: an unconfirmed POST can be safely retried with the same key")
if __name__ == "__main__":
run_tests([
test_replay_returns_same_message,
test_same_key_parallel_through_replicas,
test_same_key_different_bodies_parallel,
test_key_scope,
test_key_validation,
test_failed_request_does_not_burn_key,
test_replay_checks_session_and_access,
test_lost_response_then_retry,
])
+57
View File
@@ -0,0 +1,57 @@
import threading
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from common import PASSWORD, call, check, new_chat, new_user, read_history, run_tests, send
CLIENTS = 10
MESSAGES_PER_CLIENT = 10
REGISTRATIONS = 20
def test_concurrent_messages():
users = [new_user(f"race{i}") for i in range(CLIENTS)]
chat = new_chat(*users, title="race")
barrier = threading.Barrier(CLIENTS) # все клиенты стартуют одновременно
def client(index):
barrier.wait()
for n in range(MESSAGES_PER_CLIENT):
send(users[index], chat["id"], f"client-{index}-message-{n}")
started = time.monotonic()
with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
list(pool.map(client, range(CLIENTS))) # list() пробрасывает ошибки из потоков
elapsed = time.monotonic() - started
history, pages = read_history(users[0], chat["id"], limit=30)
ids = {message["id"] for message in history}
expected = {f"client-{i}-message-{n}" for i in range(CLIENTS) for n in range(MESSAGES_PER_CLIENT)}
print(f"sent {CLIENTS * MESSAGES_PER_CLIENT} messages from {CLIENTS} clients in {elapsed:.2f} s; "
f"read {len(history)} in {pages} pages, unique ids: {len(ids)}")
check(len(history) == CLIENTS * MESSAGES_PER_CLIENT, "wrong number of messages")
check(len(ids) == len(history), "duplicate message ids")
check({message["text"] for message in history} == expected, "lost or changed message texts")
print("PASS: 100 concurrent messages from 10 clients, no losses and no duplicates")
def test_concurrent_registration():
username = "race_" + uuid.uuid4().hex[:10]
barrier = threading.Barrier(REGISTRATIONS)
def register(index):
barrier.wait()
body = {"username": username, "display_name": f"Client {index}", "password": PASSWORD}
return call("POST", "/api/v1/users", (201, 409), body=body).status
with ThreadPoolExecutor(max_workers=REGISTRATIONS) as pool:
statuses = list(pool.map(register, range(REGISTRATIONS)))
created, conflicts = statuses.count(201), statuses.count(409)
print(f"{REGISTRATIONS} parallel registrations of one username: 201 x{created}, 409 x{conflicts}")
check(created == 1 and conflicts == REGISTRATIONS - 1, "exactly one registration must win")
print("PASS: concurrent registration created exactly one user")
if __name__ == "__main__":
run_tests([test_concurrent_messages, test_concurrent_registration])