HAProxy checks get fastinter 500ms and timeout check 2.5s (hung replica detected within 6.5 s), http-reuse never with uvicorn keep-alive 60 s so the LB closes idle replica connections, and app connections set idle_in_transaction_session_timeout so a frozen replica releases its idempotency key. The bench stand runs behind HAProxy with N replicas and gains the failover profile (make bench_failover / bench_failover_quick): constant-rate writes with a key and reads while each replica is stopped, killed or paused, with per-second timeline, detection and recovery time and write reconciliation. Driver commands idle-conns and hang-key check the keep-alive and hung-transaction decisions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
84 lines
3.1 KiB
Python
84 lines
3.1 KiB
Python
from collections.abc import AsyncIterator
|
|
from contextlib import asynccontextmanager
|
|
|
|
import uvicorn
|
|
from fastapi import FastAPI
|
|
|
|
from src.api import errors
|
|
from src.api.middlewares import RequestContextMiddleware
|
|
from src.api.routers import health_router, v1_router
|
|
from src.config import settings
|
|
from src.infra.cache.instance import cache
|
|
from src.infra.db.session import engine
|
|
from src.infra.logger import AbstractLogger, get_logger
|
|
from src.infra.password import prepare_dummy_hash
|
|
from src.schemas.enums import RunModeEnum
|
|
|
|
logger: AbstractLogger = get_logger().bind(module="startup")
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
|
database = settings.database
|
|
# engine и кэш подключаются лениво: без Postgres сервис стартует, а
|
|
# /health/ready отвечает 503; без Valkey запросы идут в Postgres
|
|
if not database.password.get_secret_value():
|
|
logger.warning("Database password is empty")
|
|
if not settings.cache.password.get_secret_value():
|
|
logger.warning("Cache password is empty")
|
|
# ~30 мс CPU при старте: время ответа на вход с неизвестным username
|
|
# ровное с первого запроса
|
|
await prepare_dummy_hash()
|
|
logger.info(
|
|
"Started API",
|
|
host=settings.app.host,
|
|
port=settings.app.port,
|
|
run_mode=settings.app.run_mode,
|
|
database_host=database.host,
|
|
database_port=database.port,
|
|
database_name=database.name,
|
|
cache_host=settings.cache.host,
|
|
cache_port=settings.cache.port,
|
|
)
|
|
try:
|
|
yield
|
|
finally:
|
|
await engine.dispose()
|
|
await cache.aclose()
|
|
logger.info("Stopped API")
|
|
|
|
|
|
def create_app() -> FastAPI:
|
|
# версия — info.version контракта (contracts/openapi.json)
|
|
app = FastAPI(title="MTUSI Messenger", version="1.3.0", lifespan=lifespan)
|
|
app.add_middleware(RequestContextMiddleware)
|
|
errors.register(app)
|
|
app.include_router(health_router)
|
|
app.include_router(v1_router)
|
|
return app
|
|
|
|
|
|
app = create_app()
|
|
|
|
|
|
def main() -> None:
|
|
reload = settings.app.run_mode == RunModeEnum.CONSOLE
|
|
uvicorn.run(
|
|
"src.main:app",
|
|
host=settings.app.host,
|
|
port=settings.app.port,
|
|
reload=reload,
|
|
# без reload uvicorn пишет warning на reload_dirs при каждом старте
|
|
reload_dirs=["src"] if reload else None,
|
|
# один процесс: реплики — лаба 3, пул соединений рассчитан на один
|
|
# процесс
|
|
workers=1,
|
|
timeout_graceful_shutdown=settings.app.graceful_shutdown_seconds,
|
|
# простаивающее соединение закрывает HAProxy раньше реплики
|
|
# (design change graceful-failover, решение 3)
|
|
timeout_keep_alive=settings.app.keep_alive_seconds,
|
|
# логи uvicorn идут через наш JSON-форматтер (src/infra/logger.py)
|
|
log_config=None,
|
|
access_log=False,
|
|
)
|