"""Shared asyncpg pool and transaction wrapper.""" from __future__ import annotations import asyncio import logging import os from contextlib import asynccontextmanager from dataclasses import dataclass from typing import Any, AsyncIterator, Awaitable, Callable, Mapping import asyncpg from .config import DatabaseConfig _logger = logging.getLogger(__name__) # The same connection failures that database.js treats as transient: refused, # reset and broken sockets, an administrative shutdown, a dropped connection # (SQLSTATE class 08) and a connect timeout. Other errors, such as bad # credentials or a missing database, are raised at once instead of retried. _TRANSIENT_CONNECTION_ERRORS = ( ConnectionRefusedError, ConnectionResetError, BrokenPipeError, TimeoutError, asyncpg.exceptions.AdminShutdownError, asyncpg.exceptions.PostgresConnectionError, ) def is_transient_connection_error(exc: BaseException) -> bool: """Return True for connection failures that a startup retry can recover from.""" return isinstance(exc, _TRANSIENT_CONNECTION_ERRORS) @dataclass(frozen=True, slots=True) class StartupRetryOptions: """Common startup retry policy used by database-backed services.""" interval_seconds: float = 5.0 max_attempts: int = 0 def startup_retry_options_from_env(env: Mapping[str, str] | None = None) -> StartupRetryOptions: """Load the common startup retry policy from environment variables.""" source = os.environ if env is None else env try: interval_ms = int(source.get("DB_INIT_RETRY_INTERVAL_MS", "5000")) except (TypeError, ValueError): interval_ms = 5000 interval_ms = max(250, interval_ms) try: max_attempts = int(source.get("DB_INIT_RETRY_MAX_ATTEMPTS", "0")) except (TypeError, ValueError): max_attempts = 0 max_attempts = max(0, max_attempts) return StartupRetryOptions( interval_seconds=interval_ms / 1000, max_attempts=max_attempts, ) async def retry_startup( operation: Callable[[], Awaitable[Any]], options: StartupRetryOptions | None = None, ) -> Any: """Retry a startup operation on transient connection errors only. Any other exception is raised immediately, so a wrong password or a missing database does not spin until the process is stopped. """ policy = options or startup_retry_options_from_env() attempt = 0 while True: attempt += 1 try: return await operation() except asyncio.CancelledError: raise except Exception as exc: if not is_transient_connection_error(exc): raise if policy.max_attempts and attempt >= policy.max_attempts: raise _logger.warning( "database startup attempt %d failed: %s; retrying in %.3fs", attempt, exc, policy.interval_seconds, ) await asyncio.sleep(policy.interval_seconds) class Database: """Own one asyncpg pool and expose common lifecycle/query operations.""" def __init__(self, pool: asyncpg.Pool) -> None: self.pool = pool @classmethod async def connect(cls, config: DatabaseConfig | str) -> "Database": settings = config if isinstance(config, DatabaseConfig) else DatabaseConfig(dsn=config) async def connect_once() -> "Database": pool = await asyncpg.create_pool( dsn=settings.dsn, min_size=settings.min_size, max_size=settings.max_size, timeout=settings.timeout, command_timeout=settings.command_timeout, ) try: await pool.fetchval("SELECT 1") except Exception: await pool.close() raise return cls(pool) return await retry_startup(connect_once) async def ping(self) -> None: await self.pool.fetchval("SELECT 1") async def close(self) -> None: await self.pool.close() async def execute(self, query: str, *args: Any) -> str: return await self.pool.execute(query, *args) async def fetch(self, query: str, *args: Any) -> list[asyncpg.Record]: return await self.pool.fetch(query, *args) async def fetchrow(self, query: str, *args: Any) -> asyncpg.Record | None: return await self.pool.fetchrow(query, *args) async def fetchval(self, query: str, *args: Any) -> Any: return await self.pool.fetchval(query, *args) @asynccontextmanager async def transaction(self) -> AsyncIterator[asyncpg.Connection]: async with self.pool.acquire() as connection: async with connection.transaction(): yield connection async def with_transaction( self, callback: Callable[[asyncpg.Connection], Awaitable[Any]], ) -> Any: async with self.transaction() as connection: return await callback(connection)