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+M2 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`, `curate-fundamentals`, `curate-sentiment`, * `curate-macro`, `curate-intraday`). */ export const RAW_BSON_EXPORT_COLLECTIONS = Object.freeze([ 'eodPrices', 'qmSplits', 'qmDividends', 'qmPrices', 'teMarketData', 'ceoShorts', 'qmFilings', 'qmEarnings', 'qmFinancials', 'qmFinancials-old', 'ceoPosts', 'teData', 'eodIntraday1M', 'qmIntraday', ] as const); export type RawBsonExportCollection = (typeof RAW_BSON_EXPORT_COLLECTIONS)[number]; const RAW_BSON_EXPORT_COLLECTION_SET: ReadonlySet = 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 { close?(): Promise; } export interface ReadOnlyRawBsonCollection { find(filter: Record, options: RawBsonFindOptions): ReadOnlyRawBsonCursor; } export interface ReadOnlyMongoRawBsonClient { isReadOnly(): boolean; getCollection(name: string): ReadOnlyRawBsonCollection; } export interface ReadOnlyRawBsonSource { isReadOnly(): boolean; find( collectionName: string, filter: Record, options: RawBsonFindOptions ): Promise> | AsyncIterable; } // Compile-time structural compatibility check (type-only, erased at runtime): // verifies the real `MongoDBClient` satisfies `ReadOnlyMongoRawBsonClient`. type AssertAssignable = 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; close(): Promise; } export interface ExportRawBsonFsHooks { readonly mkdir?: typeof mkdir; readonly open?: (path: string, flags: string) => Promise; 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>; } function isAsyncIterable(value: unknown): value is AsyncIterable { if (value === null || typeof value !== 'object' || Array.isArray(value)) { return false; } return typeof (value as Partial>)[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, options: RawBsonFindOptions ): AsyncIterable { 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 hasPrimaryError = false; try { for await (const doc of cursor) { yield doc; } } catch (error) { hasPrimaryError = true; throw error; } finally { if (typeof cursor.close === 'function') { if (hasPrimaryError) { try { await cursor.close(); } catch { // Preserve primary iteration error when close also fails. } } else { await cursor.close(); } } } }, }; }, }; } /** * 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 = '' ): 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>; 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 || '', detail: `collection "${collectionName}" is not in the M1+M2 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 = {}; 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 { 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 * `/.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 { 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 = 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 => { 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, }; }