T-210: M2.3s — Implement MarketDataStore.macroAsOf, crossSection, QuestDB fx('1m'), and copilot 1m routing

This commit is contained in:
Studio 2026-12-04 15:23:16 -05:00
parent c60365237f
commit 5e255d7e30
8 changed files with 587 additions and 37 deletions

View file

@ -360,6 +360,7 @@
"version": "1.0.0",
"dependencies": {
"@duckdb/node-api": "^1.4.4-r.1",
"@stock-bot/questdb": "workspace:*",
"@stock-bot/research": "workspace:*",
},
"devDependencies": {

View file

@ -38,9 +38,13 @@ export {
type M2IntradayTableName,
} from './schema';
export {
assertNoConflictingQuestDbSsl,
hasConflictingQuestDbUrlSsl,
openQuestDbPgExecutor,
type OpenQuestDbPgExecutorOptions,
type QuestDbPgExecutorConfig,
type QuestDbPgExecutorHandle,
type QuestDbPgPoolLike,
type QuestDbPgQueryExecutor,
} from './pg-executor';

View file

@ -25,13 +25,179 @@ export interface QuestDbPgExecutorHandle {
close(): Promise<void>;
}
/** Minimal `pg.Pool` surface used by {@link openQuestDbPgExecutor}. */
export interface QuestDbPgPoolLike {
on(event: 'error', listener: (err: Error) => void): unknown;
query(
sql: string,
params?: unknown[]
): Promise<{ readonly rows: readonly unknown[] }>;
end(): Promise<void>;
}
export interface OpenQuestDbPgExecutorOptions {
/** Optional pool factory override for unit tests; defaults to `new Pool(cfg)`. */
readonly createPool?: (poolConfig: PoolConfig) => QuestDbPgPoolLike;
/**
* Optional diagnostic callback invoked when an idle pool client emits `'error'`.
* Always receives a credential-safe `Error`.
*/
readonly onPoolError?: (error: Error) => void;
}
const SAFE_ERROR_CODE_RE = /^[A-Z0-9_]{1,32}$/;
/**
* Returns `true` when an explicit boolean `ssl` setting conflicts with SSL
* query parameters (`sslmode`, `ssl`, `sslcert`, `sslkey`, `sslrootcert`)
* embedded in `rawUrl`.
*/
export function hasConflictingQuestDbUrlSsl(rawUrl: string, explicitSsl: boolean): boolean {
let parsed: URL;
try {
parsed = new URL(rawUrl);
} catch {
return false;
}
for (const [rawKey, rawValue] of parsed.searchParams.entries()) {
const key = rawKey.toLowerCase();
const value = rawValue.trim().toLowerCase();
if (key === 'sslmode') {
if (value === 'disable') {
if (explicitSsl) {
return true;
}
} else if (
value === 'require' ||
value === 'verify-ca' ||
value === 'verify-full' ||
value === 'no-verify'
) {
if (!explicitSsl) {
return true;
}
} else {
// `allow`, `prefer`, or any unrecognized sslmode conflicts with an explicit boolean override.
return true;
}
} else if (key === 'ssl') {
if (value === 'false' || value === '0') {
if (explicitSsl) {
return true;
}
} else if (value === 'true' || value === '1') {
if (!explicitSsl) {
return true;
}
} else {
return true;
}
} else if (
(key === 'sslcert' || key === 'sslkey' || key === 'sslrootcert') &&
value.length > 0 &&
!explicitSsl
) {
return true;
}
}
return false;
}
/**
* Throws a credential-free `RangeError` if `explicitSsl` conflicts with SSL
* query parameters in `rawUrl`.
*/
export function assertNoConflictingQuestDbSsl(rawUrl: string, explicitSsl: boolean): void {
if (hasConflictingQuestDbUrlSsl(rawUrl, explicitSsl)) {
throw new RangeError(
'Conflicting QuestDB SSL configuration: explicit "ssl" option conflicts with SSL query parameters in the QuestDB URL.'
);
}
}
function addRawAndDecodedNeedle(needles: Set<string>, raw: string): void {
if (raw.length === 0) {
return;
}
needles.add(raw);
try {
const decoded = decodeURIComponent(raw);
if (decoded.length > 0) {
needles.add(decoded);
}
} catch {
// Malformed percent-encoding: raw needle is already registered.
}
}
function collectConfigSecretNeedles(config: QuestDbPgExecutorConfig): readonly string[] {
const needles = new Set<string>();
if (typeof config.password === 'string' && config.password.length > 0) {
addRawAndDecodedNeedle(needles, config.password);
}
if (typeof config.url === 'string' && config.url.length > 0) {
needles.add(config.url);
try {
const parsed = new URL(config.url);
if (parsed.href.length > 0) {
needles.add(parsed.href);
}
addRawAndDecodedNeedle(needles, parsed.password);
for (const [key, value] of parsed.searchParams.entries()) {
if (key.toLowerCase() === 'password' && value.length > 0) {
addRawAndDecodedNeedle(needles, value);
}
}
} catch {
// Non-URL string: raw string is already covered.
}
}
return Array.from(needles);
}
function sanitizePoolError(err: unknown, needles: readonly string[]): Error {
const rawCode =
typeof err === 'object' && err !== null && 'code' in err
? (err as { readonly code?: unknown }).code
: undefined;
const safeCode =
typeof rawCode === 'string' && SAFE_ERROR_CODE_RE.test(rawCode) ? rawCode : undefined;
if (err instanceof Error) {
const messageHasSecret = needles.some(needle => err.message.includes(needle));
const stackHasSecret =
typeof err.stack === 'string' && needles.some(needle => err.stack?.includes(needle) === true);
if (!messageHasSecret && !stackHasSecret) {
return err;
}
}
const message =
safeCode !== undefined
? `QuestDB PGWire idle pool client error (${safeCode}; details redacted).`
: 'QuestDB PGWire idle pool client error (details redacted).';
const sanitized = new Error(message);
if (safeCode !== undefined) {
(sanitized as Error & { code?: string }).code = safeCode;
}
return sanitized;
}
/**
* Opens a lightweight PGWire `pg.Pool` executor for QuestDB read queries or
* opt-in DDL without creating legacy tables or starting background health timers.
*/
export async function openQuestDbPgExecutor(
config: QuestDbPgExecutorConfig
config: QuestDbPgExecutorConfig,
options?: OpenQuestDbPgExecutorOptions
): Promise<QuestDbPgExecutorHandle> {
if (config.url !== undefined && config.ssl !== undefined) {
assertNoConflictingQuestDbSsl(config.url, config.ssl);
}
const poolConfig: PoolConfig = {
max: config.max ?? 4,
connectionTimeoutMillis: config.connectionTimeoutMillis ?? 5_000,
@ -48,7 +214,25 @@ export async function openQuestDbPgExecutor(
...(config.ssl !== undefined ? { ssl: config.ssl } : {}),
};
const pool = new Pool(poolConfig);
const secretNeedles = collectConfigSecretNeedles(config);
const createPool = options?.createPool ?? ((cfg: PoolConfig) => new Pool(cfg));
const pool = createPool(poolConfig);
// Register an idle-client error listener before the startup probe so backend
// restarts or network disconnects on idle connections cannot crash the host
// with an unhandled EventEmitter 'error' event; pg-pool automatically drops
// the failed idle client and opens a fresh connection on the next query.
pool.on('error', (err: Error) => {
if (options?.onPoolError !== undefined) {
const safeError = sanitizePoolError(err, secretNeedles);
try {
options.onPoolError(safeError);
} catch {
// Never allow diagnostic callbacks to re-throw from an EventEmitter error handler.
}
}
});
try {
await pool.query('SELECT 1');
} catch (err: unknown) {

View file

@ -1,6 +1,11 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { EventEmitter } from 'node:events';
import { QuestDBHealthMonitor } from '../src/health';
import { QuestDBInfluxWriter } from '../src/influx-writer';
import {
openQuestDbPgExecutor,
type QuestDbPgPoolLike,
} from '../src/pg-executor';
import { QuestDBQueryBuilder } from '../src/query-builder';
import {
applyM2IntradayDDL,
@ -571,4 +576,143 @@ describe('QuestDB', () => {
monitor.stopMonitoring();
});
});
describe('openQuestDbPgExecutor', () => {
it('registers pool error listener before SELECT 1, redacts credentials, and recovers on next query after idle disconnect', async () => {
const secret = 'qdb_idle_s3cr3t!';
const url = `postgresql://admin:${encodeURIComponent(secret)}@10.0.0.51:8812/qdb`;
class FakePool extends EventEmitter implements QuestDbPgPoolLike {
connectionEpoch = 1;
probeSawErrorListener = false;
ended = false;
readonly queries: Array<{ readonly sql: string; readonly epoch: number }> = [];
async query(sql: string): Promise<{ readonly rows: readonly unknown[] }> {
if (sql === 'SELECT 1') {
this.probeSawErrorListener = this.listenerCount('error') > 0;
this.queries.push({ sql, epoch: this.connectionEpoch });
return { rows: [{ '?column?': 1 }] };
}
this.queries.push({ sql, epoch: this.connectionEpoch });
return { rows: [{ ok: true, epoch: this.connectionEpoch }] };
}
async end(): Promise<void> {
this.ended = true;
}
}
const fakePool = new FakePool();
const observedErrors: Error[] = [];
const handle = await openQuestDbPgExecutor(
{ url },
{
createPool: () => fakePool,
onPoolError: err => {
observedErrors.push(err);
},
}
);
try {
// Listener must be attached before the startup probe runs.
expect(fakePool.probeSawErrorListener).toBe(true);
expect(fakePool.listenerCount('error')).toBeGreaterThan(0);
// Simulate QuestDB restarting while the connection opened by SELECT 1 is idle.
const idleErr = Object.assign(
new Error(`idle connection dropped for ${url} (password=${secret})`),
{ code: 'ECONNRESET' }
);
expect(() => fakePool.emit('error', idleErr)).not.toThrow();
// Diagnostic callback receives a credential-free Error with the safe error code.
expect(observedErrors).toHaveLength(1);
expect(observedErrors[0]?.message).not.toContain(secret);
expect(observedErrors[0]?.message).not.toContain(url);
expect(observedErrors[0]?.message).toContain('ECONNRESET');
expect((observedErrors[0] as Error & { code?: string }).code).toBe('ECONNRESET');
// Pool replaces the failed idle client and serves the next query cleanly.
fakePool.connectionEpoch = 2;
const result = await handle.executor.query('SELECT pair FROM fx_1m LIMIT 1');
expect(result.rows).toEqual([{ ok: true, epoch: 2 }]);
expect(fakePool.queries).toEqual([
{ sql: 'SELECT 1', epoch: 1 },
{ sql: 'SELECT pair FROM fx_1m LIMIT 1', epoch: 2 },
]);
} finally {
await handle.close();
await handle.close();
}
expect(fakePool.ended).toBe(true);
});
it('rejects conflicting URL SSL query parameters and explicit ssl before creating a pool', async () => {
const secret = 'qdb_ssl_s3cr3t!';
const base = `postgresql://admin:${encodeURIComponent(secret)}@10.0.0.51:8812/qdb`;
const conflictingCases: ReadonlyArray<readonly [string, boolean]> = [
[`${base}?sslmode=disable`, true],
[`${base}?SSLMODE=DISABLE`, true],
[`${base}?sslmode=require`, false],
[`${base}?sslmode=verify-ca`, false],
[`${base}?sslmode=verify-full`, false],
[`${base}?sslmode=no-verify`, false],
[`${base}?sslmode=prefer`, true],
[`${base}?sslmode=prefer`, false],
[`${base}?sslmode=allow`, true],
[`${base}?ssl=false`, true],
[`${base}?ssl=0`, true],
[`${base}?ssl=true`, false],
[`${base}?ssl=1`, false],
[`${base}?sslrootcert=/etc/ssl/ca.pem`, false],
];
let createPoolCalls = 0;
for (const [url, ssl] of conflictingCases) {
let caught: unknown;
try {
await openQuestDbPgExecutor(
{ url, ssl },
{
createPool: () => {
createPoolCalls += 1;
throw new Error('createPool must not be called on conflicting SSL config');
},
}
);
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(RangeError);
expect((caught as Error).message).toContain('SSL');
expect((caught as Error).message).not.toContain(secret);
expect((caught as Error).message).not.toContain(url);
}
expect(createPoolCalls).toBe(0);
// Compatible combinations proceed to pool creation.
const compatibleCases: ReadonlyArray<readonly [string, boolean]> = [
[base, true],
[`${base}?sslmode=require`, true],
[`${base}?sslmode=disable`, false],
[`${base}?ssl=true`, true],
[`${base}?ssl=false`, false],
];
for (const [url, ssl] of compatibleCases) {
const pool = Object.assign(new EventEmitter(), {
query: async () => ({ rows: [{ '?column?': 1 }] }),
end: async () => {},
}) as unknown as QuestDbPgPoolLike;
const handle = await openQuestDbPgExecutor(
{ url, ssl },
{ createPool: () => pool }
);
await handle.close();
}
});
});
});

View file

@ -282,6 +282,60 @@ function parseQuestDbPort(raw: string): number {
return port;
}
function hasConflictingUrlSslSetting(rawUrl: string, explicitSsl: boolean): boolean {
let parsed: URL;
try {
parsed = new URL(rawUrl);
} catch {
return false;
}
for (const [rawKey, rawValue] of parsed.searchParams.entries()) {
const key = rawKey.toLowerCase();
const value = rawValue.trim().toLowerCase();
if (key === 'sslmode') {
if (value === 'disable') {
if (explicitSsl) {
return true;
}
} else if (
value === 'require' ||
value === 'verify-ca' ||
value === 'verify-full' ||
value === 'no-verify'
) {
if (!explicitSsl) {
return true;
}
} else {
// `allow`, `prefer`, or any unrecognized sslmode conflicts with an explicit boolean override.
return true;
}
} else if (key === 'ssl') {
if (value === 'false' || value === '0') {
if (explicitSsl) {
return true;
}
} else if (value === 'true' || value === '1') {
if (!explicitSsl) {
return true;
}
} else {
return true;
}
} else if (
(key === 'sslcert' || key === 'sslkey' || key === 'sslrootcert') &&
value.length > 0 &&
!explicitSsl
) {
return true;
}
}
return false;
}
function parseQuestDbConfig(data: {
readonly [ENV_QUESTDB_URL]?: string;
readonly [ENV_QUESTDB_HOST]?: string;
@ -320,6 +374,12 @@ function parseQuestDbConfig(data: {
);
}
const url = parsePgWireUrl(rawUrl, ENV_QUESTDB_URL);
if (ssl !== undefined && hasConflictingUrlSslSetting(url, ssl)) {
throw new ResearchCopilotHostConfigError(
ENV_QUESTDB_SSL,
`Conflicting configuration variable "${ENV_QUESTDB_SSL}": conflicts with SSL query parameters in "${ENV_QUESTDB_URL}".`
);
}
return {
url,
...(ssl !== undefined ? { ssl } : {}),

View file

@ -1242,20 +1242,73 @@ describe('runResearchCopilotStdioHost', () => {
ssl: false,
});
// 4. Rejects conflicting URL + host, partial port-without-host, bad port, bad ssl, unknown var.
// 4. Rejects conflicting URL + host, partial port-without-host, bad port, bad ssl, unknown var,
// and conflicting URL SSL query parameters vs RESEARCH_MCP_QUESTDB_SSL without leaking secrets.
const invalidEnvs: Array<Record<string, string>> = [
{ RESEARCH_MCP_QUESTDB_URL: questUrl, RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51' },
{ RESEARCH_MCP_QUESTDB_PG_PORT: '8812' },
{ RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51', RESEARCH_MCP_QUESTDB_PG_PORT: '99999' },
{ RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51', RESEARCH_MCP_QUESTDB_SSL: 'maybe' },
{ RESEARCH_MCP_QUESTDB_UNKNOWN: '1' },
{
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=disable`,
RESEARCH_MCP_QUESTDB_SSL: 'true',
},
{
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=require`,
RESEARCH_MCP_QUESTDB_SSL: 'false',
},
{
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?ssl=false`,
RESEARCH_MCP_QUESTDB_SSL: 'true',
},
{
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?ssl=true`,
RESEARCH_MCP_QUESTDB_SSL: 'false',
},
{
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=prefer`,
RESEARCH_MCP_QUESTDB_SSL: 'true',
},
{
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslrootcert=/etc/ssl/ca.pem`,
RESEARCH_MCP_QUESTDB_SSL: 'false',
},
];
for (const override of invalidEnvs) {
expect(() => parseResearchCopilotHostConfig(buildValidEnv(override))).toThrow(
ResearchCopilotHostConfigError
);
let caughtInvalid: unknown;
try {
parseResearchCopilotHostConfig(buildValidEnv(override));
} catch (err) {
caughtInvalid = err;
}
expect(caughtInvalid).toBeInstanceOf(ResearchCopilotHostConfigError);
expect((caughtInvalid as Error).message).not.toContain(questSecret);
expect((caughtInvalid as Error).message).not.toContain(questUrl);
}
// Compatible URL SSL query params + matching RESEARCH_MCP_QUESTDB_SSL are accepted.
const consistentSslEnable = parseResearchCopilotHostConfig(
buildValidEnv({
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=require`,
RESEARCH_MCP_QUESTDB_SSL: 'true',
})
);
expect(consistentSslEnable.questdb).toEqual({
url: `${questUrl}?sslmode=require`,
ssl: true,
});
const consistentSslDisable = parseResearchCopilotHostConfig(
buildValidEnv({
RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=disable`,
RESEARCH_MCP_QUESTDB_SSL: 'false',
})
);
expect(consistentSslDisable.questdb).toEqual({
url: `${questUrl}?sslmode=disable`,
ssl: false,
});
// 5. Redacts QuestDB URL / password on openStore and cleanup errors.
for (const cfg of [urlConfig, hostFullConfig]) {
let caught: unknown;

View file

@ -15,12 +15,17 @@
import {
applyM2IntradayDDL,
assertNoConflictingQuestDbSsl,
openQuestDbPgExecutor,
type QuestDbPgExecutorConfig,
} from '@stock-bot/questdb';
function readEnv(primary: string, fallback: string): string | undefined {
const value = process.env[primary] ?? process.env[fallback];
function readEnv(
env: Readonly<Record<string, string | undefined>>,
primary: string,
fallback: string
): string | undefined {
const value = env[primary] ?? env[fallback];
if (value === undefined) {
return undefined;
}
@ -28,34 +33,47 @@ function readEnv(primary: string, fallback: string): string | undefined {
return trimmed.length > 0 ? trimmed : undefined;
}
function resolveConfig(): QuestDbPgExecutorConfig {
const url = readEnv('QUESTDB_URL', 'RESEARCH_MCP_QUESTDB_URL');
const sslRaw = readEnv('QUESTDB_SSL', 'RESEARCH_MCP_QUESTDB_SSL');
const ssl =
sslRaw === undefined
? undefined
: sslRaw.toLowerCase() === 'true' || sslRaw === '1'
? true
: sslRaw.toLowerCase() === 'false' || sslRaw === '0'
? false
: undefined;
function parseSslFlag(raw: string): boolean {
const normalized = raw.trim().toLowerCase();
if (normalized === 'true' || normalized === '1') {
return true;
}
if (normalized === 'false' || normalized === '0') {
return false;
}
throw new RangeError(
'Invalid QuestDB SSL configuration: expected "true", "false", "1", or "0".'
);
}
export function resolveQuestDbInitM2Config(
env: Readonly<Record<string, string | undefined>> = process.env
): QuestDbPgExecutorConfig {
const url = readEnv(env, 'QUESTDB_URL', 'RESEARCH_MCP_QUESTDB_URL');
const sslRaw = readEnv(env, 'QUESTDB_SSL', 'RESEARCH_MCP_QUESTDB_SSL');
const ssl = sslRaw !== undefined ? parseSslFlag(sslRaw) : undefined;
if (url !== undefined) {
if (ssl !== undefined) {
assertNoConflictingQuestDbSsl(url, ssl);
}
return {
url,
...(ssl !== undefined ? { ssl } : {}),
};
}
const host = readEnv('QUESTDB_HOST', 'RESEARCH_MCP_QUESTDB_HOST') ?? 'localhost';
const portRaw = readEnv('QUESTDB_PG_PORT', 'RESEARCH_MCP_QUESTDB_PG_PORT');
const host = readEnv(env, 'QUESTDB_HOST', 'RESEARCH_MCP_QUESTDB_HOST') ?? 'localhost';
const portRaw = readEnv(env, 'QUESTDB_PG_PORT', 'RESEARCH_MCP_QUESTDB_PG_PORT');
const port = portRaw !== undefined ? Number(portRaw) : 8812;
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error(`Invalid QuestDB PGWire port "${String(portRaw)}". Expected 1..65535.`);
throw new RangeError(
`Invalid QuestDB PGWire port "${String(portRaw)}". Expected 1..65535.`
);
}
const database = readEnv('QUESTDB_DATABASE', 'RESEARCH_MCP_QUESTDB_DATABASE') ?? 'qdb';
const user = readEnv('QUESTDB_USER', 'RESEARCH_MCP_QUESTDB_USER');
const password = readEnv('QUESTDB_PASSWORD', 'RESEARCH_MCP_QUESTDB_PASSWORD');
const database = readEnv(env, 'QUESTDB_DATABASE', 'RESEARCH_MCP_QUESTDB_DATABASE') ?? 'qdb';
const user = readEnv(env, 'QUESTDB_USER', 'RESEARCH_MCP_QUESTDB_USER');
const password = readEnv(env, 'QUESTDB_PASSWORD', 'RESEARCH_MCP_QUESTDB_PASSWORD');
return {
host,
@ -67,21 +85,29 @@ function resolveConfig(): QuestDbPgExecutorConfig {
};
}
async function main(): Promise<void> {
const config = resolveConfig();
const handle = await openQuestDbPgExecutor(config);
export async function runQuestDbInitM2(
env: Readonly<Record<string, string | undefined>> = process.env,
openExecutor: typeof openQuestDbPgExecutor = openQuestDbPgExecutor
): Promise<{ readonly appliedTables: readonly string[] }> {
const config = resolveQuestDbInitM2Config(env);
const handle = await openExecutor(config);
try {
const result = await applyM2IntradayDDL(handle.executor);
process.stdout.write(
`Initialized QuestDB M2 intraday tables: ${result.appliedTables.join(', ')}\n`
);
return await applyM2IntradayDDL(handle.executor);
} finally {
await handle.close();
}
}
main().catch((err: unknown) => {
const message = err instanceof Error ? err.message : String(err);
process.stderr.write(`questdb-init-m2 failed: ${message}\n`);
process.exit(1);
});
if (import.meta.main) {
runQuestDbInitM2()
.then(result => {
process.stdout.write(
`Initialized QuestDB M2 intraday tables: ${result.appliedTables.join(', ')}\n`
);
})
.catch((err: unknown) => {
const message = err instanceof Error ? err.message : String(err);
process.stderr.write(`questdb-init-m2 failed: ${message}\n`);
process.exit(1);
});
}

View file

@ -0,0 +1,78 @@
import { describe, expect, test } from 'bun:test';
import { M2_INTRADAY_TABLE_NAMES } from '@stock-bot/questdb';
import { resolveQuestDbInitM2Config, runQuestDbInitM2 } from '../questdb-init-m2';
describe('scripts/questdb-init-m2', () => {
test('rejects conflicting URL SSL settings before opening a QuestDB connection', async () => {
const secret = 'ddl_init_s3cr3t!';
const baseUrl = `postgresql://admin:${encodeURIComponent(secret)}@10.0.0.51:8812/qdb`;
const conflictingEnvs: Array<Record<string, string>> = [
{ QUESTDB_URL: `${baseUrl}?sslmode=disable`, QUESTDB_SSL: 'true' },
{ RESEARCH_MCP_QUESTDB_URL: `${baseUrl}?sslmode=disable`, RESEARCH_MCP_QUESTDB_SSL: 'true' },
{ QUESTDB_URL: `${baseUrl}?sslmode=require`, QUESTDB_SSL: 'false' },
{ QUESTDB_URL: `${baseUrl}?ssl=false`, QUESTDB_SSL: 'true' },
{ QUESTDB_URL: `${baseUrl}?sslmode=prefer`, QUESTDB_SSL: 'true' },
];
let openCalls = 0;
for (const env of conflictingEnvs) {
let caught: unknown;
try {
await runQuestDbInitM2(env, async () => {
openCalls += 1;
throw new Error('openExecutor must not be called on conflicting SSL config');
});
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(RangeError);
expect((caught as Error).message).toContain('SSL');
expect((caught as Error).message).not.toContain(secret);
expect((caught as Error).message).not.toContain(baseUrl);
}
expect(openCalls).toBe(0);
});
test('rejects invalid SSL flag values and accepts consistent URL + SSL configs', async () => {
expect(() =>
resolveQuestDbInitM2Config({
QUESTDB_HOST: '10.0.0.51',
QUESTDB_SSL: 'maybe',
})
).toThrow(RangeError);
const resolved = resolveQuestDbInitM2Config({
QUESTDB_URL: 'postgresql://admin:pass@10.0.0.51:8812/qdb?sslmode=require',
QUESTDB_SSL: 'true',
});
expect(resolved).toEqual({
url: 'postgresql://admin:pass@10.0.0.51:8812/qdb?sslmode=require',
ssl: true,
});
const executed: string[] = [];
let closed = false;
const result = await runQuestDbInitM2(
{
QUESTDB_URL: 'postgresql://admin:pass@10.0.0.51:8812/qdb?sslmode=disable',
QUESTDB_SSL: 'false',
},
async () => ({
executor: {
async query(sql: string) {
executed.push(sql);
return { rows: [] };
},
},
async close() {
closed = true;
},
})
);
expect(result.appliedTables).toEqual([...M2_INTRADAY_TABLE_NAMES]);
expect(executed).toHaveLength(3);
expect(closed).toBe(true);
});
});