428 lines
14 KiB
TypeScript
428 lines
14 KiB
TypeScript
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('accepts Unix-domain socket host query parameter and resolves domain-socket parameters in pg', async () => {
|
|
const capturedConfigs: PoolConfig[] = [];
|
|
const fakePool: ResearchCopilotExecutorPool = {
|
|
async query() {
|
|
return { rows: [{ '?column?': 1 }] };
|
|
},
|
|
async end() {},
|
|
on() {
|
|
return fakePool;
|
|
},
|
|
};
|
|
|
|
const handle = await openResearchCopilotExecutor(
|
|
{
|
|
postgresUrl:
|
|
'postgres:///research_db?host=/var/run/postgresql&statement_timeout=99999&lock_timeout=88888',
|
|
},
|
|
{
|
|
createPool(poolConfig) {
|
|
capturedConfigs.push(poolConfig);
|
|
return fakePool;
|
|
},
|
|
}
|
|
);
|
|
|
|
expect(capturedConfigs).toHaveLength(1);
|
|
const client = new Client(capturedConfigs[0]);
|
|
const params = (
|
|
client as unknown as {
|
|
connectionParameters: {
|
|
host?: string;
|
|
database?: string;
|
|
isDomainSocket?: boolean;
|
|
statement_timeout?: unknown;
|
|
lock_timeout?: unknown;
|
|
query_timeout?: unknown;
|
|
};
|
|
}
|
|
).connectionParameters;
|
|
|
|
expect(params.host).toBe('/var/run/postgresql');
|
|
expect(params.database).toBe('research_db');
|
|
expect(params.isDomainSocket).toBe(true);
|
|
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);
|
|
|
|
await handle.close();
|
|
});
|
|
|
|
test('rejects URLs missing host or database even when PGHOST and PGDATABASE are set', async () => {
|
|
const previousPgHost = process.env.PGHOST;
|
|
const previousPgDatabase = process.env.PGDATABASE;
|
|
process.env.PGHOST = '127.0.0.1';
|
|
process.env.PGDATABASE = 'fallback_db';
|
|
cleanup.push(() => {
|
|
if (previousPgHost === undefined) {
|
|
delete process.env.PGHOST;
|
|
} else {
|
|
process.env.PGHOST = previousPgHost;
|
|
}
|
|
if (previousPgDatabase === undefined) {
|
|
delete process.env.PGDATABASE;
|
|
} else {
|
|
process.env.PGDATABASE = previousPgDatabase;
|
|
}
|
|
});
|
|
|
|
let createPoolCalls = 0;
|
|
for (const postgresUrl of [
|
|
'postgres:///research_db',
|
|
'postgres://127.0.0.1:5432/',
|
|
'postgres://127.0.0.1:5432',
|
|
]) {
|
|
await expect(
|
|
openResearchCopilotExecutor(
|
|
{ postgresUrl },
|
|
{
|
|
createPool() {
|
|
createPoolCalls += 1;
|
|
return {
|
|
async query() {
|
|
return { rows: [] };
|
|
},
|
|
async end() {},
|
|
on() {
|
|
return undefined;
|
|
},
|
|
};
|
|
},
|
|
}
|
|
)
|
|
).rejects.toMatchObject({
|
|
name: 'ResearchCopilotExecutorError',
|
|
code: 'INVALID_CONFIG',
|
|
});
|
|
}
|
|
expect(createPoolCalls).toBe(0);
|
|
});
|
|
|
|
test('preserves PGOPTIONS startup precedence while enforcing executor timeouts', async () => {
|
|
const previousPgOptions = process.env.PGOPTIONS;
|
|
cleanup.push(() => {
|
|
if (previousPgOptions === undefined) {
|
|
delete process.env.PGOPTIONS;
|
|
} else {
|
|
process.env.PGOPTIONS = previousPgOptions;
|
|
}
|
|
});
|
|
|
|
const fakePool: ResearchCopilotExecutorPool = {
|
|
async query() {
|
|
return { rows: [{ '?column?': 1 }] };
|
|
},
|
|
async end() {},
|
|
on() {
|
|
return fakePool;
|
|
},
|
|
};
|
|
|
|
// 1. No URL options and no PGOPTIONS -> PoolConfig.options omitted.
|
|
delete process.env.PGOPTIONS;
|
|
let captured: PoolConfig | undefined;
|
|
const h1 = await openResearchCopilotExecutor(
|
|
{ postgresUrl: 'postgres://127.0.0.1:5432/research_db' },
|
|
{
|
|
createPool(poolConfig) {
|
|
captured = poolConfig;
|
|
return fakePool;
|
|
},
|
|
}
|
|
);
|
|
expect(captured?.options).toBeUndefined();
|
|
const c1 = new Client(captured);
|
|
const p1 = (
|
|
c1 as unknown as {
|
|
connectionParameters: {
|
|
options?: string;
|
|
statement_timeout?: unknown;
|
|
lock_timeout?: unknown;
|
|
};
|
|
}
|
|
).connectionParameters;
|
|
expect(p1.options).toBeUndefined();
|
|
expect(p1.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS);
|
|
expect(p1.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS);
|
|
await h1.close();
|
|
|
|
// 2. PGOPTIONS set with no URL options -> PGOPTIONS preserved + executor timeouts appended.
|
|
process.env.PGOPTIONS = '-c search_path=research -c statement_timeout=99999 -c lock_timeout=88888';
|
|
captured = undefined;
|
|
const h2 = await openResearchCopilotExecutor(
|
|
{ postgresUrl: 'postgres://127.0.0.1:5432/research_db' },
|
|
{
|
|
createPool(poolConfig) {
|
|
captured = poolConfig;
|
|
return fakePool;
|
|
},
|
|
}
|
|
);
|
|
expect(captured?.options).toBe(
|
|
`-c search_path=research -c statement_timeout=99999 -c lock_timeout=88888 ` +
|
|
`-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`
|
|
);
|
|
const c2 = new Client(captured);
|
|
const p2 = (
|
|
c2 as unknown as { connectionParameters: { options?: string } }
|
|
).connectionParameters;
|
|
expect(p2.options).toBe(captured?.options);
|
|
await h2.close();
|
|
|
|
// 3. Both URL options and PGOPTIONS set -> URL options wins over PGOPTIONS, timeouts still appended.
|
|
process.env.PGOPTIONS = '-c search_path=env_schema';
|
|
captured = undefined;
|
|
const h3 = await openResearchCopilotExecutor(
|
|
{
|
|
postgresUrl:
|
|
'postgres://127.0.0.1:5432/research_db?options=-c%20search_path%3Durl_schema',
|
|
},
|
|
{
|
|
createPool(poolConfig) {
|
|
captured = poolConfig;
|
|
return fakePool;
|
|
},
|
|
}
|
|
);
|
|
expect(captured?.options).toBe(
|
|
`-c search_path=url_schema ` +
|
|
`-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`
|
|
);
|
|
await h3.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/);
|
|
});
|
|
});
|