fix: standardize startup database retries

This commit is contained in:
Gabriel20xx committed 2026-09-23 04:56:32 +02:00
1 parent c743ee7f5b
commit b85601ae32
5 files changed
+225 -24

No files matched your search

+101
View File
@@ -6,6 +6,7 @@ import (
"context"
"errors"
"fmt"
"log"
"strings"
"time"
@@ -28,6 +29,87 @@ type Config struct {
ConnectTimeout time.Duration
}
// StartupRetryOptions controls retries while a service is waiting for
// PostgreSQL to become reachable during startup.
type StartupRetryOptions struct {
Interval time.Duration
MaxAttempts int64
}
const (
defaultStartupRetryInterval = 5 * time.Second
defaultStartupRetryAttempts = 0 // 0 = retry indefinitely
minimumStartupRetryInterval = 250 * time.Millisecond
)
// StartupRetryOptionsFromEnv loads the common startup retry policy. The
// database has to be reachable before settings stored in it can be read, so
// these options intentionally come from the environment.
func StartupRetryOptionsFromEnv() StartupRetryOptions {
intervalMs := config.Int("DB_INIT_RETRY_INTERVAL_MS", int(defaultStartupRetryInterval/time.Millisecond))
if intervalMs < int(minimumStartupRetryInterval/time.Millisecond) {
intervalMs = int(minimumStartupRetryInterval / time.Millisecond)
}
maxAttempts := int64(config.Int("DB_INIT_RETRY_MAX_ATTEMPTS", defaultStartupRetryAttempts))
if maxAttempts < 0 {
maxAttempts = defaultStartupRetryAttempts
}
return StartupRetryOptions{
Interval: time.Duration(intervalMs) * time.Millisecond,
MaxAttempts: maxAttempts,
}
}
// RetryStartup reruns fn until it succeeds, the configured attempt limit is
// reached, or ctx is canceled.
func RetryStartup(ctx context.Context, fn func() error) error {
return RetryStartupWithOptions(ctx, StartupRetryOptionsFromEnv(), fn)
}
// RetryStartupWithOptions is the configurable form of RetryStartup, useful
// when a caller has already loaded the startup options.
func RetryStartupWithOptions(ctx context.Context, options StartupRetryOptions, fn func() error) error {
if fn == nil {
return errors.New("startup retry callback is nil")
}
if options.Interval < minimumStartupRetryInterval {
options.Interval = minimumStartupRetryInterval
}
if options.MaxAttempts < 0 {
options.MaxAttempts = defaultStartupRetryAttempts
}
var lastErr error
for attempt := int64(1); ; attempt++ {
if err := ctx.Err(); err != nil {
return err
}
if err := fn(); err == nil {
return nil
} else {
lastErr = err
}
if options.MaxAttempts > 0 && attempt >= options.MaxAttempts {
return lastErr
}
log.Printf("[postgres] startup attempt %d failed: %v; retrying in %s", attempt, lastErr, options.Interval)
timer := time.NewTimer(options.Interval)
select {
case <-ctx.Done():
if !timer.Stop() {
<-timer.C
}
return ctx.Err()
case <-timer.C:
}
}
}
// DefaultConfig returns sensible defaults for a small self-hosted service.
func DefaultConfig(url string) Config {
return Config{
@@ -111,6 +193,25 @@ func Open(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
return pool, nil
}
// OpenWithRetry opens and verifies a PostgreSQL pool using the common startup
// retry policy.
func OpenWithRetry(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
var pool *pgxpool.Pool
err := RetryStartup(ctx, func() error {
if pool != nil {
pool.Close()
pool = nil
}
var err error
pool, err = Open(ctx, cfg)
return err
})
if err != nil {
return nil, err
}
return pool, nil
}
// WithTx runs fn in a transaction and rolls back on all error paths.
func WithTx(ctx context.Context, pool *pgxpool.Pool, fn func(pgx.Tx) error) error {
if pool == nil {
+3
View File
@@ -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
+37 -9
View File
@@ -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 = []) {
+4 -1
View File
@@ -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")