fix: standardize startup database retries
This commit is contained in:
1 parent
668e9dd310
commit
d9e2d64535
6 files changed
+230
-44
No files matched your search
@@ -2,13 +2,75 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any, AsyncIterator, Awaitable, Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, AsyncIterator, Awaitable, Callable, Mapping
|
||||
|
||||
import asyncpg
|
||||
|
||||
from .config import DatabaseConfig
|
||||
|
||||
_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)
|
||||
|
||||
|
||||
class Database:
|
||||
"""Own one asyncpg pool and expose common lifecycle/query operations."""
|
||||
@@ -19,19 +81,23 @@ class Database:
|
||||
@classmethod
|
||||
async def connect(cls, config: DatabaseConfig | str) -> "Database":
|
||||
settings = config if isinstance(config, DatabaseConfig) else DatabaseConfig(dsn=config)
|
||||
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)
|
||||
|
||||
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")
|
||||
|
||||
Reference in new issue
Block a user