import pg from 'pg'; import { databaseConfigFromEnv } from './config.js'; const { Pool } = pg; 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 && (TRANSIENT_CODES.has(error.code) || TRANSIENT_MESSAGE.test(String(error.message || ''))) ); } const READ_ONLY_STATEMENT = /^\s*select\b/i; const LOCKING_OR_WRITING_READ = /\bfor\s+(update|share|no\s+key\s+update|key\s+share)\b|\binto\b|\b(nextval|setval)\s*\(/i; /** * True for a plain SELECT that cannot change data or sequences. Only these * statements are retried after a transient error by default. */ export function isReadOnlyStatement(text) { const sql = String(text); return READ_ONLY_STATEMENT.test(sql) && !LOCKING_OR_WRITING_READ.test(sql); } /** * Owns one pg pool and exposes bounded startup, retry, transaction, and * shutdown behavior. Domain repositories should depend on this abstraction * instead of creating independent pools. */ export class Database { constructor(options = {}) { const { pool, log = console.error, ...poolOptions } = options; this.pool = pool || new Pool(poolOptions); this.ownsPool = !pool; this.ready = false; this.log = log; if (typeof this.pool.on === 'function') { // pg emits 'error' for an idle client that fails, for example after a // database restart. With no listener the event is thrown and can end the process. this.pool.on('error', error => { this.log(`[database] idle pool client error: ${error?.message || error}`); }); } } static fromEnv(env = process.env) { return new Database(databaseConfigFromEnv(env)); } async connect(options = {}) { if (this.ready) return this; 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) { if ( (maxAttempts > 0 && attempt >= maxAttempts) || !isTransientConnectionError(error) ) { throw error; } await new Promise(resolve => setTimeout(resolve, retryIntervalMs)); } } } /** * Runs one statement. After a transient connection error the statement is * retried only when it is read-only, so a write that committed before the * connection dropped is not applied twice. Pass `{ retry: true }` to opt a * known-idempotent statement in, or `{ retry: false }` to opt a read out. */ async query(text, values = [], options = {}) { await this.connect(); try { return await this.pool.query(text, values); } catch (error) { const retry = options.retry ?? isReadOnlyStatement(text); if (!retry || !isTransientConnectionError(error)) throw error; return this.pool.query(text, values); } } async transaction(callback) { if (typeof callback !== 'function') throw new TypeError('transaction callback is required'); await this.connect(); const client = await this.pool.connect(); try { await client.query('BEGIN'); const result = await callback(client); await client.query('COMMIT'); return result; } catch (error) { try { await client.query('ROLLBACK'); } catch { // Preserve the original application error. } throw error; } finally { client.release(); } } async close() { if (!this.pool || !this.ownsPool) return; await this.pool.end(); this.ready = false; } } export function createDatabaseFromEnv(env = process.env) { return Database.fromEnv(env); }