"""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")