160 lines
6.3 KiB
Python
160 lines
6.3 KiB
Python
"""Dependency outage behaviour: Valkey down, then PostgreSQL down.
|
|
|
|
Requires Docker access on the same host as the Compose stand and is therefore
|
|
opt-in:
|
|
|
|
STUDENT_DOCKER_TESTS=1 python -m unittest -v test_degradation
|
|
|
|
The test never removes volumes and restores both services in `finally`.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import statistics
|
|
import subprocess
|
|
import time
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
import common
|
|
|
|
|
|
REPO_ROOT = Path(__file__).resolve().parents[1]
|
|
PROJECT = os.environ.get("COMPOSE_PROJECT_NAME", "mtusi2026lab2")
|
|
ENV_FILE = os.environ.get("COMPOSE_ENV_FILE", ".env")
|
|
ENABLED = os.environ.get("STUDENT_DOCKER_TESTS") == "1"
|
|
|
|
|
|
def compose(*arguments: str, timeout: int = 120) -> None:
|
|
result = subprocess.run(
|
|
["docker", "compose", "-p", PROJECT, "--env-file", ENV_FILE, *arguments],
|
|
cwd=str(REPO_ROOT),
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=timeout,
|
|
)
|
|
if result.returncode != 0:
|
|
raise AssertionError(
|
|
"docker compose %s failed: %s" % (" ".join(arguments), result.stderr[-500:])
|
|
)
|
|
|
|
|
|
def wait_ready(expected: int, seconds: float) -> float:
|
|
started = time.monotonic()
|
|
deadline = started + seconds
|
|
last = None
|
|
while time.monotonic() < deadline:
|
|
last = common.request("GET", "/health/ready", timeout=5)
|
|
if last.status == expected:
|
|
return time.monotonic() - started
|
|
time.sleep(0.5)
|
|
raise AssertionError(
|
|
"readiness did not reach %s within %.0fs (last=%s %r)"
|
|
% (expected, seconds, last.status if last else None, last.json if last else None)
|
|
)
|
|
|
|
|
|
@unittest.skipUnless(ENABLED, "set STUDENT_DOCKER_TESTS=1 to stop real containers")
|
|
class DependencyOutages(unittest.TestCase):
|
|
def test_valkey_loss_degrades_then_postgres_loss_is_bounded(self) -> None:
|
|
alice = common.actor("degrade")
|
|
chat = common.create_chat(alice.token, [alice.id], "Устойчивость")
|
|
# Warm the session cache.
|
|
self.assertEqual(common.request("GET", "/api/v1/users/me", token=alice.token).status, 200)
|
|
|
|
cached = self._sample_latency(alice.token, 60)
|
|
summary = {"cached_p50_ms": round(cached["p50"], 2)}
|
|
try:
|
|
# 1. Valkey is a cache: auth still works, without DB-free fast path.
|
|
compose("stop", "valkey")
|
|
ready = common.request("GET", "/health/ready")
|
|
self.assertEqual(
|
|
ready.status, 200, "session cache must not be a readiness dependency"
|
|
)
|
|
me = common.request("GET", "/api/v1/users/me", token=alice.token)
|
|
self.assertEqual(me.status, 200, me.json)
|
|
sent = common.request(
|
|
"POST",
|
|
"/api/v1/chats/" + chat["id"] + "/messages",
|
|
body={"text": "без кэша"},
|
|
token=alice.token,
|
|
)
|
|
self.assertEqual(sent.status, 201, sent.json)
|
|
without_cache = self._sample_latency(alice.token, 60)
|
|
summary["cache_down_p50_ms"] = round(without_cache["p50"], 2)
|
|
summary["cache_down_p95_ms"] = round(without_cache["p95"], 2)
|
|
|
|
compose("start", "valkey")
|
|
time.sleep(3)
|
|
self.assertEqual(common.request("GET", "/health/ready").status, 200)
|
|
|
|
# 2. PostgreSQL is the source of truth: bounded errors, never a 200
|
|
# for a token the server cannot verify, and never a raw 500.
|
|
compose("stop", "postgres")
|
|
ready = common.request("GET", "/health/ready")
|
|
self.assertEqual(ready.status, 503, ready.json)
|
|
self.assertEqual(ready.json["error"]["code"], "unavailable")
|
|
|
|
started = time.monotonic()
|
|
write = common.request(
|
|
"POST",
|
|
"/api/v1/chats/" + chat["id"] + "/messages",
|
|
body={"text": "без базы"},
|
|
token=alice.token,
|
|
timeout=30,
|
|
)
|
|
bounded = time.monotonic() - started
|
|
self.assertEqual(write.status, 503, write.json)
|
|
self.assertEqual(write.json["error"]["code"], "unavailable")
|
|
self.assertLess(bounded, 10, "database failure must fail fast")
|
|
summary["db_down_write_seconds"] = round(bounded, 2)
|
|
|
|
for leaked in ("psycopg", "postgresql://", "password", "Traceback"):
|
|
self.assertNotIn(leaked, json.dumps(write.json))
|
|
unknown = common.request(
|
|
"GET", "/api/v1/users/me", token="unknown-token-value", timeout=30
|
|
)
|
|
self.assertIn(unknown.status, (401, 503))
|
|
self.assertNotEqual(unknown.status, 200)
|
|
|
|
# 3. Recovery keeps the same session and the stored chat.
|
|
compose("start", "postgres")
|
|
summary["recovery_seconds"] = round(wait_ready(200, 90), 2)
|
|
after = common.request("GET", "/api/v1/chats/" + chat["id"], token=alice.token)
|
|
self.assertEqual(after.status, 200, after.json)
|
|
recovered = common.request(
|
|
"POST",
|
|
"/api/v1/chats/" + chat["id"] + "/messages",
|
|
body={"text": "после восстановления"},
|
|
token=alice.token,
|
|
)
|
|
self.assertEqual(recovered.status, 201, recovered.json)
|
|
messages = common.history(alice.token, chat["id"])
|
|
self.assertIn("после восстановления", [message["text"] for message in messages])
|
|
finally:
|
|
compose("start", "valkey", "postgres")
|
|
try:
|
|
wait_ready(200, 90)
|
|
except AssertionError:
|
|
pass
|
|
print("\n outage summary: " + json.dumps(summary, ensure_ascii=False))
|
|
|
|
def _sample_latency(self, token: str, count: int) -> dict[str, float]:
|
|
samples = []
|
|
for _ in range(count):
|
|
started = time.monotonic()
|
|
response = common.request("GET", "/api/v1/users/me", token=token, timeout=30)
|
|
samples.append(time.monotonic() - started)
|
|
self.assertEqual(response.status, 200, response.json)
|
|
ordered = sorted(samples)
|
|
return {
|
|
"p50": statistics.median(samples) * 1000,
|
|
"p95": ordered[max(0, int(len(ordered) * 0.95) - 1)] * 1000,
|
|
}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|