import { WorkflowWorldError } from '@workflow/errors'; /** * SQLSTATE codes outside class `08` (connection exception) that mean the * server ended or refused the connection, not the statement: `57P01` * admin_shutdown, `57P02` crash_shutdown, `57P03` cannot_connect_now (a server * starting up or a standby being promoted during a failover). */ const CONNECTION_SQLSTATES = new Set(['57P01', '57P02', '57P03']); /** Socket and DNS errors a connection to the server fails with. */ const SOCKET_ERROR_CODES = new Set([ 'ECONNRESET', 'ECONNREFUSED', 'ECONNABORTED', 'EPIPE', 'ETIMEDOUT', 'EHOSTUNREACH', 'ENETUNREACH', 'EAI_AGAIN', ]); /** * Messages `pg` and pg-pool throw, without a code, for a connection that * ended or never opened. A client the World itself closed ("Client was closed * and is not queryable") is not among them: that is a shutdown, not a lost * connection. */ const CONNECTION_LOST_MESSAGES = [ 'Connection terminated', 'Client has encountered a connection error and is not queryable', 'timeout exceeded when trying to connect', ]; /** Drizzle wraps a driver error in one of its own, so causes are followed. */ const MAX_CAUSE_DEPTH = 5; /** * The error in `error`'s cause chain that says the connection to PostgreSQL * was lost or could not be opened, or `undefined` when none does. Contention * the World retries itself (serialization failures, deadlocks) and every * statement error are not connection loss. */ export function connectionLossOf( error: unknown ): { message: string; code?: string } | undefined { let current: unknown = error; for (let depth = 0; depth < MAX_CAUSE_DEPTH; depth++) { if (typeof current !== 'object' || current === null) return undefined; const { code, message } = current as { code?: unknown; message?: unknown }; const text = typeof message === 'string' ? message : ''; if (typeof code === 'string') { if ( (code.length === 5 && code.startsWith('08')) || CONNECTION_SQLSTATES.has(code) || SOCKET_ERROR_CODES.has(code) ) { return { message: text, code }; } } if (CONNECTION_LOST_MESSAGES.some((lost) => text.startsWith(lost))) { return { message: text }; } current = (current as { cause?: unknown }).cause; } return undefined; } /** * `error` as a retryable World error (`code: 'TRANSPORT'`) when it is a lost * connection ({@link connectionLossOf}), otherwise `error` itself. * * The runtime treats a transport error as transient: a delivery that hits one * is retried rather than failing its run. A write cut off this way has an * outcome nobody knows, which the in-band fence keeps safe even when the * connection dropped after the server ran the COMMIT: that attempt moved the * run's in-band count, so a later write sent with the old count is refused as * superseded. * * The mapped error names only the driver's message and code. The original is * not kept as its cause: a pg-pool error carries the client and its connection * parameters, the password included, and a Drizzle error's message holds the * statement and its parameters. */ export function asTransportError(error: unknown): unknown { if (WorkflowWorldError.is(error)) return error; const lost = connectionLossOf(error); if (!lost) return error; return new WorkflowWorldError( `PostgreSQL connection lost${lost.code ? ` (${lost.code})` : ''}: ${lost.message}`, { code: 'TRANSPORT' } ); } /** * `target` with every method's lost-connection failure rethrown as a * transport error ({@link asTransportError}), whether the method rejects or * throws. A method that returns no promise (`events.subscribe`) keeps * returning its value as it is. */ export function withTransportErrors(target: T): T { const wrapped: Record = {}; for (const [key, value] of Object.entries(target)) { if (typeof value !== 'function') { wrapped[key] = value; continue; } wrapped[key] = function (this: unknown, ...args: unknown[]) { let result: unknown; try { result = value.apply(target, args); } catch (error) { throw asTransportError(error); } if ( result !== null && typeof result === 'object' && typeof (result as { then?: unknown }).then === 'function' ) { return (result as Promise).catch((error: unknown) => { throw asTransportError(error); }); } return result; }; } return wrapped as T; }