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
+32 -10
View File
@@ -1,16 +1,20 @@
"""Entry point: `python -m messenger`. The HTTP server is the main process (PID 1 in Docker).
Shutdown sequence on SIGTERM/SIGINT:
1. readiness flips to 503 (`app.state.draining = True`);
2. uvicorn closes the listening socket, so new connections are refused;
3. in-flight requests get up to SHUTDOWN_TIMEOUT_SECONDS (default 8 s < Docker's 10 s) to finish;
Shutdown sequence on SIGTERM/SIGINT (lab 3: the replica stands behind HAProxy):
1. readiness flips to 503 (`app.state.draining = True`), requests are still served;
2. after DRAIN_SECONDS (compose: 3 s > HAProxy detection 2 x 1 s) the load balancer has
marked this replica DOWN and sends nothing new here;
3. uvicorn closes the listening socket; in-flight requests get up to
SHUTDOWN_TIMEOUT_SECONDS (compose: 8 s) to finish;
4. the lifespan closes the DB pool and the Valkey client; the process exits with code 0.
Data stays in PostgreSQL and Valkey volumes.
DRAIN + SHUTDOWN (11 s) < compose stop_grace_period (15 s), so Docker never needs SIGKILL.
A second signal during the drain skips the rest of it. Data stays in PostgreSQL and Valkey.
"""
from __future__ import annotations
import logging
import sys
import threading
from types import FrameType
import uvicorn
@@ -23,12 +27,30 @@ log = logging.getLogger("messenger")
class GracefulServer(uvicorn.Server):
"""uvicorn.Server that marks the app as draining before the normal graceful stop."""
"""uvicorn.Server that drains (readiness 503, still serving) before the normal graceful stop."""
def __init__(self, config: uvicorn.Config, drain_seconds: float):
super().__init__(config)
self.drain_seconds = drain_seconds
self.drain_timer: threading.Timer | None = None
def handle_exit(self, sig: int, frame: FrameType | None) -> None:
if not self.should_exit:
log.info("shutdown_requested", extra={"fields": {"signal": sig, "timeout_s": self.config.timeout_graceful_shutdown}})
self.config.app.state.draining = True # config.app is our Starlette instance
if self.drain_timer is None and self.drain_seconds > 0 and not self.should_exit:
log.info("drain_started", extra={"fields": {"signal": sig, "drain_s": self.drain_seconds,
"timeout_s": self.config.timeout_graceful_shutdown}})
# uvicorn polls should_exit in its main loop, so setting it from a timer thread is safe.
self.drain_timer = threading.Timer(self.drain_seconds, self._stop, args=(sig, frame))
self.drain_timer.daemon = True
self.drain_timer.start()
return
if self.drain_timer is not None:
self.drain_timer.cancel() # second signal: stop draining now
self._stop(sig, frame)
def _stop(self, sig: int, frame: FrameType | None) -> None:
if not self.should_exit:
log.info("shutdown_requested", extra={"fields": {"signal": sig}})
super().handle_exit(sig, frame)
@@ -51,10 +73,10 @@ def main() -> int:
lifespan="on",
timeout_graceful_shutdown=settings.shutdown_timeout,
)
server = GracefulServer(config)
server = GracefulServer(config, settings.drain_seconds)
log.info("starting", extra={"fields": {
"version": __version__, "env": settings.env, "host": settings.host, "port": settings.port,
"python": sys.version.split()[0], "storage": "postgresql",
"python": sys.version.split()[0], "storage": "postgresql", "instance_id": settings.instance_id,
}})
server.run()
log.info("stopped")