2026-08-04 15:17:15 +02:00
|
|
|
"""Shared asyncpg pool and transaction wrapper."""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
2026-09-23 04:56:32 +02:00
|
|
|
import asyncio
|
|
|
|
|
import logging
|
|
|
|
|
import os
|
2026-08-04 15:17:15 +02:00
|
|
|
from contextlib import asynccontextmanager
|
2026-09-23 04:56:32 +02:00
|
|
|
from dataclasses import dataclass
|
|
|
|
|
from typing import Any, AsyncIterator, Awaitable, Callable, Mapping
|
2026-08-04 15:17:15 +02:00
|
|
|
|
|
|
|
|
import asyncpg
|
|
|
|
|
|
|
|
|
|
from .config import DatabaseConfig
|
|
|
|
|
|
2026-09-23 04:56:32 +02:00
|
|
|
_logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@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 until it succeeds or the context is cancelled."""
|
|
|
|
|
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 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)
|
|
|
|
|
|
2026-08-04 15:17:15 +02:00
|
|
|
|
|
|
|
|
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)
|
2026-09-23 04:56:32 +02:00
|
|
|
|
|
|
|
|
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)
|
2026-08-04 15:17:15 +02:00
|
|
|
|
|
|
|
|
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)
|