feat: HAProxy и N API-реплик, X-Instance-Id, общая идемпотентность, drain при SIGTERM

- compose: один масштабируемый сервис api (deploy.replicas=2, без ports и
  container_name), HAProxy 3.2 LTS по digest — единственная точка входа
  (127.0.0.1), разовый migrate до старта реплик, CPU/RAM-лимиты у всех сервисов,
  каждому сервису только его secrets.
- HAProxy: server-template + Docker DNS (re-resolve 1 с), активная проверка
  GET /health/ready каждую 1 с (fall 2 / rise 2), без backup-серверов,
  retry только conn-failure, ошибки самого LB — в формате контракта с X-Request-Id.
- API: X-Instance-Id = hostname контейнера на каждом ответе (и на 500/503);
  Idempotency-Key обязателен; ключ, сообщение и результат пишутся в ОДНОЙ
  транзакции (миграция 0002), конкурентный повтор ждёт уникальный индекс;
  другой body — 409, посторонний — всегда 404; attachment_ids=[] равен
  отсутствию поля; дубли ключей JSON и тело у POST /auth/sessions — 400.
- SIGTERM: readiness 503 + DRAIN_SECONDS=3 обслуживания, затем graceful stop.
- scripts: stop-one.sh (+ .cmd для Windows), restore-api.sh, restart.sh
  перезапускает и LB, lbctl.py — состояние бэкендов HAProxy -> контейнеры.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alexey Bodanyuk
2026-10-16 13:32:13 +03:00
co-authored by Claude Opus 5.5
parent 4f6cfda37a
commit 3f12698676
16 changed files with 629 additions and 61 deletions
+24 -6
View File
@@ -30,14 +30,14 @@ test-failover:
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
# ---------------------------------------------------------------------------
# Student solution (lab 2, Python). On Windows without make run the commands from
# REPORT.md directly (public tests there need PYTHONUTF8=1; restart hook: scripts/restart.cmd).
.PHONY: secrets up down logs ps migrate student-test unit-test explain
# Student solution (lab 3, Python). On Windows: PowerShell/Git Bash with GNU make, public
# tests need PYTHONUTF8=1, and the hooks are started through scripts/*.cmd (Git Bash).
.PHONY: secrets up down logs ps migrate student-test unit-test explain lb-status restore rolling-update failover-series
secrets:
$(PYTHON) scripts/init_secrets.py
# Build, apply migrations (service migrate) and wait until every service is healthy.
# Build, apply migrations ONCE (service migrate), start API replicas and the LB, wait for healthy.
up: secrets
docker compose up -d --build --wait
@@ -46,14 +46,32 @@ down:
docker compose down
logs:
docker compose logs --tail 50 api
docker compose logs --tail 50 api lb
ps:
docker compose ps
docker compose ps -a
migrate:
docker compose run --rm migrate
# HAProxy view of the replicas (UP/DOWN) mapped to containers and X-Instance-Id.
lb-status:
$(PYTHON) scripts/lbctl.py status
$(PYTHON) scripts/lbctl.py replicas
# Start replicas stopped by scripts/stop-one.sh again and wait until the LB has them all UP.
restore:
sh scripts/restore-api.sh
$(PYTHON) scripts/lbctl.py wait-up $${API_REPLICAS:-2}
# Replace every API replica one by one with a freshly built image (no downtime).
rolling-update:
sh scripts/rolling-update.sh
# Level 4: stop each replica in turn under load, measure RPS/errors/recovery (evidence/failover/).
failover-series:
$(PYTHON) bench/failover_series.py --output evidence/failover
# Own tests: unit + black-box against the running stand (needs requirements*.txt in a venv).
student-test:
$(PYTHON) -m pytest student-tests -v