forked from mtusi2026/mtusi2026lab3
ЛР3
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
"""Отозванный токен не «воскресает» из кэша после возвращения Valkey (замечание к MR).
|
||||
|
||||
Запуск: make failure-valkey-pause
|
||||
|
||||
Сценарий преподавателя: Valkey ставится на паузу (docker compose pause) — процесс жив,
|
||||
данные в его памяти сохраняются, но он не отвечает. В это время делается logout: PostgreSQL
|
||||
отзывает сессию, а убрать запись из кэша нельзя. После unpause в кэше всё ещё лежит старая
|
||||
запись «токен -> пользователь». Она не должна снова пропускать этот токен.
|
||||
"""
|
||||
import time
|
||||
|
||||
from helpers import Client, compose, run, wait_ready
|
||||
|
||||
|
||||
def main():
|
||||
api = Client()
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
dave = api.user("dave")
|
||||
for _ in range(2): # запись о сессии dave точно лежит в кэше
|
||||
api.call("GET", "/api/v1/users/me", actor=dave, schema="User")
|
||||
|
||||
print("pausing valkey (docker compose pause valkey): данные в кэше сохраняются")
|
||||
compose("pause", "valkey")
|
||||
try:
|
||||
api.call("GET", "/api/v1/users/me", actor=dave, schema="User") # этот запрос обнаруживает сбой кэша
|
||||
api.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=dave)
|
||||
api.call("GET", "/api/v1/users/me", 401, actor=dave)
|
||||
print("во время паузы: logout -> 204, тот же токен -> 401")
|
||||
finally:
|
||||
print("unpausing valkey")
|
||||
compose("unpause", "valkey")
|
||||
|
||||
wait_ready(api)
|
||||
# Фоновая проверка возвращает кэш в работу в течение 5 с. Смотрим 12 с — дольше, чем она.
|
||||
deadline = time.monotonic() + 12
|
||||
checks = 0
|
||||
while time.monotonic() < deadline:
|
||||
api.call("GET", "/api/v1/users/me", 401, actor=dave)
|
||||
api.call("POST", "/api/v1/chats", 401, actor=dave, body={"title": "x", "member_ids": [dave["id"]]})
|
||||
checks += 1
|
||||
time.sleep(0.5)
|
||||
print(f"после unpause: {checks} проверок за 12 с, отозванный токен всегда 401 (и GET, и POST)")
|
||||
|
||||
api.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
api.message(bob, chat, "после возвращения Valkey")
|
||||
print("действующие токены других пользователей работают")
|
||||
print("PASS: revoked session stays revoked after Valkey comes back with stale data")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,83 @@
|
||||
"""lab3, уровень 4: проверка устройства стенда по реальным контейнерам и docker compose config.
|
||||
|
||||
make check-stack (= python student-tests/check_stack.py)
|
||||
|
||||
- не меньше 2 работающих реплик api, у них нет опубликованных портов (обойти балансировщик нельзя);
|
||||
- ни у одного сервиса нет container_name (иначе нельзя запустить несколько реплик одного сервиса);
|
||||
- наружу опубликован только балансировщик и только на 127.0.0.1;
|
||||
- у каждого работающего контейнера есть лимиты CPU и RAM;
|
||||
- сети: postgres и valkey только во внутренней сети backend, lb только в edge, api в обеих;
|
||||
- секреты получает только тот, кому они нужны;
|
||||
- версии Docker, Compose и образов (для отчёта).
|
||||
"""
|
||||
import json
|
||||
|
||||
from helpers import check, run
|
||||
from stand import api_containers, compose_config, compose_output, docker, inspect
|
||||
|
||||
|
||||
def main():
|
||||
config = compose_config()
|
||||
services = config["services"]
|
||||
networks = config.get("networks", {})
|
||||
|
||||
print("docker: " + docker("version", "--format", "{{.Server.Version}}"))
|
||||
print("compose: " + compose_output("version", "--short").strip())
|
||||
|
||||
check(not [name for name, svc in services.items() if "container_name" in svc], "container_name is set")
|
||||
print("container_name: not set for any service (replicas of one service are possible)")
|
||||
|
||||
replicas = api_containers()
|
||||
check(len(replicas) >= 2, f"need >= 2 running api replicas, got {len(replicas)}")
|
||||
print(f"api replicas running: {len(replicas)} -> {[c[:12] for c in replicas]} "
|
||||
f"(deploy.replicas = {services['api'].get('deploy', {}).get('replicas')})")
|
||||
|
||||
print()
|
||||
print(f"{'service':<14} {'container':<13} {'cpus':>5} {'memory':>8} {'published ports':<34} networks")
|
||||
published = {}
|
||||
for container in sorted(compose_output("ps", "-q").split()):
|
||||
service = inspect(container, '{{index .Config.Labels "com.docker.compose.service"}}')
|
||||
nano_cpus = int(inspect(container, "{{.HostConfig.NanoCpus}}") or 0)
|
||||
memory = int(inspect(container, "{{.HostConfig.Memory}}") or 0)
|
||||
ports = json.loads(inspect(container, "{{json .NetworkSettings.Ports}}") or "{}") or {}
|
||||
bindings = [f"{b['HostIp']}:{b['HostPort']}->{port}" for port, items in ports.items() for b in (items or [])]
|
||||
nets = sorted(json.loads(inspect(container, "{{json .NetworkSettings.Networks}}") or "{}"))
|
||||
nets = [name.split("_", 1)[-1] for name in nets]
|
||||
published[service] = published.get(service, []) + bindings
|
||||
print(f"{service:<14} {container[:12]:<13} {nano_cpus / 1e9:>5.2f} {memory // 2**20:>6}Mi "
|
||||
f"{', '.join(bindings) or '-':<34} {', '.join(nets)}")
|
||||
check(nano_cpus > 0 and memory > 0, f"{service} {container[:12]} has no CPU/RAM limit")
|
||||
print()
|
||||
|
||||
check(not published.get("api"), "api publishes ports and can be reached bypassing the balancer")
|
||||
others = {service: ports for service, ports in published.items() if ports and service != "lb"}
|
||||
check(not others, f"only the balancer may publish ports, got {others}")
|
||||
check(published.get("lb") and all(b.startswith("127.0.0.1:") for b in published["lb"]),
|
||||
"the balancer must be published on 127.0.0.1 only")
|
||||
print("published: only lb, only on 127.0.0.1 (api replicas have no ports)")
|
||||
print("limits: every running container has CPU and RAM limits")
|
||||
|
||||
def nets_of(name):
|
||||
return sorted(services[name].get("networks", {}))
|
||||
|
||||
check(nets_of("postgres") == ["backend"] and nets_of("valkey") == ["backend"], "stores must be on backend only")
|
||||
check(nets_of("lb") == ["edge"], "lb must be on edge only")
|
||||
check(nets_of("api") == ["backend", "edge"], "api must be on edge and backend")
|
||||
check(networks.get("backend", {}).get("internal") is True, "backend network must be internal")
|
||||
print("networks: lb -> edge; api -> edge + backend; postgres, valkey -> backend (internal: no way out)")
|
||||
|
||||
def secrets_of(name):
|
||||
return sorted(item["source"] for item in services[name].get("secrets", []))
|
||||
|
||||
expected = {"api": ["cache_url", "database_url"], "migrate": ["database_url"], "lb": [],
|
||||
"postgres": ["postgres_password"], "valkey": ["valkey_acl"]}
|
||||
for name, wanted in expected.items():
|
||||
check(secrets_of(name) == wanted, f"{name} secrets {secrets_of(name)} != {wanted}")
|
||||
print("secrets: " + "; ".join(f"{name} -> {', '.join(wanted) or 'none'}" for name, wanted in expected.items()))
|
||||
print("images: " + "; ".join(f"{name} {services[name]['image']}" for name in ("lb", "api", "postgres", "valkey")))
|
||||
print("PASS: one entry point (lb on 127.0.0.1), >= 2 api replicas without ports and container_name, "
|
||||
"CPU/RAM limits everywhere, stores only on the internal network")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Интеграционные тесты хранилища на настоящей PostgreSQL (уровень 4).
|
||||
|
||||
Выполняются ВНУТРИ контейнера приложения (там есть psycopg и доступ к БД по сети стенда):
|
||||
make db-test == docker compose --profile tools run --rm db-test
|
||||
|
||||
Что проверяется:
|
||||
- повторный запуск миграций ничего не меняет;
|
||||
- составная операция «создать чат» откатывается целиком, если упала на середине;
|
||||
- одновременная регистрация одного username даёт ровно одного пользователя;
|
||||
- сама база не даёт записать сообщение от не-участника (внешний ключ);
|
||||
- (lab3) 20 одновременных add_message с одним Idempotency-Key создают одну строку;
|
||||
- (lab3) тот же ключ с другим телом — Conflict (409), строка одна;
|
||||
- (lab3) миграция 004 совместима со старой версией: INSERT сообщения без ключа, как делает
|
||||
код lab2, по-прежнему работает (поэтому миграцию можно применить до замены реплик).
|
||||
"""
|
||||
import hashlib
|
||||
import threading
|
||||
import unittest
|
||||
import uuid
|
||||
from unittest import mock
|
||||
|
||||
import psycopg
|
||||
from psycopg import errors as pg_errors
|
||||
|
||||
from messenger import config, db
|
||||
from messenger.errors import Conflict, InvalidRequest
|
||||
from messenger.store import PostgresStore
|
||||
|
||||
|
||||
class StoreIntegrationTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
config.validate()
|
||||
db.migrate()
|
||||
cls.pool = db.create_pool()
|
||||
cls.pool.open(wait=True)
|
||||
cls.store = PostgresStore(cls.pool)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.pool.close()
|
||||
|
||||
def scalar(self, sql, *params):
|
||||
with self.pool.connection() as conn:
|
||||
return conn.execute(sql, params).fetchone()[0]
|
||||
|
||||
def new_user(self):
|
||||
return self.store.create_user("db_" + uuid.uuid4().hex[:12], "DB test", "not-a-real-hash")
|
||||
|
||||
def test_migrations_rerun_is_noop(self):
|
||||
versions = self.scalar("SELECT array_agg(version ORDER BY version) FROM schema_migrations")
|
||||
users = self.scalar("SELECT count(*) FROM users")
|
||||
self.assertEqual(db.migrate(), []) # второй прогон: применять нечего
|
||||
self.assertEqual(self.scalar("SELECT array_agg(version ORDER BY version) FROM schema_migrations"), versions)
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM users"), users)
|
||||
print(f"\n schema_migrations: {versions}; повторный migrate() ничего не применил")
|
||||
|
||||
def test_create_chat_rolls_back_when_failing_midway(self):
|
||||
alice = self.new_user()
|
||||
ghost = str(uuid.uuid4()) # такого пользователя нет
|
||||
title = "rollback-" + uuid.uuid4().hex[:8]
|
||||
# Отключаем предварительную проверку участников, чтобы ошибка случилась ВНУТРИ транзакции:
|
||||
# строка чата уже вставлена, а вставка участника-призрака нарушает внешний ключ.
|
||||
with mock.patch.object(PostgresStore, "_check_members_exist", staticmethod(lambda conn, members: None)):
|
||||
with self.assertRaises(InvalidRequest):
|
||||
self.store.create_chat(alice.id, title, [alice.id, ghost])
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM chats WHERE title = %s", title), 0)
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM chat_members WHERE user_id = %s", uuid.UUID(alice.id)), 0)
|
||||
print("\n чат с несуществующим участником: транзакция откатилась, строк chats/chat_members не осталось")
|
||||
|
||||
def test_concurrent_registration_has_one_winner(self):
|
||||
username = "dbrace_" + uuid.uuid4().hex[:10]
|
||||
threads, barrier, results = 20, threading.Barrier(20), []
|
||||
|
||||
def register():
|
||||
barrier.wait()
|
||||
try:
|
||||
self.store.create_user(username, "Race", "not-a-real-hash")
|
||||
results.append("created")
|
||||
except Conflict:
|
||||
results.append("conflict")
|
||||
|
||||
workers = [threading.Thread(target=register) for _ in range(threads)]
|
||||
for w in workers:
|
||||
w.start()
|
||||
for w in workers:
|
||||
w.join()
|
||||
self.assertEqual(results.count("created"), 1)
|
||||
self.assertEqual(results.count("conflict"), threads - 1)
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM users WHERE username = %s", username), 1)
|
||||
print(f"\n {threads} параллельных create_user: 1 создан, {threads - 1} получили Conflict (409)")
|
||||
|
||||
def test_concurrent_same_idempotency_key_creates_one_row(self):
|
||||
alice = self.new_user()
|
||||
chat = self.store.create_chat(alice.id, "idem", [alice.id])
|
||||
key, digest = "db-" + uuid.uuid4().hex, hashlib.sha256(b"same body").digest()
|
||||
threads, barrier, results, errors = 20, threading.Barrier(20), [], []
|
||||
|
||||
def send():
|
||||
barrier.wait()
|
||||
try:
|
||||
results.append(self.store.add_message(alice.id, chat.id, "один раз", key, digest))
|
||||
except Exception as exc: # noqa: BLE001 — любая ошибка = провал теста
|
||||
errors.append(exc)
|
||||
|
||||
workers = [threading.Thread(target=send) for _ in range(threads)]
|
||||
for w in workers:
|
||||
w.start()
|
||||
for w in workers:
|
||||
w.join()
|
||||
self.assertEqual(errors, [])
|
||||
self.assertEqual(len({message.id for message, _ in results}), 1)
|
||||
self.assertEqual(sum(1 for _, replayed in results if not replayed), 1)
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM messages WHERE chat_id = %s", uuid.UUID(chat.id)), 1)
|
||||
print(f"\n {threads} одновременных add_message с одним ключом: 1 строка, 1 новое + "
|
||||
f"{threads - 1} повторов с тем же сообщением")
|
||||
|
||||
def test_same_key_other_body_is_conflict(self):
|
||||
alice = self.new_user()
|
||||
chat = self.store.create_chat(alice.id, "idem409", [alice.id])
|
||||
key = "db-" + uuid.uuid4().hex
|
||||
self.store.add_message(alice.id, chat.id, "первый", key, hashlib.sha256(b"first").digest())
|
||||
with self.assertRaises(Conflict):
|
||||
self.store.add_message(alice.id, chat.id, "другой", key, hashlib.sha256(b"other").digest())
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM messages WHERE chat_id = %s", uuid.UUID(chat.id)), 1)
|
||||
print("\n тот же ключ с другим телом: Conflict (409), в базе по-прежнему одна строка")
|
||||
|
||||
def test_old_version_insert_without_key_still_works(self):
|
||||
alice = self.new_user()
|
||||
chat = self.store.create_chat(alice.id, "compat", [alice.id])
|
||||
with psycopg.connect(config.DATABASE_URL) as conn:
|
||||
for _ in range(2): # две строки без ключа: NULL не нарушает уникальность
|
||||
conn.execute("INSERT INTO messages (id, chat_id, sender_id, text) VALUES (%s, %s, %s, %s)",
|
||||
(uuid.uuid4(), uuid.UUID(chat.id), uuid.UUID(alice.id), b"lab2 style"))
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM messages WHERE chat_id = %s AND idempotency_key IS NULL",
|
||||
uuid.UUID(chat.id)), 2)
|
||||
print("\n INSERT как в lab2 (без ключа) после миграции 004 работает: старая версия совместима со схемой")
|
||||
|
||||
def test_database_rejects_message_from_non_member(self):
|
||||
alice, mallory = self.new_user(), self.new_user()
|
||||
chat = self.store.create_chat(alice.id, "fk", [alice.id])
|
||||
with self.assertRaises(pg_errors.ForeignKeyViolation):
|
||||
with psycopg.connect(config.DATABASE_URL) as conn:
|
||||
conn.execute("INSERT INTO messages (id, chat_id, sender_id, text) VALUES (%s, %s, %s, 'x')",
|
||||
(uuid.uuid4(), uuid.UUID(chat.id), uuid.UUID(mallory.id)))
|
||||
print("\n INSERT сообщения от не-участника напрямую в БД: ForeignKeyViolation")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Демонстрация для защиты: пользователи, вход, чат, сообщения, logout — через балансировщик.
|
||||
|
||||
Запуск: make demo (печатает шаги; пароли и токены не выводятся)
|
||||
У каждого шага в скобках — какая реплика API ответила (X-Instance-Id = ID контейнера в `make ps`).
|
||||
"""
|
||||
import uuid
|
||||
|
||||
from helpers import Client, read_history, run
|
||||
|
||||
|
||||
def main():
|
||||
api = Client()
|
||||
|
||||
def who(reply):
|
||||
return reply["headers"]["X-Instance-Id"]
|
||||
|
||||
ready = api.call("GET", "/health/ready", schema="Health")
|
||||
print(f"1. /health/ready -> 200 ({who(ready)}): API запущен, PostgreSQL доступна, схема актуальна")
|
||||
alice, bob, eve, chat = api.bootstrap() # регистрация с паролем + вход через Basic у каждого
|
||||
for name, actor in (("alice", alice), ("bob", bob), ("eve", eve)):
|
||||
print(f"2. зарегистрирован {name}: {actor['user']['username']}, вход через Basic -> Bearer-токен")
|
||||
print(f"3. alice создала чат {chat['id']} с bob (eve не участник)")
|
||||
served = [who(api.call("GET", "/api/v1/users/me", actor=alice, schema="User")) for _ in range(4)]
|
||||
print(f"4. один и тот же токен alice, 4 запроса -> реплики {served}: повторный вход не нужен")
|
||||
key = uuid.uuid4().hex
|
||||
first = api.message(alice, chat, "Привет, Боб! Это сообщение лежит в PostgreSQL", key=key)
|
||||
again = api.message(alice, chat, "Привет, Боб! Это сообщение лежит в PostgreSQL", key=key)
|
||||
print(f"5. alice отправила сообщение ({who(first)}) и повторила его с тем же Idempotency-Key "
|
||||
f"({who(again)}): тот же id {again['json']['id'] == first['json']['id']}")
|
||||
api.message(bob, chat, "Привет, Алиса! Переживёт перезапуск и отказ реплики")
|
||||
history, pages = read_history(api, bob, chat["id"], limit=1)
|
||||
print(f"6. история чата (по 1 сообщению на страницу, страниц: {pages}) — дубля нет:")
|
||||
names = {alice["id"]: "alice", bob["id"]: "bob"}
|
||||
for m in history:
|
||||
print(f" {m['created_at']} {names[m['sender_id']]}: {m['text']}")
|
||||
api.call("GET", f"/api/v1/chats/{chat['id']}/messages", 404, actor=eve)
|
||||
print("7. eve читает чужой чат -> 404 (существование чата не раскрывается)")
|
||||
api.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
after = [who(api.call("GET", "/api/v1/users/me", 401, actor=alice)) for _ in range(2)]
|
||||
print(f"8. alice logout -> 204, тот же токен -> 401 на репликах {after}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Отказ зависимости (уровень 4). Запуск: make failure-valkey или make failure-postgres
|
||||
|
||||
Тест сам останавливает указанный контейнер (docker compose stop), проверяет поведение API
|
||||
и запускает контейнер обратно (docker compose start). Volumes не трогаются.
|
||||
|
||||
valkey — кэш недоступен: API обходит его и работает через PostgreSQL; logout действует сразу.
|
||||
postgres — источник истины недоступен: API отвечает ограниченной ошибкой 503 (без деталей),
|
||||
/health/ready = 503, аноним и неизвестный токен НЕ получают успешный ответ.
|
||||
После запуска БД прежний токен и данные снова доступны.
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from helpers import Client, basic, check, compose, idempotency, read_history, run, wait_ready
|
||||
|
||||
|
||||
def timed(fn):
|
||||
started = time.monotonic()
|
||||
result = fn()
|
||||
return result, (time.monotonic() - started) * 1000
|
||||
|
||||
|
||||
def valkey_down(api, alice, bob, chat):
|
||||
ready, ms = timed(lambda: api.call("GET", "/health/ready", schema="Health"))
|
||||
print(f"/health/ready -> 200 ({ms:.0f} ms): Valkey не критичен, API готов")
|
||||
_, ms = timed(lambda: api.call("GET", "/api/v1/users/me", actor=alice, schema="User"))
|
||||
print(f"existing token: GET /users/me -> 200 ({ms:.0f} ms), сессия проверена по PostgreSQL (этот запрос и обнаружил сбой кэша)")
|
||||
sent = api.message(bob, chat, "во время отказа Valkey")["json"]
|
||||
history, _ = read_history(api, alice, chat["id"])
|
||||
check(sent["id"] in [m["id"] for m in history], "message written during Valkey outage is missing")
|
||||
print("POST message -> 201, история читается")
|
||||
carol = api.user("carol") # регистрация и вход тоже работают без кэша
|
||||
print("register + login new user -> 201")
|
||||
api.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=carol)
|
||||
api.call("GET", "/api/v1/users/me", 401, actor=carol)
|
||||
print("logout -> 204, затем тот же токен -> 401 (отзыв записан в PostgreSQL)")
|
||||
latencies = [timed(lambda: api.call("GET", "/api/v1/users/me", actor=alice))[1] for _ in range(10)]
|
||||
print(f"10 x GET /users/me без кэша: max {max(latencies):.0f} ms (кэш не ждём на каждом запросе)")
|
||||
check(max(latencies) < 1000, "requests must not wait for the dead cache on every call")
|
||||
# Фоновая проверка Valkey идёт раз в 5 с. Ждём дольше и убеждаемся, что запросы её не ждут.
|
||||
time.sleep(6)
|
||||
latencies = [timed(lambda: api.call("GET", "/api/v1/users/me", actor=alice))[1] for _ in range(10)]
|
||||
print(f"через 6 с, ещё 10 x GET /users/me: max {max(latencies):.0f} ms (повторные попытки — в фоне)")
|
||||
check(max(latencies) < 1000, "periodic reconnect attempts must not block user requests")
|
||||
return carol
|
||||
|
||||
|
||||
def postgres_down(api, alice, chat):
|
||||
api.call("GET", "/health/live", schema="Health")
|
||||
print("/health/live -> 200: процесс жив")
|
||||
_, ms = timed(lambda: api.call("GET", "/health/ready", 503))
|
||||
print(f"/health/ready -> 503 ({ms:.0f} ms): без PostgreSQL обслуживать нельзя")
|
||||
for method, path in (("GET", "/api/v1/chats"), ("GET", f"/api/v1/chats/{chat['id']}/messages")):
|
||||
error = api.call(method, path, 503, actor=alice)["json"]["error"]
|
||||
check(error["code"] == "unavailable", "expected unavailable error code")
|
||||
api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 503, actor=alice, body={"text": "не сохранится"},
|
||||
headers=idempotency())
|
||||
print("бизнес-запросы с действующим токеном -> 503 unavailable (без SQL и stack trace в ответе)")
|
||||
api.call("GET", "/api/v1/users/me", 401)
|
||||
print("без токена -> 401: аноним не становится доверенным")
|
||||
status = api.call("GET", "/api/v1/users/me", [401, 503], headers={"Authorization": "Bearer " + "x" * 43})["status"]
|
||||
print(f"неизвестный токен -> {status}: не подтверждается ни кэшем, ни базой")
|
||||
status = api.call("POST", "/api/v1/auth/sessions", [401, 503],
|
||||
headers={"Authorization": basic("nobody", "Some-password-1")})["status"]
|
||||
print(f"вход -> {status}: сессию без базы не выдаём")
|
||||
api.call("POST", "/api/v1/users", 503,
|
||||
body={"username": "pg_" + uuid.uuid4().hex[:10], "display_name": "x", "password": "Pg-down-password"})
|
||||
print("регистрация -> 503")
|
||||
|
||||
|
||||
def main():
|
||||
target = sys.argv[1] if len(sys.argv) > 1 else ""
|
||||
check(target in ("valkey", "postgres"), "usage: dependency_failure.py valkey|postgres")
|
||||
api = Client()
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
before = api.message(alice, chat, "до отказа " + target)["json"]
|
||||
|
||||
print(f"stopping {target} (docker compose stop {target})")
|
||||
compose("stop", target)
|
||||
try:
|
||||
if target == "valkey":
|
||||
carol = valkey_down(api, alice, bob, chat)
|
||||
else:
|
||||
postgres_down(api, alice, chat)
|
||||
finally:
|
||||
print(f"starting {target} again")
|
||||
compose("start", target)
|
||||
|
||||
wait_ready(api)
|
||||
history, _ = read_history(api, alice, chat["id"])
|
||||
check(before in history, "message confirmed before the outage is lost or changed")
|
||||
api.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
if target == "valkey":
|
||||
api.call("GET", "/api/v1/users/me", 401, actor=carol) # отозванный токен не «воскрес» из кэша
|
||||
print("after recovery: прежний токен работает, подтверждённые сообщения на месте")
|
||||
print(f"PASS: {target} outage handled without trusting anonymous requests")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Проверка истечения сессии при коротком TTL (уровень 4). Запуск: make expiry
|
||||
|
||||
Нужен второй экземпляр API с SESSION_TTL_SECONDS=2 (сервис api-short-ttl, make expiry
|
||||
поднимает его сам). С lab3 он, как и основные реплики, доступен только через балансировщик:
|
||||
127.0.0.1:8081. База и кэш общие с основным API.
|
||||
|
||||
Сценарий: вход -> токен работает (и попадает в кэш Valkey) -> ждём истечения ->
|
||||
токен отклоняется с 401 и на коротком, и на основном API. Значит, срок жизни — свойство
|
||||
сессии в PostgreSQL, а кэш не продлевает её.
|
||||
"""
|
||||
import datetime as dt
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from helpers import Client, check, login, run
|
||||
|
||||
|
||||
def main():
|
||||
short = Client(os.environ.get("BASE_URL_TTL", "http://127.0.0.1:8081"))
|
||||
main_api = Client()
|
||||
body = {"username": "ttl_" + uuid.uuid4().hex[:12], "display_name": "TTL", "password": "Ttl-password-123"}
|
||||
short.call("POST", "/api/v1/users", 201, body=body, schema="User")
|
||||
session = login(short, body["username"], body["password"])
|
||||
auth = {"Authorization": "Bearer " + session["token"]}
|
||||
expires_at = dt.datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||||
ttl = (expires_at - dt.datetime.now(dt.timezone.utc)).total_seconds()
|
||||
print(f"session issued by short-TTL API, expires in {ttl:.2f}s")
|
||||
check(0 < ttl <= 3, "short-TTL instance must issue ~2 second sessions")
|
||||
|
||||
for api in (short, short, main_api): # два раза подряд: второй ответ уже из кэша
|
||||
api.call("GET", "/api/v1/users/me", 200, headers=auth, schema="User")
|
||||
print("before expiry: GET /users/me -> 200 (short API twice, main API once)")
|
||||
|
||||
time.sleep(max(0.0, (expires_at - dt.datetime.now(dt.timezone.utc)).total_seconds()) + 1.0)
|
||||
for api in (short, main_api):
|
||||
api.call("GET", "/api/v1/users/me", 401, headers=auth) # клиент проверяет WWW-Authenticate: Bearer
|
||||
print("after expiry: GET /users/me -> 401 on both instances")
|
||||
print("PASS: session expired after SESSION_TTL_SECONDS; cache did not extend it")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,148 @@
|
||||
"""lab3, уровень 4: по очереди останавливаем КАЖДУЮ реплику API под нагрузкой и меряем.
|
||||
|
||||
make failover-metrics (= python student-tests/failover_metrics.py: stop и kill)
|
||||
python student-tests/failover_metrics.py stop (только плановая остановка)
|
||||
|
||||
Режимы:
|
||||
stop — docker stop (SIGTERM): плановая остановка. Реплика сначала отвечает 503 на /health/ready,
|
||||
HAProxy выводит её из балансировки, и только потом она закрывает приём (__main__.py).
|
||||
kill — docker kill (SIGKILL): авария. Процесс умирает сразу, начатые на нём запросы обрываются,
|
||||
клиент повторяет их с тем же Idempotency-Key.
|
||||
Нагрузка (loadgen.py): 4 потока пишут сообщения без пауз, 1 поток читает историю, timeout клиента 2 с.
|
||||
Меряем: успешные записи в секунду до и после отказа, ошибки и их коды, через сколько HAProxy вывел
|
||||
реплику (по его статистике, опрос раз в 0,1 с), через сколько прекратились ошибки, отвечала ли
|
||||
остановленная реплика после остановки, нет ли потерь и дублей. Затем реплика запускается снова
|
||||
(docker start) и ждём, пока HAProxy вернёт её, — только потом следующий прогон.
|
||||
Итог: таблица в консоли и evidence/failover-metrics.json (без токенов).
|
||||
"""
|
||||
import json
|
||||
import platform
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
from helpers import ROOT, check, run
|
||||
from loadgen import CLIENT_TIMEOUT_SECONDS, WRITERS, Load, summary
|
||||
from stand import api_containers, docker, lb_up_count, wait_balanced
|
||||
|
||||
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: {WRITERS} writers without pauses + 1 reader, "
|
||||
f"client timeout {CLIENT_TIMEOUT_SECONDS} s, retry with the same Idempotency-Key; "
|
||||
f"{WARMUP_SECONDS} s before and {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"last error ended {run['errors_stopped_after_seconds']} s after the failure")
|
||||
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": WRITERS, "readers": 1, "client_timeout_seconds": CLIENT_TIMEOUT_SECONDS,
|
||||
"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).as_posix()}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Общие помощники для собственных тестов.
|
||||
|
||||
Переиспользуем публичный HTTP-клиент курса (tests/client.py), а не пишем свой:
|
||||
он уже проверяет X-Request-Id, X-Instance-Id (с lab3), формат ошибок, WWW-Authenticate
|
||||
и схемы ответов из контракта.
|
||||
С lab2 клиент сам регистрирует пользователя с паролем, входит через Basic
|
||||
и подставляет Bearer-токен (токен живёт только в памяти теста и не печатается).
|
||||
"""
|
||||
import base64
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from client import Client, Failure, check, run # noqa: E402 (импорт после правки sys.path)
|
||||
|
||||
__all__ = ["Client", "Failure", "check", "run", "read_history", "basic", "login", "compose", "wait_ready",
|
||||
"idempotency", "ROOT"]
|
||||
|
||||
|
||||
def idempotency(key=None):
|
||||
"""Заголовок Idempotency-Key (обязателен для POST сообщения с lab3). Без аргумента — новый ключ."""
|
||||
return {"Idempotency-Key": key or uuid.uuid4().hex}
|
||||
|
||||
|
||||
def read_history(api, actor, chat_id, limit=100):
|
||||
"""Читает всю историю чата по страницам. Возвращает (сообщения, число_страниц)."""
|
||||
items, pages, cursor = [], 0, None
|
||||
while True:
|
||||
query = f"?limit={limit}" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
|
||||
page = api.call("GET", f"/api/v1/chats/{chat_id}/messages{query}",
|
||||
actor=actor, schema="MessagePage")["json"]
|
||||
items += page["items"]
|
||||
pages += 1
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return items, pages
|
||||
|
||||
|
||||
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(api, username, password, expected=201):
|
||||
"""POST /auth/sessions; при успехе возвращает тело Session (токен — только в памяти)."""
|
||||
schema = "Session" if expected == 201 else None
|
||||
return api.call("POST", "/api/v1/auth/sessions", expected,
|
||||
headers={"Authorization": basic(username, password)}, schema=schema)["json"]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
"""docker compose <args> из корня репозитория; вывод скрыт (там могут быть имена/секреты)."""
|
||||
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def wait_ready(api, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
try:
|
||||
api.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, f"API не стал готов за {seconds} с")
|
||||
time.sleep(0.5)
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Профиль нагрузки для отчёта: публичный tests/load.py + CPU/RAM контейнеров во время нагрузки.
|
||||
|
||||
python student-tests/load_profile.py (30 с, 4 потока — как в tests/README.md)
|
||||
|
||||
Запускает tests/load.py (closed loop: каждый поток шлёт следующий POST сразу после ответа)
|
||||
и параллельно раз в ~2 с снимает `docker stats --no-stream` по контейнерам стенда.
|
||||
Сохраняет evidence/load.json (вывод load.py: успешные RPS, ошибки, p50/p95/p99)
|
||||
и evidence/load-stats.json (максимум CPU % и RAM по каждому сервису за время нагрузки).
|
||||
Числа зависят от машины и Docker Desktop; это замер этого стенда, а не предел пропускной способности.
|
||||
"""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
from helpers import ROOT, check, run
|
||||
from stand import BASE_URL, compose_output, inspect
|
||||
|
||||
DURATION, CONCURRENCY = 30, 4
|
||||
LOAD_JSON = ROOT / "evidence" / "load.json"
|
||||
STATS_JSON = ROOT / "evidence" / "load-stats.json"
|
||||
|
||||
|
||||
def mib(text):
|
||||
"""'123.4MiB' / '1.2GiB' / '512kB' -> MiB."""
|
||||
text = text.strip()
|
||||
units = {"KiB": 1 / 1024, "kB": 1 / 1024, "MiB": 1, "MB": 1, "GiB": 1024, "GB": 1024, "B": 1 / 2**20}
|
||||
for unit in sorted(units, key=len, reverse=True):
|
||||
if text.endswith(unit):
|
||||
return float(text[: -len(unit)]) * units[unit]
|
||||
return 0.0
|
||||
|
||||
|
||||
def main():
|
||||
# Только основной путь запроса: балансировщик, реплики API, PostgreSQL, Valkey.
|
||||
names = {c[:12]: inspect(c, '{{index .Config.Labels "com.docker.compose.service"}}')
|
||||
for c in compose_output("ps", "-q").split()}
|
||||
names = {cid: service for cid, service in names.items() if service in ("lb", "api", "postgres", "valkey")}
|
||||
containers = list(names)
|
||||
peaks, stopping = {}, threading.Event()
|
||||
|
||||
def sample():
|
||||
while not stopping.is_set():
|
||||
result = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{json .}}", *containers],
|
||||
capture_output=True, text=True)
|
||||
for line in result.stdout.splitlines():
|
||||
item = json.loads(line)
|
||||
key = item["ID"][:12]
|
||||
cpu = float(item["CPUPerc"].rstrip("%") or 0)
|
||||
used, _, limit = item["MemUsage"].partition("/")
|
||||
peak = peaks.setdefault(key, {"service": names.get(key, "?"), "cpu_percent_max": 0.0,
|
||||
"mem_mib_max": 0.0, "mem_limit_mib": round(mib(limit))})
|
||||
peak["cpu_percent_max"] = max(peak["cpu_percent_max"], cpu)
|
||||
peak["mem_mib_max"] = round(max(peak["mem_mib_max"], mib(used)), 1)
|
||||
time.sleep(1)
|
||||
|
||||
sampler = threading.Thread(target=sample, daemon=True)
|
||||
sampler.start()
|
||||
result = subprocess.run([sys.executable, "tests/load.py", "--base-url", BASE_URL, "--duration", str(DURATION),
|
||||
"--concurrency", str(CONCURRENCY), "--output", str(LOAD_JSON)],
|
||||
cwd=ROOT, capture_output=True)
|
||||
stopping.set()
|
||||
sampler.join(timeout=10)
|
||||
print(result.stdout.decode("utf-8", "replace").strip())
|
||||
check(result.returncode == 0, "tests/load.py failed: " + result.stderr.decode("utf-8", "replace")[-300:])
|
||||
rows = sorted(peaks.values(), key=lambda row: row["service"])
|
||||
STATS_JSON.write_text(json.dumps({"duration_seconds": DURATION, "concurrency": CONCURRENCY,
|
||||
"containers": rows}, indent=2) + "\n", encoding="utf-8")
|
||||
print("\nservice cpu % max RAM max / limit, MiB")
|
||||
for row in rows:
|
||||
print(f"{row['service']:<14} {row['cpu_percent_max']:>9.1f} {row['mem_mib_max']:>7.1f} / {row['mem_limit_mib']}")
|
||||
print(f"PASS: load profile saved to {LOAD_JSON.relative_to(ROOT).as_posix()} and "
|
||||
f"{STATS_JSON.relative_to(ROOT).as_posix()}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Фоновая нагрузка для замеров во время отказа и rolling update
|
||||
(используют failover_metrics.py и rolling_update.py). Только стандартная библиотека.
|
||||
|
||||
WRITERS потоков без пауз пишут сообщения в один чат (closed loop: следующий запрос — сразу после
|
||||
ответа на предыдущий). Если запрос не подтверждён (обрыв, timeout, 5xx), поток повторяет ТОТ ЖЕ
|
||||
запрос с ТЕМ ЖЕ Idempotency-Key — так по контракту делает клиент. Один поток параллельно читает
|
||||
историю. Каждая попытка записывается: время, успех, код, реплика, задержка.
|
||||
В конце verify() читает всю историю и проверяет, что все подтверждённые сообщения на месте
|
||||
и дублей нет (тексты уникальны, поэтому дубль сразу виден).
|
||||
"""
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from helpers import Client, check, read_history
|
||||
from stand import try_call
|
||||
|
||||
WRITERS = 4
|
||||
CLIENT_TIMEOUT_SECONDS = 2
|
||||
|
||||
|
||||
class Load:
|
||||
def __init__(self, writers=WRITERS, timeout=CLIENT_TIMEOUT_SECONDS):
|
||||
self.api = Client()
|
||||
self.alice, self.bob = self.api.user("load_a"), self.api.user("load_b")
|
||||
self.chat = self.api.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat",
|
||||
body={"title": "load", "member_ids": [self.alice["id"], self.bob["id"]]})["json"]
|
||||
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 = uuid.uuid4().hex, 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 = uuid.uuid4().hex, 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.api, 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):
|
||||
"""Успешные записи в секунду, ошибки по кодам и задержки успешных записей на отрезке [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,
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Проверка гонок (уровень 4). Запуск: make race
|
||||
|
||||
1. 10 клиентов одновременно отправляют по 10 сообщений в один чат:
|
||||
в истории ровно 100 сообщений, все id уникальны, ни один текст не потерян.
|
||||
2. 20 клиентов одновременно регистрируют ОДИН И ТОТ ЖЕ username:
|
||||
ровно один получает 201, остальные 409; в базе один такой пользователь.
|
||||
Защита — уникальный индекс users.username в PostgreSQL, а не проверка в коде.
|
||||
"""
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from helpers import Client, check, idempotency, read_history, run
|
||||
|
||||
CLIENTS = 10
|
||||
PER_CLIENT = 10
|
||||
REGISTRATIONS = 20
|
||||
|
||||
|
||||
def concurrent_messages(api):
|
||||
users = [api.user(f"race{i}") for i in range(CLIENTS)]
|
||||
chat = api.call("POST", "/api/v1/chats", 201, actor=users[0], schema="Chat",
|
||||
body={"title": "race", "member_ids": [u["id"] for u in users]})["json"]
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
start_together = threading.Barrier(CLIENTS) # все потоки стартуют одновременно
|
||||
|
||||
def send_all(index):
|
||||
client = Client() # у каждого «клиента» свои HTTP-соединения
|
||||
start_together.wait()
|
||||
for n in range(PER_CLIENT):
|
||||
client.call("POST", path, 201, actor=users[index], body={"text": f"client-{index}-msg-{n}"},
|
||||
headers=idempotency())
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
|
||||
list(pool.map(send_all, range(CLIENTS))) # list() пробрасывает ошибки из потоков
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
history, pages = read_history(api, users[0], chat["id"], limit=25)
|
||||
expected = {f"client-{i}-msg-{n}" for i in range(CLIENTS) for n in range(PER_CLIENT)}
|
||||
print(f"messages: sent {CLIENTS * PER_CLIENT} from {CLIENTS} parallel clients in {elapsed:.2f}s")
|
||||
print(f"messages: read {len(history)} in {pages} pages, unique ids: {len({m['id'] for m in history})}")
|
||||
check(len(history) == CLIENTS * PER_CLIENT, "wrong number of messages")
|
||||
check(len({m["id"] for m in history}) == len(history), "duplicate message ids")
|
||||
check({m["text"] for m in history} == expected, "lost or corrupted message texts")
|
||||
print("PASS: 100 concurrent messages stored without loss or duplicates")
|
||||
|
||||
|
||||
def concurrent_registration():
|
||||
username = "race_" + uuid.uuid4().hex[:12]
|
||||
start_together = threading.Barrier(REGISTRATIONS)
|
||||
|
||||
def register(index):
|
||||
client = Client()
|
||||
body = {"username": username, "display_name": f"Участник {index}", "password": f"Race-password-{index:03d}"}
|
||||
start_together.wait()
|
||||
return client.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"registration: {REGISTRATIONS} parallel requests for one username -> 201 x{created}, 409 x{conflicts}")
|
||||
check(created == 1 and conflicts == REGISTRATIONS - 1, "exactly one registration must win")
|
||||
print("PASS: concurrent registration of the same username created exactly one user")
|
||||
|
||||
|
||||
def main():
|
||||
api = Client()
|
||||
concurrent_messages(api)
|
||||
concurrent_registration()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Таблицы замеров для REPORT.md из evidence/*.json (без ручного переписывания чисел).
|
||||
|
||||
make report-tables (= python student-tests/report_tables.py)
|
||||
|
||||
Берёт evidence/failover-metrics.json, rolling-update.json, load.json, load-stats.json
|
||||
и время из evidence/persistence.txt, собирает markdown-таблицы и вставляет их в REPORT.md
|
||||
между метками <!-- measurements:begin --> и <!-- measurements:end -->. Запускать после
|
||||
make failover-metrics, make rolling-update, make load-profile и make persistence.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
|
||||
from helpers import ROOT, check, run
|
||||
|
||||
EVIDENCE = ROOT / "evidence"
|
||||
REPORT = ROOT / "REPORT.md"
|
||||
BEGIN, END = "<!-- measurements:begin -->", "<!-- measurements:end -->"
|
||||
|
||||
|
||||
def load(name):
|
||||
path = EVIDENCE / name
|
||||
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else None
|
||||
|
||||
|
||||
def codes(mapping):
|
||||
return ", ".join(f"{code}: {count}" for code, count in mapping.items()) or "-"
|
||||
|
||||
|
||||
def failover_table(data):
|
||||
lines = [
|
||||
f"Остановка каждой реплики под нагрузкой (`make failover-metrics`, evidence/failover-metrics.json): "
|
||||
f"{data['profile']['writers']} потока пишут сообщения без пауз, 1 читает историю, timeout клиента "
|
||||
f"{data['profile']['client_timeout_seconds']} с, неподтверждённая запись повторяется с тем же ключом; "
|
||||
f"{data['profile']['warmup_seconds']} с до отказа и {data['profile']['after_seconds']} с после. "
|
||||
"stop = `docker stop` (SIGTERM, плановая остановка), kill = `docker kill` (SIGKILL, авария).",
|
||||
"",
|
||||
"| Реплика | Отказ | Вывод из LB, с | Ошибок (коды) | Ошибки закончились через, с | Записей/с до → после | "
|
||||
"p95 записи после, мс | Возврат в LB после `docker start`, с | Потери / дубли |",
|
||||
"| --- | --- | --- | --- | --- | --- | --- | --- | --- |",
|
||||
]
|
||||
for r in data["runs"]:
|
||||
lines.append(f"| {r['replica']} | {r['mode']} | {r['lb_excluded_after_seconds']} | {r['errors']} "
|
||||
f"({codes(r['error_codes'])}) | {r['errors_stopped_after_seconds']} | "
|
||||
f"{r['before']['write_rps']} → {r['after']['write_rps']} | {r['after']['write_p95_ms']} | "
|
||||
f"{r['rejoin_seconds']} | 0 / 0 (подтверждено {r['integrity']['confirmed_writes']}) |")
|
||||
return lines
|
||||
|
||||
|
||||
def rolling_lines(data):
|
||||
during = data["during"]
|
||||
steps = "; ".join(f"{s['old']} → {s['new']}: новая готова через {s['new_ready_seconds']} с, шаг {s['step_seconds']} с"
|
||||
for s in data["steps"])
|
||||
return [f"Rolling update под той же нагрузкой (`make rolling-update`, evidence/rolling-update.json): версия "
|
||||
f"{data['from_version']} → {data['to_version']}, {data['replicas']} реплики заменены по одной за "
|
||||
f"{data['update_seconds']} с ({steps}). Записей/с до: {data['before']['write_rps']}, во время замены: "
|
||||
f"{during['write_rps']}; ошибок: {during['errors']} ({codes(during['error_codes'])}); p95 "
|
||||
f"{during['write_p95_ms']} мс, максимум {during['write_max_ms']} мс; подтверждено "
|
||||
f"{data['integrity']['confirmed_writes']} сообщений, потерь и дублей нет."]
|
||||
|
||||
|
||||
def load_lines(data, stats):
|
||||
latency = data["successful_latency_ms"]
|
||||
lines = [f"Публичный генератор нагрузки (`make load-profile` = `tests/load.py`, closed loop, {data['concurrency']} "
|
||||
f"потока, {data['requested_duration_seconds']:.0f} с, 2 реплики): {data['successful_rps']} успешных "
|
||||
f"POST/с, ошибок {data['failed_requests']} (доля {data['error_ratio']}), задержка успешных: p50 "
|
||||
f"{latency['p50']} мс, p95 {latency['p95']} мс, p99 {latency['p99']} мс."]
|
||||
if stats:
|
||||
lines += ["", "| Сервис | CPU, % макс. (100 % = 1 ядро) | RAM макс. / лимит, МиБ |", "| --- | --- | --- |"]
|
||||
lines += [f"| {row['service']} | {row['cpu_percent_max']:.1f} | {row['mem_mib_max']:.0f} / {row['mem_limit_mib']} |"
|
||||
for row in stats["containers"]]
|
||||
return lines
|
||||
|
||||
|
||||
def impacts(failover, rolling):
|
||||
rows = ["| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |",
|
||||
"| --- | --- | --- | --- |"]
|
||||
if failover:
|
||||
for mode, title, expect in (
|
||||
("stop", "`docker stop` одной реплики (по очереди каждой)",
|
||||
"реплика сама уходит из балансировки до выхода; ошибок нет"),
|
||||
("kill", "`docker kill` одной реплики (по очереди каждой)",
|
||||
"несколько 502 у запросов, начатых на ней; клиент повторяет с тем же ключом")):
|
||||
runs = [r for r in failover["runs"] if r["mode"] == mode]
|
||||
if not runs:
|
||||
continue
|
||||
errors = sum(r["errors"] for r in runs)
|
||||
out = max(r["lb_excluded_after_seconds"] or 0 for r in runs)
|
||||
end = max(r["errors_stopped_after_seconds"] for r in runs)
|
||||
recovery = f"ошибки закончились не позже {end} с после отказа" if errors else "ошибок не было"
|
||||
rows.append(f"| {title} | {expect} | ошибок всего {errors} за {len(runs)} прогона; HAProxy вывел реплику "
|
||||
f"не позже {out} с; остановленная реплика после остановки не отвечала | {recovery}; "
|
||||
f"потерь и дублей 0 |")
|
||||
if rolling:
|
||||
rows.append(f"| Rolling update 2 реплик под нагрузкой | замена по одной без простоя | ошибок "
|
||||
f"{rolling['during']['errors']}, записей/с {rolling['during']['write_rps']} | "
|
||||
f"{rolling['update_seconds']} с на замену; потерь и дублей 0 |")
|
||||
persistence = EVIDENCE / "persistence.txt"
|
||||
if persistence.exists():
|
||||
found = re.search(r"test took ([\d.]+) s", persistence.read_text(encoding="utf-8"))
|
||||
if found:
|
||||
rows.append(f"| Перезапуск всего стенда (`make persistence`, hook restart) | данные и действующий токен "
|
||||
f"сохраняются | PASS: те же контейнеры с новым временем старта, прежний токен работает | "
|
||||
f"{found.group(1)} с на весь тест (hook + готовность); потерь нет |")
|
||||
# Отказы зависимостей (проверки lab2, теперь через балансировщик): строка — если тест прошёл.
|
||||
for name, title, expect, seen, recovery in (
|
||||
("failure-valkey.txt", "`docker compose stop valkey`", "API работает без кэша",
|
||||
"ready 200; вход, сообщения и logout работают через PostgreSQL",
|
||||
"кэш снова включается за 1–2 с после start; потерь нет"),
|
||||
("failure-postgres.txt", "`docker compose stop postgres`", "503 без подробностей, аноним не доверенный",
|
||||
"через балансировщик (слоты fallback): ready 503, бизнес-запросы 503, без токена 401",
|
||||
"после start прежний токен и данные на месте; запросы во время отказа не сохранены (503)"),
|
||||
("failure-valkey-pause.txt", "`docker compose pause valkey`, logout, `unpause`",
|
||||
"отозванный токен не оживает ни на одной реплике", "после unpause отозванный токен всегда 401",
|
||||
"поколение кэша сменилось после возвращения Valkey; отзыв не потерян")):
|
||||
path = EVIDENCE / name
|
||||
if path.exists() and "PASS" in path.read_text(encoding="utf-8"):
|
||||
rows.append(f"| {title} | {expect} | {seen} | {recovery} |")
|
||||
return rows if len(rows) > 2 else []
|
||||
|
||||
|
||||
def main():
|
||||
failover, rolling = load("failover-metrics.json"), load("rolling-update.json")
|
||||
load_result, stats = load("load.json"), load("load-stats.json")
|
||||
parts = []
|
||||
for block in (failover and failover_table(failover), rolling and rolling_lines(rolling),
|
||||
load_result and load_lines(load_result, stats), impacts(failover, rolling)):
|
||||
if block:
|
||||
parts += block + [""]
|
||||
check(parts, "no evidence/*.json yet: run make failover-metrics, rolling-update, load-profile first")
|
||||
text = REPORT.read_text(encoding="utf-8")
|
||||
check(BEGIN in text and END in text, "REPORT.md has no measurements markers")
|
||||
head, rest = text.split(BEGIN, 1)
|
||||
_, tail = rest.split(END, 1)
|
||||
REPORT.write_text(head + BEGIN + "\n" + "\n".join(parts).strip() + "\n" + END + tail, encoding="utf-8")
|
||||
print("\n".join(parts).strip())
|
||||
print("\nPASS: tables inserted into REPORT.md between the measurements markers")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,108 @@
|
||||
"""lab3, уровень 4: rolling update под нагрузкой — реплики по одной заменяются новой версией.
|
||||
|
||||
make rolling-update (= python student-tests/rolling_update.py)
|
||||
|
||||
1. Собирается новый образ с APP_VERSION=rolling-<время> (docker compose build api migrate).
|
||||
2. Миграции новой версии применяются ОДИН раз отдельным запуском: docker compose run --rm migrate.
|
||||
Миграции только добавляют (как 004: новые столбцы, которые могут быть NULL), поэтому старые
|
||||
реплики продолжают работать с новой схемой, пока их не заменят.
|
||||
3. Для каждой старой реплики: запустить ещё одну, новую (docker compose up --scale api=N+1
|
||||
--no-recreate), дождаться healthy и UP в HAProxy, затем остановить старую (docker stop:
|
||||
сначала readiness 503 и выход из балансировки) и удалить её. Реплик всё время не меньше N.
|
||||
4. Всё это время идёт нагрузка (loadgen.py): ошибки, RPS, задержки; в конце — проверка,
|
||||
что подтверждённые сообщения на месте и дублей нет.
|
||||
Итог: таблица в консоли и evidence/rolling-update.json. После скрипта стенд работает на новой
|
||||
версии. Обычный `docker compose up -d --build` потом вернёт версию dev, пересоздав реплики разом
|
||||
(это уже не rolling update).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
from helpers import ROOT, check, run
|
||||
from loadgen import CLIENT_TIMEOUT_SECONDS, WRITERS, Load, summary
|
||||
from stand import api_containers, compose_output, compose_quiet, docker, health, lb_summary, lb_up_count, wait_balanced
|
||||
|
||||
OUTPUT = ROOT / "evidence" / "rolling-update.json"
|
||||
|
||||
|
||||
def version_of(container):
|
||||
lines = docker("inspect", "-f", "{{range .Config.Env}}{{println .}}{{end}}", container).splitlines()
|
||||
env = dict(line.split("=", 1) for line in lines if "=" in line)
|
||||
return env.get("APP_VERSION")
|
||||
|
||||
|
||||
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 = version_of(old[0])
|
||||
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_quiet("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)
|
||||
lines = [line for line in migrate_log.splitlines() if "Миграции" in line]
|
||||
print("migrations (one run, before replacing replicas): " + (lines[-1].split("messenger.db: ")[-1] if lines else "?"))
|
||||
|
||||
load = Load()
|
||||
load.start()
|
||||
time.sleep(3)
|
||||
t0 = time.monotonic()
|
||||
steps = []
|
||||
for container in old:
|
||||
step_start = time.monotonic()
|
||||
before = set(api_containers())
|
||||
compose_quiet("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 healthy and UP in HAProxy after "
|
||||
f"{ready:.1f} s, then the old one drained and stopped; step {steps[-1]['step_seconds']} s "
|
||||
f"(HAProxy: {lb_summary()})")
|
||||
t1 = time.monotonic()
|
||||
time.sleep(3)
|
||||
load.stop()
|
||||
|
||||
final = api_containers()
|
||||
versions = sorted({version_of(c) 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": WRITERS, "readers": 1, "client_timeout_seconds": CLIENT_TIMEOUT_SECONDS},
|
||||
"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).as_posix()}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Публичный тест отказа (tests/resilience.py --mode failover) для КАЖДОЙ реплики по очереди.
|
||||
|
||||
make failover (= python student-tests/run_failover.py)
|
||||
|
||||
Публичный тест сам выбирает реплику — ту, что ответила на его первое сообщение, — и вызывает
|
||||
hook scripts/stop-one.cmd (Windows) или scripts/stop-one.sh, который останавливает именно её.
|
||||
Этот скрипт печатает контейнеры до и после теста (видно, какой контейнер реально остановлен
|
||||
и что postgres, valkey и lb не тронуты), запускает реплику обратно (docker start), ждёт,
|
||||
пока HAProxy вернёт её в балансировку, и повторяет тест, пока каждая реплика не будет
|
||||
остановлена хотя бы раз (не больше 6 прогонов).
|
||||
|
||||
Как попасть в нужную реплику: при 2 репликах HAProxy отвечает строго по очереди, а до первого
|
||||
сообщения тест делает 9 запросов. Значит, его сообщение (10-й запрос) уйдёт на ту же реплику,
|
||||
что ответила на наш последний запрос. Поэтому перед прогоном один-два запроса /health/live
|
||||
«сдвигают» очередь так, чтобы последней ответила ещё не проверенная реплика.
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from helpers import ROOT, Client, check, run
|
||||
from stand import BASE_URL, api_containers, docker, lb_summary, ps_table, wait_balanced
|
||||
|
||||
HOOK = ROOT / "scripts" / ("stop-one.cmd" if os.name == "nt" else "stop-one.sh")
|
||||
|
||||
|
||||
def aim(api, wanted):
|
||||
"""Для 2 реплик: последним перед тестом должна ответить реплика из wanted."""
|
||||
probe = api.call("GET", "/health/live", schema="Health")["headers"]["X-Instance-Id"]
|
||||
if not any(container.startswith(probe) for container in wanted):
|
||||
api.call("GET", "/health/live", schema="Health") # теперь последней ответила другая реплика
|
||||
|
||||
|
||||
def main():
|
||||
api = Client()
|
||||
containers = api_containers()
|
||||
check(len(containers) >= 2, "need at least 2 running api replicas")
|
||||
print(f"hook: {HOOK.relative_to(ROOT).as_posix()}; 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(api, set(containers) - stopped_once)
|
||||
print(f"\n=== run {attempt}: containers before (HAProxy: {lb_summary()})")
|
||||
print(ps_table())
|
||||
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(f"containers after (HAProxy: {lb_summary()})")
|
||||
print(ps_table())
|
||||
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, postgres, valkey and lb kept running")
|
||||
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 ({lb_summary()})")
|
||||
if stopped_once == set(containers):
|
||||
break
|
||||
check(stopped_once == set(containers), "not every replica was stopped by the public test")
|
||||
print(f"\nPASS: public failover test passed {attempt} times; every api replica was stopped once and restored")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Публичный тест сохранности (tests/resilience.py --mode persistence) и доказательство,
|
||||
что hook scripts/restart.cmd (Windows) или scripts/restart.sh действительно перезапустил процессы.
|
||||
|
||||
make persistence (= python student-tests/run_persistence.py)
|
||||
|
||||
До и после теста печатаются все контейнеры стенда с временем старта (StartedAt). После теста
|
||||
у postgres, valkey, обеих реплик api и lb должен быть ТОТ ЖЕ ID контейнера (контейнеры и volumes
|
||||
те же, ничего не пересоздано) и НОВОЕ время старта (процесс перезапущен). Сам тест проверяет,
|
||||
что данные и прежний токен на месте. Сервис migrate при `docker compose start api` запускается
|
||||
снова как зависимость: он видит, что новых миграций нет, и сразу завершается.
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from helpers import ROOT, check, run
|
||||
from stand import BASE_URL, compose_output, inspect, ps_table
|
||||
|
||||
HOOK = ROOT / "scripts" / ("restart.cmd" if os.name == "nt" else "restart.sh")
|
||||
MUST_RESTART = ("api", "postgres", "valkey", "lb")
|
||||
|
||||
|
||||
def started_at():
|
||||
"""{ID контейнера: (сервис, время старта)} для работающих сервисов стенда."""
|
||||
result = {}
|
||||
for container in compose_output("ps", "-q").split():
|
||||
service = inspect(container, '{{index .Config.Labels "com.docker.compose.service"}}')
|
||||
result[container] = (service, inspect(container, "{{.State.StartedAt}}"))
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
print(f"hook: {HOOK.relative_to(ROOT).as_posix()}")
|
||||
print("=== containers before")
|
||||
print(ps_table())
|
||||
before = started_at()
|
||||
env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8")
|
||||
t0 = 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)
|
||||
took = time.monotonic() - t0
|
||||
print((result.stdout + result.stderr).decode("utf-8", "replace").strip())
|
||||
check(result.returncode == 0, "public persistence test failed")
|
||||
print(f"=== containers after (test took {took:.1f} s: hook + waiting for readiness + data checks)")
|
||||
print(ps_table())
|
||||
after = started_at()
|
||||
for container, (service, start) in sorted(before.items(), key=lambda item: item[1]):
|
||||
if service not in MUST_RESTART:
|
||||
continue
|
||||
check(container in after, f"{service} {container[:12]} was recreated or is not running")
|
||||
check(after[container][1] != start, f"{service} {container[:12]} was not restarted")
|
||||
print(f"{service:<9} {container[:12]}: same container, start time {start[11:19]} -> {after[container][1][11:19]}")
|
||||
print("PASS: api replicas, postgres, valkey and lb were restarted (same containers and volumes, "
|
||||
"new start time); data and the existing token survived")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Помощники lab3 для собственных проверок: реплики, балансировщик, Docker.
|
||||
|
||||
Только стандартная библиотека Python. Docker вызывается прямо из Python (`docker compose ...`),
|
||||
поэтому всё работает одинаково в Git Bash, PowerShell и cmd на Windows.
|
||||
Вывод проверок — латиницей и кириллицей в UTF-8 (в Git Bash задан PYTHONUTF8=1).
|
||||
"""
|
||||
import csv
|
||||
import http.client
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from helpers import ROOT, check
|
||||
|
||||
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")
|
||||
|
||||
|
||||
class Reply:
|
||||
"""Ответ без проверок: для нагрузки во время отказа, где ошибки — ожидаемая часть замера."""
|
||||
|
||||
def __init__(self, status, headers, data):
|
||||
self.status = status
|
||||
self.headers = {name.lower(): value for name, value in headers.items()}
|
||||
try:
|
||||
self.json = json.loads(data.decode("utf-8")) if data else None
|
||||
except ValueError:
|
||||
self.json = None
|
||||
|
||||
@property
|
||||
def instance(self):
|
||||
return self.headers.get("x-instance-id")
|
||||
|
||||
|
||||
def try_call(method, path, *, body=None, raw=None, token=None, headers=None, timeout=2.0):
|
||||
"""HTTP-запрос через балансировщик. Reply или None, если соединение оборвалось / вышел timeout.
|
||||
|
||||
Обрыв возможен и посреди ответа (реплику убили, когда заголовки уже ушли): http.client.HTTPException.
|
||||
"""
|
||||
all_headers = dict(headers or {})
|
||||
data = raw
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).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:
|
||||
return Reply(reply.status, reply.headers, reply.read())
|
||||
except urllib.error.HTTPError as error:
|
||||
try:
|
||||
return Reply(error.code, error.headers, error.read())
|
||||
except (OSError, http.client.HTTPException):
|
||||
return None
|
||||
except (urllib.error.URLError, OSError, http.client.HTTPException):
|
||||
return None
|
||||
|
||||
|
||||
# ---------- Docker ----------
|
||||
|
||||
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 compose_output(*args, env=None):
|
||||
"""docker compose <args> и его вывод (stdout + stderr). Секретов в нём нет: ps, logs, build."""
|
||||
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 compose_config():
|
||||
"""Итоговая конфигурация стенда (docker compose config) как словарь: только stdout, без предупреждений."""
|
||||
result = subprocess.run(["docker", "compose", "config", "--format", "json"], cwd=ROOT,
|
||||
capture_output=True, check=True)
|
||||
return json.loads(result.stdout.decode("utf-8"))
|
||||
|
||||
|
||||
def compose_quiet(*args, env=None):
|
||||
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, env=env,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
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 inspect(container, template):
|
||||
return docker("inspect", "-f", template, container, check_exit=False)
|
||||
|
||||
|
||||
def health(container):
|
||||
"""Статус Docker healthcheck: starting / healthy / unhealthy / ''."""
|
||||
return inspect(container, "{{if .State.Health}}{{.State.Health.Status}}{{end}}")
|
||||
|
||||
|
||||
def ps_table():
|
||||
"""Все контейнеры стенда: сервис, короткий ID (= X-Instance-Id у api), состояние, время старта."""
|
||||
lines = []
|
||||
for container in sorted(compose_output("ps", "-a", "-q").split()):
|
||||
info = inspect(container, '{{index .Config.Labels "com.docker.compose.service"}}|{{.State.Status}}|'
|
||||
'{{.State.StartedAt}}|{{if .State.Health}}{{.State.Health.Status}}{{end}}')
|
||||
service, status, started, healthy = (info.split("|") + ["", "", "", ""])[:4]
|
||||
shown = f"{status} ({healthy})" if healthy and status == "running" else status
|
||||
lines.append((service, container[:12], shown, started[:23]))
|
||||
lines.sort()
|
||||
width = max((len(service) for service, *_ in lines), default=7)
|
||||
text = [f"{'SERVICE':<{width}} CONTAINER STATE STARTED AT (UTC)"]
|
||||
text += [f"{service:<{width}} {cid} {state:<19} {started}" for service, cid, state, started in lines]
|
||||
return "\n".join(text)
|
||||
|
||||
|
||||
# ---------- балансировщик ----------
|
||||
|
||||
def lb_servers(backend="api"):
|
||||
"""Слоты backend в HAProxy (страница статистики, CSV): {имя: статус}, например {'api1': 'UP'}."""
|
||||
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") == backend and item.get("svname") not in ("FRONTEND", "BACKEND"):
|
||||
servers[item["svname"]] = item.get("status", "")
|
||||
return servers
|
||||
|
||||
|
||||
def lb_up_count():
|
||||
"""Сколько основных слотов (api1..api6, без аварийных fallback) HAProxy держит в балансировке (UP)."""
|
||||
return sum(1 for name, status in lb_servers().items() if name.startswith("api") and status.startswith("UP"))
|
||||
|
||||
|
||||
def lb_summary():
|
||||
"""Короткая строка состояния основных слотов: 'api1 UP, api2 DOWN' (пустые слоты MAINT не показываем)."""
|
||||
servers = lb_servers()
|
||||
shown = [f"{name} {status}" for name, status in sorted(servers.items())
|
||||
if name.startswith("api") and not status.startswith("MAINT")]
|
||||
return ", ".join(shown) or "no api servers"
|
||||
|
||||
|
||||
def wait_balanced(replicas, seconds=90):
|
||||
"""Ждёт, пока replicas контейнеров api healthy и HAProxy держит их в балансировке (UP)."""
|
||||
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 valkey_stats():
|
||||
"""keyspace_hits и keyspace_misses Valkey (пользователь health без пароля: только info/ping/dbsize)."""
|
||||
output = compose_output("exec", "-T", "valkey", "valkey-cli", "--user", "health", "--pass", "none",
|
||||
"--no-auth-warning", "info", "stats")
|
||||
stats = dict(line.strip().split(":", 1) for line in output.splitlines() if line.startswith("keyspace_"))
|
||||
return int(stats["keyspace_hits"]), int(stats["keyspace_misses"])
|
||||
@@ -0,0 +1,164 @@
|
||||
"""Собственные тесты API (перенесены из lab1, переведены на пароль и Bearer).
|
||||
|
||||
Тесты «чёрного ящика»: шлют настоящие HTTP-запросы на уже запущенный стенд
|
||||
(BASE_URL, по умолчанию http://127.0.0.1:8080 из Makefile; с lab3 это балансировщик,
|
||||
и запросы обслуживают разные реплики). С lab3 POST сообщения несёт Idempotency-Key.
|
||||
Запуск вместе с остальными test_*.py одной командой: make student-test
|
||||
"""
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
from helpers import Client, basic, idempotency, read_history
|
||||
|
||||
PASSWORD = "Test-password-123"
|
||||
|
||||
|
||||
class MessengerApiTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.api = Client()
|
||||
cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap() # eve не состоит в чате
|
||||
|
||||
def messages_path(self, chat_id):
|
||||
return f"/api/v1/chats/{chat_id}/messages"
|
||||
|
||||
def send(self, actor, chat_id, text, expected=201):
|
||||
schema = "Message" if expected == 201 else None # клиент разбирает JSON успешного ответа только со схемой
|
||||
return self.api.call("POST", self.messages_path(chat_id), expected, actor=actor,
|
||||
body={"text": text}, headers=idempotency(), schema=schema)
|
||||
|
||||
def new_chat(self):
|
||||
body = {"title": "Тест", "member_ids": [self.alice["id"], self.bob["id"]]}
|
||||
return self.api.call("POST", "/api/v1/chats", 201, actor=self.alice, body=body, schema="Chat")["json"]
|
||||
|
||||
def test_malformed_json_returns_400(self):
|
||||
json_header = {"Content-Type": "application/json"}
|
||||
for raw in (b'{"username": "abc",', b"not json", b""):
|
||||
self.api.call("POST", "/api/v1/users", 400, raw=raw, headers=json_header)
|
||||
self.api.call("POST", self.messages_path(self.chat["id"]), 400,
|
||||
actor=self.alice, raw=raw, headers={**json_header, **idempotency()})
|
||||
|
||||
def test_wrong_types_and_extra_fields_return_400(self):
|
||||
self.api.call("POST", "/api/v1/users", 400,
|
||||
body={"username": 123, "display_name": "x", "password": PASSWORD})
|
||||
self.api.call("POST", "/api/v1/users", 400,
|
||||
body={"username": "valid_name", "display_name": "x", "password": PASSWORD, "is_admin": True})
|
||||
self.api.call("POST", "/api/v1/users", 400,
|
||||
body={"username": "Bad Name!", "display_name": "x", "password": PASSWORD})
|
||||
# Отправителя нельзя подставить: он берётся из сессии.
|
||||
self.api.call("POST", self.messages_path(self.chat["id"]), 400, actor=self.alice,
|
||||
body={"text": "hi", "sender_id": self.bob["id"]}, headers=idempotency())
|
||||
|
||||
def test_outsider_gets_404_for_foreign_chat(self):
|
||||
chat_id = self.chat["id"]
|
||||
self.api.call("GET", f"/api/v1/chats/{chat_id}", 404, actor=self.eve)
|
||||
self.api.call("GET", self.messages_path(chat_id), 404, actor=self.eve)
|
||||
self.send(self.eve, chat_id, "чужое", expected=404)
|
||||
# Несуществующий чат выглядит так же, как чужой: существование не раскрывается.
|
||||
self.api.call("GET", f"/api/v1/chats/{uuid.uuid4()}", 404, actor=self.eve)
|
||||
|
||||
def test_auth_checked_before_access_and_body(self):
|
||||
# Без токена — всегда 401, даже если тело кривое или чат чужой: сначала «кто ты».
|
||||
self.api.call("POST", self.messages_path(self.chat["id"]), 401, raw=b"not json",
|
||||
headers={"Content-Type": "application/json", **idempotency()})
|
||||
self.api.call("GET", f"/api/v1/chats/{uuid.uuid4()}", 401)
|
||||
|
||||
def test_empty_blank_and_too_long_messages_return_400(self):
|
||||
for text in ("", " ", "\n\t "):
|
||||
self.send(self.alice, self.chat["id"], text, expected=400)
|
||||
self.send(self.alice, self.chat["id"], "я" * 4001, expected=400)
|
||||
self.send(self.alice, self.chat["id"], "я" * 4000) # ровно на границе — можно
|
||||
|
||||
def test_duplicate_username_returns_409(self):
|
||||
body = {"username": "dup_" + uuid.uuid4().hex[:12], "display_name": "Первый", "password": PASSWORD}
|
||||
self.api.call("POST", "/api/v1/users", 201, body=body)
|
||||
self.api.call("POST", "/api/v1/users", 409, body=dict(body, display_name="Второй"))
|
||||
|
||||
def test_unicode_roundtrip(self):
|
||||
text = "Привет 👋 你好 ﷽ é"
|
||||
sent = self.send(self.alice, self.chat["id"], text)["json"]
|
||||
self.assertEqual(sent["text"], text)
|
||||
history, _ = read_history(self.api, self.bob, self.chat["id"])
|
||||
self.assertIn(text, [m["text"] for m in history])
|
||||
# Длина считается в символах Unicode: 100 эмодзи можно, 101 — нет.
|
||||
name = "n_" + uuid.uuid4().hex[:12]
|
||||
self.api.call("POST", "/api/v1/users", 400,
|
||||
body={"username": name, "display_name": "👋" * 101, "password": PASSWORD})
|
||||
self.api.call("POST", "/api/v1/users", 201,
|
||||
body={"username": name, "display_name": "👋" * 100, "password": PASSWORD})
|
||||
|
||||
def test_nul_character_is_stored(self):
|
||||
# Замечание к MR: U+0000 допустим по контракту и должен сохраняться как есть, а не давать 500.
|
||||
name = "nul_" + uuid.uuid4().hex[:10]
|
||||
password = "Pass\u0000word-123"
|
||||
user = self.api.call("POST", "/api/v1/users", 201, schema="User",
|
||||
body={"username": name, "display_name": "A\u0000B", "password": password})["json"]
|
||||
self.assertEqual(user["display_name"], "A\u0000B")
|
||||
session = self.api.call("POST", "/api/v1/auth/sessions", 201, schema="Session",
|
||||
headers={"Authorization": basic(name, password)})["json"]
|
||||
self.assertEqual(session["user"]["display_name"], "A\u0000B")
|
||||
chat = self.api.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat",
|
||||
body={"title": "T\u0000itle", "member_ids": [self.alice["id"], self.bob["id"]]})["json"]
|
||||
self.assertEqual(chat["title"], "T\u0000itle")
|
||||
sent = self.send(self.alice, chat["id"], "hello\u0000world")["json"]
|
||||
self.assertEqual(sent["text"], "hello\u0000world")
|
||||
history, _ = read_history(self.api, self.bob, chat["id"])
|
||||
self.assertEqual([m["text"] for m in history], ["hello\u0000world"])
|
||||
got = self.api.call("GET", f"/api/v1/chats/{chat['id']}", actor=self.bob, schema="Chat")["json"]
|
||||
self.assertEqual(got["title"], "T\u0000itle")
|
||||
# username с U+0000 существовать не может: вход — обычный 401, а не 500.
|
||||
self.api.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic("ab\u0000c", password)})
|
||||
|
||||
def test_pagination_walks_several_pages(self):
|
||||
chat = self.new_chat()
|
||||
sent = [self.send(self.alice, chat["id"], f"msg {i}")["json"] for i in range(7)]
|
||||
history, pages = read_history(self.api, self.bob, chat["id"], limit=3)
|
||||
self.assertEqual(pages, 3) # 3 + 3 + 1
|
||||
self.assertEqual([m["id"] for m in history], [m["id"] for m in sent]) # без потерь, дублей и перестановок
|
||||
|
||||
def test_chat_list_pagination(self):
|
||||
created = [self.new_chat()["id"] for _ in range(3)]
|
||||
seen, cursor = [], None
|
||||
while True:
|
||||
query = "?limit=2" + (f"&cursor={cursor}" if cursor else "")
|
||||
page = self.api.call("GET", "/api/v1/chats" + query, actor=self.bob, schema="ChatPage")["json"]
|
||||
seen += [c["id"] for c in page["items"]]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertEqual(len(seen), len(set(seen)))
|
||||
self.assertEqual(seen[-3:], created) # новые чаты в конце, порядок (created_at, id)
|
||||
|
||||
def test_bad_cursor_returns_400(self):
|
||||
chat_a, chat_b = self.new_chat(), self.new_chat()
|
||||
for i in range(2):
|
||||
self.send(self.alice, chat_a["id"], f"a{i}")
|
||||
first = self.api.call("GET", self.messages_path(chat_a["id"]) + "?limit=1",
|
||||
actor=self.alice, schema="MessagePage")["json"]
|
||||
foreign_cursor = first["next_cursor"]
|
||||
self.api.call("GET", self.messages_path(chat_b["id"]) + "?cursor=" + foreign_cursor, 400, actor=self.alice)
|
||||
self.api.call("GET", self.messages_path(chat_a["id"]) + "?cursor=garbage", 400, actor=self.alice)
|
||||
# Курсор правильной формы, но с испорченным временем/UUID: 400, а не ошибка БД (500).
|
||||
import base64
|
||||
import json
|
||||
scope = "messages:" + chat_a["id"]
|
||||
for bad in ([scope, "not-a-time", str(uuid.uuid4())],
|
||||
[scope, "2026-01-01T00:00:00.000000Z", "not-a-uuid"],
|
||||
[scope, "2026-01-01T00:00:00", str(uuid.uuid4())], # без часового пояса
|
||||
[scope, "0001-01-01T00:00:00+14:00", str(uuid.uuid4())], # в UTC это год 0
|
||||
[scope, "9999-12-31T23:59:59-14:00", str(uuid.uuid4())]): # в UTC это год 10000
|
||||
forged = base64.urlsafe_b64encode(json.dumps(bad).encode()).decode()
|
||||
self.api.call("GET", self.messages_path(chat_a["id"]) + "?cursor=" + forged, 400, actor=self.alice)
|
||||
for limit in ("0", "101", "abc"):
|
||||
self.api.call("GET", self.messages_path(chat_a["id"]) + "?limit=" + limit, 400, actor=self.alice)
|
||||
|
||||
def test_chat_membership_rules(self):
|
||||
alice, bob = self.alice["id"], self.bob["id"]
|
||||
for members in ([bob], [alice, alice], [alice, str(uuid.uuid4())]): # без себя, дубль, неизвестный
|
||||
self.api.call("POST", "/api/v1/chats", 400, actor=self.alice, body={"title": "x", "member_ids": members})
|
||||
chats = self.api.call("GET", "/api/v1/chats?limit=100", actor=self.eve, schema="ChatPage")["json"]
|
||||
self.assertNotIn(self.chat["id"], [c["id"] for c in chats["items"]])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Собственные тесты аутентификации (уровень 4): пароль, Basic -> Bearer, logout.
|
||||
|
||||
Запуск: make student-test (вместе с test_api.py)
|
||||
"""
|
||||
import base64
|
||||
import datetime as dt
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
from helpers import Client, basic, login
|
||||
|
||||
PASSWORD = "Test-password-123"
|
||||
|
||||
|
||||
def iso(value):
|
||||
return dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
|
||||
|
||||
class AuthTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.api = Client()
|
||||
|
||||
def register(self, password=PASSWORD, expected=201):
|
||||
body = {"username": "a_" + uuid.uuid4().hex[:12], "display_name": "Auth", "password": password}
|
||||
user = self.api.call("POST", "/api/v1/users", expected, body=body,
|
||||
schema="User" if expected == 201 else None)["json"]
|
||||
return body, user
|
||||
|
||||
def me(self, token, expected=200):
|
||||
return self.api.call("GET", "/api/v1/users/me", expected, headers={"Authorization": "Bearer " + token},
|
||||
schema="User" if expected == 200 else None)
|
||||
|
||||
def test_login_returns_opaque_token_with_expiry(self):
|
||||
body, user = self.register()
|
||||
session = login(self.api, body["username"], body["password"])
|
||||
self.assertEqual(session["user"], user)
|
||||
token = session["token"]
|
||||
self.assertGreaterEqual(len(token), 43) # 32 случайных байта в base64url
|
||||
self.assertNotIn(body["username"], token)
|
||||
self.assertNotIn(user["id"], token)
|
||||
# Обычный стенд: TTL не меньше 300 с (по умолчанию 3600).
|
||||
left = iso(session["expires_at"]) - dt.datetime.now(dt.timezone.utc)
|
||||
self.assertGreater(left.total_seconds(), 290)
|
||||
self.assertEqual(self.me(token)["json"], user)
|
||||
|
||||
def test_user_never_contains_password(self):
|
||||
body, user = self.register()
|
||||
self.assertEqual(set(user), {"id", "username", "display_name", "created_at"})
|
||||
self.assertNotIn(body["password"], str(user))
|
||||
|
||||
def test_wrong_password_and_unknown_user_look_the_same(self):
|
||||
body, _ = self.register()
|
||||
wrong = login(self.api, body["username"], "Wrong-password-000", expected=401)
|
||||
unknown = login(self.api, "nobody_" + uuid.uuid4().hex[:8], body["password"], expected=401)
|
||||
# Одинаковый код и текст: по ответу нельзя узнать, существует ли username.
|
||||
self.assertEqual(wrong["error"]["code"], unknown["error"]["code"])
|
||||
self.assertEqual(wrong["error"]["message"], unknown["error"]["message"])
|
||||
|
||||
def test_malformed_basic_returns_401(self):
|
||||
path = "/api/v1/auth/sessions"
|
||||
no_colon = base64.b64encode(b"just_username").decode()
|
||||
for header in (None, "Basic", "Basic !!!not-base64!!!", "Basic " + no_colon, "Bearer something"):
|
||||
headers = {} if header is None else {"Authorization": header}
|
||||
self.api.call("POST", path, 401, headers=headers) # клиент проверяет WWW-Authenticate: Basic
|
||||
|
||||
def test_password_with_colon_and_unicode(self):
|
||||
password = "пароль:с:двоеточием 👋"
|
||||
body, user = self.register(password=password)
|
||||
session = login(self.api, body["username"], password)
|
||||
self.assertEqual(session["user"], user)
|
||||
|
||||
def test_password_length_rules(self):
|
||||
self.register(password="x" * 11, expected=400)
|
||||
self.register(password="x" * 129, expected=400)
|
||||
self.register(password=" " * 12, expected=400) # только пробелы — нельзя
|
||||
self.register(password="x" * 12)
|
||||
self.register(password="я" * 128) # 128 символов Unicode — можно
|
||||
|
||||
def test_bearer_required_on_business_endpoints(self):
|
||||
body, user = self.register()
|
||||
session = login(self.api, body["username"], body["password"])
|
||||
for headers in ({}, {"Authorization": basic(body["username"], body["password"])},
|
||||
{"X-User-Id": user["id"]}, {"Authorization": "Bearer " + "A" * 43},
|
||||
{"Authorization": "Bearer"}, {"Authorization": "Token " + session["token"]}):
|
||||
self.api.call("GET", "/api/v1/users/me", 401, headers=headers) # WWW-Authenticate: Bearer
|
||||
# Схема нечувствительна к регистру (RFC 7235).
|
||||
self.api.call("GET", "/api/v1/users/me", 200, headers={"Authorization": "bearer " + session["token"]})
|
||||
|
||||
def test_x_user_id_does_not_change_identity(self):
|
||||
body, user = self.register()
|
||||
_, other = self.register()
|
||||
session = login(self.api, body["username"], body["password"])
|
||||
me = self.api.call("GET", "/api/v1/users/me", headers={
|
||||
"Authorization": "Bearer " + session["token"], "X-User-Id": other["id"]}, schema="User")["json"]
|
||||
self.assertEqual(me["id"], user["id"])
|
||||
|
||||
def test_logout_revokes_only_current_session(self):
|
||||
body, _ = self.register()
|
||||
first = login(self.api, body["username"], body["password"])["token"]
|
||||
second = login(self.api, body["username"], body["password"])["token"]
|
||||
self.me(first) # запись попадает в кэш Valkey
|
||||
self.api.call("DELETE", "/api/v1/auth/sessions/current", 204, headers={"Authorization": "Bearer " + first})
|
||||
self.me(first, expected=401) # кэш инвалидирован: отозванный токен не принимается сразу
|
||||
self.api.call("DELETE", "/api/v1/auth/sessions/current", 401, headers={"Authorization": "Bearer " + first})
|
||||
self.me(second) # другая сессия того же пользователя продолжает работать
|
||||
|
||||
def test_relogin_after_logout(self):
|
||||
body, _ = self.register()
|
||||
token = login(self.api, body["username"], body["password"])["token"]
|
||||
self.api.call("DELETE", "/api/v1/auth/sessions/current", 204, headers={"Authorization": "Bearer " + token})
|
||||
again = login(self.api, body["username"], body["password"])["token"]
|
||||
self.assertNotEqual(token, again)
|
||||
self.me(again)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,85 @@
|
||||
"""lab3: несколько реплик API за балансировщиком и общее состояние.
|
||||
|
||||
Запуск при запущенном стенде: make balancing (или вместе со всеми: make student-test).
|
||||
Все запросы идут на BASE_URL = балансировщик HAProxy (127.0.0.1:8080).
|
||||
|
||||
1. Один токен обслуживают разные реплики (X-Instance-Id), повторный вход не нужен:
|
||||
сессии в общем PostgreSQL + кэш в общем Valkey, а не в памяти реплики.
|
||||
2. Записал через одну реплику — сразу читаешь через другую: данные в общем PostgreSQL.
|
||||
3. Logout через одну реплику действует на всех.
|
||||
4. X-Instance-Id есть в каждом ответе (и в ошибках, и в health) и совпадает с ID
|
||||
настоящего запущенного контейнера api: заголовок — не выдумка, это разные процессы.
|
||||
5. Кэш сессий общий: запись, положенную одной репликой, используют все (промахов кэша нет).
|
||||
"""
|
||||
import unittest
|
||||
from collections import Counter
|
||||
|
||||
from helpers import Client, idempotency
|
||||
from stand import api_containers, valkey_stats
|
||||
|
||||
|
||||
class BalancingTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.api = Client()
|
||||
cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap()
|
||||
|
||||
def me(self, actor, expected=200):
|
||||
reply = self.api.call("GET", "/api/v1/users/me", expected, actor=actor,
|
||||
schema="User" if expected == 200 else None)
|
||||
return reply["headers"]["X-Instance-Id"], reply["json"]
|
||||
|
||||
def test_one_session_is_served_by_every_replica(self):
|
||||
replies = [self.me(self.alice) for _ in range(20)]
|
||||
served = Counter(instance for instance, _ in replies)
|
||||
self.assertTrue(all(user["id"] == self.alice["id"] for _, user in replies), "another user returned")
|
||||
self.assertGreaterEqual(len(served), 2, "all requests went to one replica: balancing does not work")
|
||||
running = api_containers()
|
||||
for instance in served:
|
||||
self.assertTrue(any(container.startswith(instance) for container in running),
|
||||
f"X-Instance-Id {instance} is not a running api container")
|
||||
print(f"\n 20 x GET /users/me с одним токеном -> реплики {dict(served)}; "
|
||||
f"это ID запущенных контейнеров api, повторный вход не нужен")
|
||||
|
||||
def test_write_on_one_replica_read_on_another(self):
|
||||
sent = self.api.message(self.alice, self.chat, "записано через одну реплику")
|
||||
writer = sent["headers"]["X-Instance-Id"]
|
||||
readers = set()
|
||||
for _ in range(6):
|
||||
page = self.api.call("GET", f"/api/v1/chats/{self.chat['id']}/messages?limit=100",
|
||||
actor=self.bob, schema="MessagePage")
|
||||
self.assertIn(sent["json"], page["json"]["items"], "confirmed message is not visible")
|
||||
readers.add(page["headers"]["X-Instance-Id"])
|
||||
self.assertTrue(readers - {writer}, "no read went to another replica")
|
||||
print(f"\n сообщение записала реплика {writer}, сразу прочитали {sorted(readers)}")
|
||||
|
||||
def test_logout_applies_on_every_replica(self):
|
||||
carol = self.api.user("carol")
|
||||
self.api.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=carol)
|
||||
after = [self.me(carol, expected=401)[0] for _ in range(6)]
|
||||
self.assertGreaterEqual(len(set(after)), 2, "401 came from one replica only")
|
||||
print(f"\n logout через одну реплику -> 401 на {sorted(set(after))}")
|
||||
|
||||
def test_instance_id_on_errors_and_health(self):
|
||||
# Клиент курса сам проверяет X-Request-Id и X-Instance-Id у каждого ответа.
|
||||
self.api.call("GET", "/health/live", schema="Health")
|
||||
self.api.call("GET", "/health/ready", schema="Health")
|
||||
self.api.call("GET", "/api/v1/no-such-path", 404, actor=self.alice)
|
||||
self.api.call("GET", "/api/v1/users/me", 401)
|
||||
self.api.call("POST", f"/api/v1/chats/{self.chat['id']}/messages", 400, actor=self.alice,
|
||||
body={"text": ""}, headers=idempotency())
|
||||
print("\n X-Instance-Id есть в health, 404, 401 и 400")
|
||||
|
||||
def test_session_cache_is_shared_between_replicas(self):
|
||||
dave = self.api.user("dave") # вход уже положил запись о сессии в общий Valkey
|
||||
hits_before, misses_before = valkey_stats()
|
||||
served = Counter(self.me(dave)[0] for _ in range(10))
|
||||
hits_after, misses_after = valkey_stats()
|
||||
self.assertGreaterEqual(len(served), 2, "requests did not reach both replicas")
|
||||
self.assertEqual(misses_after - misses_before, 0, "cache miss: a replica did not use the shared entry")
|
||||
print(f"\n 10 x GET /users/me через реплики {dict(served)}: попаданий в кэш "
|
||||
f"+{hits_after - hits_before}, промахов +{misses_after - misses_before} — кэш общий")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,159 @@
|
||||
"""lab3: Idempotency-Key у POST /chats/{id}/messages.
|
||||
|
||||
Запуск при запущенном стенде: make idempotency (или вместе со всеми: make student-test).
|
||||
Все запросы идут через балансировщик, поэтому повторы попадают на разные реплики.
|
||||
|
||||
- повтор того же запроса (в том числе через другую реплику) -> тот же 201 и то же сообщение;
|
||||
- 20 одновременных запросов с одним ключом через обе реплики -> ровно одно сообщение;
|
||||
- одновременные разные тела с одним ключом -> одно сообщение, остальным 409;
|
||||
- форматирование JSON не важно; другое тело с тем же ключом -> 409;
|
||||
- область ключа: пользователь + чат (тот же ключ у другого пользователя или в другом чате независим);
|
||||
- нет ключа или он неверный -> 400; ошибка 400 ключ не «занимает»;
|
||||
- повтор заново проверяет сессию (401 после logout) и доступ к чату (404 постороннему).
|
||||
"""
|
||||
import threading
|
||||
import unittest
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from helpers import Client, idempotency, login, read_history
|
||||
|
||||
PARALLEL = 20
|
||||
|
||||
|
||||
class IdempotencyTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.api = Client()
|
||||
cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap()
|
||||
|
||||
def path(self, chat=None):
|
||||
return f"/api/v1/chats/{(chat or self.chat)['id']}/messages"
|
||||
|
||||
def post(self, actor, text, key, expected=201, chat=None, api=None):
|
||||
return (api or self.api).call("POST", self.path(chat), expected, actor=actor, body={"text": text},
|
||||
headers=idempotency(key), schema="Message" if expected == 201 else None)
|
||||
|
||||
def count_text(self, text, chat=None):
|
||||
history, _ = read_history(self.api, self.alice, (chat or self.chat)["id"])
|
||||
return sum(1 for message in history if message["text"] == text)
|
||||
|
||||
def test_replay_through_another_replica_returns_same_message(self):
|
||||
key, text = uuid.uuid4().hex, "повтор " + uuid.uuid4().hex
|
||||
first = self.post(self.alice, text, key)
|
||||
replies = [self.post(self.alice, text, key) for _ in range(4)]
|
||||
self.assertTrue(all(reply["json"] == first["json"] for reply in replies), "replay differs")
|
||||
instances = {first["headers"]["X-Instance-Id"]} | {r["headers"]["X-Instance-Id"] for r in replies}
|
||||
self.assertGreaterEqual(len(instances), 2, "replays did not switch replica")
|
||||
self.assertEqual(self.count_text(text), 1)
|
||||
print(f"\n 1 запрос + 4 повтора через реплики {sorted(instances)}: 201 и то же сообщение, в истории 1")
|
||||
|
||||
def test_parallel_same_key_through_replicas_creates_one_message(self):
|
||||
key, text = uuid.uuid4().hex, "параллельно " + uuid.uuid4().hex
|
||||
start = threading.Barrier(PARALLEL)
|
||||
|
||||
def send(_):
|
||||
client = Client() # у каждого «клиента» свои соединения
|
||||
start.wait()
|
||||
return self.post(self.alice, text, key, api=client)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=PARALLEL) as pool:
|
||||
replies = list(pool.map(send, range(PARALLEL)))
|
||||
ids = {reply["json"]["id"] for reply in replies}
|
||||
instances = Counter(reply["headers"]["X-Instance-Id"] for reply in replies)
|
||||
self.assertEqual(len(ids), 1, "different messages for one key")
|
||||
self.assertGreaterEqual(len(instances), 2, "parallel requests did not reach both replicas")
|
||||
self.assertEqual(self.count_text(text), 1, "duplicate message created")
|
||||
print(f"\n {PARALLEL} одновременных POST с одним ключом через реплики {dict(instances)}: "
|
||||
f"все 201 с одним id, в истории 1 сообщение")
|
||||
|
||||
def test_parallel_different_bodies_same_key(self):
|
||||
key = uuid.uuid4().hex
|
||||
texts = [f"тело {n} {key}" for n in range(10)]
|
||||
start = threading.Barrier(len(texts))
|
||||
|
||||
def send(text):
|
||||
client = Client()
|
||||
start.wait()
|
||||
reply = client.call("POST", self.path(), [201, 409], actor=self.alice, body={"text": text},
|
||||
headers=idempotency(key))
|
||||
return text, reply["status"], reply["json"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=len(texts)) as pool:
|
||||
results = list(pool.map(send, texts))
|
||||
created = [text for text, status, _ in results if status == 201]
|
||||
self.assertEqual(len(created), 1, f"expected exactly one 201, got {len(created)}")
|
||||
self.assertEqual(sum(1 for _, status, _ in results if status == 409), len(texts) - 1)
|
||||
self.assertEqual(sum(self.count_text(text) for text in texts), 1)
|
||||
print(f"\n {len(texts)} одновременных разных тел с одним ключом: 201 x1, 409 x{len(texts) - 1}, "
|
||||
f"в истории 1 сообщение")
|
||||
|
||||
def test_json_formatting_does_not_matter(self):
|
||||
key, text = uuid.uuid4().hex, "формат " + uuid.uuid4().hex
|
||||
first = self.post(self.alice, text, key)["json"]
|
||||
for raw in (('{ "text" : "%s" }' % text).encode("utf-8"), ('{\n "text": "%s"\n}' % text).encode("utf-8")):
|
||||
again = self.api.call("POST", self.path(), 201, actor=self.alice, raw=raw, schema="Message",
|
||||
headers={"Content-Type": "application/json", **idempotency(key)})["json"]
|
||||
self.assertEqual(again, first)
|
||||
print("\n тот же JSON с другими пробелами и переносами -> тот же 201 и то же сообщение")
|
||||
|
||||
def test_same_key_other_body_is_409(self):
|
||||
key, text = uuid.uuid4().hex, "оригинал " + uuid.uuid4().hex
|
||||
self.post(self.alice, text, key)
|
||||
error = self.post(self.alice, text + " (изменено)", key, expected=409)["json"]["error"]
|
||||
self.assertEqual(error["code"], "conflict")
|
||||
self.assertEqual(self.count_text(text), 1)
|
||||
self.assertEqual(self.count_text(text + " (изменено)"), 0)
|
||||
print("\n другой текст с тем же ключом -> 409 conflict, второе сообщение не создано")
|
||||
|
||||
def test_key_scope_is_user_and_chat(self):
|
||||
key, text = uuid.uuid4().hex, "область " + uuid.uuid4().hex
|
||||
other_chat = self.api.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat",
|
||||
body={"title": "второй чат", "member_ids": [self.alice["id"], self.bob["id"]]})["json"]
|
||||
by_alice = self.post(self.alice, text, key)["json"]
|
||||
by_bob = self.post(self.bob, text, key)["json"]
|
||||
in_other_chat = self.post(self.alice, text, key, chat=other_chat)["json"]
|
||||
self.assertEqual(len({by_alice["id"], by_bob["id"], in_other_chat["id"]}), 3)
|
||||
print("\n тот же ключ у другого пользователя и в другом чате -> независимые сообщения")
|
||||
|
||||
def test_key_is_required_and_validated(self):
|
||||
text = "без ключа " + uuid.uuid4().hex
|
||||
self.api.call("POST", self.path(), 400, actor=self.alice, body={"text": text})
|
||||
for bad in ("", "a" * 129, "пробел есть", "a b", "slash/no", "ключ"):
|
||||
# Не-ASCII отправляем как есть, байтами UTF-8 (так их пришлёт реальный клиент).
|
||||
header = bad.encode("utf-8").decode("latin-1")
|
||||
self.api.call("POST", self.path(), 400, actor=self.alice, body={"text": text},
|
||||
headers={"Idempotency-Key": header})
|
||||
self.post(self.alice, text + " 128", "k" * 128)
|
||||
self.post(self.alice, text + " punct", "Az09._:-" + uuid.uuid4().hex)
|
||||
self.assertEqual(self.count_text(text), 0)
|
||||
print("\n нет ключа, пустой, 129 символов, пробел, '/', кириллица -> 400; 128 символов и ._:- -> 201")
|
||||
|
||||
def test_failed_request_does_not_burn_key(self):
|
||||
key, text = uuid.uuid4().hex, "после ошибки " + uuid.uuid4().hex
|
||||
self.post(self.alice, " ", key, expected=400) # пустой текст: 400, ничего не сохранено
|
||||
created = self.post(self.alice, text, key)["json"]
|
||||
self.assertEqual(created["text"], text)
|
||||
print("\n с тем же ключом: сначала 400 (пустой текст), потом 201 — ошибка ключ не заняла")
|
||||
|
||||
def test_replay_rechecks_session_and_access(self):
|
||||
key, text = uuid.uuid4().hex, "проверка доступа " + uuid.uuid4().hex
|
||||
frank = self.api.user("frank")
|
||||
chat = self.api.call("POST", "/api/v1/chats", 201, actor=frank, schema="Chat",
|
||||
body={"title": "frank", "member_ids": [frank["id"], self.bob["id"]]})["json"]
|
||||
first = self.post(frank, text, key, chat=chat)["json"]
|
||||
self.post(self.eve, text, key, expected=404, chat=chat) # посторонний: 404, а не сохранённый ответ
|
||||
token = frank["token"]
|
||||
self.api.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=frank)
|
||||
self.post(frank, text, key, expected=401, chat=chat) # отозванный токен: 401
|
||||
session = login(self.api, frank["registration"]["username"], frank["registration"]["password"])
|
||||
frank_again = dict(frank, token=session["token"]) # новый вход, новый токен
|
||||
self.assertNotEqual(frank_again["token"], token)
|
||||
again = self.post(frank_again, text, key, chat=chat)["json"]
|
||||
self.assertEqual(again, first)
|
||||
print("\n повтор: посторонний -> 404, после logout -> 401, после нового входа -> то же сообщение")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user