Compare commits
9 commits
b51ce9b22b
...
042409393e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
042409393e | ||
|
|
9d39380ca8 | ||
|
|
4315d956ea | ||
|
|
8fd525ce4e | ||
|
|
524114411a | ||
|
|
23ec7df52f | ||
|
|
77803bb20d | ||
|
|
b1f2c3bd0c | ||
|
|
e9fbea3dda |
14 changed files with 2808 additions and 5 deletions
|
|
@ -1,6 +1,21 @@
|
|||
export { PostgreSQLClient } from './client';
|
||||
export { PostgreSQLTransactionManager } from './transactions';
|
||||
export { runPostgresMigrations, type MigrationTrack } from './migrations';
|
||||
export {
|
||||
RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS,
|
||||
RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS,
|
||||
RESEARCH_COPILOT_PG_POOL_MAX,
|
||||
RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS,
|
||||
RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS,
|
||||
ResearchCopilotExecutorError,
|
||||
openResearchCopilotExecutor,
|
||||
type ManagedResearchCopilotExecutor,
|
||||
type ResearchCopilotExecutor,
|
||||
type ResearchCopilotExecutorConfig,
|
||||
type ResearchCopilotExecutorDeps,
|
||||
type ResearchCopilotExecutorErrorCode,
|
||||
type ResearchCopilotExecutorPool,
|
||||
} from './research-copilot-executor';
|
||||
export type {
|
||||
ConnectionEvents,
|
||||
PoolMetrics,
|
||||
|
|
|
|||
357
libs/data/postgres/src/research-copilot-executor.ts
Normal file
357
libs/data/postgres/src/research-copilot-executor.ts
Normal file
|
|
@ -0,0 +1,357 @@
|
|||
/**
|
||||
* Real PostgreSQL executor factory for the MCP research copilot stdio host.
|
||||
*
|
||||
* 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 number of PostgreSQL connections in the copilot executor pool. */
|
||||
export const RESEARCH_COPILOT_PG_POOL_MAX = 4;
|
||||
|
||||
/** TCP/startup connection timeout in milliseconds. */
|
||||
export const RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS = 5_000;
|
||||
|
||||
/** Server-side PostgreSQL `statement_timeout` in milliseconds. */
|
||||
export const RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS = 10_000;
|
||||
|
||||
/** Driver-side `pg` `query_timeout` in milliseconds. */
|
||||
export const RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS = 15_000;
|
||||
|
||||
/** Server-side PostgreSQL `lock_timeout` in milliseconds. */
|
||||
export const RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS = 2_000;
|
||||
|
||||
/** Typed error codes emitted by {@link ResearchCopilotExecutorError}. */
|
||||
export type ResearchCopilotExecutorErrorCode =
|
||||
| 'INVALID_CONFIG'
|
||||
| 'OPEN_FAILED'
|
||||
| 'QUERY_FAILED'
|
||||
| 'EXECUTOR_CLOSED'
|
||||
| 'CLOSE_FAILED'
|
||||
| '23505';
|
||||
|
||||
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 STRIPPED_TIMEOUT_PARAMS: ReadonlySet<string> = new Set([
|
||||
'statement_timeout',
|
||||
'lock_timeout',
|
||||
'query_timeout',
|
||||
'connect_timeout',
|
||||
'connectiontimeoutmillis',
|
||||
]);
|
||||
|
||||
const CONTROL_CHAR_RE = /[\r\n\0]/;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
|
||||
constructor(code: ResearchCopilotExecutorErrorCode, message: string) {
|
||||
super(message);
|
||||
this.name = 'ResearchCopilotExecutorError';
|
||||
this.code = code;
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
/** Configuration accepted by {@link openResearchCopilotExecutor}. */
|
||||
export interface ResearchCopilotExecutorConfig {
|
||||
readonly postgresUrl: string;
|
||||
}
|
||||
|
||||
/** 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,
|
||||
params?: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Row[] }>;
|
||||
}
|
||||
|
||||
/** Managed executor handle structurally assignable to `ManagedPostgresExecutor`. */
|
||||
export interface ManagedResearchCopilotExecutor {
|
||||
readonly executor: ResearchCopilotExecutor;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
function invalidConfigError(): ResearchCopilotExecutorError {
|
||||
return new ResearchCopilotExecutorError('INVALID_CONFIG', ERROR_MESSAGES.INVALID_CONFIG);
|
||||
}
|
||||
|
||||
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)) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(rawUrl);
|
||||
} catch {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
|
||||
if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasAuthorityHost && queryHost.length === 0) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
|
||||
if (parsed.port.length > 0) {
|
||||
const portNum = Number(parsed.port);
|
||||
if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
try {
|
||||
if (parsed.username.length > 0) {
|
||||
decodeURIComponent(parsed.username);
|
||||
}
|
||||
if (parsed.password.length > 0) {
|
||||
decodeURIComponent(parsed.password);
|
||||
}
|
||||
} catch {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
|
||||
const existingOptions: string[] = [];
|
||||
const keysToDelete: string[] = [];
|
||||
for (const [key, value] of parsed.searchParams.entries()) {
|
||||
const lower = key.toLowerCase();
|
||||
if (lower === 'options') {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length > 0) {
|
||||
existingOptions.push(trimmed);
|
||||
}
|
||||
keysToDelete.push(key);
|
||||
} else if (STRIPPED_TIMEOUT_PARAMS.has(lower)) {
|
||||
keysToDelete.push(key);
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < keysToDelete.length; i += 1) {
|
||||
parsed.searchParams.delete(keysToDelete[i] as string);
|
||||
}
|
||||
|
||||
const envOptions = typeof process.env.PGOPTIONS === 'string' ? process.env.PGOPTIONS.trim() : '';
|
||||
const baseOptions = existingOptions.length > 0 ? existingOptions.join(' ') : envOptions;
|
||||
|
||||
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, probed PostgreSQL executor for the MCP research copilot
|
||||
* stdio host.
|
||||
*/
|
||||
export async function openResearchCopilotExecutor(
|
||||
config: ResearchCopilotExecutorConfig,
|
||||
deps?: ResearchCopilotExecutorDeps
|
||||
): Promise<ManagedResearchCopilotExecutor> {
|
||||
const poolConfig = parseAndNormalizePoolConfig(config);
|
||||
const createPool = resolveCreatePool(deps);
|
||||
|
||||
let pool: ResearchCopilotExecutorPool;
|
||||
try {
|
||||
pool = createPool(poolConfig);
|
||||
} catch {
|
||||
throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED);
|
||||
}
|
||||
|
||||
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 {
|
||||
// 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 {
|
||||
await safeEndPool(pool);
|
||||
throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED);
|
||||
}
|
||||
|
||||
let closed = false;
|
||||
let closePromise: Promise<void> | null = null;
|
||||
|
||||
const executor: ResearchCopilotExecutor = {
|
||||
async query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
params?: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Row[] }> {
|
||||
if (closed) {
|
||||
throw new ResearchCopilotExecutorError('EXECUTOR_CLOSED', ERROR_MESSAGES.EXECUTOR_CLOSED);
|
||||
}
|
||||
|
||||
let rawResult: { readonly rows: readonly unknown[] };
|
||||
try {
|
||||
rawResult =
|
||||
params === undefined ? await pool.query(text) : await pool.query(text, [...params]);
|
||||
} catch (error) {
|
||||
if (getPostgresErrorCode(error) === '23505') {
|
||||
throw new ResearchCopilotExecutorError('23505', ERROR_MESSAGES['23505']);
|
||||
}
|
||||
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> => {
|
||||
closed = true;
|
||||
if (closePromise === null) {
|
||||
closePromise = Promise.resolve()
|
||||
.then(() => pool.end())
|
||||
.catch(() => {
|
||||
throw new ResearchCopilotExecutorError('CLOSE_FAILED', ERROR_MESSAGES.CLOSE_FAILED);
|
||||
});
|
||||
}
|
||||
return closePromise;
|
||||
};
|
||||
|
||||
return { executor, close };
|
||||
}
|
||||
428
libs/data/postgres/test/research-copilot-executor-edge.test.ts
Normal file
428
libs/data/postgres/test/research-copilot-executor-edge.test.ts
Normal file
|
|
@ -0,0 +1,428 @@
|
|||
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/);
|
||||
});
|
||||
});
|
||||
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 { 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 previousPgOptions = process.env.PGOPTIONS;
|
||||
delete process.env.PGOPTIONS;
|
||||
try {
|
||||
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,
|
||||
});
|
||||
expect(capturedConfigs[0]?.options).toBeUndefined();
|
||||
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);
|
||||
} finally {
|
||||
if (previousPgOptions === undefined) {
|
||||
delete process.env.PGOPTIONS;
|
||||
} else {
|
||||
process.env.PGOPTIONS = previousPgOptions;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('accepts postgresql:// scheme and Unix-domain socket host query parameters', async () => {
|
||||
for (const postgresUrl of [
|
||||
'postgresql://127.0.0.1:5432/research_db',
|
||||
'postgres:///research_db?host=/var/run/postgresql',
|
||||
'postgresql:///research_db?host=/var/run/postgresql',
|
||||
]) {
|
||||
const fake = createFakePool();
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl },
|
||||
{ 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:///research_db?host=',
|
||||
'postgres:///research_db?host=%20%20',
|
||||
'postgres:///research_db?host=/var/run/postgresql&host=/tmp',
|
||||
'postgres:///research_db?HOST=/var/run/postgresql',
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?host=`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?host=/a&host=/b`,
|
||||
`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({});
|
||||
391
test/postgres/mcp-copilot-executor.test.ts
Normal file
391
test/postgres/mcp-copilot-executor.test.ts
Normal file
|
|
@ -0,0 +1,391 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Client, Pool, type PoolConfig } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import {
|
||||
PostgreSQLClient,
|
||||
RESEARCH_COPILOT_PG_POOL_MAX,
|
||||
ResearchCopilotExecutorError,
|
||||
openResearchCopilotExecutor,
|
||||
runPostgresMigrations,
|
||||
} from '@stock-bot/postgres';
|
||||
import {
|
||||
createPostgresFindingWritePort,
|
||||
createPostgresKnowledgeReaders,
|
||||
createPostgresTrialRefLookupPort,
|
||||
} from '../../libs/research/src/mcp/index';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('mcp-copilot-executor-pg-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url));
|
||||
|
||||
const VAULT_CUTOFF_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0);
|
||||
const FIXED_TS = '2026-01-15T12:34:56.789Z';
|
||||
|
||||
const cleanup: Array<() => Promise<void> | void> = [];
|
||||
afterEach(async () => {
|
||||
let firstError: unknown;
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
try {
|
||||
await close();
|
||||
} catch (err) {
|
||||
firstError ??= err;
|
||||
}
|
||||
}
|
||||
if (firstError !== undefined) {
|
||||
throw firstError;
|
||||
}
|
||||
});
|
||||
|
||||
function assertSafetyDatabaseUrl(connectionString: string | undefined): string {
|
||||
if (!connectionString) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(connectionString);
|
||||
} catch {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
const client = new Client({ connectionString });
|
||||
const effectiveDb = (
|
||||
client as unknown as { connectionParameters?: { database?: unknown } }
|
||||
).connectionParameters?.database;
|
||||
if (
|
||||
typeof effectiveDb !== 'string' ||
|
||||
!effectiveDb.startsWith('stock_bot_safety') ||
|
||||
!parsed.pathname.startsWith('/stock_bot_safety')
|
||||
) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
return connectionString;
|
||||
}
|
||||
|
||||
function buildIsolatedPoolConfig(connectionString: string, schema: string): PoolConfig {
|
||||
const safeUrl = assertSafetyDatabaseUrl(connectionString);
|
||||
const parsed = new URL(safeUrl);
|
||||
const existingOptions = parsed.searchParams
|
||||
.getAll('options')
|
||||
.map(value => value.trim())
|
||||
.filter(value => value.length > 0);
|
||||
parsed.searchParams.delete('options');
|
||||
|
||||
const options = [
|
||||
...existingOptions,
|
||||
`-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`,
|
||||
].join(' ');
|
||||
|
||||
return {
|
||||
connectionString: parsed.toString(),
|
||||
options,
|
||||
};
|
||||
}
|
||||
|
||||
function buildExecutorUrl(
|
||||
connectionString: string,
|
||||
schema: string,
|
||||
applicationName: string,
|
||||
extraParams?: Readonly<Record<string, string>>
|
||||
): string {
|
||||
const safeUrl = assertSafetyDatabaseUrl(connectionString);
|
||||
const parsed = new URL(safeUrl);
|
||||
const existingOptions = parsed.searchParams
|
||||
.getAll('options')
|
||||
.map(value => value.trim())
|
||||
.filter(value => value.length > 0);
|
||||
parsed.searchParams.delete('options');
|
||||
const combinedOptions = [...existingOptions, `-c search_path=${schema}`].join(' ');
|
||||
parsed.searchParams.set('options', combinedOptions);
|
||||
parsed.searchParams.set('application_name', applicationName);
|
||||
if (extraParams) {
|
||||
for (const [k, v] of Object.entries(extraParams)) {
|
||||
parsed.searchParams.set(k, v);
|
||||
}
|
||||
}
|
||||
return parsed.toString();
|
||||
}
|
||||
|
||||
async function createIsolatedFixture(connectionString: string | undefined = url) {
|
||||
const safeUrl = assertSafetyDatabaseUrl(connectionString);
|
||||
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
|
||||
const admin = new Pool({ connectionString: safeUrl });
|
||||
cleanup.push(() => admin.end());
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
cleanup.push(() => admin.query(`DROP SCHEMA ${schema} CASCADE`).then(() => undefined));
|
||||
|
||||
const setupPool = new Pool(buildIsolatedPoolConfig(safeUrl, schema));
|
||||
cleanup.push(() => setupPool.end());
|
||||
|
||||
const { rows: schemaRows } = await setupPool.query<{ current_schema: string | null }>(
|
||||
'SELECT current_schema() AS current_schema'
|
||||
);
|
||||
if (schemaRows[0]?.current_schema !== schema) {
|
||||
throw new Error(
|
||||
`Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}`
|
||||
);
|
||||
}
|
||||
|
||||
for (const filename of [
|
||||
'06-create-backtest-tables.sql',
|
||||
'07-fix-execution-time-type.sql',
|
||||
'08-create-runs-table.sql',
|
||||
]) {
|
||||
await setupPool.query(readFileSync(`${initDir}${filename}`, 'utf8'));
|
||||
}
|
||||
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', {
|
||||
get: () => ({
|
||||
connect: () => setupPool.connect(),
|
||||
}),
|
||||
});
|
||||
|
||||
await runPostgresMigrations(postgres, { track: 'research' });
|
||||
|
||||
return { admin, setupPool, schema, safeUrl };
|
||||
}
|
||||
|
||||
async function waitForZeroBackends(admin: Pool, applicationName: string): Promise<number> {
|
||||
const deadline = Date.now() + 2_000;
|
||||
let count = -1;
|
||||
while (Date.now() < deadline) {
|
||||
const { rows } = await admin.query<{ c: number }>(
|
||||
'SELECT count(*)::int AS c FROM pg_stat_activity WHERE application_name = $1',
|
||||
[applicationName]
|
||||
);
|
||||
count = rows[0]?.c ?? -1;
|
||||
if (count === 0) {
|
||||
return 0;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 25));
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
describe('PostgreSQL MCP copilot executor safety guard', () => {
|
||||
test('rejects missing or non-safety database URLs', () => {
|
||||
expect(() => assertSafetyDatabaseUrl(undefined)).toThrow(
|
||||
'Dedicated stock_bot_safety database required'
|
||||
);
|
||||
expect(() =>
|
||||
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot')
|
||||
).toThrow('Dedicated stock_bot_safety database required');
|
||||
expect(() =>
|
||||
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev')
|
||||
).toThrow('Dedicated stock_bot_safety database required');
|
||||
expect(
|
||||
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test')
|
||||
).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test');
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(!url)('PostgreSQL MCP copilot executor (real PostgreSQL)', () => {
|
||||
test('enforces effective 10s statement_timeout and 2s lock_timeout even when URL specifies overrides', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const appName = `copilot_timeouts_${randomUUID().slice(0, 8)}`;
|
||||
const executorUrl = buildExecutorUrl(f.safeUrl, f.schema, appName, {
|
||||
statement_timeout: '99999',
|
||||
lock_timeout: '99999',
|
||||
query_timeout: '99999',
|
||||
});
|
||||
|
||||
const handle = await openResearchCopilotExecutor({ postgresUrl: executorUrl });
|
||||
cleanup.push(() => handle.close());
|
||||
|
||||
const { rows: stmtRows } = await handle.executor.query<{ statement_timeout: string }>(
|
||||
'SHOW statement_timeout'
|
||||
);
|
||||
const { rows: lockRows } = await handle.executor.query<{ lock_timeout: string }>(
|
||||
'SHOW lock_timeout'
|
||||
);
|
||||
|
||||
expect(stmtRows[0]?.statement_timeout).toBe('10s');
|
||||
expect(lockRows[0]?.lock_timeout).toBe('2s');
|
||||
});
|
||||
|
||||
test('preserves PGOPTIONS search_path when URL omits options while enforcing 10s/2s timeouts', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const appName = `copilot_pgoptions_${randomUUID().slice(0, 8)}`;
|
||||
|
||||
// Build a URL with NO options query parameter so pg must honor PGOPTIONS.
|
||||
const parsed = new URL(f.safeUrl);
|
||||
parsed.searchParams.delete('options');
|
||||
parsed.searchParams.set('application_name', appName);
|
||||
|
||||
const previousPgOptions = process.env.PGOPTIONS;
|
||||
process.env.PGOPTIONS = `-c search_path=${f.schema} -c statement_timeout=99999 -c lock_timeout=88888`;
|
||||
cleanup.push(() => {
|
||||
if (previousPgOptions === undefined) {
|
||||
delete process.env.PGOPTIONS;
|
||||
} else {
|
||||
process.env.PGOPTIONS = previousPgOptions;
|
||||
}
|
||||
});
|
||||
|
||||
const handle = await openResearchCopilotExecutor({ postgresUrl: parsed.toString() });
|
||||
cleanup.push(() => handle.close());
|
||||
|
||||
const { rows: schemaRows } = await handle.executor.query<{ current_schema: string | null }>(
|
||||
'SELECT current_schema() AS current_schema'
|
||||
);
|
||||
const { rows: stmtRows } = await handle.executor.query<{ statement_timeout: string }>(
|
||||
'SHOW statement_timeout'
|
||||
);
|
||||
const { rows: lockRows } = await handle.executor.query<{ lock_timeout: string }>(
|
||||
'SHOW lock_timeout'
|
||||
);
|
||||
|
||||
expect(schemaRows[0]?.current_schema).toBe(f.schema);
|
||||
expect(stmtRows[0]?.statement_timeout).toBe('10s');
|
||||
expect(lockRows[0]?.lock_timeout).toBe('2s');
|
||||
|
||||
// Verify unqualified findings writes and reads resolve against the PGOPTIONS search_path.
|
||||
const writePort = createPostgresFindingWritePort({ executor: handle.executor });
|
||||
const readers = createPostgresKnowledgeReaders({ executor: handle.executor });
|
||||
const created = await writePort.appendFinding(
|
||||
{
|
||||
id: 'finding-pgoptions-0001',
|
||||
kind: 'finding',
|
||||
title: 'PGOPTIONS search_path finding',
|
||||
summary: 'Resolved via PGOPTIONS search_path without explicit schema option.',
|
||||
status: 'pending_review',
|
||||
createdAt: FIXED_TS,
|
||||
trialRefs: [],
|
||||
evidenceRefs: [],
|
||||
},
|
||||
'idem-pgoptions-0001'
|
||||
);
|
||||
expect(created.status).toBe('created');
|
||||
|
||||
const listed = await readers.listFindings({ query: 'PGOPTIONS search_path' });
|
||||
expect(listed).toHaveLength(1);
|
||||
expect(listed[0]?.id).toBe('finding-pgoptions-0001');
|
||||
});
|
||||
|
||||
test('supports migrated findings writes, reads, and idempotent same-ID 23505 replay', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const appName = `copilot_findings_${randomUUID().slice(0, 8)}`;
|
||||
const executorUrl = buildExecutorUrl(f.safeUrl, f.schema, appName);
|
||||
|
||||
const handle = await openResearchCopilotExecutor({ postgresUrl: executorUrl });
|
||||
cleanup.push(() => handle.close());
|
||||
|
||||
const writePort = createPostgresFindingWritePort({
|
||||
executor: handle.executor,
|
||||
schema: f.schema,
|
||||
});
|
||||
const readers = createPostgresKnowledgeReaders({
|
||||
executor: handle.executor,
|
||||
schema: f.schema,
|
||||
});
|
||||
|
||||
const record = {
|
||||
id: 'finding-exec-0001',
|
||||
kind: 'finding' as const,
|
||||
title: 'Executor integration finding',
|
||||
summary: 'Verified against migrated schema via openResearchCopilotExecutor.',
|
||||
status: 'pending_review' as const,
|
||||
createdAt: FIXED_TS,
|
||||
trialRefs: ['101'],
|
||||
evidenceRefs: ['snap:2025-06-29:ic'],
|
||||
};
|
||||
|
||||
const first = await writePort.appendFinding(record, 'idem-key-0001');
|
||||
expect(first).toEqual({
|
||||
status: 'created',
|
||||
id: 'finding-exec-0001',
|
||||
createdAt: FIXED_TS,
|
||||
});
|
||||
|
||||
// Same ID + same idempotency key collides on PK (23505) and must replay cleanly.
|
||||
const replay = await writePort.appendFinding(record, 'idem-key-0001');
|
||||
expect(replay).toEqual({
|
||||
status: 'replayed',
|
||||
id: 'finding-exec-0001',
|
||||
createdAt: FIXED_TS,
|
||||
});
|
||||
|
||||
const listed = await readers.listFindings({ query: 'Executor integration' });
|
||||
expect(listed).toHaveLength(1);
|
||||
expect(listed[0]?.id).toBe('finding-exec-0001');
|
||||
expect(listed[0]?.trialRefs).toEqual(['101']);
|
||||
|
||||
// Executor remains usable after 23505 collision.
|
||||
const { rows } = await handle.executor.query<{ count: number }>(
|
||||
`SELECT count(*)::int AS count FROM "${f.schema}".findings`
|
||||
);
|
||||
expect(rows[0]?.count).toBe(1);
|
||||
});
|
||||
|
||||
test('enforces Vault cutoff when wired into createPostgresTrialRefLookupPort', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
await f.setupPool.query(
|
||||
`INSERT INTO trial_ledger (
|
||||
trial_id, principal_id, stage, universe_market, horizon_bucket, expression_hash,
|
||||
sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series
|
||||
)
|
||||
OVERRIDING SYSTEM VALUE
|
||||
VALUES
|
||||
(1, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), '2020-01-01'::date, '2025-06-29'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[]),
|
||||
(2, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), '2020-01-01'::date, '2025-06-30'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])`
|
||||
);
|
||||
|
||||
const appName = `copilot_vault_${randomUUID().slice(0, 8)}`;
|
||||
const handle = await openResearchCopilotExecutor({
|
||||
postgresUrl: buildExecutorUrl(f.safeUrl, f.schema, appName),
|
||||
});
|
||||
cleanup.push(() => handle.close());
|
||||
|
||||
const trialLookup = createPostgresTrialRefLookupPort({
|
||||
executor: handle.executor,
|
||||
vaultCutoffTs: VAULT_CUTOFF_TS,
|
||||
schema: f.schema,
|
||||
});
|
||||
|
||||
expect(await trialLookup.hasResearchVisibleTrial('1')).toBe(true);
|
||||
expect(await trialLookup.hasResearchVisibleTrial('2')).toBe(false);
|
||||
});
|
||||
|
||||
test('caps concurrent backend connections at 4 and disconnects all backends on close()', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const appName = `copilot_cap_${randomUUID().slice(0, 8)}`;
|
||||
const handle = await openResearchCopilotExecutor({
|
||||
postgresUrl: buildExecutorUrl(f.safeUrl, f.schema, appName),
|
||||
});
|
||||
cleanup.push(() => handle.close());
|
||||
|
||||
const results = await Promise.all(
|
||||
Array.from({ length: RESEARCH_COPILOT_PG_POOL_MAX + 2 }, () =>
|
||||
handle.executor.query<{ pid: number }>(
|
||||
'SELECT pg_backend_pid() AS pid FROM pg_sleep(0.15)'
|
||||
)
|
||||
)
|
||||
);
|
||||
const distinctPids = new Set(results.map(r => r.rows[0]?.pid));
|
||||
expect(distinctPids.size).toBeGreaterThanOrEqual(1);
|
||||
expect(distinctPids.size).toBeLessThanOrEqual(RESEARCH_COPILOT_PG_POOL_MAX);
|
||||
|
||||
await handle.close();
|
||||
|
||||
const remainingBackends = await waitForZeroBackends(f.admin, appName);
|
||||
expect(remainingBackends).toBe(0);
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await handle.executor.query('SELECT 1');
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED');
|
||||
});
|
||||
});
|
||||
|
|
@ -1749,6 +1749,22 @@ curate-etl curate-fx-1m \
|
|||
- **Outputs & fail-closed publication:** writes `<out>/fx_1m.shard-<NN>.ilp` (`00`..`<shards-1>`) and prints the `format_curate_fx_1m_report` summary to stdout. Inherits the runner's fail-closed preflight and staging/rollback guarantees (refuses to overwrite existing `fx_1m.shard-*.ilp` files and leaves no partial shard or staging files on error).
|
||||
- **File mode only:** MongoDB streaming flags (such as `--from-mongo` and `--mongo-uri`) are rejected; `--from-mongo` streaming and live QuestDB ingestion remain follow-ups.
|
||||
|
||||
### `send-ilp` Command (`M2.3q`)
|
||||
|
||||
CLI command wiring `discover_ilp_shard_files`, `tcp_ilp_connector`, and `send_ilp_shard_files` (`run_send_ilp`) into the `curate-etl` binary to stream published intraday ILP v2 shard files to an explicit QuestDB TCP endpoint:
|
||||
|
||||
```bash
|
||||
curate-etl send-ilp \
|
||||
--dir ./out \
|
||||
--prefix bars_1m \
|
||||
--addr <approved-questdb-host:ilp-port>
|
||||
```
|
||||
|
||||
- **Required flags (no default target):** `--dir <published-shard-dir>`, `--prefix <bars_1m|bars_1m_qm|fx_1m>`, and `--addr <host:port>` are all required (accepting both `--flag value` and `--flag=value`). There is **no default address and no environment-variable fallback**, which prevents implicit targeting; operators must explicitly supply and verify an approved endpoint so QA QuestDB is not targeted by mistake.
|
||||
- **Allowed prefixes:** restricted to `bars_1m` (`curate-bars-1m`), `bars_1m_qm` (`run_curate_qm_bars_1m`), and `fx_1m` (`curate-fx-1m`).
|
||||
- **Fail-closed order & reporting:** validates and discovers the contiguous `0..N` shard set in `--dir` before resolving `--addr` or opening any socket; streams each shard verbatim over its own TCP socket using `IlpTcpOptions::default()` and `IlpSendOptions::default()`; prints `format_ilp_send_report` to stdout on exit `0`, or `error: ...` plus any formatted partial report (`per_shard_bytes`) to stderr on non-zero exit.
|
||||
- **Delivery & protocol caveats:** TCP ILP provides no per-row or per-batch server acknowledgement — exit `0` means all bytes were accepted by local sockets and write-half shutdown succeeded, **not** that rows were committed in QuestDB; verify committed row counts and representative values via PGWire after loading. QuestDB `10.2.0` acceptance of ILP v2 binary `DOUBLE` payloads over TCP without a handshake remains **unverified** until the manual `quant` load check.
|
||||
|
||||
## `run_curate_qm_bars_1m` Bounded-Memory File-to-File Runner (`M2.3m`)
|
||||
|
||||
`run_curate_qm_bars_1m` / `run_curate_qm_bars_1m_with_readers` (`src/run_curate_qm_bars_1m.rs`) streams a concatenated raw BSON `qmIntraday` dump alongside a headerless 5-column `provider_mapping.tsv` (`load_provider_mapping_tsv`) into per-shard QuestDB ILP v2 files (`<out_dir>/bars_1m_qm.shard-<NN>.ilp`) via `curate_and_write_qm_bars_1m` (`src/curate_qm_bars_1m.rs`):
|
||||
|
|
|
|||
|
|
@ -44,6 +44,7 @@ use crate::bson_qm_events::{
|
|||
use crate::bson_stream::BsonStreamOptions;
|
||||
use crate::curate_adj::AdjPointInTimeFence;
|
||||
use crate::ilp::IlpWriterOptions;
|
||||
use crate::ilp_send::SendIlpArgs;
|
||||
use crate::mongo_stream::{
|
||||
MongoCliOptions, MongoUriSource, DEFAULT_MONGO_BATCH_SIZE, DEFAULT_MONGO_URI_ENV,
|
||||
MAX_MONGO_BATCH_SIZE,
|
||||
|
|
@ -87,6 +88,7 @@ pub enum CliAction {
|
|||
CurateBars1m(CurateBars1mArgs),
|
||||
CurateFx1m(CurateFx1mArgs),
|
||||
CuratePosts(CuratePostsArgs),
|
||||
SendIlp(SendIlpArgs),
|
||||
BenchSplit(usize),
|
||||
BenchAdj(usize),
|
||||
BenchCorporateActions(usize),
|
||||
|
|
@ -154,6 +156,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
Curate USD/CAD 1-minute FX bars from eodIntraday1M BSON into fx_1m.shard-<NN>.ilp\n\
|
||||
{name} curate-posts --ceo-posts <path> --provider-mapping <path> --out <dir> --timestamp-unit <seconds|millis> [--key-field <name>] [--spiel-id-field <name>] [--timestamp-field <name>] [--edited-field <name>] [--bot-field <name>] [--user-id-field <name>] [--text-field <name>] [--mapping-source <name>]\n\
|
||||
Curate ceoPosts from BSON + provider_mapping TSV into <out>/events/year=YYYY/part.parquet using a dedicated --out directory (--timestamp-unit has no default; defaults: --key-field {DEFAULT_POSTS_KEY_FIELD}, --spiel-id-field {DEFAULT_POSTS_SPIEL_ID_FIELD}, --timestamp-field {DEFAULT_POSTS_TIMESTAMP_FIELD}, --edited-field {DEFAULT_POSTS_EDITED_FIELD}, --bot-field {DEFAULT_POSTS_BOT_FIELD}, --user-id-field {DEFAULT_POSTS_USER_ID_FIELD}, --text-field {DEFAULT_POSTS_TEXT_FIELD}, --mapping-source {DEFAULT_POSTS_MAPPING_SOURCE})\n\
|
||||
{name} send-ilp --dir <dir> --prefix <bars_1m|bars_1m_qm|fx_1m> --addr <host:port>\n\
|
||||
Stream published ILP v2 shard files to an explicit QuestDB TCP endpoint (no default address; success means bytes were accepted by local sockets, not rows committed — verify row counts via PGWire; ILP v2 binary doubles over TCP on QuestDB 10.2.0 are unverified until the manual quant load check)\n\
|
||||
{name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\
|
||||
{name} bench-adj [events] Run fixed-seed adj_factors build benchmark (default: {DEFAULT_ADJ_BENCH_EVENTS})\n\
|
||||
{name} bench-corporate-actions [events] Run fixed-seed corporate_actions build benchmark (default: {DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS})\n\
|
||||
|
|
@ -205,6 +209,7 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} curate-bars-1m --eod-intraday <path> --qm-splits <path> --provider-mapping <path> --out <dir> --shards <N> --known-at-micros <i64> [--mapping-source <name>]\n\
|
||||
{name} curate-fx-1m --eod-intraday <path> --out <dir> --shards <N>\n\
|
||||
{name} curate-posts --ceo-posts <path> --provider-mapping <path> --out <dir> --timestamp-unit <seconds|millis> [--key-field <name>] [--spiel-id-field <name>] [--timestamp-field <name>] [--edited-field <name>] [--bot-field <name>] [--user-id-field <name>] [--text-field <name>] [--mapping-source <name>]\n\
|
||||
{name} send-ilp --dir <dir> --prefix <bars_1m|bars_1m_qm|fx_1m> --addr <host:port>\n\
|
||||
{name} bench-split [rows]\n\
|
||||
{name} bench-adj [events]\n\
|
||||
{name} bench-corporate-actions [events]\n\
|
||||
|
|
@ -1818,6 +1823,80 @@ fn parse_curate_fx_1m_args(args: &[&str]) -> Result<CliAction, String> {
|
|||
}))
|
||||
}
|
||||
|
||||
const ALLOWED_SEND_ILP_PREFIXES: [&str; 3] = ["bars_1m", "bars_1m_qm", "fx_1m"];
|
||||
|
||||
fn parse_send_ilp_args(args: &[&str]) -> Result<CliAction, String> {
|
||||
let mut dir: Option<PathBuf> = None;
|
||||
let mut prefix: Option<String> = None;
|
||||
let mut addr: Option<String> = None;
|
||||
|
||||
let mut i = 0usize;
|
||||
while i < args.len() {
|
||||
let token = args[i];
|
||||
if !token.starts_with("--") {
|
||||
return Err(format!(
|
||||
"unexpected positional argument '{token}' for send-ilp"
|
||||
));
|
||||
}
|
||||
|
||||
let (flag, value) = if let Some((k, v)) = token.split_once('=') {
|
||||
i += 1;
|
||||
(k, v)
|
||||
} else {
|
||||
let Some(&v) = args.get(i + 1) else {
|
||||
return Err(format!("missing value for flag '{token}'"));
|
||||
};
|
||||
if v.starts_with("--") {
|
||||
return Err(format!("missing value for flag '{token}'"));
|
||||
}
|
||||
i += 2;
|
||||
(token, v)
|
||||
};
|
||||
|
||||
match flag {
|
||||
"--dir" => {
|
||||
if dir.is_some() {
|
||||
return Err("duplicate flag '--dir'".to_string());
|
||||
}
|
||||
if value.is_empty() {
|
||||
return Err("empty value for flag '--dir'".to_string());
|
||||
}
|
||||
dir = Some(PathBuf::from(value));
|
||||
}
|
||||
"--prefix" => {
|
||||
if prefix.is_some() {
|
||||
return Err("duplicate flag '--prefix'".to_string());
|
||||
}
|
||||
if value.is_empty() {
|
||||
return Err("empty value for flag '--prefix'".to_string());
|
||||
}
|
||||
if !ALLOWED_SEND_ILP_PREFIXES.contains(&value) {
|
||||
return Err(format!(
|
||||
"unsupported --prefix '{value}' for send-ilp (expected one of: bars_1m, bars_1m_qm, fx_1m)"
|
||||
));
|
||||
}
|
||||
prefix = Some(value.to_string());
|
||||
}
|
||||
"--addr" => {
|
||||
if addr.is_some() {
|
||||
return Err("duplicate flag '--addr'".to_string());
|
||||
}
|
||||
if value.trim().is_empty() {
|
||||
return Err("empty value for flag '--addr'".to_string());
|
||||
}
|
||||
addr = Some(value.to_string());
|
||||
}
|
||||
other => return Err(format!("unknown flag '{other}' for send-ilp")),
|
||||
}
|
||||
}
|
||||
|
||||
let dir = dir.ok_or_else(|| "missing required flag '--dir'".to_string())?;
|
||||
let prefix = prefix.ok_or_else(|| "missing required flag '--prefix'".to_string())?;
|
||||
let addr = addr.ok_or_else(|| "missing required flag '--addr'".to_string())?;
|
||||
|
||||
Ok(CliAction::SendIlp(SendIlpArgs { dir, prefix, addr }))
|
||||
}
|
||||
|
||||
/// Parses CLI arguments (excluding `argv[0]`) into a [`CliAction`].
|
||||
pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
||||
let slices: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
|
|
@ -1836,6 +1915,7 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
["curate-bars-1m", rest @ ..] => parse_curate_bars_1m_args(rest),
|
||||
["curate-fx-1m", rest @ ..] => parse_curate_fx_1m_args(rest),
|
||||
["curate-posts", rest @ ..] => parse_curate_posts_args(rest),
|
||||
["send-ilp", rest @ ..] => parse_send_ilp_args(rest),
|
||||
["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)),
|
||||
["bench-split", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)),
|
||||
|
|
@ -4814,4 +4894,290 @@ mod tests {
|
|||
.unwrap_err();
|
||||
assert!(err.contains("cannot share BSON field 'shared'"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_send_ilp_valid_space_and_equals_forms_and_all_allowed_prefixes() {
|
||||
for prefix in ["bars_1m", "bars_1m_qm", "fx_1m"] {
|
||||
let expected = CliAction::SendIlp(SendIlpArgs {
|
||||
dir: PathBuf::from("/tmp/shards"),
|
||||
prefix: prefix.to_string(),
|
||||
addr: "127.0.0.1:9009".to_string(),
|
||||
});
|
||||
|
||||
let parsed_space = parse_args(&to_args(&[
|
||||
"send-ilp",
|
||||
"--dir",
|
||||
"/tmp/shards",
|
||||
"--prefix",
|
||||
prefix,
|
||||
"--addr",
|
||||
"127.0.0.1:9009",
|
||||
]))
|
||||
.expect("valid send-ilp args in space form");
|
||||
assert_eq!(parsed_space, expected);
|
||||
|
||||
let prefix_eq = format!("--prefix={prefix}");
|
||||
let parsed_eq = parse_args(&to_args(&[
|
||||
"send-ilp",
|
||||
"--dir=/tmp/shards",
|
||||
&prefix_eq,
|
||||
"--addr=127.0.0.1:9009",
|
||||
]))
|
||||
.expect("valid send-ilp args in equals form");
|
||||
assert_eq!(parsed_eq, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_ilp_usage_mentions_command_flags_and_delivery_caveat() {
|
||||
let expected_flags = ["--dir", "--prefix", "--addr"];
|
||||
let usage = format_usage("curate-etl", "0.1.0");
|
||||
let usage_stderr = format_usage_stderr("curate-etl");
|
||||
let usage_line = usage
|
||||
.lines()
|
||||
.find(|line| line.trim_start().starts_with("curate-etl send-ilp "))
|
||||
.expect("format_usage missing send-ilp command line");
|
||||
let stderr_line = usage_stderr
|
||||
.lines()
|
||||
.find(|line| line.trim_start().starts_with("curate-etl send-ilp "))
|
||||
.expect("format_usage_stderr missing send-ilp command line");
|
||||
for flag in expected_flags {
|
||||
assert!(
|
||||
usage_line.contains(flag),
|
||||
"format_usage send-ilp line missing {flag}: {usage_line}"
|
||||
);
|
||||
assert!(
|
||||
stderr_line.contains(flag),
|
||||
"format_usage_stderr send-ilp line missing {flag}: {stderr_line}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
usage.contains("no default address"),
|
||||
"format_usage missing no-default-address note"
|
||||
);
|
||||
assert!(
|
||||
usage.contains("PGWire"),
|
||||
"format_usage missing PGWire verification note"
|
||||
);
|
||||
assert!(
|
||||
usage.contains("10.2.0"),
|
||||
"format_usage missing QuestDB 10.2.0 unverified note"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_send_ilp_rejects_missing_required_flags_with_no_default_addr() {
|
||||
let required: [(&str, &str); 3] = [
|
||||
("--dir", "/tmp/shards"),
|
||||
("--prefix", "fx_1m"),
|
||||
("--addr", "127.0.0.1:9009"),
|
||||
];
|
||||
|
||||
for omit in 0..required.len() {
|
||||
let mut argv: Vec<&str> = vec!["send-ilp"];
|
||||
for (idx, &(flag, val)) in required.iter().enumerate() {
|
||||
if idx != omit {
|
||||
argv.push(flag);
|
||||
argv.push(val);
|
||||
}
|
||||
}
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
let missing_flag = required[omit].0;
|
||||
assert!(
|
||||
err.contains(&format!("missing required flag '{missing_flag}'")),
|
||||
"expected missing required flag '{missing_flag}', got: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_send_ilp_rejects_duplicates_empty_missing_value_unknown_positional_and_bad_prefix() {
|
||||
let base = [
|
||||
"send-ilp",
|
||||
"--dir",
|
||||
"/tmp/shards",
|
||||
"--prefix",
|
||||
"bars_1m",
|
||||
"--addr",
|
||||
"127.0.0.1:9009",
|
||||
];
|
||||
|
||||
// Duplicate flags.
|
||||
for (flag, extra_val) in [
|
||||
("--dir", "/tmp/other"),
|
||||
("--prefix", "fx_1m"),
|
||||
("--addr", "127.0.0.1:9010"),
|
||||
] {
|
||||
let mut argv = base.to_vec();
|
||||
argv.push(flag);
|
||||
argv.push(extra_val);
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert!(
|
||||
err.contains(&format!("duplicate flag '{flag}'")),
|
||||
"expected duplicate error for {flag}, got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
// Empty values via --flag=.
|
||||
for flag in ["--dir", "--prefix", "--addr"] {
|
||||
let empty_token = format!("{flag}=");
|
||||
let err = parse_args(&to_args(&["send-ilp", &empty_token])).unwrap_err();
|
||||
assert!(
|
||||
err.contains(&format!("empty value for flag '{flag}'")),
|
||||
"expected empty value error for {flag}, got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
// Whitespace-only --addr.
|
||||
let err = parse_args(&to_args(&[
|
||||
"send-ilp",
|
||||
"--dir",
|
||||
"/tmp/shards",
|
||||
"--prefix",
|
||||
"fx_1m",
|
||||
"--addr",
|
||||
" ",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert!(err.contains("empty value for flag '--addr'"), "{err}");
|
||||
|
||||
// Missing value at end of input or followed by another flag.
|
||||
let err = parse_args(&to_args(&["send-ilp", "--dir"])).unwrap_err();
|
||||
assert!(err.contains("missing value for flag '--dir'"), "{err}");
|
||||
let err = parse_args(&to_args(&[
|
||||
"send-ilp",
|
||||
"--prefix",
|
||||
"--addr",
|
||||
"127.0.0.1:9009",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert!(err.contains("missing value for flag '--prefix'"), "{err}");
|
||||
|
||||
// Unknown flag (including --from-mongo).
|
||||
for flag in ["--nope", "--from-mongo", "--timeout"] {
|
||||
let mut argv = base.to_vec();
|
||||
argv.push(flag);
|
||||
argv.push("1");
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert!(
|
||||
err.contains(&format!("unknown flag '{flag}' for send-ilp")),
|
||||
"expected unknown flag error for {flag}, got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
// Positional argument.
|
||||
let err = parse_args(&to_args(&["send-ilp", "positional"])).unwrap_err();
|
||||
assert!(
|
||||
err.contains("unexpected positional argument 'positional' for send-ilp"),
|
||||
"{err}"
|
||||
);
|
||||
|
||||
// Unsupported non-empty prefixes must list all three allowed values.
|
||||
for bad_prefix in [
|
||||
"bars_1d",
|
||||
"../x",
|
||||
"BARS_1M",
|
||||
"fx_1d",
|
||||
"fx_1m_extra",
|
||||
" bars_1m",
|
||||
"bars_1m ",
|
||||
"./bars_1m",
|
||||
"dir/fx_1m",
|
||||
] {
|
||||
let err = parse_args(&to_args(&[
|
||||
"send-ilp",
|
||||
"--dir",
|
||||
"/tmp/shards",
|
||||
"--prefix",
|
||||
bad_prefix,
|
||||
"--addr",
|
||||
"127.0.0.1:9009",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.contains("bars_1m") && err.contains("bars_1m_qm") && err.contains("fx_1m"),
|
||||
"expected allowed prefixes in error for '{bad_prefix}', got: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_send_ilp_edge_cases_bare_empty_space_form_order_equals_in_dir_and_ipv6() {
|
||||
// Bare `send-ilp` with no flags fails with missing required flag.
|
||||
let err = parse_args(&to_args(&["send-ilp"])).unwrap_err();
|
||||
assert!(err.contains("missing required flag '--dir'"), "{err}");
|
||||
|
||||
// Empty values in space form.
|
||||
for (argv, flag) in [
|
||||
(
|
||||
&[
|
||||
"send-ilp",
|
||||
"--dir",
|
||||
"",
|
||||
"--prefix",
|
||||
"fx_1m",
|
||||
"--addr",
|
||||
"127.0.0.1:9009",
|
||||
][..],
|
||||
"--dir",
|
||||
),
|
||||
(
|
||||
&[
|
||||
"send-ilp",
|
||||
"--dir",
|
||||
"/tmp/shards",
|
||||
"--prefix",
|
||||
"",
|
||||
"--addr",
|
||||
"127.0.0.1:9009",
|
||||
][..],
|
||||
"--prefix",
|
||||
),
|
||||
(
|
||||
&[
|
||||
"send-ilp",
|
||||
"--dir",
|
||||
"/tmp/shards",
|
||||
"--prefix",
|
||||
"fx_1m",
|
||||
"--addr",
|
||||
"",
|
||||
][..],
|
||||
"--addr",
|
||||
),
|
||||
] {
|
||||
let err = parse_args(&to_args(argv)).unwrap_err();
|
||||
assert!(
|
||||
err.contains(&format!("empty value for flag '{flag}'")),
|
||||
"expected empty value error for {flag}, got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
// Mixed flag order, `=` inside --dir path, and IPv6 --addr in both forms.
|
||||
let expected = CliAction::SendIlp(SendIlpArgs {
|
||||
dir: PathBuf::from("/tmp/year=2025/shards"),
|
||||
prefix: "bars_1m_qm".to_string(),
|
||||
addr: "[::1]:9009".to_string(),
|
||||
});
|
||||
let parsed_mixed = parse_args(&to_args(&[
|
||||
"send-ilp",
|
||||
"--addr",
|
||||
"[::1]:9009",
|
||||
"--prefix=bars_1m_qm",
|
||||
"--dir=/tmp/year=2025/shards",
|
||||
]))
|
||||
.expect("mixed order with equals in dir and IPv6 addr");
|
||||
assert_eq!(parsed_mixed, expected);
|
||||
|
||||
let parsed_space = parse_args(&to_args(&[
|
||||
"send-ilp",
|
||||
"--prefix",
|
||||
"bars_1m_qm",
|
||||
"--addr=[::1]:9009",
|
||||
"--dir",
|
||||
"/tmp/year=2025/shards",
|
||||
]))
|
||||
.expect("space dir with equals and IPv6 equals addr");
|
||||
assert_eq!(parsed_space, expected);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -825,6 +825,26 @@ pub fn tcp_ilp_connector(
|
|||
tcp_ilp_connector_for_addrs(resolved, options)
|
||||
}
|
||||
|
||||
/// Arguments for the `send-ilp` CLI subcommand and [`run_send_ilp`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SendIlpArgs {
|
||||
pub dir: PathBuf,
|
||||
pub prefix: String,
|
||||
pub addr: String,
|
||||
}
|
||||
|
||||
/// Discovers published `<prefix>.shard-<digits>.ilp` files in `args.dir`, validates and resolves
|
||||
/// `args.addr` via [`tcp_ilp_connector`] with [`IlpTcpOptions::default()`], and streams all shards
|
||||
/// via [`send_ilp_shard_files`] with [`IlpSendOptions::default()`].
|
||||
///
|
||||
/// Discovery runs before address resolution or any socket connection so a bad directory or
|
||||
/// incomplete shard set never opens a socket.
|
||||
pub fn run_send_ilp(args: &SendIlpArgs) -> Result<IlpSendReport, IlpSendError> {
|
||||
let files = discover_ilp_shard_files(&args.dir, &args.prefix)?;
|
||||
let connector = tcp_ilp_connector(&args.addr, IlpTcpOptions::default())?;
|
||||
send_ilp_shard_files(&files, connector, IlpSendOptions::default())
|
||||
}
|
||||
|
||||
/// Formats [`IlpSendReport`] into a deterministic machine-readable `key=value` summary in the
|
||||
/// style of the crate's `format_curate_*_report` helpers.
|
||||
pub fn format_ilp_send_report(report: &IlpSendReport) -> String {
|
||||
|
|
|
|||
|
|
@ -1300,3 +1300,508 @@ fn tcp_connector_skips_unreachable_address_then_pins_reachable_one_for_all_shard
|
|||
payloads.iter().map(|p| p.len() as u64).sum::<u64>()
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// `run_send_ilp` wrapper tests (`M2.3q`).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn run_send_ilp_end_to_end_over_loopback() {
|
||||
let dir = TempDirGuard::new("run-send-ilp-e2e");
|
||||
let payload0: Vec<u8> = vec![
|
||||
b'f', b'x', b'_', b'1', b'm', b',', b'p', b'a', b'i', b'r', b'=', b'U', b'S', b'D', b'C',
|
||||
b'A', b'D', b' ', b'c', b'=', b'=', 0x10, 0x0A, 0xFF, 0xFE, 0x80, 0x00, 0x00, 0xF0, 0x3F,
|
||||
b' ', b'1', b'7', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0',
|
||||
b'0', b'0', b't', b'\n',
|
||||
];
|
||||
let payload1: Vec<u8> = Vec::new();
|
||||
let payload2: Vec<u8> = vec![
|
||||
b'f', b'x', b'_', b'1', b'm', b',', b'p', b'a', b'i', b'r', b'=', b'U', b'S', b'D', b'C',
|
||||
b'A', b'D', b' ', b'c', b'=', b'=', 0x10, 0xC0, 0x81, 0x0A, 0x0A, 0x01, 0x02, 0xF5, 0x3F,
|
||||
b' ', b'1', b'7', b'0', b'0', b'0', b'0', b'0', b'0', b'6', b'0', b'0', b'0', b'0', b'0',
|
||||
b'0', b'0', b't', b'\n',
|
||||
];
|
||||
assert!(std::str::from_utf8(&payload0).is_err());
|
||||
assert!(std::str::from_utf8(&payload2).is_err());
|
||||
assert!(payload0.contains(&0x0A));
|
||||
assert!(payload2.contains(&0x0A));
|
||||
|
||||
write_bytes(&dir.path().join("fx_1m.shard-00.ilp"), &payload0);
|
||||
write_bytes(&dir.path().join("fx_1m.shard-01.ilp"), &payload1);
|
||||
write_bytes(&dir.path().join("fx_1m.shard-02.ilp"), &payload2);
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener");
|
||||
let listen_addr = listener.local_addr().expect("local addr");
|
||||
listener
|
||||
.set_nonblocking(true)
|
||||
.expect("set loopback listener nonblocking");
|
||||
|
||||
let server_handle = thread::spawn(move || {
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
let mut reader_handles = Vec::with_capacity(3);
|
||||
for accepted in 0..3 {
|
||||
let (mut stream, peer) = accept_with_deadline(&listener, deadline, accepted, 3);
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.expect("set server read timeout");
|
||||
reader_handles.push(thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
stream
|
||||
.read_to_end(&mut buf)
|
||||
.expect("read shard stream to EOF");
|
||||
(peer, buf)
|
||||
}));
|
||||
}
|
||||
let received: Vec<(SocketAddr, Vec<u8>)> = reader_handles
|
||||
.into_iter()
|
||||
.map(|h| h.join().expect("join reader thread"))
|
||||
.collect();
|
||||
(listener, received)
|
||||
});
|
||||
|
||||
let report = run_send_ilp(&SendIlpArgs {
|
||||
dir: dir.path().to_path_buf(),
|
||||
prefix: "fx_1m".to_string(),
|
||||
addr: listen_addr.to_string(),
|
||||
})
|
||||
.expect("run_send_ilp should succeed over loopback");
|
||||
|
||||
let (listener, received) = server_handle.join().expect("join server thread");
|
||||
|
||||
// Verify no extra 4th connection was opened.
|
||||
match listener.accept() {
|
||||
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
||||
Ok((_, peer)) => panic!("unexpected extra connection from {peer}"),
|
||||
Err(err) => panic!("unexpected error checking accept queue: {err}"),
|
||||
}
|
||||
|
||||
assert_eq!(received.len(), 3);
|
||||
let distinct_peers: HashSet<SocketAddr> = received.iter().map(|(peer, _)| *peer).collect();
|
||||
assert_eq!(distinct_peers.len(), 3, "expected 3 separate connections");
|
||||
|
||||
let mut received_payloads: Vec<Vec<u8>> = received.into_iter().map(|(_, buf)| buf).collect();
|
||||
received_payloads.sort();
|
||||
let mut expected_payloads = vec![payload0.clone(), payload1.clone(), payload2.clone()];
|
||||
expected_payloads.sort();
|
||||
assert_eq!(received_payloads, expected_payloads);
|
||||
|
||||
let expected_total = (payload0.len() + payload1.len() + payload2.len()) as u64;
|
||||
assert_eq!(report.total_shards, 3);
|
||||
assert_eq!(report.shards[0].shard, 0);
|
||||
assert_eq!(report.shards[0].bytes_sent, payload0.len() as u64);
|
||||
assert_eq!(report.shards[1].shard, 1);
|
||||
assert_eq!(report.shards[1].bytes_sent, 0);
|
||||
assert_eq!(report.shards[2].shard, 2);
|
||||
assert_eq!(report.shards[2].bytes_sent, payload2.len() as u64);
|
||||
assert_eq!(report.total_bytes_sent, expected_total);
|
||||
|
||||
assert_eq!(
|
||||
format_ilp_send_report(&report),
|
||||
format!(
|
||||
"curate-etl ilp-send\n ilp_send: shards=3 total_bytes_sent={expected_total} per_shard_bytes=00={},01=0,02={}",
|
||||
payload0.len(),
|
||||
payload2.len()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_send_ilp_fails_closed_on_discovery_and_address_errors_with_zero_connections() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener");
|
||||
let listen_addr = listener.local_addr().expect("local addr");
|
||||
listener
|
||||
.set_nonblocking(true)
|
||||
.expect("set listener nonblocking");
|
||||
|
||||
let assert_zero_accepts = |label: &str| match listener.accept() {
|
||||
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
||||
Ok((_, peer)) => panic!("{label}: unexpectedly accepted connection from {peer}"),
|
||||
Err(err) => panic!("{label}: unexpected accept error: {err}"),
|
||||
};
|
||||
|
||||
// (a) Missing directory -> ReadDir(NotFound), zero connections.
|
||||
let base = TempDirGuard::new("run-send-ilp-fail-closed");
|
||||
let missing_dir = base.path().join("does-not-exist");
|
||||
let err = run_send_ilp(&SendIlpArgs {
|
||||
dir: missing_dir.clone(),
|
||||
prefix: "fx_1m".to_string(),
|
||||
addr: listen_addr.to_string(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, IlpSendError::ReadDir { ref source, .. } if source.kind() == io::ErrorKind::NotFound),
|
||||
"expected ReadDir(NotFound), got {err:?}"
|
||||
);
|
||||
assert_zero_accepts("missing directory");
|
||||
|
||||
// (b) Empty directory -> NoShardFiles, zero connections.
|
||||
let empty_dir = TempDirGuard::new("run-send-ilp-empty");
|
||||
let err = run_send_ilp(&SendIlpArgs {
|
||||
dir: empty_dir.path().to_path_buf(),
|
||||
prefix: "fx_1m".to_string(),
|
||||
addr: listen_addr.to_string(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, IlpSendError::NoShardFiles { .. }),
|
||||
"expected NoShardFiles, got {err:?}"
|
||||
);
|
||||
assert_zero_accepts("empty directory");
|
||||
|
||||
// (c) Discovery failure paired with malformed address -> discovery error takes precedence.
|
||||
let err = run_send_ilp(&SendIlpArgs {
|
||||
dir: empty_dir.path().to_path_buf(),
|
||||
prefix: "fx_1m".to_string(),
|
||||
addr: "not-an-addr".to_string(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, IlpSendError::NoShardFiles { .. }),
|
||||
"expected discovery error before address validation, got {err:?}"
|
||||
);
|
||||
assert_zero_accepts("empty directory with malformed address");
|
||||
|
||||
// (d) Shard gap (00 + 02) -> MissingShardIndex, zero connections.
|
||||
let gap_dir = TempDirGuard::new("run-send-ilp-gap");
|
||||
write_bytes(&gap_dir.path().join("fx_1m.shard-00.ilp"), b"a");
|
||||
write_bytes(&gap_dir.path().join("fx_1m.shard-02.ilp"), b"c");
|
||||
let err = run_send_ilp(&SendIlpArgs {
|
||||
dir: gap_dir.path().to_path_buf(),
|
||||
prefix: "fx_1m".to_string(),
|
||||
addr: listen_addr.to_string(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
IlpSendError::MissingShardIndex {
|
||||
expected: 1,
|
||||
found: 2,
|
||||
..
|
||||
}
|
||||
),
|
||||
"expected MissingShardIndex(1, 2), got {err:?}"
|
||||
);
|
||||
assert_zero_accepts("shard gap");
|
||||
|
||||
// (e) Valid shards + malformed address -> InvalidAddress before any connect.
|
||||
let valid_dir = TempDirGuard::new("run-send-ilp-bad-addr");
|
||||
write_bytes(&valid_dir.path().join("fx_1m.shard-00.ilp"), b"ok");
|
||||
for bad_addr in ["not-an-addr", "127.0.0.1", "127.0.0.1:notaport"] {
|
||||
let err = run_send_ilp(&SendIlpArgs {
|
||||
dir: valid_dir.path().to_path_buf(),
|
||||
prefix: "fx_1m".to_string(),
|
||||
addr: bad_addr.to_string(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, IlpSendError::InvalidAddress { .. }),
|
||||
"expected InvalidAddress for {bad_addr:?}, got {err:?}"
|
||||
);
|
||||
}
|
||||
assert_zero_accepts("malformed address");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_send_ilp_refused_connection_returns_connect_error_and_zero_partial_report() {
|
||||
let dir = TempDirGuard::new("run-send-ilp-refused");
|
||||
let p0 = dir.path().join("fx_1m.shard-00.ilp");
|
||||
let p1 = dir.path().join("fx_1m.shard-01.ilp");
|
||||
let p2 = dir.path().join("fx_1m.shard-02.ilp");
|
||||
write_bytes(&p0, b"shard0");
|
||||
write_bytes(&p1, b"");
|
||||
write_bytes(&p2, b"shard2");
|
||||
|
||||
let dead = refused_loopback_addr();
|
||||
let err = run_send_ilp(&SendIlpArgs {
|
||||
dir: dir.path().to_path_buf(),
|
||||
prefix: "fx_1m".to_string(),
|
||||
addr: dead.to_string(),
|
||||
})
|
||||
.unwrap_err();
|
||||
|
||||
match err {
|
||||
IlpSendError::ShardIo {
|
||||
op,
|
||||
shard,
|
||||
path,
|
||||
source,
|
||||
partial_report,
|
||||
} => {
|
||||
assert_eq!(op, IlpSendOp::Connect);
|
||||
assert_eq!(shard, 0);
|
||||
assert_eq!(path, p0);
|
||||
assert_eq!(source.kind(), io::ErrorKind::ConnectionRefused);
|
||||
assert_eq!(partial_report.total_shards, 3);
|
||||
assert_eq!(partial_report.total_bytes_sent, 0);
|
||||
assert_eq!(partial_report.shards.len(), 3);
|
||||
for (idx, entry) in partial_report.shards.iter().enumerate() {
|
||||
assert_eq!(entry.shard, idx);
|
||||
assert_eq!(entry.bytes_sent, 0);
|
||||
}
|
||||
}
|
||||
other => panic!("expected ShardIo(Connect), got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_send_ilp_mixed_folder_isolates_bars_1m_bars_1m_qm_and_fx_1m() {
|
||||
let dir = TempDirGuard::new("run-send-ilp-mixed-folder");
|
||||
let bars0 = b"bars_1m,listing_id=1 close=10.0 1700000000000000t\n".to_vec();
|
||||
let bars1 = b"bars_1m,listing_id=2 close=20.0 1700000060000000t\n".to_vec();
|
||||
let qm0 = b"bars_1m,listing_id=1,source=qm_raw close=10.5 1700000000000000t\n".to_vec();
|
||||
let fx0 = b"fx_1m,pair=USDCAD close=1.38 1700000000000000t\n".to_vec();
|
||||
|
||||
write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), &bars0);
|
||||
write_bytes(&dir.path().join("bars_1m.shard-01.ilp"), &bars1);
|
||||
write_bytes(&dir.path().join("bars_1m_qm.shard-00.ilp"), &qm0);
|
||||
write_bytes(&dir.path().join("fx_1m.shard-00.ilp"), &fx0);
|
||||
write_bytes(&dir.path().join("notes.txt"), b"unrelated");
|
||||
|
||||
let cases: [(&str, Vec<Vec<u8>>); 3] = [
|
||||
("bars_1m", vec![bars0.clone(), bars1.clone()]),
|
||||
("bars_1m_qm", vec![qm0.clone()]),
|
||||
("fx_1m", vec![fx0.clone()]),
|
||||
];
|
||||
|
||||
for (prefix, mut expected) in cases {
|
||||
let count = expected.len();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener");
|
||||
let listen_addr = listener.local_addr().expect("local addr");
|
||||
listener
|
||||
.set_nonblocking(true)
|
||||
.expect("set loopback listener nonblocking");
|
||||
|
||||
let server_handle = thread::spawn(move || {
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
let mut readers = Vec::with_capacity(count);
|
||||
for accepted in 0..count {
|
||||
let (mut stream, _) = accept_with_deadline(&listener, deadline, accepted, count);
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.expect("set server read timeout");
|
||||
readers.push(thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
stream.read_to_end(&mut buf).expect("read shard to EOF");
|
||||
buf
|
||||
}));
|
||||
}
|
||||
let received: Vec<Vec<u8>> = readers
|
||||
.into_iter()
|
||||
.map(|h| h.join().expect("join reader"))
|
||||
.collect();
|
||||
(listener, received)
|
||||
});
|
||||
|
||||
let report = run_send_ilp(&SendIlpArgs {
|
||||
dir: dir.path().to_path_buf(),
|
||||
prefix: prefix.to_string(),
|
||||
addr: listen_addr.to_string(),
|
||||
})
|
||||
.expect("run_send_ilp should send only matching prefix");
|
||||
|
||||
let (listener, mut received) = server_handle.join().expect("join server");
|
||||
match listener.accept() {
|
||||
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
||||
Ok((_, peer)) => panic!("{prefix}: unexpected extra connection from {peer}"),
|
||||
Err(err) => panic!("{prefix}: unexpected accept error: {err}"),
|
||||
}
|
||||
|
||||
received.sort();
|
||||
expected.sort();
|
||||
assert_eq!(received, expected, "payload mismatch for prefix {prefix}");
|
||||
assert_eq!(report.total_shards, count);
|
||||
let expected_bytes: u64 = expected.iter().map(|b| b.len() as u64).sum();
|
||||
assert_eq!(report.total_bytes_sent, expected_bytes);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_send_ilp_gap_precedes_malformed_addr_and_file_as_dir_rejected_with_zero_connections() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener");
|
||||
let listen_addr = listener.local_addr().expect("local addr");
|
||||
listener
|
||||
.set_nonblocking(true)
|
||||
.expect("set listener nonblocking");
|
||||
|
||||
let assert_zero_accepts = |label: &str| match listener.accept() {
|
||||
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
||||
Ok((_, peer)) => panic!("{label}: unexpectedly accepted connection from {peer}"),
|
||||
Err(err) => panic!("{label}: unexpected accept error: {err}"),
|
||||
};
|
||||
|
||||
// Shard gap paired with malformed address -> MissingShardIndex precedes InvalidAddress.
|
||||
let gap_dir = TempDirGuard::new("run-send-ilp-gap-precedence");
|
||||
write_bytes(&gap_dir.path().join("bars_1m.shard-00.ilp"), b"a");
|
||||
write_bytes(&gap_dir.path().join("bars_1m.shard-02.ilp"), b"c");
|
||||
let err = run_send_ilp(&SendIlpArgs {
|
||||
dir: gap_dir.path().to_path_buf(),
|
||||
prefix: "bars_1m".to_string(),
|
||||
addr: "not-an-addr".to_string(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
IlpSendError::MissingShardIndex {
|
||||
expected: 1,
|
||||
found: 2,
|
||||
..
|
||||
}
|
||||
),
|
||||
"expected MissingShardIndex(1, 2) before InvalidAddress, got {err:?}"
|
||||
);
|
||||
assert_zero_accepts("shard gap with malformed addr");
|
||||
|
||||
// Regular file passed as --dir -> InvalidDirectory, zero connections.
|
||||
let file_dir = TempDirGuard::new("run-send-ilp-file-as-dir");
|
||||
let file_path = file_dir.path().join("not_a_dir.ilp");
|
||||
write_bytes(&file_path, b"not a directory");
|
||||
let err = run_send_ilp(&SendIlpArgs {
|
||||
dir: file_path,
|
||||
prefix: "bars_1m".to_string(),
|
||||
addr: listen_addr.to_string(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, IlpSendError::InvalidDirectory { .. }),
|
||||
"expected InvalidDirectory, got {err:?}"
|
||||
);
|
||||
assert_zero_accepts("file passed as dir");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_send_ilp_streams_payloads_larger_than_default_buffer_byte_for_byte() {
|
||||
// Arrange: two shards spanning several DEFAULT_ILP_SEND_BUFFER_BYTES chunks with a
|
||||
// non-aligned tail, filled from a fixed-seed LCG so contents are deterministic.
|
||||
let dir = TempDirGuard::new("run-send-ilp-large");
|
||||
let mut state: u64 = 0x5EED_1234_ABCD_0001;
|
||||
let mut next_byte = || {
|
||||
state = state
|
||||
.wrapping_mul(6_364_136_223_846_793_005)
|
||||
.wrapping_add(1_442_695_040_888_963_407);
|
||||
(state >> 56) as u8
|
||||
};
|
||||
let len0 = DEFAULT_ILP_SEND_BUFFER_BYTES * 3 + 17;
|
||||
let len1 = DEFAULT_ILP_SEND_BUFFER_BYTES + 1;
|
||||
let payload0: Vec<u8> = (0..len0).map(|_| next_byte()).collect();
|
||||
let payload1: Vec<u8> = (0..len1).map(|_| next_byte()).collect();
|
||||
assert_ne!(payload0[..len1], payload1[..]);
|
||||
write_bytes(&dir.path().join("bars_1m_qm.shard-00.ilp"), &payload0);
|
||||
write_bytes(&dir.path().join("bars_1m_qm.shard-01.ilp"), &payload1);
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener");
|
||||
let listen_addr = listener.local_addr().expect("local addr");
|
||||
listener
|
||||
.set_nonblocking(true)
|
||||
.expect("set loopback listener nonblocking");
|
||||
let server = thread::spawn(move || {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let mut readers = Vec::with_capacity(2);
|
||||
for accepted in 0..2 {
|
||||
let (mut stream, _) = accept_with_deadline(&listener, deadline, accepted, 2);
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
.expect("set server read timeout");
|
||||
readers.push(thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
stream.read_to_end(&mut buf).expect("read shard to EOF");
|
||||
buf
|
||||
}));
|
||||
}
|
||||
let received: Vec<Vec<u8>> = readers
|
||||
.into_iter()
|
||||
.map(|h| h.join().expect("join reader"))
|
||||
.collect();
|
||||
(listener, received)
|
||||
});
|
||||
|
||||
// Act
|
||||
let report = run_send_ilp(&SendIlpArgs {
|
||||
dir: dir.path().to_path_buf(),
|
||||
prefix: "bars_1m_qm".to_string(),
|
||||
addr: listen_addr.to_string(),
|
||||
})
|
||||
.expect("run_send_ilp should stream multi-chunk shards");
|
||||
let (listener, mut received) = server.join().expect("join server");
|
||||
|
||||
// Assert
|
||||
match listener.accept() {
|
||||
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
||||
Ok((_, peer)) => panic!("unexpected extra connection from {peer}"),
|
||||
Err(err) => panic!("unexpected accept error: {err}"),
|
||||
}
|
||||
received.sort();
|
||||
let mut expected = vec![payload0.clone(), payload1.clone()];
|
||||
expected.sort();
|
||||
assert!(
|
||||
received == expected,
|
||||
"received payloads differ from shard files"
|
||||
);
|
||||
assert_eq!(report.total_shards, 2);
|
||||
assert_eq!(report.shards[0].bytes_sent, len0 as u64);
|
||||
assert_eq!(report.shards[1].bytes_sent, len1 as u64);
|
||||
assert_eq!(report.total_bytes_sent, (len0 + len1) as u64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_send_ilp_resolves_hostname_addr_and_delivers_every_shard() {
|
||||
// Arrange: `--addr` is passed through as `host:port`, so a hostname (not only an IP
|
||||
// literal) must resolve and pin the reachable loopback address for every shard.
|
||||
let dir = TempDirGuard::new("run-send-ilp-hostname");
|
||||
let payload0 = b"bars_1m,listing_id=7 close=1.5 1700000000000000t\n".to_vec();
|
||||
let payload1 = b"bars_1m,listing_id=8 close=2.5 1700000060000000t\n".to_vec();
|
||||
write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), &payload0);
|
||||
write_bytes(&dir.path().join("bars_1m.shard-01.ilp"), &payload1);
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener");
|
||||
let port = listener.local_addr().expect("local addr").port();
|
||||
listener
|
||||
.set_nonblocking(true)
|
||||
.expect("set loopback listener nonblocking");
|
||||
let server = thread::spawn(move || {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let mut readers = Vec::with_capacity(2);
|
||||
for accepted in 0..2 {
|
||||
let (mut stream, _) = accept_with_deadline(&listener, deadline, accepted, 2);
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
.expect("set server read timeout");
|
||||
readers.push(thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
stream.read_to_end(&mut buf).expect("read shard to EOF");
|
||||
buf
|
||||
}));
|
||||
}
|
||||
let received: Vec<Vec<u8>> = readers
|
||||
.into_iter()
|
||||
.map(|h| h.join().expect("join reader"))
|
||||
.collect();
|
||||
(listener, received)
|
||||
});
|
||||
|
||||
// Act
|
||||
let report = run_send_ilp(&SendIlpArgs {
|
||||
dir: dir.path().to_path_buf(),
|
||||
prefix: "bars_1m".to_string(),
|
||||
addr: format!("localhost:{port}"),
|
||||
})
|
||||
.expect("run_send_ilp should resolve localhost and deliver");
|
||||
let (listener, mut received) = server.join().expect("join server");
|
||||
|
||||
// Assert
|
||||
match listener.accept() {
|
||||
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
||||
Ok((_, peer)) => panic!("unexpected extra connection from {peer}"),
|
||||
Err(err) => panic!("unexpected accept error: {err}"),
|
||||
}
|
||||
received.sort();
|
||||
let mut expected = vec![payload0.clone(), payload1.clone()];
|
||||
expected.sort();
|
||||
assert_eq!(received, expected);
|
||||
assert_eq!(report.total_shards, 2);
|
||||
assert_eq!(
|
||||
report.total_bytes_sent,
|
||||
(payload0.len() + payload1.len()) as u64
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -158,10 +158,10 @@ pub use ilp::{
|
|||
FNV1A_64_PRIME, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M,
|
||||
};
|
||||
pub use ilp_send::{
|
||||
discover_ilp_shard_files, format_ilp_send_report, send_ilp_shard_files, tcp_ilp_connector,
|
||||
IlpSendError, IlpSendOp, IlpSendOptions, IlpSendReport, IlpShardFile, IlpShardSendReport,
|
||||
IlpTcpOptions, IlpTcpSink, DEFAULT_ILP_SEND_BUFFER_BYTES, DEFAULT_ILP_TCP_CONNECT_TIMEOUT,
|
||||
DEFAULT_ILP_TCP_WRITE_TIMEOUT,
|
||||
discover_ilp_shard_files, format_ilp_send_report, run_send_ilp, send_ilp_shard_files,
|
||||
tcp_ilp_connector, IlpSendError, IlpSendOp, IlpSendOptions, IlpSendReport, IlpShardFile,
|
||||
IlpShardSendReport, IlpTcpOptions, IlpTcpSink, SendIlpArgs, DEFAULT_ILP_SEND_BUFFER_BYTES,
|
||||
DEFAULT_ILP_TCP_CONNECT_TIMEOUT, DEFAULT_ILP_TCP_WRITE_TIMEOUT,
|
||||
};
|
||||
pub use macro_series::{
|
||||
build_macro_rows, MacroBuild, MacroBuildStats, MacroError, MacroLagClass, MacroObservation,
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ use curate_etl::bench::{
|
|||
run_shorts_benchmark, run_split_benchmark,
|
||||
};
|
||||
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
|
||||
use curate_etl::ilp_send::{format_ilp_send_report, run_send_ilp};
|
||||
use curate_etl::run_curate_adj::{
|
||||
format_curate_adj_report, run_curate_adj_factors, run_curate_adj_factors_fenced,
|
||||
};
|
||||
|
|
@ -230,6 +231,19 @@ fn main() -> ExitCode {
|
|||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
Ok(CliAction::SendIlp(send_args)) => match run_send_ilp(&send_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_ilp_send_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
if let Some(partial) = err.partial_report() {
|
||||
eprintln!("{}", format_ilp_send_report(partial));
|
||||
}
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
Ok(CliAction::BenchSplit(rows)) => {
|
||||
let report = match run_split_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
|
|
|
|||
|
|
@ -1742,3 +1742,241 @@ fn bench_curate_shorts_command_small_run_is_deterministic_and_reports_stages() {
|
|||
assert_eq!(field(&text_a, "checksum="), field(&text_b, "checksum="));
|
||||
assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out="));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_ilp_cli_help_missing_flag_success_and_partial_error_routing() {
|
||||
use std::io::{self, Read};
|
||||
use std::net::TcpListener;
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
// 1. --help lists send-ilp, required flags, and delivery caveat.
|
||||
let help = run(&["--help"]);
|
||||
assert!(help.status.success(), "{}", stderr(&help));
|
||||
let help_text = stdout(&help);
|
||||
assert!(help_text.contains("send-ilp"), "{help_text}");
|
||||
assert!(
|
||||
help_text.contains("--dir")
|
||||
&& help_text.contains("--prefix")
|
||||
&& help_text.contains("--addr"),
|
||||
"{help_text}"
|
||||
);
|
||||
assert!(help_text.contains("PGWire"), "{help_text}");
|
||||
assert!(help_text.contains("10.2.0"), "{help_text}");
|
||||
|
||||
// 2. Missing --addr exits non-zero with error + Usage on stderr and empty stdout.
|
||||
let missing_addr = run(&["send-ilp", "--dir", "/tmp/shards", "--prefix", "fx_1m"]);
|
||||
assert!(!missing_addr.status.success());
|
||||
assert_eq!(missing_addr.status.code(), Some(1));
|
||||
assert!(stdout(&missing_addr).is_empty());
|
||||
let missing_err = stderr(&missing_addr);
|
||||
assert!(
|
||||
missing_err.contains("error: missing required flag '--addr'"),
|
||||
"{missing_err}"
|
||||
);
|
||||
assert!(missing_err.contains("Usage:"), "{missing_err}");
|
||||
assert!(missing_err.contains("send-ilp"), "{missing_err}");
|
||||
|
||||
// 3. Binary success path over loopback prints format_ilp_send_report to stdout.
|
||||
let dir = CliTempDir::new("send-ilp-bin");
|
||||
let payload0 = b"fx_1m,pair=USDCAD close=1.38 1700000000000000t\n";
|
||||
let payload1 = b"";
|
||||
write_file(&dir.path.join("fx_1m.shard-00.ilp"), payload0);
|
||||
write_file(&dir.path.join("fx_1m.shard-01.ilp"), payload1);
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener");
|
||||
let listen_addr = listener.local_addr().expect("local addr");
|
||||
listener
|
||||
.set_nonblocking(true)
|
||||
.expect("set loopback listener nonblocking");
|
||||
let server = thread::spawn(move || {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let mut received = Vec::with_capacity(2);
|
||||
for accepted in 0..2 {
|
||||
let mut stream = loop {
|
||||
match listener.accept() {
|
||||
Ok((s, _)) => {
|
||||
s.set_nonblocking(false).expect("set stream blocking");
|
||||
break s;
|
||||
}
|
||||
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"timed out waiting for connection {accepted}/2"
|
||||
);
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
Err(err) => panic!("accept failed: {err}"),
|
||||
}
|
||||
};
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.expect("set read timeout");
|
||||
let mut buf = Vec::new();
|
||||
stream.read_to_end(&mut buf).expect("read shard to EOF");
|
||||
received.push(buf);
|
||||
}
|
||||
received
|
||||
});
|
||||
|
||||
let ok_out = run(&[
|
||||
"send-ilp",
|
||||
"--dir",
|
||||
dir.path.to_str().unwrap(),
|
||||
"--prefix",
|
||||
"fx_1m",
|
||||
"--addr",
|
||||
&listen_addr.to_string(),
|
||||
]);
|
||||
let mut received = server.join().expect("join server");
|
||||
received.sort();
|
||||
let mut expected_payloads = vec![payload0.to_vec(), payload1.to_vec()];
|
||||
expected_payloads.sort();
|
||||
assert_eq!(received, expected_payloads);
|
||||
|
||||
assert!(ok_out.status.success(), "{}", stderr(&ok_out));
|
||||
assert!(stderr(&ok_out).is_empty(), "{}", stderr(&ok_out));
|
||||
assert_eq!(
|
||||
stdout(&ok_out),
|
||||
format!(
|
||||
"curate-etl ilp-send\n ilp_send: shards=2 total_bytes_sent={} per_shard_bytes=00={},01=0\n",
|
||||
payload0.len(),
|
||||
payload0.len()
|
||||
)
|
||||
);
|
||||
|
||||
// 4. Runtime connect failure prints error + formatted partial report to stderr, empty stdout.
|
||||
let dead_listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
|
||||
let dead_addr = dead_listener.local_addr().expect("ephemeral addr");
|
||||
drop(dead_listener);
|
||||
|
||||
let fail_out = run(&[
|
||||
"send-ilp",
|
||||
"--dir",
|
||||
dir.path.to_str().unwrap(),
|
||||
"--prefix",
|
||||
"fx_1m",
|
||||
"--addr",
|
||||
&dead_addr.to_string(),
|
||||
]);
|
||||
assert!(!fail_out.status.success());
|
||||
assert_eq!(fail_out.status.code(), Some(1));
|
||||
assert!(stdout(&fail_out).is_empty());
|
||||
let fail_err = stderr(&fail_out);
|
||||
assert!(fail_err.contains("error: ILP shard 0"), "{fail_err}");
|
||||
assert!(
|
||||
fail_err.contains(
|
||||
"curate-etl ilp-send\n ilp_send: shards=2 total_bytes_sent=0 per_shard_bytes=00=0,01=0"
|
||||
),
|
||||
"{fail_err}"
|
||||
);
|
||||
assert!(!fail_err.contains("Usage:"), "{fail_err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_ilp_cli_shard_gap_exits_without_partial_report_or_connect_and_bad_prefix_prints_usage() {
|
||||
use std::io;
|
||||
use std::net::TcpListener;
|
||||
|
||||
// 1. Shard gap -> exits 1, empty stdout, error on stderr, no partial report, zero connections.
|
||||
let gap_dir = CliTempDir::new("send-ilp-bin-gap");
|
||||
write_file(&gap_dir.path.join("bars_1m.shard-00.ilp"), b"a");
|
||||
write_file(&gap_dir.path.join("bars_1m.shard-02.ilp"), b"c");
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener");
|
||||
let listen_addr = listener.local_addr().expect("local addr");
|
||||
listener
|
||||
.set_nonblocking(true)
|
||||
.expect("set listener nonblocking");
|
||||
|
||||
let gap_out = run(&[
|
||||
"send-ilp",
|
||||
"--dir",
|
||||
gap_dir.path.to_str().unwrap(),
|
||||
"--prefix",
|
||||
"bars_1m",
|
||||
"--addr",
|
||||
&listen_addr.to_string(),
|
||||
]);
|
||||
assert!(!gap_out.status.success());
|
||||
assert_eq!(gap_out.status.code(), Some(1));
|
||||
assert!(stdout(&gap_out).is_empty());
|
||||
let gap_err = stderr(&gap_out);
|
||||
assert!(gap_err.contains("error:"), "{gap_err}");
|
||||
assert!(!gap_err.contains("curate-etl ilp-send"), "{gap_err}");
|
||||
assert!(!gap_err.contains("Usage:"), "{gap_err}");
|
||||
match listener.accept() {
|
||||
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
||||
Ok((_, peer)) => panic!("shard gap unexpectedly connected from {peer}"),
|
||||
Err(err) => panic!("unexpected accept error: {err}"),
|
||||
}
|
||||
|
||||
// 2. Bad prefix -> exits 1, empty stdout, error + Usage on stderr.
|
||||
let bad_prefix_out = run(&[
|
||||
"send-ilp",
|
||||
"--dir",
|
||||
gap_dir.path.to_str().unwrap(),
|
||||
"--prefix",
|
||||
"bars_1d",
|
||||
"--addr",
|
||||
&listen_addr.to_string(),
|
||||
]);
|
||||
assert!(!bad_prefix_out.status.success());
|
||||
assert_eq!(bad_prefix_out.status.code(), Some(1));
|
||||
assert!(stdout(&bad_prefix_out).is_empty());
|
||||
let bad_prefix_err = stderr(&bad_prefix_out);
|
||||
assert!(bad_prefix_err.contains("error:"), "{bad_prefix_err}");
|
||||
assert!(
|
||||
bad_prefix_err.contains("bars_1m")
|
||||
&& bad_prefix_err.contains("bars_1m_qm")
|
||||
&& bad_prefix_err.contains("fx_1m"),
|
||||
"{bad_prefix_err}"
|
||||
);
|
||||
assert!(bad_prefix_err.contains("Usage:"), "{bad_prefix_err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_ilp_cli_ignores_questdb_env_vars_and_requires_explicit_addr() {
|
||||
use std::io;
|
||||
use std::net::TcpListener;
|
||||
|
||||
// Arrange: a valid shard set plus a live loopback listener advertised through every
|
||||
// plausible env name. If the binary ever fell back to env, it would connect here.
|
||||
let dir = CliTempDir::new("send-ilp-bin-env");
|
||||
write_file(&dir.path.join("fx_1m.shard-00.ilp"), b"x\n");
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener");
|
||||
let listen_addr = listener.local_addr().expect("local addr").to_string();
|
||||
listener
|
||||
.set_nonblocking(true)
|
||||
.expect("set listener nonblocking");
|
||||
|
||||
// Act
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.args([
|
||||
"send-ilp",
|
||||
"--dir",
|
||||
dir.path.to_str().unwrap(),
|
||||
"--prefix",
|
||||
"fx_1m",
|
||||
])
|
||||
.env("QUESTDB_ILP_ADDR", &listen_addr)
|
||||
.env("QUESTDB_ADDR", &listen_addr)
|
||||
.env("ILP_ADDR", &listen_addr)
|
||||
.env("QDB_CLIENT_CONF", format!("tcp::addr={listen_addr};"))
|
||||
.output()
|
||||
.expect("spawn curate-etl binary");
|
||||
|
||||
// Assert
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
assert!(stdout(&out).is_empty(), "{}", stdout(&out));
|
||||
assert!(
|
||||
stderr(&out).contains("missing required flag '--addr'"),
|
||||
"{}",
|
||||
stderr(&out)
|
||||
);
|
||||
match listener.accept() {
|
||||
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
||||
Ok((_, peer)) => panic!("env-derived address was used: connection from {peer}"),
|
||||
Err(err) => panic!("unexpected accept error: {err}"),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,7 +32,8 @@
|
|||
"apps/stock/**/src/**/*.tsx",
|
||||
"tools/**/src/**/*.ts",
|
||||
"apps/stock/orchestrator/examples/canonical-regime-research.ts",
|
||||
"libs/core/services/test/contracts.type-test.ts"
|
||||
"libs/core/services/test/contracts.type-test.ts",
|
||||
"libs/data/postgres/test/research-copilot-executor.type-test.ts"
|
||||
],
|
||||
"exclude": ["node_modules", "**/dist/**", "**/*.test.ts", "**/*.spec.ts"]
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue