ЛР3: балансировка HAProxy, 2 реплики API, идемпотентность, отказоустойчивость (на 4)
- X-Instance-Id в каждом ответе; обязательный Idempotency-Key, таблица idempotency_keys (миграция 0002, одна транзакция, конкурентные повторы через уникальный индекс) - graceful shutdown: SIGTERM -> ready=503 -> drain 3 с -> закрытие порта - compose: lb (HAProxy) + api x2 без портов + разовый migrate + postgres, лимиты CPU/RAM - хуки stop-one/restart/restore-replicas, scripts/experiments.py (failover, idempotency, rolling) - свои тесты: 44 (13 новых); evidence: smoke, pytest, persistence, failover, эксперименты
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
import socket
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
# Корень проекта (в контейнере код лежит в /app, и это будет "/").
|
||||
BASE_DIR = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class RunConfig(BaseModel):
|
||||
host: str = "0.0.0.0"
|
||||
port: int = 8080
|
||||
# Docker кладёт в hostname короткий ID контейнера: по X-Instance-Id его можно остановить через `docker stop`.
|
||||
instance_id: str = socket.gethostname()
|
||||
# SIGTERM -> сразу /health/ready=503, но порт закрывается только через drain_seconds:
|
||||
# за это время балансировщик успевает вывести реплику из ротации
|
||||
# (должно быть больше худшего времени обнаружения в haproxy.cfg: fall*inter + timeout check = 2.5 с).
|
||||
drain_seconds: int = 3
|
||||
# Версия сборки (build-arg APP_VERSION): видна в логе, различает старую и новую реплику при rolling update.
|
||||
version: str = "dev"
|
||||
# Время на завершение уже принятых запросов после закрытия порта.
|
||||
graceful_timeout: int = 5
|
||||
|
||||
|
||||
class LoggingConfig(BaseModel):
|
||||
level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"
|
||||
format: str = "[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s"
|
||||
datefmt: str = "%Y-%m-%d %H:%M:%S"
|
||||
|
||||
|
||||
class DatabaseConfig(BaseModel):
|
||||
# Значения по умолчанию — для запуска внутри Compose.
|
||||
host: str = "postgres"
|
||||
port: int = 5432
|
||||
name: str = "messenger"
|
||||
user: str = "messenger"
|
||||
password_file: Path = Path("/run/secrets/postgres_password")
|
||||
|
||||
pool_size: int = 5
|
||||
max_overflow: int = 5
|
||||
pool_timeout: int = 5
|
||||
connect_timeout: int = 3
|
||||
statement_timeout_ms: int = 5000
|
||||
echo: bool = False
|
||||
|
||||
def read_password(self) -> str:
|
||||
return read_secret(self.password_file)
|
||||
|
||||
|
||||
class JWTConfig(BaseModel):
|
||||
# Ключ должен сохраняться между перезапусками, иначе выданные токены станут недействительны.
|
||||
secret_file: Path = Path("/run/secrets/jwt_secret")
|
||||
algorithm: str = "HS256"
|
||||
session_ttl_seconds: int = 3600
|
||||
|
||||
def read_secret_key(self) -> str:
|
||||
return read_secret(self.secret_file)
|
||||
|
||||
|
||||
class IdempotencyConfig(BaseModel):
|
||||
# Контракт: повтор с тем же ключом в течение 24 часов возвращает исходный ответ.
|
||||
ttl_seconds: int = 86400
|
||||
|
||||
|
||||
def read_secret(path: Path) -> str:
|
||||
"""Прочитать файл-секрет. Относительный путь считается от корня проекта."""
|
||||
full_path = path if path.is_absolute() else BASE_DIR / path
|
||||
return full_path.read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
class ApiV1Prefix(BaseModel):
|
||||
prefix: str = "/v1"
|
||||
users: str = "/users"
|
||||
chats: str = "/chats"
|
||||
auth: str = "/auth"
|
||||
|
||||
|
||||
class ApiPrefix(BaseModel):
|
||||
prefix: str = "/api"
|
||||
v1: ApiV1Prefix = ApiV1Prefix()
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=BASE_DIR / ".env",
|
||||
case_sensitive=False,
|
||||
env_nested_delimiter="__",
|
||||
env_prefix="APP_CONFIG__",
|
||||
extra="ignore",
|
||||
)
|
||||
|
||||
run: RunConfig = RunConfig()
|
||||
api: ApiPrefix = ApiPrefix()
|
||||
logging: LoggingConfig = LoggingConfig()
|
||||
db: DatabaseConfig = DatabaseConfig()
|
||||
jwt: JWTConfig = JWTConfig()
|
||||
idempotency: IdempotencyConfig = IdempotencyConfig()
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,57 @@
|
||||
from collections.abc import Iterator
|
||||
|
||||
from sqlalchemy import URL, create_engine, text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from core.config import settings
|
||||
from core.logger import logger
|
||||
|
||||
|
||||
def build_url() -> URL:
|
||||
return URL.create(
|
||||
drivername="postgresql+psycopg",
|
||||
username=settings.db.user,
|
||||
password=settings.db.read_password(),
|
||||
host=settings.db.host,
|
||||
port=settings.db.port,
|
||||
database=settings.db.name,
|
||||
)
|
||||
|
||||
|
||||
engine = create_engine(
|
||||
build_url(),
|
||||
pool_size=settings.db.pool_size,
|
||||
max_overflow=settings.db.max_overflow,
|
||||
pool_timeout=settings.db.pool_timeout,
|
||||
# Проверять соединение перед выдачей из пула (нужно после рестарта PostgreSQL).
|
||||
pool_pre_ping=True,
|
||||
connect_args={
|
||||
"connect_timeout": settings.db.connect_timeout,
|
||||
"options": f"-c statement_timeout={settings.db.statement_timeout_ms}",
|
||||
},
|
||||
echo=settings.db.echo,
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
|
||||
|
||||
|
||||
def get_db() -> Iterator[Session]:
|
||||
"""Одна ORM-сессия на HTTP-запрос."""
|
||||
with SessionLocal() as session:
|
||||
yield session
|
||||
|
||||
|
||||
def check_database() -> bool:
|
||||
try:
|
||||
with engine.connect() as connection:
|
||||
connection.execute(text("SELECT 1"))
|
||||
return True
|
||||
except SQLAlchemyError as exc:
|
||||
# Только тип ошибки: в тексте может оказаться адрес БД.
|
||||
logger.warning(f"PostgreSQL недоступен: {type(exc).__name__}")
|
||||
return False
|
||||
|
||||
|
||||
def log_database_target():
|
||||
logger.info(f"База данных: {engine.url.render_as_string(hide_password=True)}")
|
||||
@@ -0,0 +1,15 @@
|
||||
import logging
|
||||
|
||||
from core.config import settings
|
||||
|
||||
|
||||
def setup_logger():
|
||||
logging.basicConfig(
|
||||
level=settings.logging.level,
|
||||
format=settings.logging.format,
|
||||
datefmt=settings.logging.datefmt,
|
||||
)
|
||||
return logging.getLogger("messenger")
|
||||
|
||||
|
||||
logger = setup_logger()
|
||||
Reference in New Issue
Block a user