"""PostgreSQL access: a bounded connection pool and a hard deadline for every unit of work. Three independent limits keep a request from hanging when the database misbehaves: * pool `timeout` — waiting for a free connection (pool exhausted); * server `statement_timeout` / `lock_timeout` — PostgreSQL itself cancels a slow statement or a statement stuck behind a lock; * client deadline — covers what the server cannot report, e.g. a paused/frozen PostgreSQL container or a dead network. The client deadline needs care. Every unit of work runs as its own task; at the deadline the REQUEST stops waiting and gets 503 at once, but the task is NOT cancelled: cancelling a psycopg query makes psycopg send a cancel request, and libpq starts that connection (PQcancelStart) synchronously in the event-loop thread, resolving the host name first. When the API has lost its network to PostgreSQL (lab 3 review scenario: `docker network disconnect`), that blocked the WHOLE replica, /health/live included, for ~1 minute. The abandoned task instead ends by itself, bounded by: * TCP keepalives + `tcp_user_timeout` (= the deadline): a dead peer or a vanished network breaks the socket within seconds, the connection is discarded by the pool; * `statement_timeout` / `lock_timeout` on a live but slow server; * a frozen (paused) server keeps the connection until it resumes; meanwhile new work waits at most the pool timeout and gets 503. Any failure becomes 503 `unavailable` — never 401, never a hang. """ from __future__ import annotations import asyncio import logging from collections.abc import Awaitable, Callable from typing import TypeVar import psycopg from psycopg_pool import AsyncConnectionPool, PoolTimeout from .config import Settings from .errors import Unavailable log = logging.getLogger("messenger.db") T = TypeVar("T") Work = Callable[[psycopg.AsyncConnection], Awaitable[T]] # Errors that mean "the database is unavailable right now", not "the request is wrong". # QueryCanceled (statement_timeout), LockNotAvailable (lock_timeout) and AdminShutdown # (server restart) are subclasses of OperationalError. UNAVAILABLE_ERRORS = (psycopg.OperationalError, psycopg.InterfaceError, PoolTimeout, TimeoutError) def _forget(task: asyncio.Task) -> None: """Done-callback for abandoned tasks: retrieve the result so nothing is logged as 'never retrieved'.""" if not task.cancelled(): task.exception() class Database: def __init__(self, settings: Settings): self.deadline = settings.db_timeout_seconds options = ( f"-c statement_timeout={settings.db_statement_timeout_ms} " f"-c lock_timeout={max(100, settings.db_statement_timeout_ms // 2)} " "-c idle_in_transaction_session_timeout=10000" ) self.pool = AsyncConnectionPool( conninfo=settings.database_url, min_size=settings.db_pool_min, max_size=settings.db_pool_max, timeout=settings.db_timeout_seconds, # max wait for a free connection open=False, name="messenger", check=AsyncConnectionPool.check_connection, # drop connections broken by a DB restart kwargs={ "options": options, "connect_timeout": max(1, int(settings.db_timeout_seconds)), "application_name": "messenger-api", # Autocommit connections: a single statement (post_message function, ping) is its # own transaction with ONE round trip; multi-statement work uses an explicit # conn.transaction() (BEGIN ... COMMIT), see run(). "autocommit": True, # Detect a dead peer / lost network without any cancel request (see module doc). "keepalives": 1, "keepalives_idle": 5, "keepalives_interval": 1, "keepalives_count": 3, "tcp_user_timeout": int(settings.db_timeout_seconds * 1000), }, ) async def open(self) -> None: # wait=False: the API starts (liveness 200) even if PostgreSQL is not up yet; # readiness stays 503 until the database answers. await self.pool.open(wait=False) async def close(self) -> None: await self.pool.close(timeout=2) async def run(self, work: Work[T], deadline: float | None = None, *, transaction: bool = True) -> T: """Run `work(conn)` in one transaction (COMMIT on success, ROLLBACK on any exception). transaction=False: `work` issues exactly ONE statement, which autocommit makes atomic. Domain errors raised by `work` (NotFound, Conflict, ...) propagate unchanged; database unavailability and the deadline become Unavailable (503). """ async def unit() -> T: async with self.pool.connection() as conn: if not transaction: return await work(conn) async with conn.transaction(): return await work(conn) task = asyncio.ensure_future(unit()) try: return await asyncio.wait_for(asyncio.shield(task), deadline or self.deadline) except UNAVAILABLE_ERRORS as exc: log.warning("database_unavailable", extra={"fields": {"error": type(exc).__name__}}) raise Unavailable("База данных временно недоступна") from None finally: if not task.done(): # Deadline or cancelled request: stop waiting now. The task is left to finish # on its own (no task.cancel(): that would trigger psycopg's blocking cancel). task.add_done_callback(_forget) async def ping(self, timeout: float = 1.0) -> bool: async def select_one(conn: psycopg.AsyncConnection) -> None: await conn.execute("SELECT 1") try: await self.run(select_one, deadline=timeout, transaction=False) return True except Unavailable: return False