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

@ -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) {