ЛР 3 — БПИ2303 — Костылев — на 5 #161
@@ -13,6 +13,8 @@ from stand import (
|
|||||||
bearer,
|
bearer,
|
||||||
compose,
|
compose,
|
||||||
enroll,
|
enroll,
|
||||||
|
inside_replica,
|
||||||
|
lb_up,
|
||||||
new_user,
|
new_user,
|
||||||
psql,
|
psql,
|
||||||
report,
|
report,
|
||||||
@@ -20,6 +22,7 @@ from stand import (
|
|||||||
timed,
|
timed,
|
||||||
valkey,
|
valkey,
|
||||||
wait_ready,
|
wait_ready,
|
||||||
|
waited,
|
||||||
)
|
)
|
||||||
|
|
||||||
pytestmark = pytest.mark.stack
|
pytestmark = pytest.mark.stack
|
||||||
@@ -173,7 +176,6 @@ async def test_postgres_stopped_gives_bounded_503_and_recovers(http: AsyncClient
|
|||||||
compose("stop", "postgres")
|
compose("stop", "postgres")
|
||||||
checks = {
|
checks = {
|
||||||
"ready": await timed(http.get("/health/ready")),
|
"ready": await timed(http.get("/health/ready")),
|
||||||
"live": await timed(http.get("/health/live")),
|
|
||||||
"me": await timed(http.get("/api/v1/users/me", headers=bearer(token))),
|
"me": await timed(http.get("/api/v1/users/me", headers=bearer(token))),
|
||||||
"stranger": await timed(http.get("/api/v1/users/me", headers=bearer("x" * 43))),
|
"stranger": await timed(http.get("/api/v1/users/me", headers=bearer("x" * 43))),
|
||||||
"login": await timed(
|
"login": await timed(
|
||||||
@@ -181,16 +183,28 @@ async def test_postgres_stopped_gives_bounded_503_and_recovers(http: AsyncClient
|
|||||||
),
|
),
|
||||||
"register": await timed(http.post("/api/v1/users", json=new_user("nodb"))),
|
"register": await timed(http.post("/api/v1/users", json=new_user("nodb"))),
|
||||||
}
|
}
|
||||||
|
live_inside = inside_replica("/health/live")
|
||||||
|
excluded = await waited(lambda: lb_up() == 0, 5)
|
||||||
|
through_lb = await http.get("/health/live")
|
||||||
for name, (response, elapsed) in checks.items():
|
for name, (response, elapsed) in checks.items():
|
||||||
report(f"postgres остановлен, {name}", response, elapsed)
|
report(f"postgres остановлен, {name}", response, elapsed)
|
||||||
assert elapsed < 2
|
assert elapsed < 2
|
||||||
assert checks["live"][0].status_code == 200
|
assert response.status_code == 503
|
||||||
for name in ("ready", "me", "stranger", "login", "register"):
|
assert response.json()["error"]["code"] == "unavailable"
|
||||||
assert checks[name][0].status_code == 503
|
print(
|
||||||
assert checks[name][0].json()["error"]["code"] == "unavailable"
|
f"live внутри реплики {live_inside}; LB исключил все реплики ещё через {excluded:.2f} с"
|
||||||
|
)
|
||||||
|
report("live через LB без реплик", through_lb, 0)
|
||||||
|
assert live_inside == 200
|
||||||
|
assert lb_up() == 0
|
||||||
|
assert excluded < 2
|
||||||
|
assert through_lb.status_code == 503
|
||||||
|
assert through_lb.json()["error"]["request_id"] == through_lb.headers["X-Request-Id"]
|
||||||
|
assert "X-Instance-Id" not in through_lb.headers
|
||||||
finally:
|
finally:
|
||||||
compose("start", "postgres")
|
compose("start", "postgres")
|
||||||
recovered = await wait_ready(http)
|
recovered = await wait_ready(http)
|
||||||
|
await waited(lambda: lb_up() == len(compose("ps", "-q", "api").split()))
|
||||||
me = await http.get("/api/v1/users/me", headers=bearer(token))
|
me = await http.get("/api/v1/users/me", headers=bearer(token))
|
||||||
print(f"postgres запущен: готовность через {recovered:.1f} с, прежний токен {me.status_code}")
|
print(f"postgres запущен: готовность через {recovered:.1f} с, прежний токен {me.status_code}")
|
||||||
assert me.json() == user
|
assert me.json() == user
|
||||||
|
|||||||
+31
-1
@@ -1,13 +1,15 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
|
import csv
|
||||||
import os
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import time
|
import time
|
||||||
from base64 import b64encode
|
from base64 import b64encode
|
||||||
from collections.abc import Awaitable
|
from collections.abc import Awaitable, Callable
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import httpx
|
||||||
from httpx import AsyncClient, Response, TransportError
|
from httpx import AsyncClient, Response, TransportError
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[1]
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
@@ -55,6 +57,25 @@ def started_at(service: str) -> str:
|
|||||||
).stdout.strip()
|
).stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def inside_replica(path: str) -> int:
|
||||||
|
replica = compose("ps", "-q", "api").split()[0]
|
||||||
|
probe = f"import urllib.request as u;print(u.urlopen('http://127.0.0.1:8080{path}').status)"
|
||||||
|
done = subprocess.run(
|
||||||
|
["docker", "exec", replica, "python", "-c", probe],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
return int(done.stdout.strip() or 0)
|
||||||
|
|
||||||
|
|
||||||
|
def lb_up() -> int:
|
||||||
|
stats = httpx.get(f"http://{compose('port', 'lb', '8404')}/stats;csv", timeout=2).text
|
||||||
|
rows = csv.DictReader(stats.lstrip("# ").splitlines())
|
||||||
|
servers = (r for r in rows if r["pxname"] == "api" and r["svname"] != "BACKEND")
|
||||||
|
return sum(1 for r in servers if r["status"].startswith("UP"))
|
||||||
|
|
||||||
|
|
||||||
def basic(username: str, password: str = PASSWORD) -> dict[str, str]:
|
def basic(username: str, password: str = PASSWORD) -> dict[str, str]:
|
||||||
return {"Authorization": "Basic " + b64encode(f"{username}:{password}".encode()).decode()}
|
return {"Authorization": "Basic " + b64encode(f"{username}:{password}".encode()).decode()}
|
||||||
|
|
||||||
@@ -98,5 +119,14 @@ async def wait_ready(http: AsyncClient, seconds: float = 60) -> float:
|
|||||||
raise AssertionError("стенд не вернулся в готовность")
|
raise AssertionError("стенд не вернулся в готовность")
|
||||||
|
|
||||||
|
|
||||||
|
async def waited(condition: Callable[[], bool], seconds: float = 30) -> float:
|
||||||
|
started = time.perf_counter()
|
||||||
|
while time.perf_counter() - started < seconds:
|
||||||
|
if condition():
|
||||||
|
return time.perf_counter() - started
|
||||||
|
await asyncio.sleep(0.05)
|
||||||
|
raise AssertionError("условие не выполнилось за отведённое время")
|
||||||
|
|
||||||
|
|
||||||
def report(event: str, response: Response, elapsed: float) -> None:
|
def report(event: str, response: Response, elapsed: float) -> None:
|
||||||
print(f"{event}: {response.status_code} за {elapsed:.3f} с")
|
print(f"{event}: {response.status_code} за {elapsed:.3f} с")
|
||||||
|
|||||||
Reference in New Issue
Block a user