import { Pool, type PoolConfig } from 'pg'; export interface QuestDbPgExecutorConfig { readonly url?: string; readonly host?: string; readonly port?: number; readonly database?: string; readonly user?: string; readonly password?: string; readonly ssl?: boolean; readonly max?: number; readonly connectionTimeoutMillis?: number; readonly idleTimeoutMillis?: number; } export interface QuestDbPgQueryExecutor { query( sql: string, params?: readonly unknown[] ): Promise<{ readonly rows: readonly Record[] }>; } export interface QuestDbPgExecutorHandle { readonly executor: QuestDbPgQueryExecutor; close(): Promise; } /** Minimal `pg.Pool` surface used by {@link openQuestDbPgExecutor}. */ export interface QuestDbPgPoolLike { on(event: 'error', listener: (err: Error) => void): unknown; query( sql: string, params?: unknown[] ): Promise<{ readonly rows: readonly unknown[] }>; end(): Promise; } export interface OpenQuestDbPgExecutorOptions { /** Optional pool factory override for unit tests; defaults to `new Pool(cfg)`. */ readonly createPool?: (poolConfig: PoolConfig) => QuestDbPgPoolLike; /** * Optional diagnostic callback invoked when an idle pool client emits `'error'`. * Always receives a credential-safe `Error`. */ readonly onPoolError?: (error: Error) => void; } const SAFE_ERROR_CODE_RE = /^[A-Z0-9_]{1,32}$/; function isQuestDbUrlTlsParamKey(rawKey: string): boolean { const key = rawKey.trim().toLowerCase(); return key === 'uselibpqcompat' || key === 'ssl' || key.startsWith('ssl'); } /** * Returns `true` when `rawUrl` contains any TLS/SSL query parameter * (`ssl`, `sslmode`, `sslcert`, `sslkey`, `sslrootcert`, `uselibpqcompat`, or * any other `ssl*` parameter). * * TLS settings must have a single source of truth: either configure TLS in the * URL query string (omitting the explicit `ssl` flag) or pass the explicit * `ssl` flag with a URL that contains no TLS query parameters. */ export function hasQuestDbUrlTlsOptions(rawUrl: string): boolean { let parsed: URL; try { parsed = new URL(rawUrl); } catch { try { parsed = new URL(rawUrl, 'postgres://base'); } catch { return false; } } for (const [rawKey] of parsed.searchParams.entries()) { if (isQuestDbUrlTlsParamKey(rawKey)) { return true; } } return false; } /** * Returns `true` when an explicit boolean `ssl` setting is combined with any * TLS/SSL query parameter embedded in `rawUrl`. */ export function hasConflictingQuestDbUrlSsl(rawUrl: string, _explicitSsl?: boolean): boolean { return hasQuestDbUrlTlsOptions(rawUrl); } /** * Throws a credential-free `RangeError` if an explicit `ssl` option is combined * with any TLS/SSL query parameter in `rawUrl`. */ export function assertNoConflictingQuestDbSsl(rawUrl: string, _explicitSsl?: boolean): void { if (hasQuestDbUrlTlsOptions(rawUrl)) { throw new RangeError( 'Conflicting QuestDB TLS/SSL configuration: cannot combine an explicit "ssl" option with TLS/SSL query parameters in the QuestDB URL. Configure TLS in either the URL or the explicit "ssl" option, not both.' ); } } function addRawAndDecodedNeedle(needles: Set, raw: string): void { if (raw.length === 0) { return; } needles.add(raw); try { const decoded = decodeURIComponent(raw); if (decoded.length > 0) { needles.add(decoded); } } catch { // Malformed percent-encoding: raw needle is already registered. } } function collectConfigSecretNeedles(config: QuestDbPgExecutorConfig): readonly string[] { const needles = new Set(); if (typeof config.password === 'string' && config.password.length > 0) { addRawAndDecodedNeedle(needles, config.password); } if (typeof config.url === 'string' && config.url.length > 0) { needles.add(config.url); try { const parsed = new URL(config.url); if (parsed.href.length > 0) { needles.add(parsed.href); } addRawAndDecodedNeedle(needles, parsed.password); for (const [key, value] of parsed.searchParams.entries()) { if (key.toLowerCase() === 'password' && value.length > 0) { addRawAndDecodedNeedle(needles, value); } } } catch { // Non-URL string: raw string is already covered. } } return Array.from(needles); } function sanitizePoolError(err: unknown, needles: readonly string[]): Error { const rawCode = typeof err === 'object' && err !== null && 'code' in err ? (err as { readonly code?: unknown }).code : undefined; const safeCode = typeof rawCode === 'string' && SAFE_ERROR_CODE_RE.test(rawCode) ? rawCode : undefined; if (err instanceof Error) { const messageHasSecret = needles.some(needle => err.message.includes(needle)); const stackHasSecret = typeof err.stack === 'string' && needles.some(needle => err.stack?.includes(needle) === true); if (!messageHasSecret && !stackHasSecret) { return err; } } const message = safeCode !== undefined ? `QuestDB PGWire idle pool client error (${safeCode}; details redacted).` : 'QuestDB PGWire idle pool client error (details redacted).'; const sanitized = new Error(message); if (safeCode !== undefined) { (sanitized as Error & { code?: string }).code = safeCode; } return sanitized; } /** * Opens a lightweight PGWire `pg.Pool` executor for QuestDB read queries or * opt-in DDL without creating legacy tables or starting background health timers. */ export async function openQuestDbPgExecutor( config: QuestDbPgExecutorConfig, options?: OpenQuestDbPgExecutorOptions ): Promise { if (config.url !== undefined && config.ssl !== undefined) { assertNoConflictingQuestDbSsl(config.url, config.ssl); } const poolConfig: PoolConfig = { max: config.max ?? 4, connectionTimeoutMillis: config.connectionTimeoutMillis ?? 5_000, idleTimeoutMillis: config.idleTimeoutMillis ?? 30_000, ...(config.url !== undefined ? { connectionString: config.url } : { host: config.host ?? 'localhost', port: config.port ?? 8812, database: config.database ?? 'qdb', ...(config.user !== undefined ? { user: config.user } : {}), ...(config.password !== undefined ? { password: config.password } : {}), }), ...(config.ssl !== undefined ? { ssl: config.ssl } : {}), }; const secretNeedles = collectConfigSecretNeedles(config); const createPool = options?.createPool ?? ((cfg: PoolConfig) => new Pool(cfg)); const pool = createPool(poolConfig); // Register an idle-client error listener before the startup probe so backend // restarts or network disconnects on idle connections cannot crash the host // with an unhandled EventEmitter 'error' event; pg-pool automatically drops // the failed idle client and opens a fresh connection on the next query. pool.on('error', (err: Error) => { if (options?.onPoolError !== undefined) { const safeError = sanitizePoolError(err, secretNeedles); try { options.onPoolError(safeError); } catch { // Never allow diagnostic callbacks to re-throw from an EventEmitter error handler. } } }); try { await pool.query('SELECT 1'); } catch (err: unknown) { await pool.end().catch(() => undefined); throw err; } let closePromise: Promise | null = null; const close = (): Promise => { if (closePromise === null) { closePromise = pool.end(); } return closePromise; }; const executor: QuestDbPgQueryExecutor = { async query(sql: string, params?: readonly unknown[]) { const result = params !== undefined && params.length > 0 ? await pool.query(sql, [...params]) : await pool.query(sql); return { rows: result.rows as readonly Record[], }; }, }; return { executor, close }; }