T-117: M1.2ag — data-pipeline: read-only MongoDB → concatenated raw-BSON file exporter for the collections curate-etl consumes (raw: true cursor, byte pass-through, atomic publish) with tests and local benchmark

This commit is contained in:
Studio 2026-11-29 06:09:51 -05:00
parent c0afe5e3f0
commit 0962f66cc3
9 changed files with 2436 additions and 1 deletions

View file

@ -0,0 +1,675 @@
import { createHash, randomUUID } from 'node:crypto';
import { mkdir, open, rename, unlink } from 'node:fs/promises';
import { join } from 'node:path';
import type { MongoDBClient } from '@stock-bot/mongodb';
/**
* M1 allowlisted MongoDB collections whose concatenated raw BSON documents are consumed by
* `tools/curate-etl` (`curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`,
* `curate-fx-1d`, `curate-shorts`, `curate-events`).
*/
export const RAW_BSON_EXPORT_COLLECTIONS = Object.freeze([
'eodPrices',
'qmSplits',
'qmDividends',
'qmPrices',
'teMarketData',
'ceoShorts',
'qmFilings',
'qmEarnings',
] as const);
export type RawBsonExportCollection = (typeof RAW_BSON_EXPORT_COLLECTIONS)[number];
const RAW_BSON_EXPORT_COLLECTION_SET: ReadonlySet<string> = new Set(RAW_BSON_EXPORT_COLLECTIONS);
export const MIN_RAW_BSON_DOC_BYTES = 5;
/** Matches `tools/curate-etl` `bson_stream` ceiling (16 MiB BSON max + 16 KiB wire headroom). */
export const DEFAULT_MAX_RAW_BSON_DOC_BYTES = 16 * 1024 * 1024 + 16 * 1024;
export const DEFAULT_WRITE_BUFFER_BYTES = 8 * 1024 * 1024;
export const MIN_WRITE_BUFFER_BYTES = 64;
export const MAX_WRITE_BUFFER_BYTES = 64 * 1024 * 1024;
export const DEFAULT_RAW_BSON_BATCH_SIZE = 4_096;
export const MAX_RAW_BSON_BATCH_SIZE = 100_000;
export function isRawBsonExportCollection(value: string): value is RawBsonExportCollection {
return RAW_BSON_EXPORT_COLLECTION_SET.has(value);
}
export type RawBsonExportErrorCode =
| 'DISALLOWED_COLLECTION'
| 'INVALID_OPTION'
| 'INVALID_SOURCE'
| 'INVALID_BSON_FRAME';
export interface RawBsonExportErrorOptions {
readonly code: RawBsonExportErrorCode;
readonly collection: string;
readonly docOrdinal?: number;
readonly detail: string;
readonly cause?: unknown;
}
export class RawBsonExportError extends Error {
readonly code: RawBsonExportErrorCode;
readonly collection: string;
readonly docOrdinal?: number;
constructor(options: RawBsonExportErrorOptions) {
const ordinalPart = options.docOrdinal !== undefined ? ` doc#${options.docOrdinal}` : '';
super(
`[${options.code}] ${options.collection}${ordinalPart}: ${options.detail}`,
options.cause !== undefined ? { cause: options.cause } : undefined
);
this.name = 'RawBsonExportError';
this.code = options.code;
this.collection = options.collection;
if (options.docOrdinal !== undefined) {
this.docOrdinal = options.docOrdinal;
}
}
}
export interface RawBsonFindOptions {
readonly raw: true;
readonly batchSize?: number;
readonly limit?: number;
}
export interface ReadOnlyRawBsonCursor extends AsyncIterable<unknown> {
close?(): Promise<unknown>;
}
export interface ReadOnlyRawBsonCollection {
find(filter: Record<string, unknown>, options: RawBsonFindOptions): ReadOnlyRawBsonCursor;
}
export interface ReadOnlyMongoRawBsonClient {
isReadOnly(): boolean;
getCollection(name: string): ReadOnlyRawBsonCollection;
}
export interface ReadOnlyRawBsonSource {
isReadOnly(): boolean;
find(
collectionName: string,
filter: Record<string, unknown>,
options: RawBsonFindOptions
): Promise<AsyncIterable<unknown>> | AsyncIterable<unknown>;
}
// Compile-time structural compatibility check (type-only, erased at runtime):
// verifies the real `MongoDBClient` satisfies `ReadOnlyMongoRawBsonClient`.
type AssertAssignable<Target, _Candidate extends Target> = true;
export type MongoDBClientRawBsonSourceCheck = AssertAssignable<
ReadOnlyMongoRawBsonClient,
MongoDBClient
>;
export interface ExportRawBsonFileHandle {
write(
buffer: Uint8Array,
offset?: number | null,
length?: number | null,
position?: number | null
): Promise<{ bytesWritten: number }>;
sync(): Promise<void>;
close(): Promise<void>;
}
export interface ExportRawBsonFsHooks {
readonly mkdir?: typeof mkdir;
readonly open?: (path: string, flags: string) => Promise<ExportRawBsonFileHandle>;
readonly rename?: typeof rename;
readonly unlink?: typeof unlink;
}
export interface ExportRawBsonCollectionOptions {
readonly collection: string;
readonly outDir: string;
readonly eodSymbol?: string;
readonly teSymbol?: string;
readonly limit?: number;
readonly batchSize?: number;
readonly writeBufferBytes?: number;
readonly maxDocBytes?: number;
readonly fs?: ExportRawBsonFsHooks;
}
export interface ExportRawBsonCollectionResult {
readonly collection: RawBsonExportCollection;
readonly outPath: string;
readonly docsWritten: number;
readonly bytesWritten: number;
readonly elapsedMs: number;
readonly sha256: string;
readonly filter: Readonly<Record<string, string>>;
}
function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
return false;
}
return typeof (value as Partial<Record<symbol, unknown>>)[Symbol.asyncIterator] === 'function';
}
/**
* Adapts a read-only `MongoDBClient` into a streaming `ReadOnlyRawBsonSource`.
* Rejects non-read-only clients and buffered/non-AsyncIterable cursor results, and
* guarantees `cursor.close()` runs in `finally` on completion, early break, or error.
*/
export function createReadOnlyMongoRawBsonSource(
client: ReadOnlyMongoRawBsonClient
): ReadOnlyRawBsonSource {
if (!client || typeof client.isReadOnly !== 'function' || client.isReadOnly() !== true) {
throw new RawBsonExportError({
code: 'INVALID_SOURCE',
collection: '*',
detail: 'MongoDB client must be configured in read-only mode (isReadOnly() === true)',
});
}
return {
isReadOnly(): boolean {
return client.isReadOnly() === true;
},
find(
collectionName: string,
filter: Record<string, unknown>,
options: RawBsonFindOptions
): AsyncIterable<unknown> {
if (client.isReadOnly() !== true) {
throw new RawBsonExportError({
code: 'INVALID_SOURCE',
collection: collectionName,
detail: 'MongoDB client must remain in read-only mode (isReadOnly() === true)',
});
}
if (!options || options.raw !== true) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: 'Raw BSON export requires find option { raw: true }',
});
}
const cursor = client.getCollection(collectionName).find(filter, options);
if (!isAsyncIterable(cursor)) {
throw new RawBsonExportError({
code: 'INVALID_SOURCE',
collection: collectionName,
detail:
'Collection find() must return a streaming AsyncIterable cursor (buffered arrays are not allowed)',
});
}
return {
async *[Symbol.asyncIterator]() {
let primaryError: unknown = undefined;
let hasPrimaryError = false;
try {
for await (const doc of cursor) {
yield doc;
}
} catch (error) {
primaryError = error;
hasPrimaryError = true;
throw error;
} finally {
if (typeof cursor.close === 'function') {
try {
await cursor.close();
} catch (closeError) {
if (!hasPrimaryError) {
// Only surface close errors if iteration itself succeeded.
primaryError = closeError;
hasPrimaryError = true;
}
}
}
}
if (hasPrimaryError) {
throw primaryError;
}
},
};
},
};
}
/**
* Validates that a single raw BSON document frame is a `Uint8Array` of length in
* `[5, maxDocBytes]` whose leading signed 32-bit little-endian length prefix equals
* `byteLength` and whose final byte is `0x00`.
*/
export function validateRawBsonFrame(
bytes: unknown,
collection: string,
docOrdinal: number,
maxDocBytes: number = DEFAULT_MAX_RAW_BSON_DOC_BYTES
): Uint8Array {
if (!(bytes instanceof Uint8Array)) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `expected Uint8Array raw BSON frame, got ${bytes === null ? 'null' : typeof bytes}`,
});
}
const byteLength = bytes.byteLength;
if (byteLength < MIN_RAW_BSON_DOC_BYTES) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `frame length ${byteLength} is below minimum BSON document size (${MIN_RAW_BSON_DOC_BYTES})`,
});
}
if (byteLength > maxDocBytes) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `frame length ${byteLength} exceeds maxDocBytes (${maxDocBytes})`,
});
}
const b0 = bytes[0] ?? 0;
const b1 = bytes[1] ?? 0;
const b2 = bytes[2] ?? 0;
const b3 = bytes[3] ?? 0;
const declaredLen = (b0 | (b1 << 8) | (b2 << 16) | (b3 << 24)) | 0;
if (declaredLen !== byteLength) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `4-byte LE length prefix (${declaredLen}) disagrees with frame byteLength (${byteLength})`,
});
}
const lastByte = bytes[byteLength - 1];
if (lastByte !== 0x00) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `missing trailing 0x00 terminator (got 0x${(lastByte ?? 0).toString(16).padStart(2, '0')})`,
});
}
return bytes;
}
/**
* Walks concatenated length-prefixed raw BSON documents using the exact framing rules
* implemented by `tools/curate-etl/src/bson_eod_prices.rs::iter_raw_bson_docs`
* (signed 32-bit LE length prefix `>= 5`, `<= maxDocBytes`, exact buffer bounds, trailing `0x00`).
*/
export function walkRawBsonFrames(
bytes: Uint8Array,
maxDocBytes: number = DEFAULT_MAX_RAW_BSON_DOC_BYTES,
collection: string = '<buffer>'
): Uint8Array[] {
const frames: Uint8Array[] = [];
let offset = 0;
let docOrdinal = 0;
while (offset < bytes.byteLength) {
const remaining = bytes.byteLength - offset;
if (remaining < 4) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `truncated BSON length prefix at byte offset ${offset} (${remaining} bytes remaining)`,
});
}
const b0 = bytes[offset] ?? 0;
const b1 = bytes[offset + 1] ?? 0;
const b2 = bytes[offset + 2] ?? 0;
const b3 = bytes[offset + 3] ?? 0;
const declaredLen = (b0 | (b1 << 8) | (b2 << 16) | (b3 << 24)) | 0;
if (declaredLen < MIN_RAW_BSON_DOC_BYTES) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `corrupt BSON document length ${declaredLen} at byte offset ${offset}`,
});
}
if (declaredLen > maxDocBytes) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `BSON document length ${declaredLen} at byte offset ${offset} exceeds maxDocBytes (${maxDocBytes})`,
});
}
if (declaredLen > remaining) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `truncated BSON document at byte offset ${offset} (declared ${declaredLen}, remaining ${remaining})`,
});
}
const frame = bytes.subarray(offset, offset + declaredLen);
const lastByte = frame[declaredLen - 1];
if (lastByte !== 0x00) {
throw new RawBsonExportError({
code: 'INVALID_BSON_FRAME',
collection,
docOrdinal,
detail: `missing trailing 0x00 terminator at byte offset ${offset}`,
});
}
frames.push(frame);
offset += declaredLen;
docOrdinal += 1;
}
return frames;
}
interface ValidatedExportOptions {
readonly collection: RawBsonExportCollection;
readonly outDir: string;
readonly filter: Readonly<Record<string, string>>;
readonly limit?: number;
readonly batchSize: number;
readonly writeBufferBytes: number;
readonly maxDocBytes: number;
}
function validateExportOptions(options: ExportRawBsonCollectionOptions): ValidatedExportOptions {
const collectionName = typeof options?.collection === 'string' ? options.collection : '';
if (!isRawBsonExportCollection(collectionName)) {
throw new RawBsonExportError({
code: 'DISALLOWED_COLLECTION',
collection: collectionName || '<empty>',
detail: `collection "${collectionName}" is not in the M1 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`,
});
}
if (typeof options.outDir !== 'string' || options.outDir.trim().length === 0) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: 'outDir must be a non-empty string',
});
}
const writeBufferBytes = options.writeBufferBytes ?? DEFAULT_WRITE_BUFFER_BYTES;
if (
!Number.isSafeInteger(writeBufferBytes) ||
writeBufferBytes < MIN_WRITE_BUFFER_BYTES ||
writeBufferBytes > MAX_WRITE_BUFFER_BYTES
) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: `writeBufferBytes must be an integer in [${MIN_WRITE_BUFFER_BYTES}, ${MAX_WRITE_BUFFER_BYTES}] (got ${String(writeBufferBytes)})`,
});
}
const maxDocBytes = options.maxDocBytes ?? DEFAULT_MAX_RAW_BSON_DOC_BYTES;
if (
!Number.isSafeInteger(maxDocBytes) ||
maxDocBytes < MIN_RAW_BSON_DOC_BYTES ||
maxDocBytes > MAX_WRITE_BUFFER_BYTES
) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: `maxDocBytes must be an integer in [${MIN_RAW_BSON_DOC_BYTES}, ${MAX_WRITE_BUFFER_BYTES}] (got ${String(maxDocBytes)})`,
});
}
const batchSize = options.batchSize ?? DEFAULT_RAW_BSON_BATCH_SIZE;
if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > MAX_RAW_BSON_BATCH_SIZE) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: `batchSize must be an integer in [1, ${MAX_RAW_BSON_BATCH_SIZE}] (got ${String(batchSize)})`,
});
}
let limit: number | undefined;
if (options.limit !== undefined) {
if (!Number.isSafeInteger(options.limit) || options.limit < 1) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: `limit must be a positive safe integer (got ${String(options.limit)})`,
});
}
limit = options.limit;
}
let filter: Record<string, string> = {};
if (options.eodSymbol !== undefined) {
if (collectionName !== 'eodPrices') {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: '--eod-symbol filter is only permitted for collection "eodPrices"',
});
}
if (typeof options.eodSymbol !== 'string' || options.eodSymbol.trim().length === 0) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: 'eodSymbol must be a non-empty string',
});
}
filter = { eodSearchCode: options.eodSymbol };
}
if (options.teSymbol !== undefined) {
if (collectionName !== 'teMarketData') {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: '--te-symbol filter is only permitted for collection "teMarketData"',
});
}
if (typeof options.teSymbol !== 'string' || options.teSymbol.trim().length === 0) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: collectionName,
detail: 'teSymbol must be a non-empty string',
});
}
filter = { teSymbol: options.teSymbol };
}
return {
collection: collectionName,
outDir: options.outDir.trim(),
filter: Object.freeze(filter),
...(limit !== undefined ? { limit } : {}),
batchSize,
writeBufferBytes,
maxDocBytes,
};
}
async function writeAll(
handle: ExportRawBsonFileHandle,
buffer: Uint8Array,
length: number,
collection: string,
tempPath: string
): Promise<void> {
let offset = 0;
while (offset < length) {
const remaining = length - offset;
const result = await handle.write(buffer, offset, remaining);
if (
!result ||
typeof result.bytesWritten !== 'number' ||
!Number.isInteger(result.bytesWritten) ||
result.bytesWritten <= 0
) {
throw new Error(
`Short write (bytesWritten=${String(result?.bytesWritten)}) while exporting "${collection}" to ${tempPath}`
);
}
if (result.bytesWritten > remaining) {
throw new Error(
`Write hook reported bytesWritten=${result.bytesWritten} exceeding requested length=${remaining} while exporting "${collection}" to ${tempPath}`
);
}
offset += result.bytesWritten;
}
}
/**
* Streams an allowlisted MongoDB collection as untouched raw BSON frames into
* `<outDir>/<collection>.bson` using a fixed-size write buffer, incremental SHA-256 hashing,
* and atomic same-directory temp-file publish (`open('wx')` -> `write` -> `sync` -> `close` -> `rename`).
*/
export async function exportRawBsonCollection(
source: ReadOnlyRawBsonSource,
options: ExportRawBsonCollectionOptions
): Promise<ExportRawBsonCollectionResult> {
const validated = validateExportOptions(options);
if (
!source ||
typeof source.isReadOnly !== 'function' ||
source.isReadOnly() !== true ||
typeof source.find !== 'function'
) {
throw new RawBsonExportError({
code: 'INVALID_SOURCE',
collection: validated.collection,
detail: 'Raw BSON exporter requires a read-only source (isReadOnly() === true)',
});
}
const mkdirFn = options.fs?.mkdir ?? mkdir;
const openFn: (path: string, flags: string) => Promise<ExportRawBsonFileHandle> =
options.fs?.open ?? ((filePath: string, flags: string) => open(filePath, flags));
const renameFn = options.fs?.rename ?? rename;
const unlinkFn = options.fs?.unlink ?? unlink;
const startMs = performance.now();
await mkdirFn(validated.outDir, { recursive: true });
const outPath = join(validated.outDir, `${validated.collection}.bson`);
const tempPath = join(
validated.outDir,
`.${validated.collection}.bson.${process.pid}.${randomUUID()}.tmp`
);
const handle = await openFn(tempPath, 'wx');
let handleClosed = false;
let renamed = false;
const writeBuffer = new Uint8Array(validated.writeBufferBytes);
let buffered = 0;
const hash = createHash('sha256');
let docsWritten = 0;
let bytesWritten = 0;
const flushBuffer = async (): Promise<void> => {
if (buffered > 0) {
await writeAll(handle, writeBuffer, buffered, validated.collection, tempPath);
buffered = 0;
}
};
try {
const findOptions: RawBsonFindOptions = {
raw: true,
batchSize: validated.batchSize,
...(validated.limit !== undefined ? { limit: validated.limit } : {}),
};
const iterable = await source.find(
validated.collection,
{ ...validated.filter },
findOptions
);
if (!isAsyncIterable(iterable)) {
throw new RawBsonExportError({
code: 'INVALID_SOURCE',
collection: validated.collection,
detail:
'Source find() must return a streaming AsyncIterable (buffered arrays are not allowed)',
});
}
for await (const rawDoc of iterable) {
if (validated.limit !== undefined && docsWritten >= validated.limit) {
break;
}
const frame = validateRawBsonFrame(
rawDoc,
validated.collection,
docsWritten,
validated.maxDocBytes
);
const frameLen = frame.byteLength;
hash.update(frame);
if (frameLen > validated.writeBufferBytes) {
await flushBuffer();
await writeAll(handle, frame, frameLen, validated.collection, tempPath);
} else {
if (buffered + frameLen > validated.writeBufferBytes) {
await flushBuffer();
}
writeBuffer.set(frame, buffered);
buffered += frameLen;
}
docsWritten += 1;
bytesWritten += frameLen;
if (validated.limit !== undefined && docsWritten >= validated.limit) {
break;
}
}
await flushBuffer();
await handle.sync();
await handle.close();
handleClosed = true;
await renameFn(tempPath, outPath);
renamed = true;
} catch (error) {
if (!handleClosed) {
await handle.close().catch(() => {});
}
if (!renamed) {
await unlinkFn(tempPath).catch(() => {});
}
throw error;
}
const elapsedMs = Math.max(0, performance.now() - startMs);
return {
collection: validated.collection,
outPath,
docsWritten,
bytesWritten,
elapsedMs,
sha256: hash.digest('hex'),
filter: validated.filter,
};
}

