forked from mtusi2026/mtusi2026lab3
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:
co-authored by
Claude Opus 5.5
parent
4f6cfda37a
commit
3f12698676
+29
-2
@@ -8,6 +8,8 @@ Invalid values stop the process at startup with a clear message.
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
@@ -16,6 +18,22 @@ class ConfigError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
INSTANCE_ID_RE = re.compile(r"[A-Za-z0-9._-]{1,64}")
|
||||
|
||||
|
||||
def _instance_id() -> str:
|
||||
"""X-Instance-Id of this process: INSTANCE_ID or the container hostname.
|
||||
|
||||
Docker sets the hostname of a container to its short container ID, so the value
|
||||
is unique per replica, stable for the life of the process and maps 1:1 to a real
|
||||
container (`docker inspect`), which scripts/stop-one.sh relies on.
|
||||
"""
|
||||
value = os.environ.get("INSTANCE_ID", "").strip() or socket.gethostname()
|
||||
if INSTANCE_ID_RE.fullmatch(value) is None:
|
||||
raise ConfigError("INSTANCE_ID must match [A-Za-z0-9._-]{1,64}")
|
||||
return value
|
||||
|
||||
|
||||
def _int(name: str, default: int, low: int, high: int) -> int:
|
||||
raw = os.environ.get(name)
|
||||
if raw is None or raw.strip() == "":
|
||||
@@ -85,6 +103,9 @@ class Settings:
|
||||
db_timeout_seconds: float = 3.0
|
||||
cache_timeout_seconds: float = 0.5
|
||||
hash_concurrency: int = 2
|
||||
instance_id: str = "local"
|
||||
drain_seconds: float = 0.0
|
||||
idempotency_ttl_seconds: int = 86400
|
||||
|
||||
@property
|
||||
def db_statement_timeout_ms(self) -> int:
|
||||
@@ -110,8 +131,8 @@ class Settings:
|
||||
port=_int("APP_PORT", 8080, 1, 65535),
|
||||
env=os.environ.get("APP_ENV", "lab").strip() or "lab",
|
||||
log_level=log_level,
|
||||
# Docker sends SIGKILL 10 s after SIGTERM by default; finish earlier.
|
||||
shutdown_timeout=_float("SHUTDOWN_TIMEOUT_SECONDS", 8.0, 0.0, 9.0),
|
||||
# DRAIN_SECONDS + SHUTDOWN_TIMEOUT_SECONDS must stay below compose stop_grace_period.
|
||||
shutdown_timeout=_float("SHUTDOWN_TIMEOUT_SECONDS", 8.0, 0.0, 30.0),
|
||||
max_body_bytes=_int("MAX_BODY_BYTES", 64 * 1024, 1024, 1024 * 1024),
|
||||
docs_enabled=_bool("DOCS_ENABLED", True),
|
||||
database_url=_secret("DATABASE_URL", required=True),
|
||||
@@ -124,4 +145,10 @@ class Settings:
|
||||
db_timeout_seconds=_float("DB_TIMEOUT_SECONDS", 3.0, 0.5, 30.0),
|
||||
cache_timeout_seconds=_float("CACHE_TIMEOUT_SECONDS", 0.5, 0.05, 10.0),
|
||||
hash_concurrency=_int("PASSWORD_HASH_CONCURRENCY", 2, 1, 16),
|
||||
instance_id=_instance_id(),
|
||||
# After SIGTERM: readiness is 503 but requests are still served for this long,
|
||||
# so the load balancer stops routing here before the listener closes.
|
||||
drain_seconds=_float("DRAIN_SECONDS", 0.0, 0.0, 10.0),
|
||||
# Contract: a replay within 24 h returns the original result.
|
||||
idempotency_ttl_seconds=_int("IDEMPOTENCY_TTL_SECONDS", 86400, 86400, 30 * 24 * 3600),
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user