2026-08-04 15:17:15 +02:00
|
|
|
import pg from 'pg';
|
|
|
|
|
import { databaseConfigFromEnv } from './config.js';
|
|
|
|
|
|
|
|
|
|
const { Pool } = pg;
|
|
|
|
|
|
2026-09-23 04:56:32 +02:00
|
|
|
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']);
|
2026-08-04 15:17:15 +02:00
|
|
|
const TRANSIENT_MESSAGE = /connection terminated|connection reset|econnreset|epipe|server closed the connection/i;
|
|
|
|
|
|
2026-09-23 04:56:32 +02:00
|
|
|
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 };
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-04 15:17:15 +02:00
|
|
|
export function isTransientConnectionError(error) {
|
|
|
|
|
return Boolean(
|
|
|
|
|
error &&
|
|
|
|
|
(TRANSIENT_CODES.has(error.code) || TRANSIENT_MESSAGE.test(String(error.message || '')))
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-19 21:14:31 +00:00
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-04 15:17:15 +02:00
|
|
|
/**
|
|
|
|
|
* 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 = {}) {
|
2026-10-19 21:14:31 +00:00
|
|
|
const { pool, log = console.error, ...poolOptions } = options;
|
2026-08-04 15:17:15 +02:00
|
|
|
this.pool = pool || new Pool(poolOptions);
|
|
|
|
|
this.ownsPool = !pool;
|
|
|
|
|
this.ready = false;
|
2026-10-19 21:14:31 +00:00
|
|
|
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}`);
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-08-04 15:17:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static fromEnv(env = process.env) {
|
|
|
|
|
return new Database(databaseConfigFromEnv(env));
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-23 04:56:32 +02:00
|
|
|
async connect(options = {}) {
|
2026-08-04 15:17:15 +02:00
|
|
|
if (this.ready) return this;
|
|
|
|
|
|
2026-09-23 04:56:32 +02:00
|
|
|
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;
|
2026-08-04 15:17:15 +02:00
|
|
|
try {
|
|
|
|
|
await this.pool.query('SELECT 1');
|
|
|
|
|
this.ready = true;
|
|
|
|
|
return this;
|
|
|
|
|
} catch (error) {
|
2026-09-23 04:56:32 +02:00
|
|
|
if (
|
|
|
|
|
(maxAttempts > 0 && attempt >= maxAttempts) ||
|
|
|
|
|
!isTransientConnectionError(error)
|
|
|
|
|
) {
|
|
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
await new Promise(resolve => setTimeout(resolve, retryIntervalMs));
|
2026-08-04 15:17:15 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-19 21:14:31 +00:00
|
|
|
/**
|
|
|
|
|
* 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 = {}) {
|
2026-08-04 15:17:15 +02:00
|
|
|
await this.connect();
|
|
|
|
|
try {
|
|
|
|
|
return await this.pool.query(text, values);
|
|
|
|
|
} catch (error) {
|
2026-10-19 21:14:31 +00:00
|
|
|
const retry = options.retry ?? isReadOnlyStatement(text);
|
|
|
|
|
if (!retry || !isTransientConnectionError(error)) throw error;
|
2026-08-04 15:17:15 +02:00
|
|
|
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);
|
|
|
|
|
}
|