feat: put API replicas behind HAProxy
HAProxy 3.4 is the only published entry point; api runs as API_REPLICAS replicas without ports, found through Docker DNS and checked on /health/ready. Retries only on connection failure, LB errors in the contract error format, resource limits and per-service secrets. Adds scripts/stop-one.sh, LB-aware restart.sh, make replicas / instances / lb_stats and replica tests driven by EXPECT_REPLICAS. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -17,15 +17,19 @@
|
||||
получает новый Idempotency-Key (печатается для повтора)
|
||||
smoke публичный tests/smoke.py против этого порта
|
||||
student собственные тесты student-tests/ (make student_test) против
|
||||
этого порта
|
||||
этого порта; против своего процесса — с EXPECT_REPLICAS=1
|
||||
instances [--count N] распределение одной сессии по репликам: вход
|
||||
одним синтетическим пользователем, N × GET /users/me с одним
|
||||
токеном, X-Instance-Id каждого ответа и итог по репликам
|
||||
stop остановить свой экземпляр на порту
|
||||
all start → flow → smoke → student (если есть student-tests/) → stop
|
||||
|
||||
Порт по умолчанию 18080, а не 8080: на 8080 обычно висит `make run_dev`
|
||||
пользователя, и его процесс трогать не надо. Экземпляр драйвера пишет в
|
||||
ту же рабочую базу Postgres, что и `make run_dev`. flow, req, smoke и
|
||||
student работают с любым сервером на порту, в том числе с контейнером
|
||||
(`make run_docker APP_OUT_PORT=<port>`).
|
||||
Порт по умолчанию 18080, а не 8080: на 8080 обычно работает стенд
|
||||
`make run_docker` (HAProxy перед репликами API) или `make run_dev`
|
||||
пользователя, и их процессы трогать не надо. Экземпляр драйвера пишет в
|
||||
ту же рабочую базу Postgres. flow, req, smoke, student и instances
|
||||
работают с любым сервером на порту, в том числе со стендом через
|
||||
балансировщик (`--port 8080`).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@@ -40,6 +44,7 @@ import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
@@ -537,10 +542,57 @@ def cmd_student(port: int) -> int:
|
||||
if not (ROOT / "student-tests").is_dir():
|
||||
print("no student-tests/ in this checkout")
|
||||
return 1
|
||||
return subprocess.call(
|
||||
["make", "student_test", f"BASE_URL=http://localhost:{port}"],
|
||||
cwd=ROOT,
|
||||
command = ["make", "student_test", f"BASE_URL=http://localhost:{port}"]
|
||||
_, pid_path = paths(port)
|
||||
if pid_path.exists():
|
||||
# на порту свой процесс драйвера: один API без балансировщика,
|
||||
# тесты реплик пропускаются с причиной
|
||||
command.append("EXPECT_REPLICAS=1")
|
||||
return subprocess.call(command, cwd=ROOT)
|
||||
|
||||
|
||||
def cmd_instances(port: int, count: int) -> int:
|
||||
"""Распределение одной сессии по репликам: один вход, `count`
|
||||
запросов `GET /users/me` с одним токеном. Токен не печатается."""
|
||||
tag = uuid.uuid4().hex[:8]
|
||||
username, password = f"lb_{tag}", f"Pw-lb-{uuid.uuid4().hex}"
|
||||
body = {
|
||||
"username": username,
|
||||
"display_name": "LB demo",
|
||||
"password": password,
|
||||
}
|
||||
status, _, _ = call(port, "POST", USERS, body=body)
|
||||
if status != 201:
|
||||
print(f"register: {status}")
|
||||
return 1
|
||||
status, _, session = call(
|
||||
port,
|
||||
"POST",
|
||||
SESSIONS,
|
||||
authorization=basic(username, password),
|
||||
)
|
||||
if status != 201 or not isinstance(session, dict):
|
||||
print(f"login: {status}")
|
||||
return 1
|
||||
token = session["token"]
|
||||
counts: Counter[str] = Counter()
|
||||
failures = 0
|
||||
for number in range(1, count + 1):
|
||||
status, hdrs, payload = call(port, "GET", f"{USERS}/me", token=token)
|
||||
instance = hdrs.get("x-instance-id", "-")
|
||||
ok = status == 200 and isinstance(payload, dict)
|
||||
ok = ok and payload.get("username") == username
|
||||
failures += not ok
|
||||
print(
|
||||
f"{number:>3} GET /api/v1/users/me {status} "
|
||||
f"x-instance-id: {instance}" + ("" if ok else " UNEXPECTED"),
|
||||
)
|
||||
counts[instance] += 1
|
||||
print(f"user {username}: one login, {count} requests with one token")
|
||||
for instance, served in counts.most_common():
|
||||
print(f" {instance}: {served}")
|
||||
print(f"instances: {len(counts)}")
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
@@ -549,6 +601,8 @@ def main() -> int:
|
||||
sub = parser.add_subparsers(dest="cmd", required=True)
|
||||
for name in ("start", "stop", "status", "flow", "smoke", "student", "all"):
|
||||
sub.add_parser(name)
|
||||
instances = sub.add_parser("instances")
|
||||
instances.add_argument("--count", type=int, default=12)
|
||||
req = sub.add_parser("req")
|
||||
req.add_argument("method")
|
||||
req.add_argument("path")
|
||||
@@ -580,6 +634,8 @@ def main() -> int:
|
||||
return flow_rc or smoke_rc or student_rc
|
||||
if args.cmd == "req":
|
||||
return cmd_req(port, args)
|
||||
if args.cmd == "instances":
|
||||
return cmd_instances(port, args.count)
|
||||
handlers = {
|
||||
"start": cmd_start,
|
||||
"stop": cmd_stop,
|
||||
|
||||
Reference in New Issue
Block a user