forked from mtusi2026/mtusi2026lab2
110 lines
5.9 KiB
Python
110 lines
5.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Отказ зависимостей: Redis/Valkey (кэш сессий) и PostgreSQL.
|
|
|
|
Команды управления задаются переменными окружения (по умолчанию — docker compose из корня репозитория):
|
|
CACHE_STOP, CACHE_START, CACHE_FLUSH, DB_STOP, DB_START
|
|
Ожидания:
|
|
* кэш недоступен/сброшен -> API продолжает работать (данные берутся из PostgreSQL), /health/ready = 200;
|
|
* PostgreSQL недоступен -> /health/ready = 503, бизнес-запросы = 503 (ограниченная ошибка),
|
|
запрос без валидной сессии НИКОГДА не получает 200;
|
|
* после восстановления прежний токен и данные на месте.
|
|
"""
|
|
import os
|
|
import shlex
|
|
import subprocess
|
|
import time
|
|
import uuid
|
|
|
|
from common import Failure, check, client, parse_json
|
|
|
|
DC = "docker compose --env-file .env"
|
|
CMD = {
|
|
"CACHE_STOP": os.environ.get("CACHE_STOP", DC + " stop valkey"),
|
|
"CACHE_START": os.environ.get("CACHE_START", DC + " start valkey"),
|
|
"CACHE_FLUSH": os.environ.get("CACHE_FLUSH", DC + " exec -T valkey sh -c 'REDISCLI_AUTH=$(cat /run/secrets/valkey_password) valkey-cli flushall'"),
|
|
"DB_STOP": os.environ.get("DB_STOP", DC + " stop postgres"),
|
|
"DB_START": os.environ.get("DB_START", DC + " start postgres"),
|
|
}
|
|
|
|
|
|
def run(name):
|
|
print(" $", name, flush=True)
|
|
r = subprocess.run(CMD[name], shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=90)
|
|
check(r.returncode == 0, "команда %s завершилась с кодом %d" % (name, r.returncode))
|
|
|
|
|
|
def wait_ready(c, seconds=60):
|
|
end = time.monotonic() + seconds
|
|
while True:
|
|
try:
|
|
c.call("GET", "/health/ready", 200)
|
|
return
|
|
except Failure:
|
|
check(time.monotonic() < end, "API не стал ready за %ds" % seconds)
|
|
time.sleep(0.5)
|
|
|
|
|
|
def main():
|
|
c = client()
|
|
alice, bob = c.user("dep_a"), c.user("dep_b")
|
|
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, body={"title": "dep", "member_ids": [alice["id"], bob["id"]]}, schema="Chat")["json"]
|
|
c.message(alice, chat, "до отказа")
|
|
c.call("GET", "/api/v1/users/me", 200, actor=alice) # токен гарантированно в кэше
|
|
stray = {"Authorization": "Bearer " + "Z" * 43}
|
|
|
|
print("1) Valkey остановлен")
|
|
run("CACHE_STOP")
|
|
try:
|
|
for _ in range(3):
|
|
c.call("GET", "/health/ready", 200) # кэш — не критичная зависимость
|
|
check(c.call("GET", "/api/v1/users/me", 200, actor=alice)["elapsed"] < 2.5, "обход кэша слишком медленный")
|
|
c.message(alice, chat, "пока кэш лежит")
|
|
c.call("GET", "/api/v1/users/me", 401, headers=stray) # анонимный/чужой токен по-прежнему 401
|
|
c.call("GET", "/api/v1/users/me", 401)
|
|
new = c.user("dep_new") # вход и регистрация работают без кэша
|
|
c.call("GET", "/api/v1/users/me", 200, actor=new)
|
|
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=new) # logout без кэша: истина в PostgreSQL
|
|
c.call("GET", "/api/v1/users/me", 401, actor=new)
|
|
finally:
|
|
run("CACHE_START")
|
|
time.sleep(2.5) # окно circuit breaker
|
|
c.call("GET", "/api/v1/users/me", 200, actor=alice)
|
|
|
|
print("2) Кэш сброшен (FLUSHALL): сессии берутся из PostgreSQL")
|
|
run("CACHE_FLUSH")
|
|
c.call("GET", "/api/v1/users/me", 200, actor=alice)
|
|
c.call("GET", "/api/v1/users/me", 200, actor=bob)
|
|
|
|
print("3) PostgreSQL остановлен")
|
|
run("DB_STOP")
|
|
try:
|
|
r = c.call("GET", "/health/ready", 503)
|
|
check(r["json"]["error"]["code"] == "unavailable", "ready: ожидали code=unavailable")
|
|
for path in ("/api/v1/chats", "/api/v1/chats/%s/messages" % chat["id"]):
|
|
r = c.call("GET", path, [200, 503], actor=alice)
|
|
check(r["status"] == 503, "данные отданы без БД: " + path)
|
|
check("psycopg" not in r["bytes"].decode() and "Traceback" not in r["bytes"].decode(), "утечка деталей в 503")
|
|
c.call("POST", "/api/v1/users", 503, body={"username": "u" + uuid.uuid4().hex[:10], "display_name": "x", "password": "Password-123456"})
|
|
c.call("GET", "/api/v1/users/me", 401) # без токена — всегда 401, не «доверенный аноним»
|
|
r = c.call("GET", "/api/v1/users/me", [401, 503], headers=stray)
|
|
check(r["status"] != 200, "неизвестный токен принят при недоступной БД")
|
|
c.call("GET", "/health/live", 200) # процесс жив, хоть и не ready
|
|
finally:
|
|
run("DB_START")
|
|
wait_ready(c)
|
|
|
|
print("4) Восстановление")
|
|
c.call("GET", "/api/v1/users/me", 200, actor=alice) # тот же токен, без повторного входа
|
|
texts = [m["text"] for m in parse_json(c.call("GET", "/api/v1/chats/%s/messages?limit=100" % chat["id"], actor=bob))["items"]]
|
|
check(texts == ["до отказа", "пока кэш лежит"], "история изменилась: %s" % texts)
|
|
c.message(bob, chat, "после восстановления")
|
|
print("PASS: кэш и БД отказывают предсказуемо: кэш обходится, БД -> 503, анонимный доступ невозможен, данные и сессии целы")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except Failure as exc:
|
|
print("FAIL:", exc)
|
|
raise SystemExit(1)
|