From 0962f66cc3f7bfecbc45b1484ea861d3a72ce076 Mon Sep 17 00:00:00 2001 From: Studio Date: Sun, 29 Nov 2026 06:09:51 -0500 Subject: [PATCH] =?UTF-8?q?T-117:=20M1.2ag=20=E2=80=94=20data-pipeline:=20?= =?UTF-8?q?read-only=20MongoDB=20=E2=86=92=20concatenated=20raw-BSON=20fil?= =?UTF-8?q?e=20exporter=20for=20the=20collections=20`curate-etl`=20consume?= =?UTF-8?q?s=20(`raw:=20true`=20cursor,=20byte=20pass-through,=20atomic=20?= =?UTF-8?q?publish)=20with=20tests=20and=20local=20benchmark?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/stock/data-pipeline/README.md | 64 ++ .../benchmarks/export-raw-bson-benchmark.ts | 140 ++++ .../src/security-master/export-raw-bson.ts | 675 ++++++++++++++++++ .../src/security-master/index.ts | 45 ++ .../security-master/run-export-raw-bson.ts | 472 ++++++++++++ .../test/export-raw-bson.test.ts | 604 ++++++++++++++++ .../test/run-export-raw-bson.test.ts | 348 +++++++++ test/unit/mongodb-read-only.test.ts | 80 ++- tools/curate-etl/README.md | 9 + 9 files changed, 2436 insertions(+), 1 deletion(-) create mode 100644 apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts create mode 100644 apps/stock/data-pipeline/src/security-master/export-raw-bson.ts create mode 100644 apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts create mode 100644 apps/stock/data-pipeline/test/export-raw-bson.test.ts create mode 100644 apps/stock/data-pipeline/test/run-export-raw-bson.test.ts diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index f9a22adb..9a7e4038 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -267,3 +267,67 @@ bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts - **Recorded baseline (`2026-11-29`, local sandbox, in-memory cursor/keyset queryable, `chunkSize = 5000`):** - Workload: `500,000` `provider_mapping` rows, `100,000` `listing` rows, `2,000` OTC continuities, terminal delistings, and skipped rows (`606,680` exported rows, `17,203,861` bytes written across all three TSVs). - Observed throughput: `1,506,181 rows/s` (`402.8 ms` elapsed, `277.01 MiB` peak RSS). + +## Read-Only Raw-BSON Exporter (`export-raw-bson.ts`) +`apps/stock/data-pipeline/src/security-master/export-raw-bson.ts` and its CLI `run-export-raw-bson.ts` stream M1 allowlisted MongoDB collections directly to `/.bson` as untouched length-prefixed raw BSON bytes (`find(filter, { raw: true, batchSize })` — zero per-document JS decoding), validating every frame (`byteLength >= 5`, `<= 16 MiB + 16 KiB`, 4-byte LE length prefix `=== byteLength`, trailing `0x00`), coalescing writes through a fixed-size 8 MiB buffer with strict backpressure, computing an incremental SHA-256 digest, and publishing atomically via a same-directory temp file (`open('wx')` -> `write` -> `sync` -> `close` -> `rename`). + +- **Allowlisted collections (`RAW_BSON_EXPORT_COLLECTIONS`):** `eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`. Any other collection (including M2 collections such as `eodIntraday1M`, `qmIntraday`, `qmFinancials`, `ceoPosts`) is rejected before any MongoDB call. +- **Flags:** + - `--out-dir ` *(required)* — destination directory for `.bson` files. + - `--collections ` *(optional)* — comma-separated subset of allowlisted collections (defaults to all 8). + - `--eod-symbol ` *(optional)* — exact `{ eodSearchCode: }` filter; only permitted when `--collections` is strictly `eodPrices` (for example `CAD.FOREX` for `curate-fx-1d`). Use a **separate `--out-dir`** so a filtered slice never overwrites the full `eodPrices.bson`. + - `--te-symbol ` *(optional)* — exact `{ teSymbol: }` filter; only permitted when `--collections` is strictly `teMarketData` (for example `USDCAD`). + - `--limit ` *(optional)* — positive integer document cap per collection for smoke runs. + - `--batch-size ` *(optional)* — MongoDB cursor `batchSize` (`1..100000`, default `4096`). + - `--help` — print usage and exit with zero config/Mongo/fs I/O. +- **Read-only safety:** Initializes config via `initializeStockConfig('dataPipeline', { mongoReadOnly: true })`, enforces `assertEnvironmentSafety()` via `assertExportRawBsonSafety()`, connects through `resolveReadOnlyMongoClientConfig()`, issues strictly `find(..., { raw: true })`, and always closes the MongoDB client in `finally`. Running against live QA MongoDB is a **separate manual host step** (never executed by automated tests or benchmarks). + +### Full M1 Step 2 Chain Order (Manual Host Run) +1. **Export PostgreSQL security-master TSVs (`run-export-curate-inputs.ts`):** +```bash +NODE_ENV=development \ +POSTGRES_HOST=localhost \ +POSTGRES_PORT=5433 \ +POSTGRES_DATABASE=trading_bot_dev \ + bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts \ + --out-dir ./tmp/curate-inputs +``` +2. **Export raw BSON collections from read-only QA MongoDB (`run-export-raw-bson.ts`):** +```bash +MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock" \ + bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts \ + --out-dir ./tmp/raw-bson \ + --collections eodPrices,qmSplits,qmDividends,qmPrices,ceoShorts,qmFilings,qmEarnings + +# Export filtered FX inputs to a separate directory so full eodPrices.bson is not overwritten: +MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock" \ + bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts \ + --out-dir ./tmp/raw-bson-fx \ + --collections eodPrices \ + --eod-symbol CAD.FOREX + +MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock" \ + bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts \ + --out-dir ./tmp/raw-bson-fx \ + --collections teMarketData \ + --te-symbol USDCAD +``` +3. **Run `tools/curate-etl` commands (`curate-bars-1d` first, then the remaining datasets):** + - `curate-etl curate-bars-1d` (`eodPrices.bson`, `qmSplits.bson`, optional `qmPrices.bson`, `--curate-inputs ./tmp/curate-inputs`) + - `curate-etl curate-adj-factors` (`qmSplits.bson`, `qmDividends.bson`, `bars_1d`, `--curate-inputs ./tmp/curate-inputs`) + - `curate-etl curate-corporate-actions` (`qmSplits.bson`, `qmDividends.bson`, `--curate-inputs ./tmp/curate-inputs`) + - `curate-etl curate-fx-1d` (`./tmp/raw-bson-fx/eodPrices.bson`, `./tmp/raw-bson-fx/teMarketData.bson`) + - `curate-etl curate-shorts` (`ceoShorts.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`) + - `curate-etl curate-events` (`qmFilings.bson`, `qmEarnings.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`) + +- **Local synthetic benchmark (zero MongoDB):** Run the fixed-seed 1,000,000-doc streaming benchmark with: + +```bash +bun run apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts +``` + +- **Recorded baseline (`2026-11-29`, local sandbox, in-memory async cursor fake source, `writeBufferBytes = 8 MiB`):** + - Workload: `1,000,000` synthetic `eodPrices` raw BSON frames (`123.9 B` avg, `123,863,264` bytes written, deterministic `sha256=67f035eba7060d6312f3d5faecc9e6a6fa14f6239c0c4dc1859794b4cd895886`). + - Run 1 (`1,000,000` docs): `3,574,267 docs/s`, `422.21 MiB/s` (`279.8 ms` elapsed, `rss_before=97.00 MiB`, `rss_after=149.91 MiB`, `peak_rss=150.19 MiB`). + - Run 2 (`1,000,000` docs): `3,692,715 docs/s`, `436.20 MiB/s` (`270.8 ms` elapsed, `peak_rss=151.03 MiB`, identical `sha256`). + - Scaling check (`2,000,000` docs, `247,726,576` bytes): `3,833,075 docs/s`, `452.78 MiB/s` (`521.8 ms` elapsed, `peak_rss=146.88 MiB` — confirms peak RSS stays bounded independent of document count). diff --git a/apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts b/apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts new file mode 100644 index 00000000..7b3b86e6 --- /dev/null +++ b/apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts @@ -0,0 +1,140 @@ +/** + * Reproducible headless benchmark for `exportRawBsonCollection`. + * Streams >= 1,000,000 fixed-seed synthetic ~100 B raw BSON `eodPrices` frames through + * `exportRawBsonCollection` into a temporary directory (cleaned up in `finally`), with zero + * MongoDB or network dependencies. + * + * Usage: + * bun run apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts [docCount] + */ + +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { BSON } from 'mongodb'; +import { + DEFAULT_WRITE_BUFFER_BYTES, + exportRawBsonCollection, + type ReadOnlyRawBsonSource, +} from '../src/security-master/export-raw-bson'; + +const DEFAULT_DOC_COUNT = 1_000_000; +const POOL_SIZE = 1_024; + +function parseDocCount(): number { + const raw = process.argv[2]; + if (raw === undefined) { + return DEFAULT_DOC_COUNT; + } + if (!/^\d+$/.test(raw)) { + throw new Error(`Invalid docCount "${raw}": expected a positive integer`); + } + const parsed = Number(raw); + if (!Number.isSafeInteger(parsed) || parsed < 1) { + throw new Error(`Invalid docCount "${raw}": expected a positive integer`); + } + return parsed; +} + +/** + * Deterministic PRNG (Mulberry32) so the synthetic BSON pool is identical across runs. + */ +function createSeededRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function buildSyntheticBsonPool(): Uint8Array[] { + const rng = createSeededRng(0x5eed117); + const pool = new Array(POOL_SIZE); + for (let i = 0; i < POOL_SIZE; i++) { + const base = 10 + Math.round(rng() * 20000) / 100; + const high = Math.round((base + rng() * 3) * 100) / 100; + const low = Math.max(0.01, Math.round((base - rng() * 3) * 100) / 100); + const close = Math.round((low + rng() * (high - low)) * 100) / 100; + const volume = Math.floor(1_000 + rng() * 5_000_000); + const month = String((i % 12) + 1).padStart(2, '0'); + const day = String((i % 28) + 1).padStart(2, '0'); + const doc = { + eodSearchCode: `SYM${String(i).padStart(4, '0')}.US`, + date: `2025-${month}-${day}`, + open: base, + high, + low, + close, + volume, + }; + pool[i] = Uint8Array.from(BSON.serialize(doc)); + } + return pool; +} + +function createSyntheticRawSource(pool: readonly Uint8Array[], totalDocs: number): ReadOnlyRawBsonSource { + const poolLen = pool.length; + return { + isReadOnly: () => true, + find() { + return { + async *[Symbol.asyncIterator]() { + for (let i = 0; i < totalDocs; i++) { + const frame = pool[i % poolLen]; + if (frame !== undefined) { + yield frame; + } + } + }, + }; + }, + }; +} + +async function main(): Promise { + const docCount = parseDocCount(); + const pool = buildSyntheticBsonPool(); + const avgDocBytes = + pool.reduce((acc, frame) => acc + frame.byteLength, 0) / pool.length; + const source = createSyntheticRawSource(pool, docCount); + const outDir = await mkdtemp(join(tmpdir(), 'export-raw-bson-bench-')); + + try { + const rssBeforeMiB = process.memoryUsage().rss / (1024 * 1024); + const startNs = Bun.nanoseconds(); + const result = await exportRawBsonCollection(source, { + collection: 'eodPrices', + outDir, + writeBufferBytes: DEFAULT_WRITE_BUFFER_BYTES, + }); + const elapsedMs = (Bun.nanoseconds() - startNs) / 1e6; + const rssAfterMiB = process.memoryUsage().rss / (1024 * 1024); + // process.resourceUsage().maxRSS is reported in KiB on Linux. + const peakRssMiB = process.resourceUsage().maxRSS / 1024; + + const elapsedSec = elapsedMs / 1000; + const docsPerSec = result.docsWritten / elapsedSec; + const mibPerSec = result.bytesWritten / (1024 * 1024) / elapsedSec; + + process.stdout.write('exportRawBsonCollection benchmark complete\n'); + process.stdout.write( + ` docs=${result.docsWritten} avg_doc_bytes=${avgDocBytes.toFixed(1)} bytes_written=${result.bytesWritten} write_buffer_bytes=${DEFAULT_WRITE_BUFFER_BYTES}\n` + ); + process.stdout.write( + ` elapsed_ms=${elapsedMs.toFixed(1)} throughput=${Math.round(docsPerSec)} docs/s rate=${mibPerSec.toFixed(2)} MiB/s\n` + ); + process.stdout.write( + ` rss_before=${rssBeforeMiB.toFixed(2)} MiB rss_after=${rssAfterMiB.toFixed(2)} MiB peak_rss=${peakRssMiB.toFixed(2)} MiB\n` + ); + process.stdout.write(` sha256=${result.sha256}\n`); + } finally { + await rm(outDir, { recursive: true, force: true }); + } +} + +main().catch(error => { + process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`); + process.exit(1); +}); diff --git a/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts b/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts new file mode 100644 index 00000000..1ebd0791 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts @@ -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 = 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 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 = '' +): 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 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, + }; +} diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index dc8b5714..85707ca8 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -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, diff --git a/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts b/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts new file mode 100644 index 00000000..84df40ba --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts @@ -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 [--collections ] [--eod-symbol ] [--te-symbol ] [--limit ] [--batch-size ] [--help]', + '', + 'Options:', + ' --out-dir Required. Output directory for .bson files.', + ` --collections Optional. Comma-separated allowlisted collections (default: ${RAW_BSON_EXPORT_COLLECTIONS.join(',')}).`, + ' --eod-symbol Optional. Exact eodSearchCode filter (only valid when --collections is strictly eodPrices).', + ' --te-symbol Optional. Exact teSymbol filter (only valid when --collections is strictly teMarketData).', + ' --limit Optional. Max documents to export per collection (positive integer, for smoke runs).', + ` --batch-size 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; +} + +export interface RunExportRawBsonDeps { + readonly assertSafety?: () => void; + readonly createMongoClient: () => Promise | RawBsonMongoHandle; + readonly exportFn?: typeof exportRawBsonCollection; + readonly writeStdout?: (text: string) => void; +} + +export interface RunExportRawBsonCliOverrides extends Partial { + 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(); + + 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(); + + 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 '); + } + + 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 = 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 { + 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 { + 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 => { + const mongoConfig = resolveReadOnlyMongoClientConfig(config); + const mongo = new MongoDBClient(mongoConfig, logger); + await mongo.connect(); + let closed = false; + return { + client: mongo, + async close(): Promise { + 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); + }); +} diff --git a/apps/stock/data-pipeline/test/export-raw-bson.test.ts b/apps/stock/data-pipeline/test/export-raw-bson.test.ts new file mode 100644 index 00000000..75661fd0 --- /dev/null +++ b/apps/stock/data-pipeline/test/export-raw-bson.test.ts @@ -0,0 +1,604 @@ +import { describe, expect, mock, test } from 'bun:test'; +import { createHash } from 'node:crypto'; +import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { BSON } from 'mongodb'; +import { + createReadOnlyMongoRawBsonSource, + exportRawBsonCollection, + RAW_BSON_EXPORT_COLLECTIONS, + RawBsonExportError, + validateRawBsonFrame, + walkRawBsonFrames, + type ExportRawBsonFileHandle, + type ExportRawBsonFsHooks, + type RawBsonFindOptions, + type ReadOnlyMongoRawBsonClient, + type ReadOnlyRawBsonSource, +} from '../src/security-master/export-raw-bson'; + +const EMPTY_SHA256 = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'; + +function sha256Hex(bytes: Uint8Array): string { + return createHash('sha256').update(bytes).digest('hex'); +} + +function concatBytes(chunks: readonly Uint8Array[]): Uint8Array { + const total = chunks.reduce((acc, c) => acc + c.byteLength, 0); + const out = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + out.set(chunk, offset); + offset += chunk.byteLength; + } + return out; +} + +function createFakeSource( + docs: readonly unknown[], + options: { + readOnly?: boolean; + errorAfter?: number; + error?: Error; + onFind?: (collection: string, filter: Record, findOpts: RawBsonFindOptions) => void; + onCursorClose?: () => void; + } = {} +): ReadOnlyRawBsonSource { + const readOnly = options.readOnly ?? true; + return { + isReadOnly: () => readOnly, + find(collection, filter, findOpts) { + options.onFind?.(collection, filter, findOpts); + return { + async *[Symbol.asyncIterator]() { + let index = 0; + try { + for (const doc of docs) { + if (options.errorAfter !== undefined && index === options.errorAfter) { + throw options.error ?? new Error('Simulated mid-stream cursor failure'); + } + yield doc; + index += 1; + } + } finally { + options.onCursorClose?.(); + } + }, + }; + }, + }; +} + +async function withTempDir(fn: (dir: string) => Promise): Promise { + const dir = await mkdtemp(join(tmpdir(), 'export-raw-bson-test-')); + try { + return await fn(dir); + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +describe('exportRawBsonCollection', () => { + test('streams raw BSON frames verbatim, matches concatenation, round-trips via 4-byte LE framing, and is deterministic', async () => { + const originalDocs = [ + { + eodSearchCode: 'AAPL.US', + date: '2025-01-02', + open: 248.93, + high: 249.1, + low: 241.82, + close: 243.85, + volume: 55740731, + ts: new Date('2025-01-02T21:00:00.000Z'), + meta: { exchange: 'US', adjusted: false }, + }, + { + eodSearchCode: 'RY.TO', + date: '2025-01-02', + open: 173.4, + high: 175.0, + low: 172.8, + close: 174.65, + volume: 2150000, + tags: ['CA', 'TSX'], + }, + { + eodSearchCode: 'NVDA.US', + date: '2024-06-10', + open: 120.37, + high: 123.1, + low: 117.01, + close: 121.79, + volume: 314162700, + }, + ]; + const serialized = originalDocs.map(doc => Uint8Array.from(BSON.serialize(doc))); + const expectedBytes = concatBytes(serialized); + const expectedSha = sha256Hex(expectedBytes); + + await withTempDir(async outDir => { + const findCalls: Array<{ + collection: string; + filter: Record; + options: RawBsonFindOptions; + }> = []; + const source = createFakeSource(serialized, { + onFind: (collection, filter, options) => { + findCalls.push({ collection, filter, options }); + }, + }); + + const run1 = await exportRawBsonCollection(source, { + collection: 'eodPrices', + outDir, + }); + + expect(run1.collection).toBe('eodPrices'); + expect(run1.outPath).toBe(join(outDir, 'eodPrices.bson')); + expect(run1.docsWritten).toBe(originalDocs.length); + expect(run1.bytesWritten).toBe(expectedBytes.byteLength); + expect(run1.elapsedMs).toBeGreaterThanOrEqual(0); + expect(run1.sha256).toBe(expectedSha); + expect(run1.filter).toEqual({}); + expect(findCalls).toEqual([ + { + collection: 'eodPrices', + filter: {}, + options: { raw: true, batchSize: 4096 }, + }, + ]); + + const fileBytes = Uint8Array.from(await readFile(run1.outPath)); + expect(fileBytes).toEqual(expectedBytes); + + // Cross-language framing parity: walk output by 4-byte LE length prefix + const walked = walkRawBsonFrames(fileBytes); + expect(walked).toHaveLength(originalDocs.length); + for (let i = 0; i < originalDocs.length; i++) { + const frame = walked[i]; + expect(frame).toEqual(serialized[i]); + expect(BSON.deserialize(frame!)).toEqual(originalDocs[i]); + } + + // Determinism / replay invariant: running twice yields byte-identical output and sha256 + const run2 = await exportRawBsonCollection(source, { + collection: 'eodPrices', + outDir, + }); + const fileBytes2 = Uint8Array.from(await readFile(run2.outPath)); + expect(run2.sha256).toBe(run1.sha256); + expect(run2.bytesWritten).toBe(run1.bytesWritten); + expect(fileBytes2).toEqual(fileBytes); + expect(await readdir(outDir)).toEqual(['eodPrices.bson']); + }); + }); + + test('publishes a 0-byte file with docsWritten === 0 and empty SHA-256 for an empty collection', async () => { + await withTempDir(async outDir => { + const source = createFakeSource([]); + const result = await exportRawBsonCollection(source, { + collection: 'ceoShorts', + outDir, + }); + + expect(result.collection).toBe('ceoShorts'); + expect(result.docsWritten).toBe(0); + expect(result.bytesWritten).toBe(0); + expect(result.sha256).toBe(EMPTY_SHA256); + + const fileBytes = await readFile(result.outPath); + expect(fileBytes.byteLength).toBe(0); + expect(await readdir(outDir)).toEqual(['ceoShorts.bson']); + }); + }); + + test('rejects invalid BSON frames with typed error naming collection and ordinal, cleans temp file, and preserves existing output', async () => { + const validDoc = Uint8Array.from(BSON.serialize({ a: 1 })); + const shortFrame = new Uint8Array([4, 0, 0, 0]); + const tooSmallPrefix = Uint8Array.from(validDoc); + tooSmallPrefix[0] = (tooSmallPrefix[0] ?? 0) - 1; + const tooLargePrefix = Uint8Array.from(validDoc); + tooLargePrefix[0] = (tooLargePrefix[0] ?? 0) + 1; + const missingTerminator = Uint8Array.from(validDoc); + missingTerminator[missingTerminator.byteLength - 1] = 0x01; + const oversizedDoc = Uint8Array.from(BSON.serialize({ payload: 'x'.repeat(200) })); + + const cases: Array<{ + name: string; + docs: unknown[]; + expectedOrdinal: number; + maxDocBytes?: number; + }> = [ + { name: 'shorter than 5 bytes', docs: [validDoc, shortFrame], expectedOrdinal: 1 }, + { name: 'LE prefix smaller than byteLength', docs: [validDoc, tooSmallPrefix], expectedOrdinal: 1 }, + { name: 'LE prefix larger than byteLength', docs: [tooLargePrefix], expectedOrdinal: 0 }, + { name: 'missing trailing 0x00', docs: [validDoc, validDoc, missingTerminator], expectedOrdinal: 2 }, + { name: 'non-Uint8Array chunk', docs: [validDoc, { plain: 'object' }], expectedOrdinal: 1 }, + { + name: 'exceeds maxDocBytes', + docs: [validDoc, oversizedDoc], + expectedOrdinal: 1, + maxDocBytes: 64, + }, + ]; + + for (const c of cases) { + await withTempDir(async outDir => { + const existingPath = join(outDir, 'qmSplits.bson'); + const sentinel = Uint8Array.from(BSON.serialize({ sentinel: c.name })); + await writeFile(existingPath, sentinel); + + const source = createFakeSource(c.docs); + let caught: unknown; + try { + await exportRawBsonCollection(source, { + collection: 'qmSplits', + outDir, + maxDocBytes: c.maxDocBytes, + }); + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(RawBsonExportError); + const typed = caught as RawBsonExportError; + expect(typed.code).toBe('INVALID_BSON_FRAME'); + expect(typed.collection).toBe('qmSplits'); + expect(typed.docOrdinal).toBe(c.expectedOrdinal); + expect(typed.message).toContain('qmSplits'); + expect(typed.message).toContain(`doc#${c.expectedOrdinal}`); + + // No temp file left behind and pre-existing output is byte-identical + expect(await readdir(outDir)).toEqual(['qmSplits.bson']); + expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel); + }); + } + }); + + test('cleans up temp file, closes cursor/handle, and preserves existing output on mid-stream cursor, write, short-write, fsync, and rename errors', async () => { + const docs = [ + Uint8Array.from(BSON.serialize({ seq: 0 })), + Uint8Array.from(BSON.serialize({ seq: 1 })), + Uint8Array.from(BSON.serialize({ seq: 2 })), + ]; + + // 1. Mid-stream cursor error + await withTempDir(async outDir => { + const existingPath = join(outDir, 'qmDividends.bson'); + const sentinel = Uint8Array.from(BSON.serialize({ sentinel: 'cursor-err' })); + await writeFile(existingPath, sentinel); + + let cursorClosed = false; + const source = createFakeSource(docs, { + errorAfter: 2, + error: new Error('Cursor network reset'), + onCursorClose: () => { + cursorClosed = true; + }, + }); + + await expect( + exportRawBsonCollection(source, { collection: 'qmDividends', outDir }) + ).rejects.toThrow('Cursor network reset'); + + expect(cursorClosed).toBe(true); + expect(await readdir(outDir)).toEqual(['qmDividends.bson']); + expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel); + }); + + // 2. Write, short-write, fsync, and rename errors + const failureModes = ['write', 'shortWrite', 'sync', 'rename'] as const; + for (const mode of failureModes) { + await withTempDir(async outDir => { + const existingPath = join(outDir, 'qmPrices.bson'); + const sentinel = Uint8Array.from(BSON.serialize({ sentinel: mode })); + await writeFile(existingPath, sentinel); + + let handleClosed = false; + let tempFileCreated: string | null = null; + let unlinkedPath: string | null = null; + + const fsHooks: ExportRawBsonFsHooks = { + open: async (filePath: string) => { + tempFileCreated = filePath; + await writeFile(filePath, new Uint8Array()); + const handle: ExportRawBsonFileHandle = { + write: async (_buf, _off, len) => { + if (mode === 'write') { + throw new Error('ENOSPC simulated write failure'); + } + if (mode === 'shortWrite') { + return { bytesWritten: 0 }; + } + return { bytesWritten: len ?? 0 }; + }, + sync: async () => { + if (mode === 'sync') { + throw new Error('EIO simulated fsync failure'); + } + }, + close: async () => { + handleClosed = true; + }, + }; + return handle; + }, + rename: async () => { + if (mode === 'rename') { + throw new Error('EXDEV simulated rename failure'); + } + }, + unlink: async filePath => { + unlinkedPath = String(filePath); + await rm(filePath, { force: true }); + }, + }; + + const source = createFakeSource(docs); + await expect( + exportRawBsonCollection(source, { + collection: 'qmPrices', + outDir, + fs: fsHooks, + }) + ).rejects.toThrow(); + + expect(handleClosed).toBe(true); + expect(tempFileCreated).not.toBeNull(); + expect(unlinkedPath).toBe(tempFileCreated); + expect(await readdir(outDir)).toEqual(['qmPrices.bson']); + expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel); + }); + } + }); + + test('enforces bounded write buffer size, handles oversized single docs, and strictly awaits write backpressure', async () => { + const smallDocs = Array.from({ length: 120 }, (_, i) => + Uint8Array.from( + BSON.serialize({ + eodSearchCode: `SYM${String(i).padStart(4, '0')}.US`, + date: '2025-01-02', + open: 10 + i, + close: 11 + i, + volume: 1000 + i, + }) + ) + ); + const largeDoc = Uint8Array.from( + BSON.serialize({ + eodSearchCode: 'LARGE.US', + payload: 'A'.repeat(350), + }) + ); + const allDocs = [...smallDocs.slice(0, 60), largeDoc, ...smallDocs.slice(60)]; + const expectedConcat = concatBytes(allDocs); + const writeBufferBytes = 256; + + expect(largeDoc.byteLength).toBeGreaterThan(writeBufferBytes); + + const writeLengths: number[] = []; + const writtenChunks: Uint8Array[] = []; + let inFlight = 0; + let maxInFlight = 0; + + await withTempDir(async outDir => { + const fsHooks: ExportRawBsonFsHooks = { + open: async () => ({ + write: async (buf, offset, length) => { + inFlight += 1; + if (inFlight > maxInFlight) { + maxInFlight = inFlight; + } + const start = offset ?? 0; + const len = length ?? buf.byteLength - start; + writeLengths.push(len); + // Copy slice immediately to simulate kernel read of buffer before async completion + const copy = Uint8Array.from(buf.subarray(start, start + len)); + await new Promise(resolve => setTimeout(resolve, 0)); + writtenChunks.push(copy); + inFlight -= 1; + return { bytesWritten: len }; + }, + sync: async () => {}, + close: async () => {}, + }), + rename: async () => {}, + unlink: async () => {}, + }; + + const source = createFakeSource(allDocs); + const result = await exportRawBsonCollection(source, { + collection: 'eodPrices', + outDir, + writeBufferBytes, + fs: fsHooks, + }); + + expect(maxInFlight).toBe(1); + expect(writeLengths.length).toBeGreaterThan(10); + + // Every write must be <= writeBufferBytes except the single oversized document write + const oversizedWrites = writeLengths.filter(len => len > writeBufferBytes); + expect(oversizedWrites).toEqual([largeDoc.byteLength]); + for (const len of writeLengths) { + expect(len).toBeLessThanOrEqual(Math.max(writeBufferBytes, largeDoc.byteLength)); + } + + const assembled = concatBytes(writtenChunks); + expect(assembled).toEqual(expectedConcat); + expect(result.docsWritten).toBe(allDocs.length); + expect(result.bytesWritten).toBe(expectedConcat.byteLength); + expect(result.sha256).toBe(sha256Hex(expectedConcat)); + }); + }); + + test('rejects disallowed collections, invalid filters, and non-read-only sources before any source or fs call', async () => { + const findMock = mock(() => { + throw new Error('source.find should never be called'); + }); + const openMock = mock(async () => { + throw new Error('fs.open should never be called'); + }); + const source: ReadOnlyRawBsonSource = { + isReadOnly: () => true, + find: findMock, + }; + const fsHooks: ExportRawBsonFsHooks = { open: openMock }; + + for (const disallowed of ['eodIntraday1M', 'qmIntraday', 'qmFinancials', 'ceoPosts', 'symbols']) { + await expect( + exportRawBsonCollection(source, { collection: disallowed, outDir: '/tmp/unused', fs: fsHooks }) + ).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION', collection: disallowed }); + } + + await expect( + exportRawBsonCollection(source, { + collection: 'teMarketData', + outDir: '/tmp/unused', + eodSymbol: 'CAD.FOREX', + fs: fsHooks, + }) + ).rejects.toMatchObject({ code: 'INVALID_OPTION' }); + + await expect( + exportRawBsonCollection(source, { + collection: 'eodPrices', + outDir: '/tmp/unused', + teSymbol: 'USDCAD', + fs: fsHooks, + }) + ).rejects.toMatchObject({ code: 'INVALID_OPTION' }); + + const writableSource: ReadOnlyRawBsonSource = { + isReadOnly: () => false, + find: findMock, + }; + await expect( + exportRawBsonCollection(writableSource, { + collection: 'eodPrices', + outDir: '/tmp/unused', + fs: fsHooks, + }) + ).rejects.toMatchObject({ code: 'INVALID_SOURCE' }); + + expect(findMock).not.toHaveBeenCalled(); + expect(openMock).not.toHaveBeenCalled(); + }); + + test('applies eodSymbol, teSymbol, and limit filters and defensively caps output at limit', async () => { + const docs = Array.from({ length: 5 }, (_, i) => + Uint8Array.from(BSON.serialize({ seq: i })) + ); + + await withTempDir(async outDir => { + const calls: Array<{ collection: string; filter: Record; options: RawBsonFindOptions }> = []; + const source = createFakeSource(docs, { + onFind: (collection, filter, options) => { + calls.push({ collection, filter, options }); + }, + }); + + const eodRes = await exportRawBsonCollection(source, { + collection: 'eodPrices', + outDir, + eodSymbol: 'CAD.FOREX', + limit: 2, + batchSize: 64, + }); + + expect(eodRes.docsWritten).toBe(2); + expect(eodRes.filter).toEqual({ eodSearchCode: 'CAD.FOREX' }); + expect(calls[0]).toEqual({ + collection: 'eodPrices', + filter: { eodSearchCode: 'CAD.FOREX' }, + options: { raw: true, batchSize: 64, limit: 2 }, + }); + + const teRes = await exportRawBsonCollection(source, { + collection: 'teMarketData', + outDir, + teSymbol: 'USDCAD', + limit: 3, + }); + + expect(teRes.docsWritten).toBe(3); + expect(teRes.filter).toEqual({ teSymbol: 'USDCAD' }); + expect(calls[1]).toEqual({ + collection: 'teMarketData', + filter: { teSymbol: 'USDCAD' }, + options: { raw: true, batchSize: 4096, limit: 3 }, + }); + }); + }); + + test('createReadOnlyMongoRawBsonSource enforces read-only, rejects buffered arrays, and always closes cursors', async () => { + const writableClient: ReadOnlyMongoRawBsonClient = { + isReadOnly: () => false, + getCollection: () => { + throw new Error('should not be called'); + }, + }; + expect(() => createReadOnlyMongoRawBsonSource(writableClient)).toThrow(RawBsonExportError); + + const bufferedArrayClient: ReadOnlyMongoRawBsonClient = { + isReadOnly: () => true, + getCollection: () => ({ + find: () => [] as unknown as ReturnType extends { + find: (...args: never[]) => infer R; + } + ? R + : never, + }), + }; + const badSource = createReadOnlyMongoRawBsonSource(bufferedArrayClient); + expect(() => badSource.find('eodPrices', {}, { raw: true })).toThrow(RawBsonExportError); + + // Cursor close is called on normal exhaustion and early break + const closeMock = mock(async () => {}); + const docs = [ + Uint8Array.from(BSON.serialize({ a: 1 })), + Uint8Array.from(BSON.serialize({ a: 2 })), + Uint8Array.from(BSON.serialize({ a: 3 })), + ]; + const goodClient: ReadOnlyMongoRawBsonClient = { + isReadOnly: () => true, + getCollection: () => ({ + find: () => ({ + close: closeMock, + async *[Symbol.asyncIterator]() { + for (const d of docs) { + yield d; + } + }, + }), + }), + }; + const source = createReadOnlyMongoRawBsonSource(goodClient); + + await withTempDir(async outDir => { + const res = await exportRawBsonCollection(source, { + collection: 'qmFilings', + outDir, + limit: 1, + }); + expect(res.docsWritten).toBe(1); + expect(closeMock).toHaveBeenCalledTimes(1); + }); + }); + + test('exports exact M1 allowlist of 8 collections and validateRawBsonFrame accepts minimal 5-byte empty BSON doc', () => { + expect([...RAW_BSON_EXPORT_COLLECTIONS]).toEqual([ + 'eodPrices', + 'qmSplits', + 'qmDividends', + 'qmPrices', + 'teMarketData', + 'ceoShorts', + 'qmFilings', + 'qmEarnings', + ]); + const emptyBson = new Uint8Array([5, 0, 0, 0, 0]); + expect(validateRawBsonFrame(emptyBson, 'eodPrices', 0)).toBe(emptyBson); + }); +}); diff --git a/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts b/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts new file mode 100644 index 00000000..289b8087 --- /dev/null +++ b/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts @@ -0,0 +1,348 @@ +import { describe, expect, mock, test } from 'bun:test'; +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { StockAppConfig } from '@stock-bot/stock-config'; +import { BSON } from 'mongodb'; +import { + DEFAULT_RAW_BSON_BATCH_SIZE, + RAW_BSON_EXPORT_COLLECTIONS, + RawBsonExportError, + type ReadOnlyMongoRawBsonClient, +} from '../src/security-master/export-raw-bson'; +import { + assertExportRawBsonSafety, + EXPORT_RAW_BSON_USAGE, + parseExportRawBsonArgs, + runCli, + runExportRawBson, +} from '../src/security-master/run-export-raw-bson'; + +function createBaseConfig(overrides: Partial = {}): StockAppConfig { + return { + environment: 'development', + database: { + postgres: { + enabled: true, + host: 'localhost', + port: 5432, + database: 'trading_bot', + user: 'trading_user', + password: 'pw', + ssl: false, + poolSize: 5, + idleTimeout: 10000, + connectionTimeout: 5000, + }, + mongodb: { + enabled: true, + uri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock', + readUri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock', + readOnly: true, + host: 'localhost', + port: 27017, + database: 'stock', + poolSize: 5, + ...overrides, + }, + dragonfly: { + enabled: false, + host: 'localhost', + port: 6380, + }, + questdb: { + enabled: false, + host: 'localhost', + port: 9100, + }, + }, + } as unknown as StockAppConfig; +} + +describe('parseExportRawBsonArgs', () => { + test('parses valid flags in both space-separated and equals forms', () => { + const parsed1 = parseExportRawBsonArgs([ + '--out-dir', + './tmp/bson', + '--collections', + 'eodPrices', + '--eod-symbol', + 'CAD.FOREX', + '--limit', + '100', + '--batch-size', + '512', + ]); + expect(parsed1).toEqual({ + help: false, + outDir: './tmp/bson', + collections: ['eodPrices'], + eodSymbol: 'CAD.FOREX', + limit: 100, + batchSize: 512, + }); + + const parsed2 = parseExportRawBsonArgs([ + '--out-dir=./tmp/te', + '--collections=teMarketData', + '--te-symbol=USDCAD', + ]); + expect(parsed2).toEqual({ + help: false, + outDir: './tmp/te', + collections: ['teMarketData'], + teSymbol: 'USDCAD', + batchSize: DEFAULT_RAW_BSON_BATCH_SIZE, + }); + + const parsedDefault = parseExportRawBsonArgs(['--out-dir', './tmp/all']); + expect(parsedDefault).toEqual({ + help: false, + outDir: './tmp/all', + collections: [...RAW_BSON_EXPORT_COLLECTIONS], + batchSize: DEFAULT_RAW_BSON_BATCH_SIZE, + }); + + expect(parseExportRawBsonArgs(['--help'])).toEqual({ help: true }); + }); + + test('rejects unknown, duplicate, missing-value, positional, and malformed flags', () => { + expect(() => parseExportRawBsonArgs([])).toThrow(/Missing required argument: --out-dir/); + expect(() => parseExportRawBsonArgs(['--out-dir', './tmp', '--bogus'])).toThrow(/Unknown argument/); + expect(() => parseExportRawBsonArgs(['--out-dir', './tmp', 'positional'])).toThrow(/Unknown argument/); + expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--out-dir', './b'])).toThrow(/Duplicate flag/); + expect(() => + parseExportRawBsonArgs(['--out-dir', './a', '--limit', '10', '--limit=20']) + ).toThrow(/Duplicate flag/); + expect(() => parseExportRawBsonArgs(['--out-dir', '--collections', 'eodPrices'])).toThrow( + /Missing value for --out-dir/ + ); + expect(() => parseExportRawBsonArgs(['--out-dir='])).toThrow(/Missing value for --out-dir/); + expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '0'])).toThrow(/Invalid --limit/); + expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '-5'])).toThrow(/Invalid --limit/); + expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '1.5'])).toThrow(/Invalid --limit/); + expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--batch-size', '0'])).toThrow( + /Invalid --batch-size/ + ); + expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--batch-size', '999999'])).toThrow( + /Invalid --batch-size/ + ); + expect(() => + parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices,']) + ).toThrow(/Malformed --collections/); + expect(() => + parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices,eodPrices']) + ).toThrow(/Duplicate collection/); + }); + + test('rejects disallowed collections and mismatched --eod-symbol / --te-symbol filters', () => { + expect(() => + parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodIntraday1M']) + ).toThrow(RawBsonExportError); + expect(() => + parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'symbols']) + ).toThrow(RawBsonExportError); + expect(() => + parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--eod-symbol', 'CAD.FOREX']) + ).toThrow(/--eod-symbol is only permitted/); + expect(() => + parseExportRawBsonArgs([ + '--out-dir', + './a', + '--collections', + 'eodPrices,qmSplits', + '--eod-symbol', + 'CAD.FOREX', + ]) + ).toThrow(/--eod-symbol is only permitted/); + expect(() => + parseExportRawBsonArgs(['--out-dir', './a', '--eod-symbol', 'CAD.FOREX']) + ).toThrow(/--eod-symbol is only permitted/); + expect(() => + parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--te-symbol', 'USDCAD']) + ).toThrow(/--te-symbol is only permitted/); + }); +}); + +describe('assertExportRawBsonSafety', () => { + test('allows read-only dev MongoDB even if Postgres config points to QA, and rejects disabled/writable/admin MongoDB', () => { + expect(() => assertExportRawBsonSafety(createBaseConfig(), {})).not.toThrow(); + + expect(() => assertExportRawBsonSafety(createBaseConfig({ enabled: false }), {})).toThrow( + /MongoDB is disabled/ + ); + expect(() => assertExportRawBsonSafety(createBaseConfig({ readOnly: false }), {})).toThrow( + /read-only MongoDB configuration/ + ); + expect(() => + assertExportRawBsonSafety( + createBaseConfig({ + readUri: 'mongodb://trading_admin:pw@localhost:27017/stock?authSource=admin', + readOnly: true, + }), + {} + ) + ).toThrow(/Safety guard/); + }); +}); + +describe('runExportRawBson & runCli', () => { + test('--help prints usage and performs zero config, Mongo, or fs I/O', async () => { + const stdout: string[] = []; + const initConfigMock = mock(() => { + throw new Error('initializeConfig must not be called on --help'); + }); + const createClientMock = mock(() => { + throw new Error('createMongoClient must not be called on --help'); + }); + + await runCli(['--help'], { + initializeConfig: initConfigMock as never, + createMongoClient: createClientMock, + writeStdout: text => stdout.push(text), + }); + + expect(stdout.join('')).toBe(`${EXPORT_RAW_BSON_USAGE}\n`); + expect(initConfigMock).not.toHaveBeenCalled(); + expect(createClientMock).not.toHaveBeenCalled(); + }); + + test('runCli initializes config with mongoReadOnly: true, issues strictly raw find(), calls zero write methods, and closes client', async () => { + const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-cli-')); + try { + const sampleBytes = Uint8Array.from( + BSON.serialize({ eodSearchCode: 'CAD.FOREX', date: '2025-01-02', close: 1.44 }) + ); + const findCalls: Array<{ collection: string; filter: unknown; options: unknown }> = []; + const forbiddenWrite = mock(() => { + throw new Error('Write/DDL method must never be called'); + }); + const closeMongoMock = mock(async () => {}); + const closeCursorMock = mock(async () => {}); + + const fakeClient: ReadOnlyMongoRawBsonClient & Record = { + isReadOnly: () => true, + insertOne: forbiddenWrite, + updateOne: forbiddenWrite, + deleteMany: forbiddenWrite, + createIndex: forbiddenWrite, + dropCollection: forbiddenWrite, + getCollection: (name: string) => ({ + find: (filter, options) => { + findCalls.push({ collection: name, filter, options }); + return { + close: closeCursorMock, + async *[Symbol.asyncIterator]() { + yield sampleBytes; + }, + }; + }, + }), + }; + + const initCalls: Array<{ service: string; opts: unknown }> = []; + const stdout: string[] = []; + + await runCli( + [ + '--out-dir', + outDir, + '--collections', + 'eodPrices', + '--eod-symbol', + 'CAD.FOREX', + '--batch-size', + '256', + ], + { + initializeConfig: ((service: string, opts?: unknown) => { + initCalls.push({ service, opts }); + return createBaseConfig(); + }) as never, + createMongoClient: async () => ({ + client: fakeClient, + close: closeMongoMock, + }), + writeStdout: text => stdout.push(text), + } + ); + + expect(initCalls).toEqual([{ service: 'dataPipeline', opts: { mongoReadOnly: true } }]); + expect(findCalls).toEqual([ + { + collection: 'eodPrices', + filter: { eodSearchCode: 'CAD.FOREX' }, + options: { raw: true, batchSize: 256 }, + }, + ]); + expect(forbiddenWrite).not.toHaveBeenCalled(); + expect(closeCursorMock).toHaveBeenCalledTimes(1); + expect(closeMongoMock).toHaveBeenCalledTimes(1); + + const written = Uint8Array.from(await readFile(join(outDir, 'eodPrices.bson'))); + expect(written).toEqual(sampleBytes); + expect(stdout.join('')).toContain('eodPrices: docs=1'); + expect(stdout.join('')).toContain('sha256='); + } finally { + await rm(outDir, { recursive: true, force: true }); + } + }); + + test('runExportRawBson closes Mongo client on mid-stream export failure and preserves primary error', async () => { + const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-fail-')); + try { + const closeMongoMock = mock(async () => {}); + const fakeClient: ReadOnlyMongoRawBsonClient = { + isReadOnly: () => true, + getCollection: () => ({ + find: () => ({ + async *[Symbol.asyncIterator]() { + yield Uint8Array.from(BSON.serialize({ ok: 1 })); + throw new Error('Mid-stream Mongo failure'); + }, + }), + }), + }; + + await expect( + runExportRawBson( + { + createMongoClient: () => ({ client: fakeClient, close: closeMongoMock }), + writeStdout: () => {}, + }, + { + outDir, + collections: ['qmSplits'], + } + ) + ).rejects.toThrow('Mid-stream Mongo failure'); + + expect(closeMongoMock).toHaveBeenCalledTimes(1); + } finally { + await rm(outDir, { recursive: true, force: true }); + } + }); + + test('runExportRawBson rejects disallowed collections before calling assertSafety or createMongoClient', async () => { + const assertSafetyMock = mock(() => {}); + const createClientMock = mock(() => { + throw new Error('createMongoClient must not be called'); + }); + + await expect( + runExportRawBson( + { + assertSafety: assertSafetyMock, + createMongoClient: createClientMock, + }, + { + outDir: '/tmp/unused', + collections: ['eodIntraday1M' as never], + } + ) + ).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION' }); + + expect(assertSafetyMock).not.toHaveBeenCalled(); + expect(createClientMock).not.toHaveBeenCalled(); + }); +}); diff --git a/test/unit/mongodb-read-only.test.ts b/test/unit/mongodb-read-only.test.ts index 27e94434..4fc604aa 100644 --- a/test/unit/mongodb-read-only.test.ts +++ b/test/unit/mongodb-read-only.test.ts @@ -1,5 +1,5 @@ import { describe, expect, mock, test } from 'bun:test'; -import { MongoClient } from 'mongodb'; +import { BSON, MongoClient } from 'mongodb'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { MongoDBClient } from '@stock-bot/mongodb'; @@ -1196,4 +1196,82 @@ describe('MongoDBClient read-only mode (offline)', () => { expect(collectionStub.insertOne).toHaveBeenCalledTimes(2); expect(dbStub.createCollection).toHaveBeenCalledTimes(1); }); + + test('forwards find(filter, { raw: true, batchSize, limit }) through read-only collection/cursor and yields raw BSON buffers untouched', async () => { + const logger = getLogger('mongodb-read-only-raw-find-test'); + const rawFrames = [ + Buffer.from(BSON.serialize({ eodSearchCode: 'AAPL.US', date: '2025-01-02', close: 250.5 })), + Buffer.from(BSON.serialize({ eodSearchCode: 'RY.TO', date: '2025-01-02', close: 175.25 })), + ]; + const closeMock = mock(async () => {}); + const rawCursorStub = { + close: closeMock, + [Symbol.asyncIterator]: async function* () { + for (const frame of rawFrames) { + yield frame; + } + }, + }; + const findCalls: Array<{ filter: unknown; options: unknown }> = []; + const collectionStub = { + collectionName: 'eodPrices', + dbName: 'stock', + namespace: 'stock.eodPrices', + find: mock((filter: unknown, options: unknown) => { + findCalls.push({ filter, options }); + return rawCursorStub; + }), + insertOne: mock(async () => ({ insertedId: 'id-1' })), + drop: mock(async () => true), + }; + const dbStub = { + databaseName: 'stock', + namespace: 'stock', + collection: mock(() => collectionStub), + }; + + const client = new MongoDBClient( + { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, + logger + ); + Object.assign(client, { + client: { db: mock(() => dbStub) }, + db: dbStub, + isConnected: true, + }); + + const collection = client.getCollection('eodPrices'); + const cursor = collection.find( + { eodSearchCode: 'CAD.FOREX' }, + { raw: true, batchSize: 128, limit: 2 } + ); + + expect(findCalls).toEqual([ + { + filter: { eodSearchCode: 'CAD.FOREX' }, + options: { raw: true, batchSize: 128, limit: 2 }, + }, + ]); + + const yielded: unknown[] = []; + try { + for await (const frame of cursor) { + yielded.push(frame); + } + } finally { + await cursor.close(); + } + + expect(yielded).toHaveLength(2); + expect(yielded[0]).toBe(rawFrames[0]); + expect(yielded[1]).toBe(rawFrames[1]); + expect(yielded[0]).toBeInstanceOf(Uint8Array); + expect(closeMock).toHaveBeenCalledTimes(1); + + // Write and DDL guards remain intact on the same read-only collection wrapper + expect(() => collection.insertOne({ a: 1 })).toThrow(/read-only mode/); + expect(() => collection.drop()).toThrow(/read-only mode/); + expect(collectionStub.insertOne).not.toHaveBeenCalled(); + expect(collectionStub.drop).not.toHaveBeenCalled(); + }); }); diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index acc90bcb..ce79fecc 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1468,3 +1468,12 @@ Measured locally (`2026-11-29`, default `500,000` rows; two back-to-back runs wi ``` - **Key-namespace alignment between `qmFilings` and `qmEarnings`:** `qmFilings` defaults to `symbol` while `qmEarnings` defaults to `qmSearchCode`. Both exports must carry an unambiguous key in the `provider_mapping` namespace (for example, the QuoteMedia security ID, not a bare ticker — the security master records distinct QuoteMedia IDs such as `VOY:CNX` and `VOY:CC` for the same symbol and exchange, so switching earnings to bare `symbol` can merge distinct identities or drop rows). If a live `qmFilings` export lacks that unambiguous key, prepare the export with verified QuoteMedia IDs and exclude unresolved rows rather than downgrading `qmEarnings` to bare tickers. - **In-RAM buffering & single-threaded execution:** decoded filings and earnings are buffered in RAM (with shared `Arc` key interning) before sorting/curation; `rayon` key-sharded streaming, direct MongoDB/PostgreSQL connections, and M2 `fundamentals_pit` joins remain out of scope. + +## Exporting Input Files (`data-pipeline`) + +All `curate-*` commands read local TSV and concatenated raw-BSON files produced by the read-only exporters in `@stock-bot/data-pipeline`: + +- **PostgreSQL security-master TSVs (`provider_mapping.tsv`, `listing_currencies.tsv`, `delistings.tsv`):** `apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts` +- **MongoDB concatenated raw-BSON files (`.bson`):** `apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts` + +See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.md#read-only-raw-bson-exporter-export-raw-bsonts) for flags, read-only safety guards, and the full M1 Step 2 execution order (`run-export-curate-inputs.ts` → `run-export-raw-bson.ts` → `curate-etl curate-*`).