"""Ограниченный пул соединений asyncpg и перевод сбоев БД в 503.""" import asyncio from contextlib import asynccontextmanager import asyncpg from .config import Settings from .errors import unavailable # Ошибки "БД недоступна/перегружена" -> 503, а не 500 и тем более не пропуск запроса. DB_UNAVAILABLE = ( OSError, asyncio.TimeoutError, asyncpg.PostgresConnectionError, asyncpg.InterfaceError, asyncpg.CannotConnectNowError, asyncpg.TooManyConnectionsError, asyncpg.QueryCanceledError, # statement_timeout asyncpg.AdminShutdownError, ) class Database: def __init__(self, settings: Settings): self.settings = settings self.pool: asyncpg.Pool | None = None async def start(self) -> None: s = self.settings # min_size соединений создаётся лениво (connect при первом acquire), поэтому API стартует # даже при недоступной БД и честно отвечает 503 в /health/ready. self.pool = asyncpg.create_pool( s.database_url, min_size=0, max_size=s.db_pool_max, timeout=3, # таймаут установления соединения command_timeout=s.db_statement_timeout_ms / 1000 + 1, max_inactive_connection_lifetime=300, server_settings={ 'application_name': 'messenger-api', 'statement_timeout': str(s.db_statement_timeout_ms), 'idle_in_transaction_session_timeout': '10000', 'timezone': 'UTC', }, ) await self.pool async def close(self) -> None: if self.pool is not None: await self.pool.close() @asynccontextmanager async def connection(self): try: async with self.pool.acquire(timeout=self.settings.db_acquire_timeout) as conn: yield conn except DB_UNAVAILABLE: raise unavailable() from None async def ping(self) -> bool: try: async with self.pool.acquire(timeout=1) as conn: return await conn.fetchval('SELECT 1', timeout=1) == 1 except DB_UNAVAILABLE: return False