compose.yaml now runs one api service with API_REPLICAS replicas and no published ports, container name or hostname, behind lb, HAProxy 3.2.26 LTS pinned by digest and the only service with ports, bound to 127.0.0.1 (LB_HTTP_PORT for HTTP, LB_STATS_PORT for read-only stats). The balancer finds replicas through Docker DNS with a server template, checks GET /health/ready every second (fall 2, rise 2), balances round robin without stickiness, retries connection failures on another replica and allows a retry after a sent request only for GET and for message posts carrying Idempotency-Key, never for users, chats or login. Its own 502/503/504 answers use the contract error body with the forwarded X-Request-Id. The network is split into edge and an internal backend, every service gets CPU and memory limits, the API runs read-only with a tmpfs /tmp, two workers per replica, an 8 s request limit and a 5 s graceful stop inside an 8 s stop_grace_period. Only api builds the image, migrate reuses it once before the replicas start. PostgreSQL loads pg_stat_statements and allows 200 connections. The short TTL instance of lab 2 published the API around the balancer and is removed; its expiry check stays as an in-process test. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
103 lines
3.2 KiB
Python
103 lines
3.2 KiB
Python
import asyncio
|
||
import os
|
||
import subprocess
|
||
import time
|
||
from base64 import b64encode
|
||
from collections.abc import Awaitable
|
||
from pathlib import Path
|
||
from typing import Any
|
||
from uuid import uuid4
|
||
|
||
from httpx import AsyncClient, Response, TransportError
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
|
||
PASSWORD = "Пароль-для-стенда-01"
|
||
BASIC = 'Basic realm="messenger", charset="UTF-8"'
|
||
BEARER = 'Bearer realm="messenger"'
|
||
VALKEY_AUTH = 'REDISCLI_AUTH="$(sed -n "s/^requirepass //p" /run/secrets/valkey.conf)"'
|
||
|
||
|
||
def compose(*args: str, stdin: str | None = None) -> str:
|
||
done = subprocess.run(
|
||
["docker", "compose", *args],
|
||
cwd=ROOT,
|
||
check=True,
|
||
capture_output=True,
|
||
text=True,
|
||
input=stdin,
|
||
)
|
||
return done.stdout.strip()
|
||
|
||
|
||
def psql(sql: str, **variables: str) -> str:
|
||
assigned = [item for name, value in variables.items() for item in ("-v", f"{name}={value}")]
|
||
command = ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tA"]
|
||
return compose(*command, *assigned, stdin=sql)
|
||
|
||
|
||
def valkey(command: str) -> str:
|
||
return compose("exec", "-T", "valkey", "sh", "-c", f"{VALKEY_AUTH} valkey-cli {command}")
|
||
|
||
|
||
def started_at(service: str) -> str:
|
||
return subprocess.run(
|
||
[
|
||
"docker",
|
||
"inspect",
|
||
"--format",
|
||
"{{.State.StartedAt}}",
|
||
*compose("ps", "-q", service).split(),
|
||
],
|
||
check=True,
|
||
capture_output=True,
|
||
text=True,
|
||
).stdout.strip()
|
||
|
||
|
||
def basic(username: str, password: str = PASSWORD) -> dict[str, str]:
|
||
return {"Authorization": "Basic " + b64encode(f"{username}:{password}".encode()).decode()}
|
||
|
||
|
||
def bearer(token: str) -> dict[str, str]:
|
||
return {"Authorization": f"Bearer {token}"}
|
||
|
||
|
||
def new_user(label: str) -> dict[str, str]:
|
||
return {
|
||
"username": f"u_{label}_{uuid4().hex[:12]}",
|
||
"display_name": f"Стенд {label}",
|
||
"password": PASSWORD,
|
||
}
|
||
|
||
|
||
async def enroll(http: AsyncClient, label: str) -> tuple[dict[str, Any], str]:
|
||
body = new_user(label)
|
||
created = await http.post("/api/v1/users", json=body)
|
||
assert created.status_code == 201, created.text
|
||
session = await http.post("/api/v1/auth/sessions", headers=basic(body["username"]))
|
||
assert session.status_code == 201, session.text
|
||
return created.json(), session.json()["token"]
|
||
|
||
|
||
async def timed(call: Awaitable[Response]) -> tuple[Response, float]:
|
||
started = time.perf_counter()
|
||
response = await call
|
||
return response, time.perf_counter() - started
|
||
|
||
|
||
async def wait_ready(http: AsyncClient, seconds: float = 60) -> float:
|
||
started = time.perf_counter()
|
||
while time.perf_counter() - started < seconds:
|
||
try:
|
||
if (await http.get("/health/ready")).status_code == 200:
|
||
return time.perf_counter() - started
|
||
except TransportError:
|
||
pass
|
||
await asyncio.sleep(0.25)
|
||
raise AssertionError("стенд не вернулся в готовность")
|
||
|
||
|
||
def report(event: str, response: Response, elapsed: float) -> None:
|
||
print(f"{event}: {response.status_code} за {elapsed:.3f} с")
|