Files
mtusi2026lab3/src/db.py
T
Tmribob e084a29303 Реализация лабораторной 3: балансировка, отказ API-реплики, idempotency
- 2 API-реплики (api-1, api-2) с уникальным INSTANCE_ID
- Nginx load balancer с health-check и failover
- PostgreSQL источник истины, Valkey кэш сессий
- Idempotency-Key в заголовке, replay возвращает исходное сообщение
- X-Instance-Id в каждом ответе для идентификации реплики
- /version и /info эндпоинты
- Housekeeping-loop для очистки истёкших сессий и ключей
- stop-one.sh/cmd для failover-теста, restart.sh/cmd для persistence
- Исправлены импорты config/models/api/store/sessions
- Добавлены миграции 004 (idempotency), 005 (indexes), 006 (message_id)
- Отчёт с доказательствами критериев уровня 3 и 4
- Все тесты проходят: smoke, 26 student tests, failover, persistence, degradation
2026-10-30 21:14:37 +03:00

50 lines
1.5 KiB
Python

"""PostgreSQL access: a bounded async pool with explicit timeouts."""
from __future__ import annotations
from psycopg.rows import dict_row
from psycopg_pool import AsyncConnectionPool
def connection_options(statement_timeout_ms: int) -> str:
"""Server-side limits so a slow query or an idle transaction cannot pile up."""
return (
"-c statement_timeout="
+ str(statement_timeout_ms)
+ " -c lock_timeout=2000 -c idle_in_transaction_session_timeout=10000"
+ " -c timezone=UTC"
)
def create_pool(
database_url: str,
*,
min_size: int,
max_size: int,
timeout_seconds: float,
connect_timeout_seconds: int,
statement_timeout_ms: int,
) -> AsyncConnectionPool:
"""Build a closed pool; the lifespan opens it and closes it on shutdown."""
return AsyncConnectionPool(
conninfo=database_url,
min_size=min_size,
max_size=max_size,
timeout=timeout_seconds,
open=False,
check=AsyncConnectionPool.check_connection,
kwargs={
"row_factory": dict_row,
"connect_timeout": connect_timeout_seconds,
"options": connection_options(statement_timeout_ms),
"application_name": "mtusi-messenger-api",
},
name="messenger-pool",
)
async def ping(pool: AsyncConnectionPool) -> None:
"""Cheap readiness probe; raises when PostgreSQL is not usable."""
async with pool.connection() as connection:
await connection.execute("SELECT 1")