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:
parent
436616b343
commit
7bf9bb6c20
7 changed files with 1635 additions and 1 deletions
247
libs/data/postgres/test/research-copilot-executor-edge.test.ts
Normal file
247
libs/data/postgres/test/research-copilot-executor-edge.test.ts
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { createServer } from 'node:net';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import type { PoolConfig } from 'pg';
|
||||
import {
|
||||
RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS,
|
||||
ResearchCopilotExecutorError,
|
||||
type ResearchCopilotPoolLike,
|
||||
openResearchCopilotExecutor,
|
||||
} from '../src';
|
||||
|
||||
function createFakePool(options?: {
|
||||
onQuery?: (text: string, values?: unknown[]) => Promise<{ readonly rows: readonly unknown[] }>;
|
||||
onEnd?: () => Promise<void>;
|
||||
}): ResearchCopilotPoolLike {
|
||||
const emitter = new EventEmitter();
|
||||
const pool: ResearchCopilotPoolLike = {
|
||||
async query(text: string, values?: unknown[]) {
|
||||
if (options?.onQuery) {
|
||||
return await options.onQuery(text, values);
|
||||
}
|
||||
return { rows: [{ ok: 1 }] };
|
||||
},
|
||||
async end() {
|
||||
if (options?.onEnd) {
|
||||
await options.onEnd();
|
||||
}
|
||||
},
|
||||
on(event: 'error', listener: (error: Error) => void) {
|
||||
emitter.on(event, listener);
|
||||
return pool;
|
||||
},
|
||||
};
|
||||
return pool;
|
||||
}
|
||||
|
||||
describe('openResearchCopilotExecutor edge cases', () => {
|
||||
test('redacts query-param passwords and nested causes on query errors while preserving SQLSTATE 23505', async () => {
|
||||
const querySecret = 'QueryPass#42';
|
||||
const dsn = `postgres://copilot@127.0.0.1:5432/research_db?password=${encodeURIComponent(querySecret)}`;
|
||||
|
||||
const pool = createFakePool({
|
||||
onQuery: async text => {
|
||||
if (text === 'SELECT 1') {
|
||||
return { rows: [{ ok: 1 }] };
|
||||
}
|
||||
if (text === 'DUP_WITH_SECRET') {
|
||||
const err = Object.assign(new Error(`duplicate key leaked ${querySecret}`), {
|
||||
code: '23505',
|
||||
});
|
||||
throw err;
|
||||
}
|
||||
if (text === 'NESTED_CAUSE') {
|
||||
const inner = new Error(`inner failure ${querySecret}`);
|
||||
throw new Error('outer message', { cause: inner });
|
||||
}
|
||||
throw 'non-error string with secret';
|
||||
},
|
||||
});
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: dsn },
|
||||
{ createPool: () => pool, env: {} }
|
||||
);
|
||||
|
||||
// SQLSTATE 23505 preserved even when the error message had to be redacted.
|
||||
let dupErr: unknown;
|
||||
try {
|
||||
await handle.executor.query('DUP_WITH_SECRET');
|
||||
} catch (error) {
|
||||
dupErr = error;
|
||||
}
|
||||
expect(dupErr).toBeInstanceOf(Error);
|
||||
expect((dupErr as { code?: string }).code).toBe('23505');
|
||||
expect((dupErr as Error).message).not.toContain(querySecret);
|
||||
expect('cause' in (dupErr as Error)).toBe(false);
|
||||
|
||||
// Nested cause containing secret is replaced with credential-free QUERY_FAILED.
|
||||
let nestedErr: unknown;
|
||||
try {
|
||||
await handle.executor.query('NESTED_CAUSE');
|
||||
} catch (error) {
|
||||
nestedErr = error;
|
||||
}
|
||||
expect(nestedErr).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
expect((nestedErr as ResearchCopilotExecutorError).code).toBe('QUERY_FAILED');
|
||||
expect((nestedErr as Error).message).not.toContain(querySecret);
|
||||
expect('cause' in (nestedErr as Error)).toBe(false);
|
||||
|
||||
// Non-Error thrown value is wrapped safely.
|
||||
let nonErr: unknown;
|
||||
try {
|
||||
await handle.executor.query('NON_ERROR');
|
||||
} catch (error) {
|
||||
nonErr = error;
|
||||
}
|
||||
expect(nonErr).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
expect((nonErr as ResearchCopilotExecutorError).code).toBe('QUERY_FAILED');
|
||||
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
test('rejects control characters in PGOPTIONS and URL options before creating a pool', async () => {
|
||||
let calls = 0;
|
||||
|
||||
let envErr: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor(
|
||||
{ postgresUrl: 'postgres://u:p@127.0.0.1:5432/research_db' },
|
||||
{
|
||||
createPool: () => {
|
||||
calls += 1;
|
||||
return createFakePool();
|
||||
},
|
||||
env: { PGOPTIONS: '-c search_path=ok\n-c evil=1' },
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
envErr = error;
|
||||
}
|
||||
expect(calls).toBe(0);
|
||||
expect(envErr).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
expect((envErr as ResearchCopilotExecutorError).code).toBe('INVALID_CONFIG');
|
||||
|
||||
let urlOptErr: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor(
|
||||
{ postgresUrl: 'postgres://u:p@127.0.0.1:5432/research_db?options=-c%20search_path%3Dok%00' },
|
||||
{
|
||||
createPool: () => {
|
||||
calls += 1;
|
||||
return createFakePool();
|
||||
},
|
||||
env: {},
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
urlOptErr = error;
|
||||
}
|
||||
expect(calls).toBe(0);
|
||||
expect(urlOptErr).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
expect((urlOptErr as ResearchCopilotExecutorError).code).toBe('INVALID_CONFIG');
|
||||
});
|
||||
|
||||
test('normalizes case-insensitive query params and combines multiple options entries', async () => {
|
||||
const captured: PoolConfig[] = [];
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{
|
||||
postgresUrl:
|
||||
'postgres://u:p@127.0.0.1:5432/research_db?OPTIONS=-c%20search_path%3Ds1&options=-c%20work_mem%3D16MB&STATEMENT_TIMEOUT=0&LOCK_TIMEOUT=0&application_name=copilot_edge',
|
||||
},
|
||||
{
|
||||
createPool: cfg => {
|
||||
captured.push(cfg);
|
||||
return createFakePool();
|
||||
},
|
||||
env: {},
|
||||
}
|
||||
);
|
||||
|
||||
const cfg = captured[0] as PoolConfig;
|
||||
expect(cfg.options).toBe(
|
||||
'-c search_path=s1 -c work_mem=16MB -c statement_timeout=10000 -c lock_timeout=2000'
|
||||
);
|
||||
expect(cfg.connectionString).toContain('application_name=copilot_edge');
|
||||
expect(cfg.connectionString?.toLowerCase()).not.toContain('statement_timeout=');
|
||||
expect(cfg.connectionString?.toLowerCase()).not.toContain('lock_timeout=');
|
||||
expect(cfg.connectionString?.toLowerCase()).not.toContain('options=');
|
||||
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
test('redacts pool.end() failure as CLOSE_FAILED without leaking credentials', async () => {
|
||||
const secret = 'close_secret_77';
|
||||
const pool = createFakePool({
|
||||
onEnd: async () => {
|
||||
throw new Error(`failed closing pool for ${secret}`);
|
||||
},
|
||||
});
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: `postgres://u:${secret}@127.0.0.1:5432/research_db` },
|
||||
{ createPool: () => pool, env: {} }
|
||||
);
|
||||
|
||||
let closeErr: unknown;
|
||||
try {
|
||||
await handle.close();
|
||||
} catch (error) {
|
||||
closeErr = error;
|
||||
}
|
||||
|
||||
expect(closeErr).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
expect((closeErr as ResearchCopilotExecutorError).code).toBe('CLOSE_FAILED');
|
||||
expect((closeErr as Error).message).not.toContain(secret);
|
||||
expect('cause' in (closeErr as Error)).toBe(false);
|
||||
});
|
||||
|
||||
test(
|
||||
'enforces real pg.Pool connectionTimeoutMillis against a silent local TCP listener',
|
||||
async () => {
|
||||
const server = createServer(socket => {
|
||||
// Intentionally accept and hold the TCP connection silent without PostgreSQL handshake.
|
||||
socket.on('error', () => {});
|
||||
});
|
||||
|
||||
const listenPort = await new Promise<number>((resolve, reject) => {
|
||||
server.once('error', reject);
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
const address = server.address();
|
||||
if (address === null || typeof address === 'string') {
|
||||
reject(new Error('Expected TCP address info'));
|
||||
return;
|
||||
}
|
||||
resolve(address.port);
|
||||
});
|
||||
});
|
||||
|
||||
const secret = 'silent_tcp_secret_99';
|
||||
const startedAt = Date.now();
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor({
|
||||
postgresUrl: `postgres://copilot:${secret}@127.0.0.1:${listenPort}/research_db`,
|
||||
});
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
} finally {
|
||||
await new Promise<void>(resolve => {
|
||||
server.close(() => resolve());
|
||||
});
|
||||
}
|
||||
|
||||
const elapsedMs = Date.now() - startedAt;
|
||||
expect(caught).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
const err = caught as ResearchCopilotExecutorError;
|
||||
expect(err.code).toBe('CONNECT_FAILED');
|
||||
expect(err.message).not.toContain(secret);
|
||||
expect(err.stack ?? '').not.toContain(secret);
|
||||
expect('cause' in err).toBe(false);
|
||||
// Bounded around the 5s connectionTimeoutMillis (allow scheduling jitter).
|
||||
expect(elapsedMs).toBeGreaterThanOrEqual(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS - 500);
|
||||
expect(elapsedMs).toBeLessThan(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS + 5_000);
|
||||
},
|
||||
15_000
|
||||
);
|
||||
});
|
||||
402
libs/data/postgres/test/research-copilot-executor.test.ts
Normal file
402
libs/data/postgres/test/research-copilot-executor.test.ts
Normal file
|
|
@ -0,0 +1,402 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import type { PoolConfig } from 'pg';
|
||||
import {
|
||||
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,
|
||||
type ResearchCopilotPoolLike,
|
||||
openResearchCopilotExecutor,
|
||||
} from '../src';
|
||||
|
||||
interface FakePoolControls {
|
||||
readonly pool: ResearchCopilotPoolLike;
|
||||
readonly emitter: EventEmitter;
|
||||
readonly queries: Array<{ readonly text: string; readonly values?: unknown[] }>;
|
||||
getEndCalls(): number;
|
||||
}
|
||||
|
||||
function createFakePool(options?: {
|
||||
onQuery?: (text: string, values?: unknown[]) => Promise<{ readonly rows: readonly unknown[] }>;
|
||||
onEnd?: () => Promise<void>;
|
||||
}): FakePoolControls {
|
||||
const emitter = new EventEmitter();
|
||||
const queries: Array<{ readonly text: string; readonly values?: unknown[] }> = [];
|
||||
let endCalls = 0;
|
||||
|
||||
const pool: ResearchCopilotPoolLike = {
|
||||
async query(text: string, values?: unknown[]) {
|
||||
queries.push({ text, values });
|
||||
if (options?.onQuery) {
|
||||
return await options.onQuery(text, values);
|
||||
}
|
||||
return { rows: [{ ok: 1 }] };
|
||||
},
|
||||
async end() {
|
||||
endCalls += 1;
|
||||
if (options?.onEnd) {
|
||||
await options.onEnd();
|
||||
}
|
||||
},
|
||||
on(event: 'error', listener: (error: Error) => void) {
|
||||
emitter.on(event, listener);
|
||||
return pool;
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
pool,
|
||||
emitter,
|
||||
queries,
|
||||
getEndCalls: () => endCalls,
|
||||
};
|
||||
}
|
||||
|
||||
describe('openResearchCopilotExecutor', () => {
|
||||
describe('pre-pool config validation (fail closed)', () => {
|
||||
const invalidConfigs: ReadonlyArray<readonly [string, unknown]> = [
|
||||
['null config', null],
|
||||
['missing postgresUrl', {}],
|
||||
['empty postgresUrl', { postgresUrl: '' }],
|
||||
['whitespace postgresUrl', { postgresUrl: ' ' }],
|
||||
[
|
||||
'leading/trailing whitespace around valid URL',
|
||||
{ postgresUrl: ' postgres://u:supersecret@localhost:5432/research_db ' },
|
||||
],
|
||||
['http scheme', { postgresUrl: 'http://u:supersecret@localhost:5432/research_db' }],
|
||||
['mysql scheme', { postgresUrl: 'mysql://u:supersecret@localhost:5432/research_db' }],
|
||||
[
|
||||
'single-slash postgres:/ URI (T-189 regression)',
|
||||
{ postgresUrl: 'postgres:/research_db?host=%2Ftmp' },
|
||||
],
|
||||
[
|
||||
'single-slash postgresql:/ URI',
|
||||
{ postgresUrl: 'postgresql:/research_db?host=%2Fvar%2Frun%2Fpostgresql' },
|
||||
],
|
||||
['missing host and host query param', { postgresUrl: 'postgres:///research_db' }],
|
||||
['empty authority with port only', { postgresUrl: 'postgres://:5432/research_db' }],
|
||||
['missing database name', { postgresUrl: 'postgres://u:supersecret@localhost:5432' }],
|
||||
['trailing slash only (missing database)', { postgresUrl: 'postgres://u:supersecret@localhost:5432/' }],
|
||||
['blank percent-encoded database', { postgresUrl: 'postgres://u:supersecret@localhost:5432/%20' }],
|
||||
['port zero', { postgresUrl: 'postgres://u:supersecret@localhost:0/research_db' }],
|
||||
['invalid percent-encoding in password', { postgresUrl: 'postgres://u:%ZZsupersecret@localhost:5432/research_db' }],
|
||||
['control character in URL', { postgresUrl: 'postgres://u:supersecret@localhost:5432/research_db\n' }],
|
||||
[
|
||||
'invalid postgresSchema with uppercase',
|
||||
{ postgresUrl: 'postgres://u:supersecret@localhost:5432/research_db', postgresSchema: 'Public' },
|
||||
],
|
||||
[
|
||||
'invalid postgresSchema with hyphen',
|
||||
{ postgresUrl: 'postgres://u:supersecret@localhost:5432/research_db', postgresSchema: 'my-schema' },
|
||||
],
|
||||
];
|
||||
|
||||
for (const [label, invalidConfig] of invalidConfigs) {
|
||||
test(`rejects ${label} before creating any pool`, async () => {
|
||||
let createPoolCalls = 0;
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor(invalidConfig as { postgresUrl: string }, {
|
||||
createPool: () => {
|
||||
createPoolCalls += 1;
|
||||
return createFakePool().pool;
|
||||
},
|
||||
env: {},
|
||||
});
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
|
||||
expect(createPoolCalls).toBe(0);
|
||||
expect(caught).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
const err = caught as ResearchCopilotExecutorError;
|
||||
expect(err.code).toBe('INVALID_CONFIG');
|
||||
expect(err.message).not.toContain('supersecret');
|
||||
expect('cause' in err).toBe(false);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe('valid Unix socket URLs and pool normalization', () => {
|
||||
const validSocketUrls = [
|
||||
'postgres:///research_db?host=/var/run/postgresql',
|
||||
'postgresql:///research_db?host=%2Ftmp',
|
||||
'postgres://research_user:socketpass@/research_db?host=/tmp',
|
||||
'postgres://%2Fvar%2Frun%2Fpostgresql/research_db',
|
||||
];
|
||||
|
||||
for (const socketUrl of validSocketUrls) {
|
||||
test(`accepts Unix socket URL: ${socketUrl}`, async () => {
|
||||
const captured: PoolConfig[] = [];
|
||||
const fake = createFakePool();
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: socketUrl },
|
||||
{
|
||||
createPool: cfg => {
|
||||
captured.push(cfg);
|
||||
return fake.pool;
|
||||
},
|
||||
env: {},
|
||||
}
|
||||
);
|
||||
|
||||
expect(captured).toHaveLength(1);
|
||||
expect(fake.queries).toEqual([{ text: 'SELECT 1', values: undefined }]);
|
||||
await handle.close();
|
||||
});
|
||||
}
|
||||
|
||||
test('applies bounded pool max and timeouts while preserving search_path from URL options and PGOPTIONS', async () => {
|
||||
const captured: PoolConfig[] = [];
|
||||
const fake = createFakePool();
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{
|
||||
postgresUrl:
|
||||
'postgresql://reader:topsecret@127.0.0.1:5432/research_db?options=-c%20search_path%3Durl_schema&statement_timeout=0&lock_timeout=0&query_timeout=0&connect_timeout=999&max=50',
|
||||
postgresSchema: 'url_schema',
|
||||
},
|
||||
{
|
||||
createPool: cfg => {
|
||||
captured.push(cfg);
|
||||
return fake.pool;
|
||||
},
|
||||
env: {
|
||||
PGOPTIONS: '-c search_path=env_schema -c statement_timeout=0',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
expect(captured).toHaveLength(1);
|
||||
const poolConfig = captured[0] as PoolConfig;
|
||||
expect(poolConfig.max).toBe(RESEARCH_COPILOT_PG_POOL_MAX);
|
||||
expect(poolConfig.max).toBe(4);
|
||||
expect(poolConfig.connectionTimeoutMillis).toBe(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS);
|
||||
expect(poolConfig.connectionTimeoutMillis).toBe(5_000);
|
||||
expect(poolConfig.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS);
|
||||
expect(poolConfig.statement_timeout).toBe(10_000);
|
||||
expect(poolConfig.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS);
|
||||
expect(poolConfig.query_timeout).toBe(15_000);
|
||||
expect(poolConfig.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS);
|
||||
expect(poolConfig.lock_timeout).toBe(2_000);
|
||||
|
||||
expect(poolConfig.connectionString).not.toContain('statement_timeout=');
|
||||
expect(poolConfig.connectionString).not.toContain('lock_timeout=');
|
||||
expect(poolConfig.connectionString).not.toContain('query_timeout=');
|
||||
expect(poolConfig.connectionString).not.toContain('connect_timeout=');
|
||||
expect(poolConfig.connectionString).not.toContain('max=');
|
||||
expect(poolConfig.connectionString).not.toContain('options=');
|
||||
|
||||
expect(poolConfig.options).toBe(
|
||||
'-c search_path=env_schema -c statement_timeout=0 -c search_path=url_schema -c statement_timeout=10000 -c lock_timeout=2000'
|
||||
);
|
||||
|
||||
await handle.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('startup probe, cleanup, and error redaction', () => {
|
||||
test('runs exactly one SELECT 1 probe and cleans up pool on connect failure without leaking credentials', async () => {
|
||||
const secret = 'P@ssw0rd_Secret_123';
|
||||
const encoded = encodeURIComponent(secret);
|
||||
const dsn = `postgres://copilot:${encoded}@127.0.0.1:5432/research_db`;
|
||||
|
||||
const fake = createFakePool({
|
||||
onQuery: async () => {
|
||||
throw new Error(`password authentication failed for ${dsn} (${secret})`);
|
||||
},
|
||||
});
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor(
|
||||
{ postgresUrl: dsn },
|
||||
{
|
||||
createPool: () => fake.pool,
|
||||
env: {},
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
|
||||
expect(fake.queries).toEqual([{ text: 'SELECT 1', values: undefined }]);
|
||||
expect(fake.getEndCalls()).toBe(1);
|
||||
expect(caught).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
const err = caught as ResearchCopilotExecutorError;
|
||||
expect(err.code).toBe('CONNECT_FAILED');
|
||||
expect(err.message).not.toContain(secret);
|
||||
expect(err.message).not.toContain(encoded);
|
||||
expect(err.message).not.toContain(dsn);
|
||||
expect(err.stack ?? '').not.toContain(secret);
|
||||
expect('cause' in err).toBe(false);
|
||||
});
|
||||
|
||||
test('preserves CONNECT_FAILED even when pool.end() also fails during startup cleanup', async () => {
|
||||
const fake = createFakePool({
|
||||
onQuery: async () => {
|
||||
throw new Error('ECONNREFUSED');
|
||||
},
|
||||
onEnd: async () => {
|
||||
throw new Error('pool end failure');
|
||||
},
|
||||
});
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor(
|
||||
{ postgresUrl: 'postgres://user:secret@127.0.0.1:5432/research_db' },
|
||||
{
|
||||
createPool: () => fake.pool,
|
||||
env: {},
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
|
||||
expect(fake.getEndCalls()).toBe(1);
|
||||
expect(caught).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('CONNECT_FAILED');
|
||||
});
|
||||
});
|
||||
|
||||
describe('idle-client error handling', () => {
|
||||
test('registers error listener and sanitizes credential-bearing idle errors', async () => {
|
||||
const fake = createFakePool();
|
||||
const received: Error[] = [];
|
||||
const secret = 'idle_secret_99';
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: `postgres://user:${secret}@127.0.0.1:5432/research_db` },
|
||||
{
|
||||
createPool: () => fake.pool,
|
||||
onPoolError: err => {
|
||||
received.push(err);
|
||||
},
|
||||
env: {},
|
||||
}
|
||||
);
|
||||
|
||||
expect(fake.emitter.listenerCount('error')).toBe(1);
|
||||
|
||||
const safeErr = new Error('terminating connection due to administrator command');
|
||||
fake.emitter.emit('error', safeErr);
|
||||
fake.emitter.emit('error', new Error(`fatal idle error with ${secret}`));
|
||||
|
||||
expect(received).toHaveLength(2);
|
||||
expect(received[0]).toBe(safeErr);
|
||||
expect(received[1]).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
expect((received[1] as ResearchCopilotExecutorError).code).toBe('POOL_ERROR');
|
||||
expect(received[1]?.message).not.toContain(secret);
|
||||
expect('cause' in (received[1] as Error)).toBe(false);
|
||||
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
test('does not crash when idle error fires without onPoolError or when callback throws', async () => {
|
||||
const fake1 = createFakePool();
|
||||
const handle1 = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: 'postgres://user:pass@127.0.0.1:5432/research_db' },
|
||||
{ createPool: () => fake1.pool, env: {} }
|
||||
);
|
||||
expect(() => fake1.emitter.emit('error', new Error('idle reset'))).not.toThrow();
|
||||
await handle1.close();
|
||||
|
||||
const fake2 = createFakePool();
|
||||
const handle2 = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: 'postgres://user:pass@127.0.0.1:5432/research_db' },
|
||||
{
|
||||
createPool: () => fake2.pool,
|
||||
onPoolError: () => {
|
||||
throw new Error('listener boom');
|
||||
},
|
||||
env: {},
|
||||
}
|
||||
);
|
||||
expect(() => fake2.emitter.emit('error', new Error('idle reset'))).not.toThrow();
|
||||
await handle2.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('shutdown lifecycle and query gating', () => {
|
||||
test('concurrent and repeated close() calls share one shutdown and reject new queries immediately', async () => {
|
||||
let releaseEnd: (() => void) | undefined;
|
||||
const endGate = new Promise<void>(resolve => {
|
||||
releaseEnd = resolve;
|
||||
});
|
||||
|
||||
const fake = createFakePool({
|
||||
onEnd: () => endGate,
|
||||
});
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: 'postgres://user:pass@127.0.0.1:5432/research_db' },
|
||||
{ createPool: () => fake.pool, env: {} }
|
||||
);
|
||||
|
||||
// Start concurrent close() calls while pool.end() is still pending.
|
||||
const close1 = handle.close();
|
||||
const close2 = handle.close();
|
||||
|
||||
// New query must reject immediately as soon as shutdown starts.
|
||||
let queryErr: unknown;
|
||||
try {
|
||||
await handle.executor.query('SELECT 2');
|
||||
} catch (error) {
|
||||
queryErr = error;
|
||||
}
|
||||
|
||||
expect(queryErr).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
expect((queryErr as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED');
|
||||
expect(fake.queries).toHaveLength(1); // Only the initial SELECT 1 ran.
|
||||
|
||||
releaseEnd?.();
|
||||
await Promise.all([close1, close2]);
|
||||
await handle.close();
|
||||
|
||||
expect(fake.getEndCalls()).toBe(1);
|
||||
});
|
||||
|
||||
test('forwards queries with cloned params and preserves SQLSTATE 23505', async () => {
|
||||
const fake = createFakePool({
|
||||
onQuery: async (text, values) => {
|
||||
if (text === 'SELECT 1') {
|
||||
return { rows: [{ ok: 1 }] };
|
||||
}
|
||||
if (text.startsWith('INSERT')) {
|
||||
const pgErr = Object.assign(new Error('duplicate key value violates unique constraint'), {
|
||||
code: '23505',
|
||||
});
|
||||
throw pgErr;
|
||||
}
|
||||
return { rows: [{ echo: values }] };
|
||||
},
|
||||
});
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: 'postgres://user:pass@127.0.0.1:5432/research_db' },
|
||||
{ createPool: () => fake.pool, env: {} }
|
||||
);
|
||||
|
||||
const params: readonly unknown[] = ['a', 42];
|
||||
const res = await handle.executor.query<{ echo: unknown[] }>('SELECT $1, $2', params);
|
||||
expect(res.rows).toEqual([{ echo: ['a', 42] }]);
|
||||
|
||||
let duplicateErr: unknown;
|
||||
try {
|
||||
await handle.executor.query('INSERT INTO findings VALUES ($1)', ['f-1']);
|
||||
} catch (error) {
|
||||
duplicateErr = error;
|
||||
}
|
||||
expect((duplicateErr as { code?: string }).code).toBe('23505');
|
||||
|
||||
await handle.close();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
import type { Pool } from 'pg';
|
||||
import type {
|
||||
ManagedPostgresExecutor,
|
||||
ResearchCopilotHostConfig,
|
||||
ResearchCopilotStdioHostDeps,
|
||||
} from '@stock-bot/research/mcp';
|
||||
import {
|
||||
type ManagedResearchCopilotExecutor,
|
||||
type ResearchCopilotPoolLike,
|
||||
openResearchCopilotExecutor,
|
||||
} from '../src';
|
||||
|
||||
// The managed handle returned by openResearchCopilotExecutor must satisfy ManagedPostgresExecutor.
|
||||
declare const managedHandle: ManagedResearchCopilotExecutor;
|
||||
managedHandle satisfies ManagedPostgresExecutor;
|
||||
|
||||
// The factory itself must be directly assignable to ResearchCopilotStdioHostDeps['openExecutor'].
|
||||
const openExecutor: ResearchCopilotStdioHostDeps['openExecutor'] = openResearchCopilotExecutor;
|
||||
void openExecutor;
|
||||
|
||||
// Calling openResearchCopilotExecutor with a full ResearchCopilotHostConfig returns ManagedPostgresExecutor.
|
||||
declare const hostConfig: ResearchCopilotHostConfig;
|
||||
const opened: Promise<ManagedPostgresExecutor> = openResearchCopilotExecutor(hostConfig);
|
||||
void opened;
|
||||
|
||||
// Real pg.Pool instances must satisfy the structural ResearchCopilotPoolLike interface.
|
||||
declare const realPool: Pool;
|
||||
realPool satisfies ResearchCopilotPoolLike;
|
||||
|
||||
// Missing postgresUrl must be rejected at compile time.
|
||||
// @ts-expect-error postgresUrl is required on ResearchCopilotExecutorConfig.
|
||||
void openResearchCopilotExecutor({});
|
||||
Loading…
Add table
Add a link
Reference in a new issue