T-200: M2.1t (retry of T-197) — Land the PostgreSQL executor factory for the MCP copilot stdio host: openResearchCopilotExecutor(config) in libs/data/postgres/src/research-copilot-executor.ts, reusing the finished T-197 branch work and completing QA sign-off (no new deps, no DuckDB, no bin, no curate-etl changes)

This commit is contained in:
Studio 2026-12-03 14:50:36 -05:00
parent 436616b343
commit 7bf9bb6c20
7 changed files with 1635 additions and 1 deletions

View file

@ -1,6 +1,21 @@
export { PostgreSQLClient } from './client';
export { PostgreSQLTransactionManager } from './transactions';
export { runPostgresMigrations, type MigrationTrack } from './migrations';
export {
RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS,
RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS,
RESEARCH_COPILOT_PG_POOL_MAX,
RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS,
RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS,
ResearchCopilotExecutorError,
openResearchCopilotExecutor,
type ManagedResearchCopilotExecutor,
type OpenResearchCopilotExecutorOptions,
type ResearchCopilotExecutor,
type ResearchCopilotExecutorConfig,
type ResearchCopilotExecutorErrorCode,
type ResearchCopilotPoolLike,
} from './research-copilot-executor';
export type {
ConnectionEvents,
PoolMetrics,

View file

@ -0,0 +1,584 @@
/**
* Managed PostgreSQL executor factory for the MCP research copilot stdio host
* (`runResearchCopilotStdioHost` in `@stock-bot/research/mcp`).
*
* - Fail-closed configuration validation before any `pg.Pool` is constructed.
* - Normalizes connection parameters and `options`/`PGOPTIONS` so every pool
* connection enforces bounded pool size (`max = 4`) and timeouts (5 s connect,
* 10 s statement, 15 s query, 2 s lock) while preserving `search_path`.
* - Runs one startup probe (`SELECT 1`), closes the pool on connect failure,
* attaches an idle-client error listener, provides idempotent shutdown, and
* never exposes credentials or raw DSNs in error messages or causes.
*/
import { Pool, type PoolConfig } from 'pg';
/** Maximum concurrent PostgreSQL connections opened by the research copilot executor. */
export const RESEARCH_COPILOT_PG_POOL_MAX = 4;
/** TCP/startup connection timeout in milliseconds (5 seconds). */
export const RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS = 5_000;
/** PostgreSQL server-side `statement_timeout` in milliseconds (10 seconds). */
export const RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS = 10_000;
/** Client-side `pg` `query_timeout` in milliseconds (15 seconds). */
export const RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS = 15_000;
/** PostgreSQL server-side `lock_timeout` in milliseconds (2 seconds). */
export const RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS = 2_000;
const POSTGRES_URL_PREFIX_RE = /^postgres(?:ql)?:\/\//i;
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
const SQLSTATE_RE = /^[0-9A-Z]{5}$/;
function hasControlChar(value: string): boolean {
for (let i = 0; i < value.length; i += 1) {
const code = value.charCodeAt(i);
if (code <= 0x1f || code === 0x7f) {
return true;
}
}
return false;
}
const OVERRIDDEN_QUERY_PARAMS = new Set([
'options',
'statement_timeout',
'lock_timeout',
'query_timeout',
'connectiontimeoutmillis',
'connect_timeout',
'max',
'min',
'idletimeoutmillis',
]);
/** Error codes thrown by {@link ResearchCopilotExecutorError}. */
export type ResearchCopilotExecutorErrorCode =
| 'INVALID_CONFIG'
| 'CONNECT_FAILED'
| 'EXECUTOR_CLOSED'
| 'CLOSE_FAILED'
| 'QUERY_FAILED'
| 'POOL_ERROR';
/**
* Credential-safe error thrown by {@link openResearchCopilotExecutor} and its
* managed executor handle. Never embeds raw DSNs, passwords, or raw driver causes.
*/
export class ResearchCopilotExecutorError extends Error {
readonly code: ResearchCopilotExecutorErrorCode;
constructor(code: ResearchCopilotExecutorErrorCode, message: string) {
super(message);
this.name = 'ResearchCopilotExecutorError';
this.code = code;
Object.setPrototypeOf(this, new.target.prototype);
}
}
/**
* Minimal structural configuration accepted by {@link openResearchCopilotExecutor}.
* Compatible with `ResearchCopilotHostConfig` from `@stock-bot/research/mcp`.
*/
export interface ResearchCopilotExecutorConfig {
readonly postgresUrl: string;
readonly postgresSchema?: string;
}
/**
* Structural query executor compatible with `PostgresResearchCopilotExecutor`
* from `@stock-bot/research/mcp`.
*/
export interface ResearchCopilotExecutor {
query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }>;
}
/**
* Managed executor handle compatible with `ManagedPostgresExecutor` from
* `@stock-bot/research/mcp`.
*/
export interface ManagedResearchCopilotExecutor {
readonly executor: ResearchCopilotExecutor;
close(): Promise<void>;
}
/**
* Minimal structural subset of `pg.Pool` required by {@link openResearchCopilotExecutor},
* allowing deterministic pool injection in unit tests while accepting real `pg.Pool`.
*/
export interface ResearchCopilotPoolLike {
query(
text: string,
values?: unknown[]
): Promise<{ readonly rows: readonly unknown[] }>;
end(): Promise<void>;
on(event: 'error', listener: (error: Error) => void): unknown;
}
/** Optional dependency injection and environment hooks for {@link openResearchCopilotExecutor}. */
export interface OpenResearchCopilotExecutorOptions {
readonly createPool?: (poolConfig: PoolConfig) => ResearchCopilotPoolLike;
readonly onPoolError?: (error: Error) => void;
readonly env?: Readonly<Record<string, string | undefined>>;
}
interface NormalizedPoolSetup {
readonly poolConfig: PoolConfig;
readonly secretNeedles: readonly string[];
}
function addRawAndDecodedNeedle(needles: Set<string>, 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 collectSecretNeedles(rawUrl: string, parsed: URL): readonly string[] {
const needles = new Set<string>();
if (rawUrl.length > 0) {
needles.add(rawUrl);
}
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) {
needles.add(value);
}
}
if (parsed.search.length > 1) {
const pairs = parsed.search.slice(1).split('&');
for (let i = 0; i < pairs.length; i += 1) {
const pair = pairs[i] as string;
const eqIdx = pair.indexOf('=');
if (eqIdx <= 0) {
continue;
}
const rawKey = pair.slice(0, eqIdx);
let decodedKey = rawKey;
try {
decodedKey = decodeURIComponent(rawKey);
} catch {
// Keep rawKey if percent-decoding fails.
}
if (decodedKey.toLowerCase() === 'password') {
addRawAndDecodedNeedle(needles, pair.slice(eqIdx + 1));
}
}
}
return Array.from(needles);
}
function containsAnyNeedle(text: string, needles: readonly string[]): boolean {
for (let i = 0; i < needles.length; i += 1) {
if (text.includes(needles[i] as string)) {
return true;
}
}
return false;
}
function isErrorSafeToSurface(
error: unknown,
needles: readonly string[],
visited: Set<unknown> = new Set(),
depth = 0
): error is Error {
if (!(error instanceof Error) || depth > 8) {
return false;
}
if (visited.has(error)) {
return true;
}
visited.add(error);
try {
if (typeof error.message !== 'string' || containsAnyNeedle(error.message, needles)) {
return false;
}
if (typeof error.stack === 'string' && containsAnyNeedle(error.stack, needles)) {
return false;
}
const record = error as unknown as Record<string, unknown>;
for (const field of ['detail', 'hint', 'where', 'internalQuery', 'routine']) {
const value = record[field];
if (typeof value === 'string' && containsAnyNeedle(value, needles)) {
return false;
}
}
if (record.cause !== undefined && !isErrorSafeToSurface(record.cause, needles, visited, depth + 1)) {
return false;
}
if (error instanceof AggregateError || 'errors' in error) {
const nested = record.errors;
if (nested !== undefined) {
if (!Array.isArray(nested)) {
return false;
}
for (let i = 0; i < nested.length; i += 1) {
if (!isErrorSafeToSurface(nested[i], needles, visited, depth + 1)) {
return false;
}
}
}
}
return true;
} catch {
return false;
}
}
function extractSqlState(error: unknown): string | undefined {
if (typeof error !== 'object' || error === null) {
return undefined;
}
const code = (error as { readonly code?: unknown }).code;
if (typeof code === 'string' && SQLSTATE_RE.test(code)) {
return code;
}
return undefined;
}
function parsePostgresUrlStrict(raw: string): { readonly url: URL; readonly usedDummyHost: boolean } {
if (raw.length === 0 || raw !== raw.trim()) {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: expected a non-empty postgres:// or postgresql:// URL without surrounding whitespace.'
);
}
if (hasControlChar(raw)) {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: URL must not contain control characters.'
);
}
if (!POSTGRES_URL_PREFIX_RE.test(raw)) {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: URL must start with postgres:// or postgresql://.'
);
}
let usedDummyHost = false;
let parsed: URL;
try {
parsed = new URL(raw);
} catch {
// Support libpq Unix socket URLs with userinfo and empty authority host,
// e.g. postgres://user:pass@/research_db?host=/tmp
if (raw.includes('@/')) {
try {
parsed = new URL(raw.replace('@/', '@___DUMMY_HOST___/'));
usedDummyHost = true;
} catch {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: expected a valid postgres:// or postgresql:// URL.'
);
}
} else {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: expected a valid postgres:// or postgresql:// URL.'
);
}
}
if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: URL must use the postgres:// or postgresql:// scheme.'
);
}
return { url: parsed, usedDummyHost };
}
function normalizePgOptions(
urlOptions: readonly string[],
envPgOptions: string | undefined
): string {
const parts: string[] = [];
if (typeof envPgOptions === 'string') {
const trimmed = envPgOptions.trim();
if (trimmed.length > 0) {
if (hasControlChar(trimmed)) {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: PGOPTIONS must not contain control characters.'
);
}
parts.push(trimmed);
}
}
for (let i = 0; i < urlOptions.length; i += 1) {
const trimmed = (urlOptions[i] as string).trim();
if (trimmed.length > 0) {
if (hasControlChar(trimmed)) {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: URL options parameter must not contain control characters.'
);
}
parts.push(trimmed);
}
}
parts.push(
`-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS}`,
`-c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`
);
return parts.join(' ');
}
function parseAndNormalizePoolConfig(
config: ResearchCopilotExecutorConfig,
env: Readonly<Record<string, string | undefined>>
): NormalizedPoolSetup {
if (typeof config !== 'object' || config === null) {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: expected a configuration object.'
);
}
if (typeof config.postgresUrl !== 'string') {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: postgresUrl must be a non-empty string.'
);
}
if (config.postgresSchema !== undefined) {
if (typeof config.postgresSchema !== 'string' || !SCHEMA_IDENT_RE.test(config.postgresSchema)) {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: postgresSchema must match ^[a-z_][a-z0-9_]*$.'
);
}
}
const { url: parsed, usedDummyHost } = parsePostgresUrlStrict(config.postgresUrl);
try {
if (parsed.username.length > 0) {
decodeURIComponent(parsed.username);
}
if (parsed.password.length > 0) {
decodeURIComponent(parsed.password);
}
if (!usedDummyHost && parsed.hostname.length > 0) {
decodeURIComponent(parsed.hostname);
}
} catch {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: URL contains invalid percent-encoding.'
);
}
if (parsed.port.length > 0) {
const portNum = Number(parsed.port);
if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: URL port must be an integer between 1 and 65535.'
);
}
}
const queryHost = parsed.searchParams.get('host')?.trim() ?? '';
const queryHostAddr = parsed.searchParams.get('hostaddr')?.trim() ?? '';
const effectiveHostname = usedDummyHost ? '' : parsed.hostname.trim();
if (effectiveHostname.length === 0 && queryHost.length === 0 && queryHostAddr.length === 0) {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: URL must specify a host or Unix socket host parameter.'
);
}
let decodedDatabase = '';
try {
decodedDatabase =
parsed.pathname.length > 1 ? decodeURIComponent(parsed.pathname.slice(1)).trim() : '';
} catch {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: URL database name contains invalid percent-encoding.'
);
}
const queryDbName = parsed.searchParams.get('dbname')?.trim() ?? '';
if (decodedDatabase.length === 0 && queryDbName.length === 0) {
throw new ResearchCopilotExecutorError(
'INVALID_CONFIG',
'Invalid PostgreSQL configuration: URL must specify a non-empty database name.'
);
}
const secretNeedles = collectSecretNeedles(config.postgresUrl, parsed);
const urlOptions: string[] = [];
const keysToDelete: string[] = [];
for (const [key, value] of parsed.searchParams.entries()) {
const lower = key.toLowerCase();
if (lower === 'options') {
urlOptions.push(value);
keysToDelete.push(key);
} else if (OVERRIDDEN_QUERY_PARAMS.has(lower)) {
keysToDelete.push(key);
}
}
for (let i = 0; i < keysToDelete.length; i += 1) {
parsed.searchParams.delete(keysToDelete[i] as string);
}
const normalizedOptions = normalizePgOptions(urlOptions, env.PGOPTIONS);
let normalizedConnectionString = parsed.toString();
if (usedDummyHost) {
normalizedConnectionString = normalizedConnectionString.replace('@___dummy_host___/', '@/');
normalizedConnectionString = normalizedConnectionString.replace('@___DUMMY_HOST___/', '@/');
}
const poolConfig: PoolConfig = {
connectionString: normalizedConnectionString,
options: normalizedOptions,
max: RESEARCH_COPILOT_PG_POOL_MAX,
connectionTimeoutMillis: RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS,
statement_timeout: RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS,
query_timeout: RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS,
lock_timeout: RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS,
};
return { poolConfig, secretNeedles };
}
/**
* Opens a bounded, fail-closed PostgreSQL executor backed by `pg.Pool` for the
* MCP research copilot stdio host (`ResearchCopilotStdioHostDeps['openExecutor']`).
*/
export async function openResearchCopilotExecutor(
config: ResearchCopilotExecutorConfig,
options?: OpenResearchCopilotExecutorOptions
): Promise<ManagedResearchCopilotExecutor> {
const env = options?.env ?? process.env;
const { poolConfig, secretNeedles } = parseAndNormalizePoolConfig(config, env);
const createPool =
options?.createPool ?? ((cfg: PoolConfig): ResearchCopilotPoolLike => new Pool(cfg));
let pool: ResearchCopilotPoolLike;
try {
pool = createPool(poolConfig);
} catch {
throw new ResearchCopilotExecutorError(
'CONNECT_FAILED',
'Failed to initialize PostgreSQL pool for research copilot executor.'
);
}
const handleIdlePoolError = (error: Error): void => {
if (options?.onPoolError === undefined) {
return;
}
const safeError = isErrorSafeToSurface(error, secretNeedles)
? error
: new ResearchCopilotExecutorError(
'POOL_ERROR',
'PostgreSQL research copilot pool encountered an idle client error.'
);
try {
options.onPoolError(safeError);
} catch {
// Never allow an idle-client error callback to crash the host process.
}
};
try {
pool.on('error', handleIdlePoolError);
await pool.query('SELECT 1');
} catch {
try {
await pool.end();
} catch {
// Preserve the primary startup connection failure.
}
throw new ResearchCopilotExecutorError(
'CONNECT_FAILED',
'Failed to connect PostgreSQL research copilot executor.'
);
}
let closing = false;
let closePromise: Promise<void> | null = null;
const executor: ResearchCopilotExecutor = {
async query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }> {
if (closing) {
throw new ResearchCopilotExecutorError(
'EXECUTOR_CLOSED',
'PostgreSQL research copilot executor is closed.'
);
}
try {
const result = await pool.query(text, params === undefined ? undefined : [...params]);
return { rows: result.rows as readonly Row[] };
} catch (error) {
if (isErrorSafeToSurface(error, secretNeedles)) {
throw error;
}
const sqlState = extractSqlState(error);
if (sqlState !== undefined) {
const sanitized = new Error('PostgreSQL research copilot query failed.');
Object.defineProperty(sanitized, 'code', {
value: sqlState,
enumerable: true,
configurable: true,
});
throw sanitized;
}
throw new ResearchCopilotExecutorError(
'QUERY_FAILED',
'PostgreSQL research copilot query failed.'
);
}
},
};
const close = (): Promise<void> => {
closing = true;
if (closePromise === null) {
closePromise = pool.end().catch(() => {
throw new ResearchCopilotExecutorError(
'CLOSE_FAILED',
'Failed to close PostgreSQL research copilot executor.'
);
});
}
return closePromise;
};
return {
executor,
close,
};
}