Files
mtusi2026lab3/student-tests/dependency_failure.py
T
2026-10-15 19:44:46 +03:00

138 lines
9.1 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 — источник истины недоступен: обе реплики не готовы (/health/ready = 503), и балансировщик
исключает их из маршрутизации. Даже запрос с действующим токеном, который реплика могла бы
подтвердить из кэша Valkey, через балансировщик получает 503 и до реплики не доходит
(замечание к MR: раньше резервные слоты без проверки пропускали его, и он получал 200).
Сами реплики при этом живы (/health/live = 200 изнутри контейнера).
Запись во время отказа не сохраняется. После запуска БД прежний токен и данные доступны.
"""
import sys
import time
import uuid
from helpers import Client, check, compose, idempotency, read_history, run, wait_ready
from stand import api_containers, lb_summary, lb_up_count, replica_status, try_call
LB_EXCLUDE_TIMEOUT_SECONDS = 15
LOST_TEXT = "во время отказа PostgreSQL, не должно сохраниться " + uuid.uuid4().hex
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 refused_by_lb(method, path, token=None, body=None, headers=None):
"""Запрос через балансировщик: ждём 503 от САМОГО балансировщика в формате ошибки контракта.
Признак того, что запрос не дошёл до реплики API: в ответе нет X-Instance-Id
(его ставит каждая реплика), а X-Request-Id и request_id в теле — от балансировщика.
"""
reply = try_call(method, path, token=token, body=body, headers=headers, timeout=5)
check(reply is not None, f"{method} {path}: no response from the balancer")
check(reply.status == 503, f"{method} {path}: expected 503 from the balancer, got {reply.status}")
check(not reply.instance, f"{method} {path}: answered by a NOT READY API replica {reply.instance}")
error = (reply.json or {}).get("error") or {}
check(error.get("code") == "unavailable", f"{method} {path}: wrong error format {reply.json}")
check(error.get("request_id") and error["request_id"] == reply.headers.get("x-request-id"),
f"{method} {path}: request_id differs from X-Request-Id")
def postgres_down(api, alice, chat):
started = time.monotonic()
while lb_up_count() > 0:
check(time.monotonic() - started < LB_EXCLUDE_TIMEOUT_SECONDS,
f"HAProxy still routes to a replica {LB_EXCLUDE_TIMEOUT_SECONDS} s after the failure")
time.sleep(0.2)
print(f"HAProxy вывел все реплики из балансировки через {time.monotonic() - started:.1f} с "
f"после остановки PostgreSQL ({lb_summary()})")
for container in api_containers():
live, ready = replica_status(container, "/health/live"), replica_status(container, "/health/ready")
check(live == 200 and ready == 503, f"replica {container[:12]}: live {live}, ready {ready}")
print(f"реплика {container[:12]} изнутри контейнера: /health/live -> {live}, /health/ready -> {ready} "
f"(жива, но не готова)")
# Главное (замечание к MR): токен alice лежит в кэше Valkey, и реплика могла бы ответить 200 без базы.
refused_by_lb("GET", "/api/v1/users/me", token=alice["token"])
print("GET /users/me с действующим токеном (он есть в кэше) -> 503 от балансировщика, без X-Instance-Id: "
"до неготовой реплики запрос не дошёл")
refused_by_lb("GET", "/api/v1/chats", token=alice["token"])
refused_by_lb("GET", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"])
refused_by_lb("POST", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"],
body={"text": LOST_TEXT}, headers=idempotency())
print("бизнес-запросы (список чатов, история, отправка сообщения) -> 503 от балансировщика")
refused_by_lb("GET", "/api/v1/users/me")
refused_by_lb("POST", "/api/v1/users", body={"username": "pg_" + uuid.uuid4().hex[:10],
"display_name": "x", "password": "Pg-down-password"})
refused_by_lb("GET", "/health/ready")
print("без токена, регистрация и /health/ready через балансировщик -> 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"]
for _ in range(4): # запись о сессии alice точно лежит в общем кэше Valkey
api.call("GET", "/api/v1/users/me", actor=alice, schema="User")
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")
check(all(m["text"] != LOST_TEXT for m in history), "a write refused during the outage was stored")
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: прежний токен работает, подтверждённые сообщения на месте")
if target == "postgres":
print("PASS: postgres outage: not ready replicas were excluded by the balancer, no request reached them, "
"nothing was stored; data and the existing token survived")
else:
print("PASS: valkey outage handled without the cache; revoked tokens stay revoked")
if __name__ == "__main__":
run(main)