View file

@ -96,6 +96,51 @@ export {
type RunExportCurateInputsOutput,
} from './run-export-curate-inputs';
export {
createReadOnlyMongoRawBsonSource,
DEFAULT_MAX_RAW_BSON_DOC_BYTES,
DEFAULT_RAW_BSON_BATCH_SIZE,
DEFAULT_WRITE_BUFFER_BYTES,
exportRawBsonCollection,
isRawBsonExportCollection,
MAX_RAW_BSON_BATCH_SIZE,
MAX_WRITE_BUFFER_BYTES,
MIN_RAW_BSON_DOC_BYTES,
MIN_WRITE_BUFFER_BYTES,
RAW_BSON_EXPORT_COLLECTIONS,
RawBsonExportError,
validateRawBsonFrame,
walkRawBsonFrames,
type ExportRawBsonCollectionOptions,
type ExportRawBsonCollectionResult,
type ExportRawBsonFileHandle,
type ExportRawBsonFsHooks,
type MongoDBClientRawBsonSourceCheck,
type RawBsonExportCollection,
type RawBsonExportErrorCode,
type RawBsonExportErrorOptions,
type RawBsonFindOptions,
type ReadOnlyMongoRawBsonClient,
type ReadOnlyRawBsonCollection,
type ReadOnlyRawBsonCursor,
type ReadOnlyRawBsonSource,
} from './export-raw-bson';
export {
assertExportRawBsonSafety,
EXPORT_RAW_BSON_USAGE,
formatExportRawBsonSummary,
parseExportRawBsonArgs,
runCli as runExportRawBsonCli,
runExportRawBson,
type ParsedExportRawBsonArgs,
type RawBsonMongoHandle,
type RunExportRawBsonCliOverrides,
type RunExportRawBsonDeps,
type RunExportRawBsonOptions,
type RunExportRawBsonOutput,
} from './run-export-raw-bson';
export {
escapeSqlLiteral,
generateExchangeSeedSql,

View file

@ -0,0 +1,472 @@
import { getLogger } from '@stock-bot/logger';
import { MongoDBClient } from '@stock-bot/mongodb';
import {
assertEnvironmentSafety,
initializeStockConfig,
type StockAppConfig,
} from '@stock-bot/stock-config';
import {
createReadOnlyMongoRawBsonSource,
DEFAULT_RAW_BSON_BATCH_SIZE,
exportRawBsonCollection,
isRawBsonExportCollection,
MAX_RAW_BSON_BATCH_SIZE,
RAW_BSON_EXPORT_COLLECTIONS,
RawBsonExportError,
type ExportRawBsonCollectionResult,
type ExportRawBsonFsHooks,
type RawBsonExportCollection,
type ReadOnlyMongoRawBsonClient,
} from './export-raw-bson';
import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed';
export const EXPORT_RAW_BSON_USAGE = [
'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts --out-dir <dir> [--collections <c1,c2,...>] [--eod-symbol <code>] [--te-symbol <sym>] [--limit <n>] [--batch-size <n>] [--help]',
'',
'Options:',
' --out-dir <dir> Required. Output directory for <collection>.bson files.',
` --collections <c1,c2,...> Optional. Comma-separated allowlisted collections (default: ${RAW_BSON_EXPORT_COLLECTIONS.join(',')}).`,
' --eod-symbol <code> Optional. Exact eodSearchCode filter (only valid when --collections is strictly eodPrices).',
' --te-symbol <sym> Optional. Exact teSymbol filter (only valid when --collections is strictly teMarketData).',
' --limit <n> Optional. Max documents to export per collection (positive integer, for smoke runs).',
` --batch-size <n> Optional. MongoDB cursor batchSize (1..${MAX_RAW_BSON_BATCH_SIZE}, default: ${DEFAULT_RAW_BSON_BATCH_SIZE}).`,
' --help Show this help message and exit.',
].join('\n');
export type ParsedExportRawBsonArgs =
| { readonly help: true }
| {
readonly help: false;
readonly outDir: string;
readonly collections: readonly RawBsonExportCollection[];
readonly eodSymbol?: string;
readonly teSymbol?: string;
readonly limit?: number;
readonly batchSize: number;
};
export interface RawBsonMongoHandle {
readonly client: ReadOnlyMongoRawBsonClient;
readonly close: () => Promise<void> | void;
}
export interface RunExportRawBsonDeps {
readonly assertSafety?: () => void;
readonly createMongoClient: () => Promise<RawBsonMongoHandle> | RawBsonMongoHandle;
readonly exportFn?: typeof exportRawBsonCollection;
readonly writeStdout?: (text: string) => void;
}
export interface RunExportRawBsonCliOverrides extends Partial<RunExportRawBsonDeps> {
readonly initializeConfig?: typeof initializeStockConfig;
}
export interface RunExportRawBsonOptions {
readonly outDir: string;
readonly collections: readonly RawBsonExportCollection[];
readonly eodSymbol?: string;
readonly teSymbol?: string;
readonly limit?: number;
readonly batchSize?: number;
readonly writeBufferBytes?: number;
readonly maxDocBytes?: number;
readonly fs?: ExportRawBsonFsHooks;
}
export interface RunExportRawBsonOutput {
readonly results: readonly ExportRawBsonCollectionResult[];
readonly summary: string;
}
const STRICT_INT_PATTERN = /^-?\d+$/;
function usageError(message: string): Error {
return new Error(`${message}\n\n${EXPORT_RAW_BSON_USAGE}`);
}
function parsePositiveIntArg(flag: string, raw: string, max?: number): number {
if (!STRICT_INT_PATTERN.test(raw)) {
throw usageError(
max !== undefined
? `Invalid ${flag} value "${raw}": expected an integer between 1 and ${max}`
: `Invalid ${flag} value "${raw}": expected a positive integer`
);
}
const parsed = Number(raw);
if (
!Number.isSafeInteger(parsed) ||
parsed < 1 ||
(max !== undefined && parsed > max)
) {
throw usageError(
max !== undefined
? `Invalid ${flag} value "${raw}": expected an integer between 1 and ${max}`
: `Invalid ${flag} value "${raw}": expected a positive integer`
);
}
return parsed;
}
function parseCollectionsList(raw: string): RawBsonExportCollection[] {
const segments = raw.split(',');
const result: RawBsonExportCollection[] = [];
const seen = new Set<string>();
for (const segment of segments) {
const trimmed = segment.trim();
if (trimmed.length === 0) {
throw usageError(`Malformed --collections value "${raw}": empty collection entry`);
}
if (!isRawBsonExportCollection(trimmed)) {
throw new RawBsonExportError({
code: 'DISALLOWED_COLLECTION',
collection: trimmed,
detail: `collection "${trimmed}" is not in the M1 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`,
});
}
if (seen.has(trimmed)) {
throw usageError(`Duplicate collection "${trimmed}" in --collections`);
}
seen.add(trimmed);
result.push(trimmed);
}
if (result.length === 0) {
throw usageError('Missing value for --collections');
}
return result;
}
function readFlagValue(
argv: readonly string[],
index: number,
flag: string
): { value: string; nextIndex: number } {
const arg = argv[index] ?? '';
const eqPrefix = `${flag}=`;
if (arg.startsWith(eqPrefix)) {
const value = arg.slice(eqPrefix.length).trim();
if (value.length === 0) {
throw usageError(`Missing value for ${flag}`);
}
return { value, nextIndex: index };
}
const next = argv[index + 1];
if (!next || next.trim().length === 0 || next.startsWith('--')) {
throw usageError(`Missing value for ${flag}`);
}
return { value: next.trim(), nextIndex: index + 1 };
}
export function parseExportRawBsonArgs(argv: readonly string[]): ParsedExportRawBsonArgs {
let help = false;
let outDir: string | undefined;
let collections: RawBsonExportCollection[] | undefined;
let eodSymbol: string | undefined;
let teSymbol: string | undefined;
let limit: number | undefined;
let batchSize = DEFAULT_RAW_BSON_BATCH_SIZE;
const seenFlags = new Set<string>();
const markSeen = (flag: string): void => {
if (seenFlags.has(flag)) {
throw usageError(`Duplicate flag: ${flag}`);
}
seenFlags.add(flag);
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--help') {
help = true;
continue;
}
if (arg === '--out-dir' || arg?.startsWith('--out-dir=')) {
markSeen('--out-dir');
const { value, nextIndex } = readFlagValue(argv, i, '--out-dir');
outDir = value;
i = nextIndex;
continue;
}
if (arg === '--collections' || arg?.startsWith('--collections=')) {
markSeen('--collections');
const { value, nextIndex } = readFlagValue(argv, i, '--collections');
collections = parseCollectionsList(value);
i = nextIndex;
continue;
}
if (arg === '--eod-symbol' || arg?.startsWith('--eod-symbol=')) {
markSeen('--eod-symbol');
const { value, nextIndex } = readFlagValue(argv, i, '--eod-symbol');
eodSymbol = value;
i = nextIndex;
continue;
}
if (arg === '--te-symbol' || arg?.startsWith('--te-symbol=')) {
markSeen('--te-symbol');
const { value, nextIndex } = readFlagValue(argv, i, '--te-symbol');
teSymbol = value;
i = nextIndex;
continue;
}
if (arg === '--limit' || arg?.startsWith('--limit=')) {
markSeen('--limit');
const { value, nextIndex } = readFlagValue(argv, i, '--limit');
limit = parsePositiveIntArg('--limit', value);
i = nextIndex;
continue;
}
if (arg === '--batch-size' || arg?.startsWith('--batch-size=')) {
markSeen('--batch-size');
const { value, nextIndex } = readFlagValue(argv, i, '--batch-size');
batchSize = parsePositiveIntArg('--batch-size', value, MAX_RAW_BSON_BATCH_SIZE);
i = nextIndex;
continue;
}
throw usageError(`Unknown argument: ${String(arg)}`);
}
if (help) {
return { help: true };
}
if (outDir === undefined || outDir.trim().length === 0) {
throw usageError('Missing required argument: --out-dir <dir>');
}
const resolvedCollections: readonly RawBsonExportCollection[] =
collections ?? [...RAW_BSON_EXPORT_COLLECTIONS];
if (eodSymbol !== undefined) {
if (resolvedCollections.length !== 1 || resolvedCollections[0] !== 'eodPrices') {
throw usageError(
'--eod-symbol is only permitted when --collections is strictly "eodPrices"'
);
}
}
if (teSymbol !== undefined) {
if (resolvedCollections.length !== 1 || resolvedCollections[0] !== 'teMarketData') {
throw usageError(
'--te-symbol is only permitted when --collections is strictly "teMarketData"'
);
}
}
return {
help: false,
outDir,
collections: resolvedCollections,
...(eodSymbol !== undefined ? { eodSymbol } : {}),
...(teSymbol !== undefined ? { teSymbol } : {}),
...(limit !== undefined ? { limit } : {}),
batchSize,
};
}
export function assertExportRawBsonSafety(
config: StockAppConfig,
env: Record<string, string | undefined> = process.env
): void {
const mongo = config.database.mongodb;
if (!mongo.enabled) {
throw new Error('MongoDB is disabled in configuration; cannot export raw BSON collections');
}
if (mongo.readOnly !== true) {
throw new Error(
'Raw BSON exporter requires read-only MongoDB configuration (database.mongodb.readOnly === true)'
);
}
const { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: _stripped, ...safeEnv } = env;
const mongoOnlyConfig: StockAppConfig = {
...config,
database: {
...config.database,
postgres: {
...config.database.postgres,
enabled: false,
},
},
};
assertEnvironmentSafety(mongoOnlyConfig, 'dataPipeline', safeEnv);
}
export function formatExportRawBsonSummary(
results: readonly ExportRawBsonCollectionResult[]
): string {
const lines = [`Raw BSON export complete (${results.length} collection(s))`];
for (const r of results) {
lines.push(
` ${r.collection}: docs=${r.docsWritten} bytes=${r.bytesWritten} elapsed_ms=${r.elapsedMs.toFixed(1)} sha256=${r.sha256} out=${r.outPath}`
);
}
return `${lines.join('\n')}\n`;
}
export async function runExportRawBson(
deps: RunExportRawBsonDeps,
options: RunExportRawBsonOptions
): Promise<RunExportRawBsonOutput> {
if (options.collections.length === 0) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: '*',
detail: 'At least one allowlisted collection must be specified',
});
}
for (const collection of options.collections) {
if (!isRawBsonExportCollection(collection)) {
throw new RawBsonExportError({
code: 'DISALLOWED_COLLECTION',
collection: String(collection),
detail: `collection "${String(collection)}" is not in the M1 allowlist`,
});
}
}
if (
options.eodSymbol !== undefined &&
(options.collections.length !== 1 || options.collections[0] !== 'eodPrices')
) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: options.collections.join(','),
detail: '--eod-symbol is only permitted when exporting strictly "eodPrices"',
});
}
if (
options.teSymbol !== undefined &&
(options.collections.length !== 1 || options.collections[0] !== 'teMarketData')
) {
throw new RawBsonExportError({
code: 'INVALID_OPTION',
collection: options.collections.join(','),
detail: '--te-symbol is only permitted when exporting strictly "teMarketData"',
});
}
if (deps.assertSafety) {
deps.assertSafety();
}
const mongoHandle = await deps.createMongoClient();
const results: ExportRawBsonCollectionResult[] = [];
let primaryError: unknown = undefined;
let hasPrimaryError = false;
try {
const source = createReadOnlyMongoRawBsonSource(mongoHandle.client);
const exportFn = deps.exportFn ?? exportRawBsonCollection;
for (const collection of options.collections) {
const result = await exportFn(source, {
collection,
outDir: options.outDir,
...(options.eodSymbol !== undefined ? { eodSymbol: options.eodSymbol } : {}),
...(options.teSymbol !== undefined ? { teSymbol: options.teSymbol } : {}),
...(options.limit !== undefined ? { limit: options.limit } : {}),
...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}),
...(options.writeBufferBytes !== undefined
? { writeBufferBytes: options.writeBufferBytes }
: {}),
...(options.maxDocBytes !== undefined ? { maxDocBytes: options.maxDocBytes } : {}),
...(options.fs !== undefined ? { fs: options.fs } : {}),
});
results.push(result);
}
} catch (error) {
primaryError = error;
hasPrimaryError = true;
} finally {
try {
await mongoHandle.close();
} catch (closeError) {
if (!hasPrimaryError) {
primaryError = closeError;
hasPrimaryError = true;
}
}
}
if (hasPrimaryError) {
throw primaryError;
}
const summary = formatExportRawBsonSummary(results);
const writeStdout =
deps.writeStdout ??
((text: string) => {
process.stdout.write(text);
});
writeStdout(summary);
return { results, summary };
}
export async function runCli(
argv: readonly string[] = process.argv.slice(2),
overrides?: RunExportRawBsonCliOverrides
): Promise<void> {
const parsed = parseExportRawBsonArgs(argv);
if (parsed.help) {
const writeStdout =
overrides?.writeStdout ??
((text: string) => {
process.stdout.write(text);
});
writeStdout(`${EXPORT_RAW_BSON_USAGE}\n`);
return;
}
const logger = getLogger('security-master-export-raw-bson-cli');
const initConfig = overrides?.initializeConfig ?? initializeStockConfig;
const config = initConfig('dataPipeline', { mongoReadOnly: true });
const assertSafety = (): void => {
assertExportRawBsonSafety(config, process.env);
};
const createMongoClient = async (): Promise<RawBsonMongoHandle> => {
const mongoConfig = resolveReadOnlyMongoClientConfig(config);
const mongo = new MongoDBClient(mongoConfig, logger);
await mongo.connect();
let closed = false;
return {
client: mongo,
async close(): Promise<void> {
if (closed) {
return;
}
closed = true;
await mongo.disconnect();
},
};
};
await runExportRawBson(
{
assertSafety: overrides?.assertSafety ?? assertSafety,
createMongoClient: overrides?.createMongoClient ?? createMongoClient,
exportFn: overrides?.exportFn,
writeStdout: overrides?.writeStdout,
},
{
outDir: parsed.outDir,
collections: parsed.collections,
...(parsed.eodSymbol !== undefined ? { eodSymbol: parsed.eodSymbol } : {}),
...(parsed.teSymbol !== undefined ? { teSymbol: parsed.teSymbol } : {}),
...(parsed.limit !== undefined ? { limit: parsed.limit } : {}),
batchSize: parsed.batchSize,
}
);
}
if (import.meta.main) {
runCli().catch(error => {
const message = error instanceof Error ? error.message : String(error);
process.stderr.write(`Error: ${message}\n`);
process.exit(1);
});
}