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
@@ -17,6 +17,9 @@ legacy package as a compatibility layer until every consumer has moved.
|
||||
Pass a service-specific `tableName` to `runMigrations` when multiple services
|
||||
share one PostgreSQL database, so their migration histories cannot collide.
|
||||
|
||||
Database startup uses `DB_INIT_RETRY_INTERVAL_MS` (default `5000`, minimum
|
||||
`250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely).
|
||||
|
||||
Run `npm test` from this package or `npm run test --workspace=@gabriel20xx/node-backend` from `shared`.
|
||||
|
||||
## `authclient`/`coreconfig`: adopting AuthGuard instead of local auth
|
||||
|
||||
@@ -3,9 +3,28 @@ import { databaseConfigFromEnv } from './config.js';
|
||||
|
||||
const { Pool } = pg;
|
||||
|
||||
const TRANSIENT_CODES = new Set(['ECONNRESET', 'EPIPE', '57P01', '08006', '08003']);
|
||||
const DEFAULT_STARTUP_RETRY_INTERVAL_MS = 5000;
|
||||
const DEFAULT_STARTUP_RETRY_MAX_ATTEMPTS = 0;
|
||||
const TRANSIENT_CODES = new Set(['ECONNREFUSED', 'ECONNRESET', 'EPIPE', '57P01', '08006', '08003']);
|
||||
const TRANSIENT_MESSAGE = /connection terminated|connection reset|econnreset|epipe|server closed the connection/i;
|
||||
|
||||
function nonNegativeInteger(value, fallback) {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isFinite(parsed) ? Math.max(0, parsed) : fallback;
|
||||
}
|
||||
|
||||
export function startupRetryOptionsFromEnv(env = process.env) {
|
||||
const intervalMs = Math.max(
|
||||
250,
|
||||
nonNegativeInteger(env.DB_INIT_RETRY_INTERVAL_MS, DEFAULT_STARTUP_RETRY_INTERVAL_MS)
|
||||
);
|
||||
const maxAttempts = nonNegativeInteger(
|
||||
env.DB_INIT_RETRY_MAX_ATTEMPTS,
|
||||
DEFAULT_STARTUP_RETRY_MAX_ATTEMPTS
|
||||
);
|
||||
return { intervalMs, maxAttempts };
|
||||
}
|
||||
|
||||
export function isTransientConnectionError(error) {
|
||||
return Boolean(
|
||||
error &&
|
||||
@@ -30,23 +49,32 @@ export class Database {
|
||||
return new Database(databaseConfigFromEnv(env));
|
||||
}
|
||||
|
||||
async connect({ retries = 10, retryDelayMs = 2000 } = {}) {
|
||||
async connect(options = {}) {
|
||||
if (this.ready) return this;
|
||||
|
||||
let lastError;
|
||||
for (let attempt = 1; attempt <= Math.max(1, retries); attempt += 1) {
|
||||
const defaults = startupRetryOptionsFromEnv();
|
||||
const maxAttempts = options.maxAttempts ?? options.retries ?? defaults.maxAttempts;
|
||||
const retryIntervalMs = Math.max(
|
||||
250,
|
||||
options.retryIntervalMs ?? options.retryDelayMs ?? defaults.intervalMs
|
||||
);
|
||||
let attempt = 0;
|
||||
while (true) {
|
||||
attempt += 1;
|
||||
try {
|
||||
await this.pool.query('SELECT 1');
|
||||
this.ready = true;
|
||||
return this;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (attempt >= retries || !isTransientConnectionError(error)) throw error;
|
||||
const delay = Math.min(Math.max(100, retryDelayMs) * 2 ** (attempt - 1), 30000);
|
||||
await new Promise(resolve => setTimeout(resolve, delay));
|
||||
if (
|
||||
(maxAttempts > 0 && attempt >= maxAttempts) ||
|
||||
!isTransientConnectionError(error)
|
||||
) {
|
||||
throw error;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, retryIntervalMs));
|
||||
}
|
||||
}
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
async query(text, values = []) {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
Shared Python backend infrastructure for services using `asyncpg`:
|
||||
|
||||
- validated `DATABASE_URL` and pool settings;
|
||||
- one async pool owner with ping and graceful shutdown;
|
||||
- one async pool owner with startup retry, ping, and graceful shutdown;
|
||||
- bcrypt password and secure session-token helpers;
|
||||
- short-lived, one-time admin reset codes printed to the server console;
|
||||
- common account/session persistence for the single-admin or optional multi-user model;
|
||||
@@ -19,6 +19,9 @@ install during development:
|
||||
pip install "git+https://repos.gfranz.ch/Gabriel20xx/shared@v0.1.0#subdirectory=packages/python-backend"
|
||||
```
|
||||
|
||||
Database startup uses `DB_INIT_RETRY_INTERVAL_MS` (default `5000`, minimum
|
||||
`250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely).
|
||||
|
||||
## `authclient`: adopting AuthGuard instead of local auth
|
||||
|
||||
`shared_backend.authclient` is how a service trades its own local user table
|
||||
|
||||
@@ -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