T-200: merge dev
This commit is contained in:
commit
267e655e63
6 changed files with 1243 additions and 1168 deletions
|
|
@ -10,11 +10,11 @@ export {
|
|||
ResearchCopilotExecutorError,
|
||||
openResearchCopilotExecutor,
|
||||
type ManagedResearchCopilotExecutor,
|
||||
type OpenResearchCopilotExecutorOptions,
|
||||
type ResearchCopilotExecutor,
|
||||
type ResearchCopilotExecutorConfig,
|
||||
type ResearchCopilotExecutorDeps,
|
||||
type ResearchCopilotExecutorErrorCode,
|
||||
type ResearchCopilotPoolLike,
|
||||
type ResearchCopilotExecutorPool,
|
||||
} from './research-copilot-executor';
|
||||
export type {
|
||||
ConnectionEvents,
|
||||
|
|
|
|||
|
|
@ -1,72 +1,72 @@
|
|||
/**
|
||||
* Managed PostgreSQL executor factory for the MCP research copilot stdio host
|
||||
* (`runResearchCopilotStdioHost` in `@stock-bot/research/mcp`).
|
||||
* Real PostgreSQL executor factory for the MCP research copilot stdio host.
|
||||
*
|
||||
* - 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.
|
||||
* Opens a bounded `pg.Pool` (`max: 4`, 5 s connect timeout, 10 s statement
|
||||
* timeout, 15 s driver query timeout, 2 s lock timeout), verifies connectivity
|
||||
* with a single `SELECT 1` probe, attaches an idle-client `'error'` listener,
|
||||
* and returns a managed `{ executor, close }` handle structurally assignable
|
||||
* to `ManagedPostgresExecutor` in `@stock-bot/research/mcp` without importing
|
||||
* `@stock-bot/research` at runtime.
|
||||
*
|
||||
* All errors thrown by this module are {@link ResearchCopilotExecutorError}
|
||||
* instances with fixed, sanitized messages and no `cause`, so connection
|
||||
* strings, credentials, hostnames, and raw `pg` error text never leak.
|
||||
* PostgreSQL unique-violation SQLSTATE `'23505'` is preserved on sanitized
|
||||
* query errors for `createPostgresFindingWritePort` idempotent retries.
|
||||
*/
|
||||
|
||||
import { Pool, type PoolConfig } from 'pg';
|
||||
|
||||
/** Maximum concurrent PostgreSQL connections opened by the research copilot executor. */
|
||||
/** Maximum number of PostgreSQL connections in the copilot executor pool. */
|
||||
export const RESEARCH_COPILOT_PG_POOL_MAX = 4;
|
||||
|
||||
/** TCP/startup connection timeout in milliseconds (5 seconds). */
|
||||
/** TCP/startup connection timeout in milliseconds. */
|
||||
export const RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS = 5_000;
|
||||
|
||||
/** PostgreSQL server-side `statement_timeout` in milliseconds (10 seconds). */
|
||||
/** Server-side PostgreSQL `statement_timeout` in milliseconds. */
|
||||
export const RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS = 10_000;
|
||||
|
||||
/** Client-side `pg` `query_timeout` in milliseconds (15 seconds). */
|
||||
/** Driver-side `pg` `query_timeout` in milliseconds. */
|
||||
export const RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS = 15_000;
|
||||
|
||||
/** PostgreSQL server-side `lock_timeout` in milliseconds (2 seconds). */
|
||||
/** Server-side PostgreSQL `lock_timeout` in milliseconds. */
|
||||
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 PORT_DIGITS_RE = /^\d+$/;
|
||||
const FINDING_REPLAY_SQLSTATE = '23505';
|
||||
/** Typed error codes emitted by {@link ResearchCopilotExecutorError}. */
|
||||
export type ResearchCopilotExecutorErrorCode =
|
||||
| 'INVALID_CONFIG'
|
||||
| 'OPEN_FAILED'
|
||||
| 'QUERY_FAILED'
|
||||
| 'EXECUTOR_CLOSED'
|
||||
| 'CLOSE_FAILED'
|
||||
| '23505';
|
||||
|
||||
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 ERROR_MESSAGES: Readonly<Record<ResearchCopilotExecutorErrorCode, string>> = {
|
||||
INVALID_CONFIG:
|
||||
'Invalid PostgreSQL configuration: expected a postgres:// or postgresql:// URL with an explicit host and database.',
|
||||
OPEN_FAILED: 'Failed to open PostgreSQL executor for research copilot.',
|
||||
QUERY_FAILED: 'PostgreSQL query failed in research copilot executor.',
|
||||
EXECUTOR_CLOSED: 'Research copilot PostgreSQL executor is closed.',
|
||||
CLOSE_FAILED: 'Failed to close PostgreSQL executor for research copilot.',
|
||||
'23505': 'PostgreSQL unique constraint violation in research copilot executor.',
|
||||
};
|
||||
|
||||
const OVERRIDDEN_QUERY_PARAMS = new Set([
|
||||
'options',
|
||||
const STRIPPED_TIMEOUT_PARAMS: ReadonlySet<string> = new Set([
|
||||
'statement_timeout',
|
||||
'lock_timeout',
|
||||
'query_timeout',
|
||||
'connectiontimeoutmillis',
|
||||
'connect_timeout',
|
||||
'max',
|
||||
'min',
|
||||
'idletimeoutmillis',
|
||||
'connectiontimeoutmillis',
|
||||
]);
|
||||
|
||||
/** Error codes thrown by {@link ResearchCopilotExecutorError}. */
|
||||
export type ResearchCopilotExecutorErrorCode =
|
||||
| 'INVALID_CONFIG'
|
||||
| 'CONNECT_FAILED'
|
||||
| 'EXECUTOR_CLOSED'
|
||||
| 'CLOSE_FAILED'
|
||||
| 'QUERY_FAILED'
|
||||
| 'POOL_ERROR';
|
||||
const POSTGRES_URL_PREFIX_RE = /^postgres(?:ql)?:\/\//i;
|
||||
const PORT_DIGITS_RE = /^\d+$/;
|
||||
const CONTROL_CHAR_RE = /[\r\n\0]/;
|
||||
|
||||
/**
|
||||
* Credential-safe error thrown by {@link openResearchCopilotExecutor} and its
|
||||
* managed executor handle. Never embeds raw DSNs, passwords, or raw driver causes.
|
||||
* Sanitized error thrown by {@link openResearchCopilotExecutor} and the
|
||||
* managed executor it returns. Never attaches a raw `cause` or embeds DSNs,
|
||||
* credentials, hostnames, or raw driver messages.
|
||||
*/
|
||||
export class ResearchCopilotExecutorError extends Error {
|
||||
readonly code: ResearchCopilotExecutorErrorCode;
|
||||
|
|
@ -79,19 +79,24 @@ export class ResearchCopilotExecutorError extends Error {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal structural configuration accepted by {@link openResearchCopilotExecutor}.
|
||||
* Compatible with `ResearchCopilotHostConfig` from `@stock-bot/research/mcp`.
|
||||
*/
|
||||
/** Configuration accepted by {@link openResearchCopilotExecutor}. */
|
||||
export interface ResearchCopilotExecutorConfig {
|
||||
readonly postgresUrl: string;
|
||||
readonly postgresSchema?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Structural query executor compatible with `PostgresResearchCopilotExecutor`
|
||||
* from `@stock-bot/research/mcp`.
|
||||
*/
|
||||
/** Minimal `pg.Pool` surface required by {@link openResearchCopilotExecutor}. */
|
||||
export interface ResearchCopilotExecutorPool {
|
||||
query(text: string, values?: unknown[]): Promise<{ readonly rows: readonly unknown[] }>;
|
||||
end(): Promise<void>;
|
||||
on(event: 'error', listener: (error: Error) => void): unknown;
|
||||
}
|
||||
|
||||
/** Optional dependency injection hooks for {@link openResearchCopilotExecutor}. */
|
||||
export interface ResearchCopilotExecutorDeps {
|
||||
readonly createPool?: (poolConfig: PoolConfig) => ResearchCopilotExecutorPool;
|
||||
}
|
||||
|
||||
/** Structural query executor compatible with MCP research copilot PostgreSQL adapters. */
|
||||
export interface ResearchCopilotExecutor {
|
||||
query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
|
|
@ -99,192 +104,107 @@ export interface ResearchCopilotExecutor {
|
|||
): Promise<{ readonly rows: readonly Row[] }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Managed executor handle compatible with `ManagedPostgresExecutor` from
|
||||
* `@stock-bot/research/mcp`.
|
||||
*/
|
||||
/** Managed executor handle structurally assignable to `ManagedPostgresExecutor`. */
|
||||
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>>;
|
||||
}
|
||||
|
||||
function extractFindingReplaySqlState(error: unknown): '23505' | undefined {
|
||||
if (typeof error !== 'object' || error === null) {
|
||||
return undefined;
|
||||
}
|
||||
const code = (error as { readonly code?: unknown }).code;
|
||||
return code === FINDING_REPLAY_SQLSTATE ? FINDING_REPLAY_SQLSTATE : undefined;
|
||||
}
|
||||
|
||||
function getLastExactQueryParam(parsed: URL, name: string): string | undefined {
|
||||
let value: string | undefined;
|
||||
for (const [key, entry] of parsed.searchParams.entries()) {
|
||||
if (key === name) {
|
||||
value = entry;
|
||||
}
|
||||
}
|
||||
return value;
|
||||
function invalidConfigError(): ResearchCopilotExecutorError {
|
||||
return new ResearchCopilotExecutorError('INVALID_CONFIG', ERROR_MESSAGES.INVALID_CONFIG);
|
||||
}
|
||||
|
||||
function assertValidPort(rawPort: string): void {
|
||||
if (!PORT_DIGITS_RE.test(rawPort)) {
|
||||
throw new ResearchCopilotExecutorError(
|
||||
'INVALID_CONFIG',
|
||||
'Invalid PostgreSQL configuration: URL port must be an integer between 1 and 65535.'
|
||||
);
|
||||
throw invalidConfigError();
|
||||
}
|
||||
const portNum = Number(rawPort);
|
||||
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.'
|
||||
);
|
||||
throw invalidConfigError();
|
||||
}
|
||||
}
|
||||
|
||||
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://.'
|
||||
);
|
||||
function parseAndNormalizePoolConfig(config: ResearchCopilotExecutorConfig): PoolConfig {
|
||||
if (typeof config !== 'object' || config === null || typeof config.postgresUrl !== 'string') {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
|
||||
const rawUrl = config.postgresUrl;
|
||||
if (
|
||||
rawUrl.length === 0 ||
|
||||
rawUrl !== rawUrl.trim() ||
|
||||
CONTROL_CHAR_RE.test(rawUrl) ||
|
||||
!POSTGRES_URL_PREFIX_RE.test(rawUrl)
|
||||
) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
|
||||
let usedDummyHost = false;
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(raw);
|
||||
parsed = new URL(rawUrl);
|
||||
} 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.'
|
||||
);
|
||||
}
|
||||
throw invalidConfigError();
|
||||
}
|
||||
|
||||
if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') {
|
||||
throw new ResearchCopilotExecutorError(
|
||||
'INVALID_CONFIG',
|
||||
'Invalid PostgreSQL configuration: URL must use the postgres:// or postgresql:// scheme.'
|
||||
);
|
||||
throw invalidConfigError();
|
||||
}
|
||||
|
||||
return { url: parsed, usedDummyHost };
|
||||
}
|
||||
const hostQueryParams = parsed.searchParams.getAll('host');
|
||||
if (hostQueryParams.length > 1) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
const queryHost = hostQueryParams.length === 1 ? (hostQueryParams[0] as string).trim() : '';
|
||||
if (hostQueryParams.length === 1 && queryHost.length === 0) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
|
||||
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);
|
||||
const hasAuthorityHost = parsed.hostname.length > 0;
|
||||
if (hasAuthorityHost) {
|
||||
let decodedHost: string;
|
||||
try {
|
||||
decodedHost = decodeURIComponent(parsed.hostname);
|
||||
} catch {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
if (decodedHost.trim().length === 0) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
if (!hasAuthorityHost && queryHost.length === 0) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
|
||||
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>>
|
||||
): PoolConfig {
|
||||
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_]*$.'
|
||||
);
|
||||
}
|
||||
if (parsed.port.length > 0) {
|
||||
assertValidPort(parsed.port);
|
||||
}
|
||||
|
||||
const { url: parsed, usedDummyHost } = parsePostgresUrlStrict(config.postgresUrl);
|
||||
const portQueryParams = parsed.searchParams.getAll('port');
|
||||
if (portQueryParams.length > 1) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
if (portQueryParams.length === 1) {
|
||||
assertValidPort((portQueryParams[0] as string).trim());
|
||||
}
|
||||
|
||||
if (!parsed.pathname.startsWith('/') || parsed.pathname.length <= 1) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
const rawDatabase = parsed.pathname.slice(1);
|
||||
if (rawDatabase.includes('/')) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
let decodedDatabase: string;
|
||||
try {
|
||||
decodedDatabase = decodeURIComponent(rawDatabase);
|
||||
} catch {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
if (decodedDatabase.trim().length === 0) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
|
||||
let decodedHostname = '';
|
||||
try {
|
||||
if (parsed.username.length > 0) {
|
||||
decodeURIComponent(parsed.username);
|
||||
|
|
@ -292,63 +212,21 @@ function parseAndNormalizePoolConfig(
|
|||
if (parsed.password.length > 0) {
|
||||
decodeURIComponent(parsed.password);
|
||||
}
|
||||
if (!usedDummyHost && parsed.hostname.length > 0) {
|
||||
decodedHostname = decodeURIComponent(parsed.hostname).trim();
|
||||
}
|
||||
} catch {
|
||||
throw new ResearchCopilotExecutorError(
|
||||
'INVALID_CONFIG',
|
||||
'Invalid PostgreSQL configuration: URL contains invalid percent-encoding.'
|
||||
);
|
||||
throw invalidConfigError();
|
||||
}
|
||||
|
||||
// Match pg-connection-string precedence: query ?port=... takes precedence over authority port.
|
||||
const queryPort = getLastExactQueryParam(parsed, 'port');
|
||||
const effectivePort = queryPort && queryPort.length > 0 ? queryPort : parsed.port;
|
||||
if (effectivePort.length > 0) {
|
||||
assertValidPort(effectivePort);
|
||||
}
|
||||
if (parsed.port.length > 0) {
|
||||
assertValidPort(parsed.port);
|
||||
}
|
||||
|
||||
// Match pg-connection-string precedence: query ?host=... takes precedence over authority host.
|
||||
// pg does not resolve hostaddr as a fallback host.
|
||||
const queryHost = getLastExactQueryParam(parsed, 'host')?.trim() ?? '';
|
||||
const effectiveHost = queryHost.length > 0 ? queryHost : decodedHostname;
|
||||
if (effectiveHost.length === 0) {
|
||||
throw new ResearchCopilotExecutorError(
|
||||
'INVALID_CONFIG',
|
||||
'Invalid PostgreSQL configuration: URL must specify a host or Unix socket host parameter.'
|
||||
);
|
||||
}
|
||||
|
||||
// Match pg-connection-string: pg reads the database strictly from the URL pathname (never ?dbname=).
|
||||
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.'
|
||||
);
|
||||
}
|
||||
if (decodedDatabase.length === 0) {
|
||||
throw new ResearchCopilotExecutorError(
|
||||
'INVALID_CONFIG',
|
||||
'Invalid PostgreSQL configuration: URL must specify a non-empty database name in the path.'
|
||||
);
|
||||
}
|
||||
|
||||
const urlOptions: string[] = [];
|
||||
const existingOptions: string[] = [];
|
||||
const keysToDelete: string[] = [];
|
||||
for (const [key, value] of parsed.searchParams.entries()) {
|
||||
const lower = key.toLowerCase();
|
||||
if (lower === 'options') {
|
||||
urlOptions.push(value);
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length > 0) {
|
||||
existingOptions.push(trimmed);
|
||||
}
|
||||
keysToDelete.push(key);
|
||||
} else if (OVERRIDDEN_QUERY_PARAMS.has(lower)) {
|
||||
} else if (STRIPPED_TIMEOUT_PARAMS.has(lower)) {
|
||||
keysToDelete.push(key);
|
||||
}
|
||||
}
|
||||
|
|
@ -356,79 +234,101 @@ function parseAndNormalizePoolConfig(
|
|||
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 envOptions = typeof process.env.PGOPTIONS === 'string' ? process.env.PGOPTIONS.trim() : '';
|
||||
const baseOptions = existingOptions.length > 0 ? existingOptions.join(' ') : envOptions;
|
||||
|
||||
return {
|
||||
connectionString: normalizedConnectionString,
|
||||
options: normalizedOptions,
|
||||
const poolConfig: PoolConfig = {
|
||||
connectionString: parsed.toString(),
|
||||
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,
|
||||
};
|
||||
|
||||
if (baseOptions.length > 0) {
|
||||
poolConfig.options = `${baseOptions} -c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`;
|
||||
}
|
||||
|
||||
return poolConfig;
|
||||
}
|
||||
|
||||
function resolveCreatePool(
|
||||
deps?: ResearchCopilotExecutorDeps
|
||||
): (poolConfig: PoolConfig) => ResearchCopilotExecutorPool {
|
||||
if (deps === undefined) {
|
||||
return poolConfig => new Pool(poolConfig);
|
||||
}
|
||||
if (typeof deps !== 'object' || deps === null) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
if (deps.createPool === undefined) {
|
||||
return poolConfig => new Pool(poolConfig);
|
||||
}
|
||||
if (typeof deps.createPool !== 'function') {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
return deps.createPool;
|
||||
}
|
||||
|
||||
function getPostgresErrorCode(error: unknown): string | undefined {
|
||||
if (typeof error === 'object' && error !== null) {
|
||||
const code = (error as { readonly code?: unknown }).code;
|
||||
if (typeof code === 'string') {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function safeEndPool(pool: ResearchCopilotExecutorPool): Promise<void> {
|
||||
try {
|
||||
await pool.end();
|
||||
} catch {
|
||||
// Best-effort cleanup during failed startup; preserve primary OPEN_FAILED error.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a bounded, fail-closed PostgreSQL executor backed by `pg.Pool` for the
|
||||
* MCP research copilot stdio host (`ResearchCopilotStdioHostDeps['openExecutor']`).
|
||||
* Opens a bounded, probed PostgreSQL executor for the MCP research copilot
|
||||
* stdio host.
|
||||
*/
|
||||
export async function openResearchCopilotExecutor(
|
||||
config: ResearchCopilotExecutorConfig,
|
||||
options?: OpenResearchCopilotExecutorOptions
|
||||
deps?: ResearchCopilotExecutorDeps
|
||||
): Promise<ManagedResearchCopilotExecutor> {
|
||||
const env = options?.env ?? process.env;
|
||||
const poolConfig = parseAndNormalizePoolConfig(config, env);
|
||||
const poolConfig = parseAndNormalizePoolConfig(config);
|
||||
const createPool = resolveCreatePool(deps);
|
||||
|
||||
const createPool =
|
||||
options?.createPool ?? ((cfg: PoolConfig): ResearchCopilotPoolLike => new Pool(cfg));
|
||||
|
||||
let pool: ResearchCopilotPoolLike;
|
||||
let pool: ResearchCopilotExecutorPool;
|
||||
try {
|
||||
pool = createPool(poolConfig);
|
||||
} catch {
|
||||
throw new ResearchCopilotExecutorError(
|
||||
'CONNECT_FAILED',
|
||||
'Failed to initialize PostgreSQL pool for research copilot executor.'
|
||||
);
|
||||
throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED);
|
||||
}
|
||||
|
||||
const handleIdlePoolError = (_error: Error): void => {
|
||||
if (options?.onPoolError === undefined) {
|
||||
return;
|
||||
}
|
||||
const safeError = 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.
|
||||
}
|
||||
};
|
||||
if (
|
||||
typeof pool !== 'object' ||
|
||||
pool === null ||
|
||||
typeof pool.query !== 'function' ||
|
||||
typeof pool.end !== 'function' ||
|
||||
typeof pool.on !== 'function'
|
||||
) {
|
||||
throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED);
|
||||
}
|
||||
|
||||
try {
|
||||
pool.on('error', handleIdlePoolError);
|
||||
// Keep idle-client disconnects from becoming unhandled EventEmitter errors.
|
||||
pool.on('error', () => {
|
||||
// Intentionally absorbed; subsequent queries surface sanitized QUERY_FAILED errors.
|
||||
});
|
||||
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.'
|
||||
);
|
||||
await safeEndPool(pool);
|
||||
throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED);
|
||||
}
|
||||
|
||||
let closing = false;
|
||||
let closed = false;
|
||||
let closePromise: Promise<void> | null = null;
|
||||
|
||||
const executor: ResearchCopilotExecutor = {
|
||||
|
|
@ -436,50 +336,44 @@ export async function openResearchCopilotExecutor(
|
|||
text: string,
|
||||
params?: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Row[] }> {
|
||||
if (closing) {
|
||||
throw new ResearchCopilotExecutorError(
|
||||
'EXECUTOR_CLOSED',
|
||||
'PostgreSQL research copilot executor is closed.'
|
||||
);
|
||||
if (closed) {
|
||||
throw new ResearchCopilotExecutorError('EXECUTOR_CLOSED', ERROR_MESSAGES.EXECUTOR_CLOSED);
|
||||
}
|
||||
|
||||
let rawResult: { readonly rows: readonly unknown[] };
|
||||
try {
|
||||
const result = await pool.query(text, params === undefined ? undefined : [...params]);
|
||||
return { rows: result.rows as readonly Row[] };
|
||||
rawResult =
|
||||
params === undefined ? await pool.query(text) : await pool.query(text, [...params]);
|
||||
} catch (error) {
|
||||
const replaySqlState = extractFindingReplaySqlState(error);
|
||||
if (replaySqlState !== undefined) {
|
||||
const sanitized = new Error('PostgreSQL research copilot query failed.');
|
||||
Object.defineProperty(sanitized, 'code', {
|
||||
value: replaySqlState,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
});
|
||||
throw sanitized;
|
||||
if (getPostgresErrorCode(error) === '23505') {
|
||||
throw new ResearchCopilotExecutorError('23505', ERROR_MESSAGES['23505']);
|
||||
}
|
||||
throw new ResearchCopilotExecutorError(
|
||||
'QUERY_FAILED',
|
||||
'PostgreSQL research copilot query failed.'
|
||||
);
|
||||
throw new ResearchCopilotExecutorError('QUERY_FAILED', ERROR_MESSAGES.QUERY_FAILED);
|
||||
}
|
||||
|
||||
if (
|
||||
typeof rawResult !== 'object' ||
|
||||
rawResult === null ||
|
||||
!Array.isArray(rawResult.rows)
|
||||
) {
|
||||
throw new ResearchCopilotExecutorError('QUERY_FAILED', ERROR_MESSAGES.QUERY_FAILED);
|
||||
}
|
||||
|
||||
return { rows: rawResult.rows as readonly Row[] };
|
||||
},
|
||||
};
|
||||
|
||||
const close = (): Promise<void> => {
|
||||
closing = true;
|
||||
closed = true;
|
||||
if (closePromise === null) {
|
||||
closePromise = pool.end().catch(() => {
|
||||
throw new ResearchCopilotExecutorError(
|
||||
'CLOSE_FAILED',
|
||||
'Failed to close PostgreSQL research copilot executor.'
|
||||
);
|
||||
});
|
||||
closePromise = Promise.resolve()
|
||||
.then(() => pool.end())
|
||||
.catch(() => {
|
||||
throw new ResearchCopilotExecutorError('CLOSE_FAILED', ERROR_MESSAGES.CLOSE_FAILED);
|
||||
});
|
||||
}
|
||||
return closePromise;
|
||||
};
|
||||
|
||||
return {
|
||||
executor,
|
||||
close,
|
||||
};
|
||||
return { executor, close };
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue