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
@@ -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 = []) {
|
||||
|
||||
Reference in new issue
Block a user