T-197: M2.1t (port to master) — Real PostgreSQL executor factory for the MCP copilot stdio host: restore openResearchCopilotExecutor(config) in libs/data/postgres/src/research-copilot-executor.ts from prior branch studio/auto-db2c48b5 (T-189) onto master (no new deps, no DuckDB, no bin)
This commit is contained in:
parent
8fd525ce4e
commit
4315d956ea
7 changed files with 1347 additions and 1 deletions
235
libs/data/postgres/test/research-copilot-executor-edge.test.ts
Normal file
235
libs/data/postgres/test/research-copilot-executor-edge.test.ts
Normal file
|
|
@ -0,0 +1,235 @@
|
|||
import { readFileSync } from 'node:fs';
|
||||
import { createServer, type AddressInfo, type Socket } from 'node:net';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Client, Pool, 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 ResearchCopilotExecutorPool,
|
||||
openResearchCopilotExecutor,
|
||||
} from '../src/index';
|
||||
|
||||
const cleanup: Array<() => Promise<void> | void> = [];
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanup.splice(0).reverse()) {
|
||||
await fn();
|
||||
}
|
||||
});
|
||||
|
||||
describe('openResearchCopilotExecutor edge cases', () => {
|
||||
test('strips URL timeout overrides while preserving search_path and enforcing executor timeouts', async () => {
|
||||
const capturedConfigs: PoolConfig[] = [];
|
||||
const fakePool: ResearchCopilotExecutorPool = {
|
||||
async query() {
|
||||
return { rows: [{ '?column?': 1 }] };
|
||||
},
|
||||
async end() {},
|
||||
on() {
|
||||
return fakePool;
|
||||
},
|
||||
};
|
||||
|
||||
const hostileUrl =
|
||||
'postgres://u:p@127.0.0.1:5432/research_db' +
|
||||
'?sslmode=disable' +
|
||||
'&application_name=copilot_edge' +
|
||||
'&statement_timeout=99999' +
|
||||
'&LOCK_TIMEOUT=88888' +
|
||||
'&query_timeout=77777' +
|
||||
'&connect_timeout=66' +
|
||||
'&connectionTimeoutMillis=55555' +
|
||||
'&options=-c%20search_path%3Disolated_schema%20-c%20statement_timeout%3D60000%20-c%20lock_timeout%3D60000';
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: hostileUrl },
|
||||
{
|
||||
createPool(poolConfig) {
|
||||
capturedConfigs.push(poolConfig);
|
||||
return fakePool;
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
expect(capturedConfigs).toHaveLength(1);
|
||||
const poolConfig = capturedConfigs[0]!;
|
||||
const normalizedUrl = new URL(poolConfig.connectionString!);
|
||||
expect(normalizedUrl.searchParams.get('sslmode')).toBe('disable');
|
||||
expect(normalizedUrl.searchParams.get('application_name')).toBe('copilot_edge');
|
||||
expect(normalizedUrl.searchParams.has('statement_timeout')).toBe(false);
|
||||
expect(normalizedUrl.searchParams.has('LOCK_TIMEOUT')).toBe(false);
|
||||
expect(normalizedUrl.searchParams.has('query_timeout')).toBe(false);
|
||||
expect(normalizedUrl.searchParams.has('connect_timeout')).toBe(false);
|
||||
expect(normalizedUrl.searchParams.has('connectionTimeoutMillis')).toBe(false);
|
||||
expect(normalizedUrl.searchParams.has('options')).toBe(false);
|
||||
|
||||
expect(poolConfig.options).toBe(
|
||||
`-c search_path=isolated_schema -c statement_timeout=60000 -c lock_timeout=60000 ` +
|
||||
`-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`
|
||||
);
|
||||
|
||||
// Verify pg's own ConnectionParameters parser resolves the enforced timeouts.
|
||||
const client = new Client(poolConfig);
|
||||
const params = (
|
||||
client as unknown as {
|
||||
connectionParameters: {
|
||||
statement_timeout?: unknown;
|
||||
lock_timeout?: unknown;
|
||||
query_timeout?: unknown;
|
||||
connect_timeout?: unknown;
|
||||
options?: string;
|
||||
application_name?: string;
|
||||
};
|
||||
}
|
||||
).connectionParameters;
|
||||
|
||||
expect(params.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS);
|
||||
expect(params.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS);
|
||||
expect(params.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS);
|
||||
expect(params.connect_timeout).toBe(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS / 1000);
|
||||
expect(params.application_name).toBe('copilot_edge');
|
||||
expect(params.options).toBe(poolConfig.options);
|
||||
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
test('absorbs idle-client pool error events without crashing the process', async () => {
|
||||
const errorListeners: Array<(error: Error) => void> = [];
|
||||
const fakePool: ResearchCopilotExecutorPool = {
|
||||
async query(text) {
|
||||
return { rows: [{ sql: text }] };
|
||||
},
|
||||
async end() {},
|
||||
on(event, listener) {
|
||||
if (event === 'error') {
|
||||
errorListeners.push(listener);
|
||||
}
|
||||
return fakePool;
|
||||
},
|
||||
};
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: 'postgres://127.0.0.1:5432/research_db' },
|
||||
{ createPool: () => fakePool }
|
||||
);
|
||||
|
||||
expect(errorListeners).toHaveLength(1);
|
||||
expect(() => errorListeners[0]!(new Error('idle client disconnected'))).not.toThrow();
|
||||
|
||||
const res = await handle.executor.query<{ sql: string }>('SELECT 2');
|
||||
expect(res.rows).toEqual([{ sql: 'SELECT 2' }]);
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
test('deduplicates concurrent close() calls and rejects queries started during shutdown', async () => {
|
||||
let resolveEnd!: () => void;
|
||||
let endCalls = 0;
|
||||
let queryCalls = 0;
|
||||
|
||||
const fakePool: ResearchCopilotExecutorPool = {
|
||||
async query() {
|
||||
queryCalls += 1;
|
||||
return { rows: [] };
|
||||
},
|
||||
end() {
|
||||
endCalls += 1;
|
||||
return new Promise<void>(resolve => {
|
||||
resolveEnd = resolve;
|
||||
});
|
||||
},
|
||||
on() {
|
||||
return fakePool;
|
||||
},
|
||||
};
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: 'postgres://127.0.0.1:5432/research_db' },
|
||||
{ createPool: () => fakePool }
|
||||
);
|
||||
expect(queryCalls).toBe(1);
|
||||
|
||||
const closeA = handle.close();
|
||||
const closeB = handle.close();
|
||||
|
||||
// Even while pool.end() is still in flight, new queries must reject immediately.
|
||||
await expect(handle.executor.query('SELECT 2')).rejects.toMatchObject({
|
||||
name: 'ResearchCopilotExecutorError',
|
||||
code: 'EXECUTOR_CLOSED',
|
||||
});
|
||||
expect(queryCalls).toBe(1);
|
||||
expect(endCalls).toBe(1);
|
||||
|
||||
resolveEnd();
|
||||
await Promise.all([closeA, closeB]);
|
||||
expect(endCalls).toBe(1);
|
||||
});
|
||||
|
||||
test('rejects with sanitized OPEN_FAILED when a real pg.Pool times out against a silent loopback listener', async () => {
|
||||
const sockets = new Set<Socket>();
|
||||
const server = createServer(socket => {
|
||||
sockets.add(socket);
|
||||
socket.on('close', () => sockets.delete(socket));
|
||||
// Intentionally accept and never reply so pg hits its connection timeout.
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once('error', reject);
|
||||
server.listen(0, '127.0.0.1', () => resolve());
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
for (const socket of sockets) {
|
||||
socket.destroy();
|
||||
}
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
});
|
||||
|
||||
const { port } = server.address() as AddressInfo;
|
||||
const secretPass = 'LoopbackSecretPass99';
|
||||
const loopbackUrl = `postgres://loopback_user:${secretPass}@127.0.0.1:${port}/research_db`;
|
||||
|
||||
let observedConfig: PoolConfig | undefined;
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor(
|
||||
{ postgresUrl: loopbackUrl },
|
||||
{
|
||||
createPool(poolConfig) {
|
||||
observedConfig = poolConfig;
|
||||
// Keep the default config assertions intact, but tighten connect timeout for fast local test execution.
|
||||
return new Pool({
|
||||
...poolConfig,
|
||||
connectionTimeoutMillis: 150,
|
||||
});
|
||||
},
|
||||
}
|
||||
);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
expect(observedConfig?.max).toBe(RESEARCH_COPILOT_PG_POOL_MAX);
|
||||
expect(observedConfig?.connectionTimeoutMillis).toBe(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS);
|
||||
expect(observedConfig?.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS);
|
||||
expect(caught).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
const typed = caught as ResearchCopilotExecutorError;
|
||||
expect(typed.code).toBe('OPEN_FAILED');
|
||||
expect((typed as { cause?: unknown }).cause).toBeUndefined();
|
||||
expect(typed.message).not.toContain('loopback_user');
|
||||
expect(typed.message).not.toContain(secretPass);
|
||||
expect(typed.message).not.toContain('127.0.0.1');
|
||||
expect(typed.message).not.toContain(String(port));
|
||||
});
|
||||
|
||||
test('has no runtime import of @stock-bot/research', () => {
|
||||
const sourcePath = fileURLToPath(
|
||||
new URL('../src/research-copilot-executor.ts', import.meta.url)
|
||||
);
|
||||
const source = readFileSync(sourcePath, 'utf8');
|
||||
expect(source).not.toMatch(/from\s+['"]@stock-bot\/research/);
|
||||
expect(source).not.toMatch(/require\(\s*['"]@stock-bot\/research/);
|
||||
});
|
||||
});
|
||||
380
libs/data/postgres/test/research-copilot-executor.test.ts
Normal file
380
libs/data/postgres/test/research-copilot-executor.test.ts
Normal file
|
|
@ -0,0 +1,380 @@
|
|||
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 ResearchCopilotExecutorPool,
|
||||
openResearchCopilotExecutor,
|
||||
} from '../src/index';
|
||||
|
||||
const SECRET_USER = 'copilot_secret_user';
|
||||
const SECRET_PASS = 'Sup3rS3cretP@ssw0rd!';
|
||||
const SECRET_HOST = 'pg-internal-secret.example.test';
|
||||
const VALID_URL = `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`;
|
||||
|
||||
interface FakePoolState {
|
||||
readonly queries: Array<{ readonly text: string; readonly values?: unknown[] }>;
|
||||
readonly errorListeners: Array<(error: Error) => void>;
|
||||
endCalls: number;
|
||||
readonly pool: ResearchCopilotExecutorPool;
|
||||
}
|
||||
|
||||
function createFakePool(options?: {
|
||||
onQuery?: (text: string, values?: unknown[]) => Promise<{ readonly rows: readonly unknown[] }>;
|
||||
onEnd?: () => Promise<void>;
|
||||
}): FakePoolState {
|
||||
const queries: Array<{ readonly text: string; readonly values?: unknown[] }> = [];
|
||||
const errorListeners: Array<(error: Error) => void> = [];
|
||||
const state: FakePoolState = {
|
||||
queries,
|
||||
errorListeners,
|
||||
endCalls: 0,
|
||||
pool: {
|
||||
async query(text: string, values?: unknown[]) {
|
||||
queries.push(values === undefined ? { text } : { text, values });
|
||||
if (options?.onQuery) {
|
||||
return options.onQuery(text, values);
|
||||
}
|
||||
return { rows: [] };
|
||||
},
|
||||
async end() {
|
||||
state.endCalls += 1;
|
||||
if (options?.onEnd) {
|
||||
return options.onEnd();
|
||||
}
|
||||
},
|
||||
on(event: 'error', listener: (error: Error) => void) {
|
||||
if (event === 'error') {
|
||||
errorListeners.push(listener);
|
||||
}
|
||||
return state.pool;
|
||||
},
|
||||
},
|
||||
};
|
||||
return state;
|
||||
}
|
||||
|
||||
function assertNoSecretsLeaked(error: unknown): void {
|
||||
expect(error).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
const typed = error as ResearchCopilotExecutorError;
|
||||
expect((typed as { cause?: unknown }).cause).toBeUndefined();
|
||||
const message = typed.message;
|
||||
for (const needle of [
|
||||
VALID_URL,
|
||||
SECRET_USER,
|
||||
SECRET_PASS,
|
||||
encodeURIComponent(SECRET_PASS),
|
||||
SECRET_HOST,
|
||||
'raw-pg-secret',
|
||||
]) {
|
||||
expect(message).not.toContain(needle);
|
||||
}
|
||||
}
|
||||
|
||||
describe('openResearchCopilotExecutor', () => {
|
||||
test('opens a bounded pg pool, probes once with SELECT 1, and attaches an error listener', async () => {
|
||||
const capturedConfigs: PoolConfig[] = [];
|
||||
const fake = createFakePool({
|
||||
async onQuery(text) {
|
||||
if (text === 'SELECT 1') {
|
||||
return { rows: [{ '?column?': 1 }] };
|
||||
}
|
||||
return { rows: [{ id: 42 }] };
|
||||
},
|
||||
});
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: VALID_URL },
|
||||
{
|
||||
createPool(poolConfig) {
|
||||
capturedConfigs.push(poolConfig);
|
||||
return fake.pool;
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
expect(capturedConfigs).toHaveLength(1);
|
||||
expect(capturedConfigs[0]).toEqual({
|
||||
connectionString: VALID_URL,
|
||||
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,
|
||||
options: `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`,
|
||||
});
|
||||
expect(RESEARCH_COPILOT_PG_POOL_MAX).toBe(4);
|
||||
expect(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS).toBe(5_000);
|
||||
expect(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS).toBe(10_000);
|
||||
expect(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS).toBe(15_000);
|
||||
expect(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS).toBe(2_000);
|
||||
|
||||
expect(fake.errorListeners).toHaveLength(1);
|
||||
expect(fake.queries).toEqual([{ text: 'SELECT 1' }]);
|
||||
|
||||
const res = await handle.executor.query<{ id: number }>('SELECT $1::int AS id', [42]);
|
||||
expect(res.rows).toEqual([{ id: 42 }]);
|
||||
expect(fake.queries).toEqual([
|
||||
{ text: 'SELECT 1' },
|
||||
{ text: 'SELECT $1::int AS id', values: [42] },
|
||||
]);
|
||||
|
||||
await handle.close();
|
||||
expect(fake.endCalls).toBe(1);
|
||||
});
|
||||
|
||||
test('accepts postgresql:// scheme as well as postgres://', async () => {
|
||||
const fake = createFakePool();
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: 'postgresql://127.0.0.1:5432/research_db' },
|
||||
{ createPool: () => fake.pool }
|
||||
);
|
||||
expect(fake.queries).toEqual([{ text: 'SELECT 1' }]);
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
test('rejects invalid URLs with INVALID_CONFIG before constructing a pool', async () => {
|
||||
const invalidUrls = [
|
||||
'',
|
||||
' ',
|
||||
` ${VALID_URL} `,
|
||||
`${VALID_URL}\n`,
|
||||
'not-a-url',
|
||||
`http://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`,
|
||||
`mysql://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:3306/research_db`,
|
||||
'postgres:///research_db',
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/%20%20`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/db/extra`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:0/research_db`,
|
||||
`postgres://%ZZ:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`,
|
||||
`postgres://${SECRET_USER}:%ZZ@${SECRET_HOST}:5432/research_db`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/%ZZ`,
|
||||
];
|
||||
|
||||
let createPoolCalls = 0;
|
||||
for (const postgresUrl of invalidUrls) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor(
|
||||
{ postgresUrl },
|
||||
{
|
||||
createPool() {
|
||||
createPoolCalls += 1;
|
||||
return createFakePool().pool;
|
||||
},
|
||||
}
|
||||
);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
assertNoSecretsLeaked(caught);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('INVALID_CONFIG');
|
||||
}
|
||||
expect(createPoolCalls).toBe(0);
|
||||
});
|
||||
|
||||
test('rejects malformed config or deps with INVALID_CONFIG', async () => {
|
||||
await expect(
|
||||
openResearchCopilotExecutor(null as unknown as { postgresUrl: string })
|
||||
).rejects.toMatchObject({
|
||||
name: 'ResearchCopilotExecutorError',
|
||||
code: 'INVALID_CONFIG',
|
||||
});
|
||||
|
||||
await expect(
|
||||
openResearchCopilotExecutor(
|
||||
{ postgresUrl: VALID_URL },
|
||||
{ createPool: 'not-a-fn' as unknown as () => ResearchCopilotExecutorPool }
|
||||
)
|
||||
).rejects.toMatchObject({
|
||||
name: 'ResearchCopilotExecutorError',
|
||||
code: 'INVALID_CONFIG',
|
||||
});
|
||||
});
|
||||
|
||||
test('ends pool and throws sanitized OPEN_FAILED when startup probe fails', async () => {
|
||||
const fake = createFakePool({
|
||||
async onQuery() {
|
||||
throw new Error(`password authentication failed for ${SECRET_USER} at ${SECRET_HOST} raw-pg-secret`);
|
||||
},
|
||||
});
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor({ postgresUrl: VALID_URL }, { createPool: () => fake.pool });
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
assertNoSecretsLeaked(caught);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('OPEN_FAILED');
|
||||
expect(fake.endCalls).toBe(1);
|
||||
});
|
||||
|
||||
test('still throws OPEN_FAILED when both probe and cleanup end() fail', async () => {
|
||||
const fake = createFakePool({
|
||||
async onQuery() {
|
||||
throw new Error(`connect ECONNREFUSED ${SECRET_HOST} raw-pg-secret`);
|
||||
},
|
||||
async onEnd() {
|
||||
throw new Error(`pool end failed ${VALID_URL}`);
|
||||
},
|
||||
});
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor({ postgresUrl: VALID_URL }, { createPool: () => fake.pool });
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
assertNoSecretsLeaked(caught);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('OPEN_FAILED');
|
||||
expect(fake.endCalls).toBe(1);
|
||||
});
|
||||
|
||||
test('forwards parameters defensively without mutating caller arrays', async () => {
|
||||
const fake = createFakePool({
|
||||
async onQuery(text, values) {
|
||||
if (values) {
|
||||
values.push('mutated-by-driver');
|
||||
}
|
||||
return { rows: [{ text }] };
|
||||
},
|
||||
});
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: VALID_URL },
|
||||
{ createPool: () => fake.pool }
|
||||
);
|
||||
|
||||
const callerParams = Object.freeze(['alpha', 7]);
|
||||
const res = await handle.executor.query('SELECT $1, $2', callerParams);
|
||||
expect(res.rows).toEqual([{ text: 'SELECT $1, $2' }]);
|
||||
expect(callerParams).toEqual(['alpha', 7]);
|
||||
|
||||
await handle.executor.query('SELECT 2');
|
||||
expect(fake.queries[2]).toEqual({ text: 'SELECT 2' });
|
||||
expect('values' in fake.queries[2]!).toBe(false);
|
||||
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
test('preserves SQLSTATE 23505 on sanitized unique-violation query errors', async () => {
|
||||
let callCount = 0;
|
||||
const fake = createFakePool({
|
||||
async onQuery() {
|
||||
callCount += 1;
|
||||
if (callCount === 1) {
|
||||
return { rows: [{ '?column?': 1 }] };
|
||||
}
|
||||
const pgErr = Object.assign(
|
||||
new Error(`duplicate key value violates unique constraint on ${SECRET_HOST} raw-pg-secret`),
|
||||
{ code: '23505', detail: `Key (id)=(dup-1) already exists (${SECRET_PASS})` }
|
||||
);
|
||||
throw pgErr;
|
||||
},
|
||||
});
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: VALID_URL },
|
||||
{ createPool: () => fake.pool }
|
||||
);
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await handle.executor.query('INSERT INTO findings (id) VALUES ($1)', ['dup-1']);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
assertNoSecretsLeaked(caught);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('23505');
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
test('sanitizes generic query errors to QUERY_FAILED with no cause or raw text', async () => {
|
||||
let callCount = 0;
|
||||
const fake = createFakePool({
|
||||
async onQuery() {
|
||||
callCount += 1;
|
||||
if (callCount === 1) {
|
||||
return { rows: [{ '?column?': 1 }] };
|
||||
}
|
||||
throw Object.assign(
|
||||
new Error(`relation "missing" does not exist on ${VALID_URL} raw-pg-secret`),
|
||||
{ code: '42P01' }
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: VALID_URL },
|
||||
{ createPool: () => fake.pool }
|
||||
);
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await handle.executor.query('SELECT * FROM missing');
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
assertNoSecretsLeaked(caught);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('QUERY_FAILED');
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
test('close() is idempotent and subsequent queries fail with EXECUTOR_CLOSED', async () => {
|
||||
const fake = createFakePool();
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: VALID_URL },
|
||||
{ createPool: () => fake.pool }
|
||||
);
|
||||
|
||||
await handle.close();
|
||||
await handle.close();
|
||||
expect(fake.endCalls).toBe(1);
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await handle.executor.query('SELECT 1');
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
assertNoSecretsLeaked(caught);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED');
|
||||
expect(fake.queries).toHaveLength(1); // Only the initial SELECT 1 probe ran.
|
||||
});
|
||||
|
||||
test('sanitizes pool.end() failures to CLOSE_FAILED with no cause or secret leakage', async () => {
|
||||
const fake = createFakePool({
|
||||
async onEnd() {
|
||||
throw new Error(`failed closing pool for ${VALID_URL} raw-pg-secret`);
|
||||
},
|
||||
});
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: VALID_URL },
|
||||
{ createPool: () => fake.pool }
|
||||
);
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await handle.close();
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
assertNoSecretsLeaked(caught);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('CLOSE_FAILED');
|
||||
expect(fake.endCalls).toBe(1);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
import type { Pool } from 'pg';
|
||||
import type {
|
||||
ManagedPostgresExecutor,
|
||||
PostgresResearchCopilotExecutor,
|
||||
ResearchCopilotHostConfig,
|
||||
ResearchCopilotStdioHostDeps,
|
||||
} from '@stock-bot/research/mcp';
|
||||
import {
|
||||
type ManagedResearchCopilotExecutor,
|
||||
type ResearchCopilotExecutor,
|
||||
type ResearchCopilotExecutorConfig,
|
||||
type ResearchCopilotExecutorDeps,
|
||||
type ResearchCopilotExecutorError,
|
||||
type ResearchCopilotExecutorErrorCode,
|
||||
type ResearchCopilotExecutorPool,
|
||||
openResearchCopilotExecutor,
|
||||
} from '../src/index';
|
||||
|
||||
// The factory must plug directly into ResearchCopilotStdioHostDeps.openExecutor.
|
||||
openResearchCopilotExecutor satisfies ResearchCopilotStdioHostDeps['openExecutor'];
|
||||
|
||||
// Full host config is structurally assignable to the minimal executor config.
|
||||
declare const hostConfig: ResearchCopilotHostConfig;
|
||||
hostConfig satisfies ResearchCopilotExecutorConfig;
|
||||
|
||||
// Returned handle and executor are structurally assignable to the MCP host ports.
|
||||
declare const managedHandle: ManagedResearchCopilotExecutor;
|
||||
managedHandle satisfies ManagedPostgresExecutor;
|
||||
|
||||
declare const executor: ResearchCopilotExecutor;
|
||||
executor satisfies PostgresResearchCopilotExecutor;
|
||||
|
||||
// Real pg.Pool satisfies the injected pool contract.
|
||||
declare const pgPool: Pool;
|
||||
pgPool satisfies ResearchCopilotExecutorPool;
|
||||
|
||||
// Optional deps contract accepts createPool returning pg.Pool.
|
||||
const validDeps: ResearchCopilotExecutorDeps = {
|
||||
createPool: () => pgPool,
|
||||
};
|
||||
void validDeps;
|
||||
|
||||
// Error code union includes all sanitized lifecycle codes plus SQLSTATE 23505.
|
||||
declare const errorInstance: ResearchCopilotExecutorError;
|
||||
const errorCode: ResearchCopilotExecutorErrorCode = errorInstance.code;
|
||||
void errorCode;
|
||||
|
||||
// Negative checks: missing postgresUrl must fail typechecking.
|
||||
// @ts-expect-error postgresUrl is required.
|
||||
void openResearchCopilotExecutor({});
|
||||
Loading…
Add table
Add a link
Reference in a new issue