Files
mtusi2026lab2/student-tests/dependency_failure.py
T
2026-10-09 13:44:23 +03:00

101 lines
6.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Отказ зависимости (уровень 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, 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": "не сохранится"})
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)