"""Dependency failure checks (Redis/Postgres/S3). Optional: RUN_DEPS_TEST=1.""" from __future__ import annotations import hashlib import os import subprocess import time import uuid import imagegen from helpers import call, chat_for, register, upload ROOT = os.path.join(os.path.dirname(__file__), "..") def _compose(*args: str) -> None: cmd = ["docker", "compose", "--env-file", ".env", *args] subprocess.check_call(cmd, cwd=ROOT) def _started_at(service: str) -> dict: ids = subprocess.check_output(["docker", "compose", "--env-file", ".env", "ps", "-q", service], cwd=ROOT, text=True).split() assert ids, service return { c: subprocess.check_output(["docker", "inspect", "-f", "{{.State.StartedAt}}", c], text=True).strip() for c in ids } def _wait_ready(timeout_s: int = 60, stable: int = 6) -> None: # Several consecutive 200s: HAProxy may still finish health checks that started # during the outage and briefly mark every replica DOWN after the first 200. deadline = time.time() + timeout_s streak = 0 while time.time() < deadline: try: streak = streak + 1 if call("GET", "/health/ready")["status"] == 200 else 0 except Exception: streak = 0 if streak >= stable: return time.sleep(1) raise AssertionError("stack did not become ready in time") def _unavailable(method: str, path: str, token: str | None = None, body=None) -> dict: # Every 503 — from a replica or from HAProxy itself — is the JSON error envelope # with X-Request-Id / X-Instance-Id (checked inside call()). resp = call(method, path, 503, token=token, body=body) assert resp["json"]["error"]["code"] == "unavailable", resp["json"] return resp def _skip(name: str) -> bool: if os.environ.get("RUN_DEPS_TEST") != "1": print(f"SKIP {name} (set RUN_DEPS_TEST=1)") return True return False def test_redis_stop_returns_503_or_unready(): if _skip("test_redis_stop_returns_503_or_unready"): return actor = register("deps") _compose("stop", "redis") time.sleep(2) try: _unavailable("GET", "/health/ready") _unavailable("GET", "/api/v1/users/me", actor["token"]) _unavailable("DELETE", "/api/v1/auth/sessions/current", actor["token"]) finally: _compose("start", "redis") _wait_ready() call("GET", "/api/v1/users/me", 200, token=actor["token"]) def test_s3_stop_degrades_only_attachments(): # S3 is on the synchronous attachment path, so readiness reports 503; HAProxy then # falls back to the liveness-checked backend and text chat/metadata keep working. if _skip("test_s3_stop_degrades_only_attachments"): return alice, bob = register("s3down_a"), register("s3down_b") chat = chat_for(alice, bob) data = imagegen.rgb_png(24, 12) att = upload(alice["token"], chat["id"], data, "before.png", "image/png", 201)["json"] _compose("stop", "s3") try: time.sleep(3) _unavailable("GET", "/health/ready") started = time.monotonic() up = upload(alice["token"], chat["id"], data, "during.png", "image/png", 503) elapsed = time.monotonic() - started assert up["json"]["error"]["code"] == "unavailable", up["json"] assert elapsed < 15, elapsed _unavailable("GET", f"/api/v1/attachments/{att['id']}/content", bob["token"]) meta = call("GET", f"/api/v1/attachments/{att['id']}", 200, token=bob["token"])["json"] assert meta["sha256"] == att["sha256"] msg = call( "POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=bob["token"], body={"text": "S3 недоступен, но чат работает", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex}, )["json"] assert msg["attachment_ids"] == [att["id"]] print(" s3 down: ready 503, upload 503 in %.2fs, download 503, metadata/messages OK" % elapsed) finally: _compose("start", "s3") _compose("restart", "s3-gw") _wait_ready() dl = call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"]) assert hashlib.sha256(dl["bytes"]).hexdigest() == att["sha256"] upload(alice["token"], chat["id"], data, "after.png", "image/png", 201) def test_postgres_stop_returns_503(): if _skip("test_postgres_stop_returns_503"): return actor = register("deps_pg") _compose("stop", "postgres") time.sleep(2) try: _unavailable("GET", "/health/ready") started = time.monotonic() _unavailable("GET", "/api/v1/users/me", actor["token"]) _unavailable("GET", "/api/v1/chats", actor["token"]) assert time.monotonic() - started < 15 finally: _compose("start", "postgres") _wait_ready(90) call("GET", "/api/v1/users/me", 200, token=actor["token"]) def test_restart_hook_restarts_api_and_stores(): # tests/README: the persistence hook must restart the API and every store. if _skip("test_restart_hook_restarts_api_and_stores"): return actor = register("deps_hook") services = ("api", "postgres", "redis", "s3") before = {s: _started_at(s) for s in services} hook = ["cmd", "/c", r"scripts\restart.cmd"] if os.name == "nt" else ["sh", "scripts/restart.sh"] subprocess.check_call(hook, cwd=ROOT, stdout=subprocess.DEVNULL) _wait_ready(90) for s in services: after = _started_at(s) if s == "api": assert len(after) >= 2, after stale = [c for c, t in after.items() if before[s].get(c) == t] assert not stale, (s, stale) call("GET", "/api/v1/users/me", 200, token=actor["token"]) def test_postgres_pause_fails_fast(): # A paused (not stopped) database never answers: no RST, statement_timeout is never # evaluated. Requests must still end as JSON 503 within a bounded time. if _skip("test_postgres_pause_fails_fast"): return actor = register("deps_pause") _compose("pause", "postgres") try: timings = [] for path in ("/api/v1/users/me", "/api/v1/chats", "/api/v1/users/me"): started = time.monotonic() _unavailable("GET", path, actor["token"]) timings.append(time.monotonic() - started) assert max(timings) < 15, timings time.sleep(4) _unavailable("GET", "/health/ready") print(" postgres paused: 503 after " + ", ".join("%.2fs" % t for t in timings)) finally: _compose("unpause", "postgres") _wait_ready(90) call("GET", "/api/v1/users/me", 200, token=actor["token"])