From d9e2d64535a22fc54a8c307c12e356f295d71b09 Mon Sep 17 00:00:00 2001 From: Gabriel20xx Date: Wed, 23 Sep 2026 04:56:42 +0200 Subject: [PATCH] fix: standardize startup database retries --- backend/server.go | 25 +---- shared/backend/postgres/postgres.go | 101 ++++++++++++++++++ shared/packages/node-backend/README.md | 3 + shared/packages/node-backend/src/db.js | 46 ++++++-- shared/packages/python-backend/README.md | 5 +- .../src/shared_backend/postgres.py | 94 +++++++++++++--- 6 files changed, 230 insertions(+), 44 deletions(-) diff --git a/backend/server.go b/backend/server.go index 1da4823..24f6187 100644 --- a/backend/server.go +++ b/backend/server.go @@ -19,6 +19,7 @@ import ( sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" "repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient" "repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig" + sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres" ) // The SvelteKit build is copied here by the Docker builder before go build. @@ -132,11 +133,7 @@ func main() { } func connectWithRetry(ctx context.Context, connectionString string) (*DB, error) { - interval := time.Duration(envInt64("DB_INIT_RETRY_INTERVAL_MS", 5000)) * time.Millisecond - if interval < 250*time.Millisecond { - interval = 250 * time.Millisecond - } - maxAttempts := envInt64("DB_INIT_RETRY_MAX_ATTEMPTS", 0) + retryOptions := sharedpostgres.StartupRetryOptionsFromEnv() for attempt := int64(1); ; attempt++ { database, err := connectDB(ctx, connectionString) @@ -153,14 +150,14 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error) } fmt.Fprintf(os.Stderr, "[DB] Initialization attempt %d failed: %v\n", attempt, err) - if maxAttempts > 0 && attempt >= maxAttempts { + if retryOptions.MaxAttempts > 0 && attempt >= retryOptions.MaxAttempts { return nil, err } - fmt.Printf("[DB] Retrying in %s...\n", interval) + fmt.Printf("[DB] Retrying in %s...\n", retryOptions.Interval) select { case <-ctx.Done(): return nil, ctx.Err() - case <-time.After(interval): + case <-time.After(retryOptions.Interval): } } } @@ -254,18 +251,6 @@ func envOrDefault(name, fallback string) string { return fallback } -func envInt64(name string, fallback int64) int64 { - value := strings.TrimSpace(os.Getenv(name)) - if value == "" { - return fallback - } - var parsed int64 - if _, err := fmt.Sscan(value, &parsed); err != nil { - return fallback - } - return parsed -} - func decodeJSON(r *http.Request, target any) error { decoder := json.NewDecoder(io.LimitReader(r.Body, 50*1024*1024)) if err := decoder.Decode(target); err != nil { diff --git a/shared/backend/postgres/postgres.go b/shared/backend/postgres/postgres.go index 6d0c379..2b56119 100644 --- a/shared/backend/postgres/postgres.go +++ b/shared/backend/postgres/postgres.go @@ -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 { diff --git a/shared/packages/node-backend/README.md b/shared/packages/node-backend/README.md index 5fc10ba..16002c8 100644 --- a/shared/packages/node-backend/README.md +++ b/shared/packages/node-backend/README.md @@ -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 diff --git a/shared/packages/node-backend/src/db.js b/shared/packages/node-backend/src/db.js index 405dc4c..c5824a4 100644 --- a/shared/packages/node-backend/src/db.js +++ b/shared/packages/node-backend/src/db.js @@ -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 = []) { diff --git a/shared/packages/python-backend/README.md b/shared/packages/python-backend/README.md index ec366fc..349430f 100644 --- a/shared/packages/python-backend/README.md +++ b/shared/packages/python-backend/README.md @@ -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 diff --git a/shared/packages/python-backend/src/shared_backend/postgres.py b/shared/packages/python-backend/src/shared_backend/postgres.py index ca39551..5764358 100644 --- a/shared/packages/python-backend/src/shared_backend/postgres.py +++ b/shared/packages/python-backend/src/shared_backend/postgres.py @@ -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")