forked from mtusi2026/mtusi2026lab3
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>
88 lines
4.2 KiB
Python
88 lines
4.2 KiB
Python
"""Engine, фабрика сессий и проверка связи с PostgreSQL.
|
||
|
||
Фабрики: глобалы процесса API создаёт `src/infra/db/session.py`, engine
|
||
закрывается в lifespan (`src/main.py`); соединения пул открывает лениво.
|
||
"""
|
||
|
||
import asyncio
|
||
|
||
import asyncpg
|
||
from sqlalchemy import text
|
||
from sqlalchemy.ext.asyncio import (
|
||
AsyncEngine,
|
||
AsyncSession,
|
||
async_sessionmaker,
|
||
create_async_engine,
|
||
)
|
||
|
||
from src.config.settings import Database
|
||
from src.utils.constants import DB_APPLICATION_NAME, DB_CLOSE_TIMEOUT_SECONDS
|
||
|
||
|
||
class BoundedCloseConnection(asyncpg.Connection):
|
||
"""Соединение asyncpg, мягкое закрытие которого ограничено сроком.
|
||
|
||
Прерванный запрос asyncpg отменяет и на сервере: открывает новое
|
||
соединение для CancelRequest и в `close()` ждёт его без срока.
|
||
SQLAlchemy при отмене задачи закрывает соединение мягко, поэтому
|
||
замёрзший Postgres держал бы запрос до разморозки. Здесь всё
|
||
закрытие ограничено: по истечении asyncpg обрывает соединение, а
|
||
SQLAlchemy переходит к принудительному закрытию.
|
||
"""
|
||
|
||
async def close(self, *, timeout: float | None = None) -> None:
|
||
limit = timeout or DB_CLOSE_TIMEOUT_SECONDS
|
||
await asyncio.wait_for(super().close(timeout=timeout), limit)
|
||
|
||
|
||
def create_engine(database: Database) -> AsyncEngine:
|
||
"""Engine с ограниченным пулом и таймаутами из `[database]`."""
|
||
server_settings = {
|
||
"application_name": DB_APPLICATION_NAME,
|
||
"statement_timeout": str(database.statement_timeout_ms),
|
||
}
|
||
if database.idle_in_transaction_timeout_ms:
|
||
# транзакцию замороженного процесса (docker pause) PostgreSQL
|
||
# прерывает сам: TCP-соединение живо, и иначе её блокировки, в
|
||
# том числе ключа идемпотентности, держались бы до разморозки
|
||
server_settings["idle_in_transaction_session_timeout"] = str(
|
||
database.idle_in_transaction_timeout_ms,
|
||
)
|
||
return create_async_engine(
|
||
database.url,
|
||
pool_size=database.pool_size,
|
||
max_overflow=database.max_overflow,
|
||
pool_timeout=database.pool_timeout_seconds,
|
||
# после рестарта Postgres соединения пула мертвы: проверка при
|
||
# выдаче не даёт первому запросу получить ошибку
|
||
pool_pre_ping=True,
|
||
# str() ошибки драйвера уходит в журнал (get_db_session, traceback
|
||
# 500): без этого в нём были бы параметры SQL — текст сообщений,
|
||
# с session-auth хэши паролей и токенов (logging.md)
|
||
hide_parameters=True,
|
||
# command_timeout asyncpg не задан: зависший сервер он не
|
||
# ограничивает (см. BoundedCloseConnection). Срок всей работы
|
||
# запроса с БД ставит asyncio в get_db_session
|
||
connect_args={
|
||
"timeout": database.connect_timeout_seconds,
|
||
"connection_class": BoundedCloseConnection,
|
||
"server_settings": server_settings,
|
||
},
|
||
)
|
||
|
||
|
||
def create_session_factory(
|
||
engine: AsyncEngine,
|
||
) -> async_sessionmaker[AsyncSession]:
|
||
# после commit DTO уже собраны, перечитывать объекты незачем
|
||
return async_sessionmaker(engine, expire_on_commit=False)
|
||
|
||
|
||
async def ping(engine: AsyncEngine, *, timeout: float) -> None:
|
||
"""`SELECT 1`; бросает исключение драйвера или `TimeoutError`.
|
||
|
||
Соединение, прерванное сроком, SQLAlchemy сам не возвращает в пул.
|
||
"""
|
||
async with asyncio.timeout(timeout), engine.connect() as connection:
|
||
await connection.execute(text("SELECT 1"))
|