diff --git a/tools/curate-etl/Cargo.toml b/tools/curate-etl/Cargo.toml index 646f30a8..98202a57 100644 --- a/tools/curate-etl/Cargo.toml +++ b/tools/curate-etl/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [dependencies] bson = { version = "=3.1.0", default-features = false, features = ["compat-3-0-0"] } +mongodb = { version = "=3.10.2", default-features = false, features = ["compat-3-0-0", "sync", "bson-3", "rustls-tls", "dns-resolver"] } parquet = { version = "=60.2.0", default-features = false, features = ["zstd"] } rayon = "=1.12.0" diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 6f391595..3e15b10b 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1,6 +1,6 @@ # `curate-etl` -Dedicated Rust crate (three exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]`, `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`, and `rayon` `=1.12.0`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`), the `M1.2ad` `ceoShorts` decoder + `curate-shorts` command, the `M1.2ae` `qmFilings` / `qmEarnings` decoders + `curate-events` command, the `M1.2ah` zero-copy `qmPrices` decoder + optional `--qm-prices` volume cross-check in `curate-bars-1d`, and the `M1.2ai` `rayon` year-sharded parallel Zstd Parquet writer (`--threads`) for `curate-bars-1d`. +Dedicated Rust crate (four exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]`, `mongodb` `=3.10.2` with `default-features = false, features = ["compat-3-0-0", "sync", "bson-3", "rustls-tls", "dns-resolver"]`, `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`, and `rayon` `=1.12.0`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`), the `M1.2ad` `ceoShorts` decoder + `curate-shorts` command, the `M1.2ae` `qmFilings` / `qmEarnings` decoders + `curate-events` command, the `M1.2ah` zero-copy `qmPrices` decoder + optional `--qm-prices` volume cross-check in `curate-bars-1d`, the `M1.2ai` `rayon` year-sharded parallel Zstd Parquet writer (`--threads`) for `curate-bars-1d`, the `M1.2ak` read-only MongoDB URI safety guard (`mongo_safety`), and the `M1.2al` sealed read-only MongoDB raw-BSON cursor adapter (`mongo_stream`). ## Scope & Sign Conventions @@ -1520,6 +1520,41 @@ Target classification (`parse_mongo_target` + `is_qa_mongo_target`) mirrors all 7. **Leading-zero decimal LAN IPs matched against `LocalHosts`:** `is_qa_mongo_target` normalizes 4-part decimal IPv4 spellings with leading zeros (e.g. `192.168.001.050:27017`) before checking `LocalHosts`, flagging them as QA even where `env-safety.ts` does not. 8. **Machine's own zoned link-local IPv6 matched against `LocalHosts`:** `is_qa_mongo_target` strips `%zone` suffixes when matching bracketed IPv6 hosts against `LocalHosts` (e.g. `[fe80::1234:5678%25eth0]:27017`), flagging the machine's own link-local IPv6 on port `27017` as QA even where `env-safety.ts` misses it. +## Sealed Read-Only MongoDB Raw-BSON Cursor Adapter (`M1.2al`) + +Library-only read-only MongoDB raw-BSON cursor adapter (`src/mongo_stream.rs`, tested offline in `src/mongo_stream_tests.rs`) bridging [`ValidatedReadOnlyMongoUri`] (`src/mongo_safety.rs`) into the existing `bson_stream` zero-copy decoders (`RawBsonChunkReader` and `decode_*_stream`) with zero CLI/command wiring yet. + +### Dependency & Build Impact + +- **New direct dependency:** `mongodb = { version = "=3.10.2", default-features = false, features = ["compat-3-0-0", "sync", "bson-3", "rustls-tls", "dns-resolver"] }` (no direct `tokio` dependency; uses `mongodb::sync::Client::with_uri_str` + `bson-3` aligned with `bson = "=3.1.0"`). +- **Pre-change crate count:** `77` unique crates in `cargo tree -p curate-etl --offline --prefix none`. +- **Post-`mongodb` transitive crate count & clean release build time:** pending online `cargo fetch` outside the no-network agent sandbox (recorded after Studio's unsandboxed dependency fetch and release build). + +### Public API & Sealing Guarantees + +- **Closed collection allowlist (`SourceCollection`):** 8 variants matching `RAW_BSON_EXPORT_COLLECTIONS` in `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts` in exact order (`eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`). No API accepts a free-form collection name string. +- **Typed read spec (`MongoReadSpec`, `MongoDateRange`, `FilterDateValue`, `build_filter_document`):** validates `batch_size` (`1..=100_000`, default `4_096`), `limit` (`1..=i64::MAX`), `max_doc_bytes` (`>= 5`, default `16 MiB + 16 KiB`), non-blank `key_eq`, and half-open `[gte, lt)` `date_range` (rejected on `teMarketData`), building `bson::Document` via `Document::from_iter(...)`. +- **Driver-independent seam (`RawDocumentSource`, `SliceRawDocumentSource`, `VecRawDocumentSource`) + bounded-memory `io::Read` adapter (`RawBsonCursorReader`):** validates every raw BSON frame (`len >= 5`, `len <= max_doc_bytes`, 4-byte LE length prefix `== len`, trailing `0x00`), copies directly into the caller's buffer when it fits, spills only the unread tail of a single current document into a reused `pending` buffer, tracks `docs_read()` / `bytes_read()` / `pending_capacity()`, and surfaces mid-stream errors as sticky `io::Error`s carrying `MongoStreamError`. +- **Sealed driver source (`MongoRawDocumentSource`):** the only public constructor is `MongoRawDocumentSource::open(uri: &ValidatedReadOnlyMongoUri, collection: SourceCollection, spec: MongoReadSpec)`. Validates database name and filter upfront without touching the network; lazily opens `mongodb::sync::Client` (`appName=curate-etl-ro`) and iterates `Collection::find(...).batch_size(...)[.limit(...)].run()` via `cursor.advance()` + `cursor.current().as_bytes()`. Exposes no `Client`, `Database`, `Collection`, or write/admin/aggregation method. +- **Error redaction (`MongoStreamError`):** never stores raw URIs, passwords, or raw driver errors; sanitizes raw URI, raw password, percent-decoded password, and embedded `mongodb://` / `mongodb+srv://` userinfo passwords to `[REDACTED]`. + +### `bench-mongo-stream` + +Offline fixed-seed benchmark comparing decoding `1,000,000` synthetic `eodPrices` documents (`285,639,152` bytes) through plain `io::Cursor<&[u8]>` → `decode_eod_price_stream` vs. `SliceRawDocumentSource` → `RawBsonCursorReader` → `decode_eod_price_stream`: + +```bash +cargo run -p curate-etl --release --offline -- bench-mongo-stream 1000000 +``` + +Measured locally (`2026-11-30`, two back-to-back offline runs with identical stats `decoded=995008`, `rejected=4992`, and checksum `0x05af9d2746d1b5e3`): + +- **Run 1:** plain `268.89 ms` (`3,719,024 docs/s`, `1,013.09 MB/s`) vs. `RawBsonCursorReader` `267.03 ms` (`3,744,860 docs/s`, `1,020.13 MB/s`, ratio `1.007x`, `peak_pending_capacity=271 bytes`) +- **Run 2:** plain `272.82 ms` (`3,665,383 docs/s`, `998.48 MB/s`) vs. `RawBsonCursorReader` `275.44 ms` (`3,630,582 docs/s`, `989.00 MB/s`, ratio `0.991x`, `peak_pending_capacity=271 bytes`) + +### Not Verified + +- **Live QA MongoDB cursor throughput on `quant`:** not verified in this task (all tests and benchmarks run 100% offline with zero network connections; live cursor throughput against read-only QA MongoDB on `quant` is deferred to the CLI wiring and live-host verification tasks). + ## 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`: diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 0ea4c1b0..2195f6c1 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -16,13 +16,15 @@ use parquet::file::reader::{FileReader, SerializedFileReader}; use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume}; -use crate::bson_eod_prices::{decode_eod_price_buffer, BsonEodDecodeStats}; +use crate::bson_eod_prices::{decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats}; use crate::bson_qm_actions::{ decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, }; use crate::bson_stream::{ - decode_eod_price_chunks, BsonStreamError, BsonStreamOptions, RawBsonChunkReader, + decode_eod_price_chunks, decode_eod_price_stream, BsonStreamError, BsonStreamOptions, + RawBsonChunkReader, }; +use crate::mongo_stream::{RawBsonCursorReader, SliceRawDocumentSource}; use crate::corporate_actions::{ build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, SplitActionEvent, @@ -87,6 +89,7 @@ pub const PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES: usize = 72; pub const DEFAULT_BSON_EOD_PRICES_BENCH_ROWS: usize = 1_000_000; pub const DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS: usize = 1_000_000; pub const DEFAULT_BSON_STREAM_BENCH_ROWS: usize = 2_000_000; +pub const DEFAULT_MONGO_STREAM_BENCH_ROWS: usize = 1_000_000; pub const BENCH_KEY_COUNT: usize = 20_000; pub const BENCH_EVENT_COUNT: usize = 19_000; pub const PROVIDER_MAPPING_BENCH_KEY_COUNT: usize = 60_000; @@ -3992,6 +3995,150 @@ pub fn run_bson_stream_benchmark(rows: usize) -> Result` +/// decode benchmark for `rows` synthetic `eodPrices` documents. +pub fn run_mongo_stream_benchmark(rows: usize) -> Result { + if rows == 0 { + return Ok(MongoStreamBenchReport { + rows: 0, + bytes: 0, + plain_elapsed_ms: 0.0, + plain_docs_per_sec: 0.0, + plain_mb_per_sec: 0.0, + cursor_elapsed_ms: 0.0, + cursor_docs_per_sec: 0.0, + cursor_mb_per_sec: 0.0, + cursor_to_plain_ratio: 0.0, + peak_pending_capacity: 0, + checksum: 0, + stats: BsonEodDecodeStats::default(), + }); + } + + let buffer = build_bson_eod_prices_bench_buffer(rows); + let bytes = buffer.len(); + + let mut doc_slices: Vec<&[u8]> = Vec::with_capacity(rows); + for doc_res in iter_raw_bson_docs(&buffer) { + let raw_doc = doc_res.expect("synthetic benchmark buffer must have valid BSON frames"); + doc_slices.push(raw_doc.as_bytes()); + } + assert_eq!(doc_slices.len(), rows); + + // Baseline: plain in-memory io::Cursor<&[u8]> -> decode_eod_price_stream. + let mut plain_hash = 0u64; + let mut plain_err_hash = 0u64; + let plain_start = Instant::now(); + let plain_stats = decode_eod_price_stream( + io::Cursor::new(buffer.as_slice()), + BsonStreamOptions::default(), + |bar| { + plain_hash = mix_bytes(plain_hash, bar.eod_search_code.as_bytes()); + plain_hash = mix_u64(plain_hash, bar.session_date as u64); + plain_hash = mix_u64(plain_hash, bar.open.to_bits()); + plain_hash = mix_u64(plain_hash, bar.high.to_bits()); + plain_hash = mix_u64(plain_hash, bar.low.to_bits()); + plain_hash = mix_u64(plain_hash, bar.close.to_bits()); + plain_hash = mix_u64(plain_hash, bar.adj_volume.to_bits()); + }, + |offset, _err| { + plain_err_hash = mix_u64(plain_err_hash, offset ^ 0xDEAD_BEEF_CAFE_BABEu64); + }, + )?; + let plain_elapsed_secs = plain_start.elapsed().as_secs_f64(); + let plain_checksum = black_box(plain_hash ^ plain_err_hash); + + // Candidate: in-memory RawDocumentSource -> RawBsonCursorReader -> decode_eod_price_stream. + let mut cursor_reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&doc_slices)); + let mut cursor_hash = 0u64; + let mut cursor_err_hash = 0u64; + let cursor_start = Instant::now(); + let cursor_stats = decode_eod_price_stream( + &mut cursor_reader, + BsonStreamOptions::default(), + |bar| { + cursor_hash = mix_bytes(cursor_hash, bar.eod_search_code.as_bytes()); + cursor_hash = mix_u64(cursor_hash, bar.session_date as u64); + cursor_hash = mix_u64(cursor_hash, bar.open.to_bits()); + cursor_hash = mix_u64(cursor_hash, bar.high.to_bits()); + cursor_hash = mix_u64(cursor_hash, bar.low.to_bits()); + cursor_hash = mix_u64(cursor_hash, bar.close.to_bits()); + cursor_hash = mix_u64(cursor_hash, bar.adj_volume.to_bits()); + }, + |offset, _err| { + cursor_err_hash = mix_u64(cursor_err_hash, offset ^ 0xDEAD_BEEF_CAFE_BABEu64); + }, + )?; + let cursor_elapsed_secs = cursor_start.elapsed().as_secs_f64(); + let cursor_checksum = black_box(cursor_hash ^ cursor_err_hash); + let peak_pending_capacity = cursor_reader.pending_capacity(); + + assert_eq!( + cursor_stats, plain_stats, + "cursor reader decode stats must match plain in-memory reader" + ); + assert_eq!( + cursor_checksum, plain_checksum, + "cursor reader decode checksum must match plain in-memory reader" + ); + assert_eq!(cursor_reader.docs_read(), rows as u64); + assert_eq!(cursor_reader.bytes_read(), bytes as u64); + + let plain_elapsed_ms = plain_elapsed_secs * 1_000.0; + let (plain_docs_per_sec, _) = compute_rates(rows, plain_elapsed_secs); + let plain_mb_per_sec = if plain_elapsed_secs > 0.0 && plain_elapsed_secs.is_finite() { + (bytes as f64 / (1024.0 * 1024.0)) / plain_elapsed_secs + } else { + 0.0 + }; + + let cursor_elapsed_ms = cursor_elapsed_secs * 1_000.0; + let (cursor_docs_per_sec, _) = compute_rates(rows, cursor_elapsed_secs); + let cursor_mb_per_sec = if cursor_elapsed_secs > 0.0 && cursor_elapsed_secs.is_finite() { + (bytes as f64 / (1024.0 * 1024.0)) / cursor_elapsed_secs + } else { + 0.0 + }; + + let cursor_to_plain_ratio = if plain_docs_per_sec > 0.0 { + cursor_docs_per_sec / plain_docs_per_sec + } else { + 0.0 + }; + + Ok(MongoStreamBenchReport { + rows, + bytes, + plain_elapsed_ms, + plain_docs_per_sec, + plain_mb_per_sec, + cursor_elapsed_ms, + cursor_docs_per_sec, + cursor_mb_per_sec, + cursor_to_plain_ratio, + peak_pending_capacity, + checksum: cursor_checksum, + stats: cursor_stats, + }) +} + /// Summary metrics produced by [`run_bson_qm_actions_benchmark`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct BsonQmActionsBenchReport { @@ -11188,6 +11335,36 @@ mod tests { assert_eq!(report.stats, BsonEodDecodeStats::default()); } + #[test] + fn mongo_stream_benchmark_small_run_is_deterministic_with_parity() { + let a = run_mongo_stream_benchmark(2_000).expect("mongo-stream bench must succeed"); + let b = run_mongo_stream_benchmark(2_000).expect("mongo-stream bench must be deterministic"); + + assert_eq!(a.rows, 2_000); + assert_eq!(a.bytes, b.bytes); + assert!(a.bytes > 0); + assert_eq!(a.checksum, b.checksum); + assert_eq!(a.stats, b.stats); + assert_eq!(a.stats.docs_in, 2_000); + assert_eq!(a.stats.decoded + a.stats.rejected_total(), a.stats.docs_in); + assert!(a.plain_docs_per_sec.is_finite() && a.plain_docs_per_sec >= 0.0); + assert!(a.cursor_docs_per_sec.is_finite() && a.cursor_docs_per_sec >= 0.0); + assert!(a.cursor_to_plain_ratio.is_finite() && a.cursor_to_plain_ratio >= 0.0); + } + + #[test] + fn mongo_stream_benchmark_zero_rows_handles_cleanly() { + let report = run_mongo_stream_benchmark(0).expect("zero-row mongo-stream bench must succeed"); + assert_eq!(report.rows, 0); + assert_eq!(report.bytes, 0); + assert_eq!(report.plain_elapsed_ms, 0.0); + assert_eq!(report.cursor_elapsed_ms, 0.0); + assert_eq!(report.cursor_to_plain_ratio, 0.0); + assert_eq!(report.peak_pending_capacity, 0); + assert_eq!(report.checksum, 0); + assert_eq!(report.stats, BsonEodDecodeStats::default()); + } + #[test] fn bson_qm_actions_benchmark_small_run_is_deterministic() { let a = run_bson_qm_actions_benchmark(20_000); diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index a99a68d1..34f8c5da 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -18,7 +18,8 @@ use crate::bench::{ DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_FX_CMD_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, - DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS, + DEFAULT_MONGO_STREAM_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, + DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS, DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS, @@ -65,6 +66,7 @@ pub enum CliAction { BenchBsonEodPrices(usize), BenchBsonQmActions(usize), BenchBsonStream(usize), + BenchMongoStream(usize), BenchCurateBars(usize), BenchCurateBarsCmd(usize), BenchCurateShorts(usize), @@ -116,6 +118,7 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-bson-eod-prices [rows] Run fixed-seed eodPrices raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_EOD_PRICES_BENCH_ROWS})\n\ {name} bench-bson-qm-actions [rows] Run fixed-seed qmSplits/qmDividends raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS})\n\ {name} bench-bson-stream [rows] Run fixed-seed eodPrices raw BSON stream vs buffer decode benchmark (default: {DEFAULT_BSON_STREAM_BENCH_ROWS})\n\ + {name} bench-mongo-stream [rows] Run offline fixed-seed RawBsonCursorReader vs plain in-memory eodPrices decode benchmark (default: {DEFAULT_MONGO_STREAM_BENCH_ROWS})\n\ {name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\ {name} bench-curate-bars-cmd [rows] Run fixed-seed end-to-end curate-bars-1d file->Parquet benchmark (default: {DEFAULT_CURATE_BARS_CMD_BENCH_ROWS})\n\ {name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})\n\ @@ -160,6 +163,7 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-bson-eod-prices [rows]\n\ {name} bench-bson-qm-actions [rows]\n\ {name} bench-bson-stream [rows]\n\ + {name} bench-mongo-stream [rows]\n\ {name} bench-curate-bars [rows]\n\ {name} bench-curate-bars-cmd [rows]\n\ {name} bench-curate-shorts [rows]\n\ @@ -1057,6 +1061,16 @@ pub fn parse_args(args: &[String]) -> Result { ["bench-bson-stream", _, ..] => { Err("too many arguments for bench-bson-stream".to_string()) } + ["bench-mongo-stream"] => Ok(CliAction::BenchMongoStream(DEFAULT_MONGO_STREAM_BENCH_ROWS)), + ["bench-mongo-stream", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchMongoStream(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-mongo-stream", _, ..] => { + Err("too many arguments for bench-mongo-stream".to_string()) + } ["bench-curate-bars"] => Ok(CliAction::BenchCurateBars(DEFAULT_CURATE_BARS_BENCH_ROWS)), ["bench-curate-bars", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchCurateBars(n)), @@ -1512,6 +1526,22 @@ mod tests { assert!(parse_args(&to_args(&["bench-bson-stream", "10", "20"])).is_err()); } + #[test] + fn parses_and_validates_bench_mongo_stream_args() { + assert_eq!( + parse_args(&to_args(&["bench-mongo-stream"])), + Ok(CliAction::BenchMongoStream(DEFAULT_MONGO_STREAM_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-mongo-stream", "100000"])), + Ok(CliAction::BenchMongoStream(100_000)) + ); + assert!(parse_args(&to_args(&["bench-mongo-stream", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-mongo-stream", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-mongo-stream", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-mongo-stream", "10", "20"])).is_err()); + } + #[test] fn usage_strings_mention_all_benchmarks() { let full = format_usage("curate-etl", "0.1.0"); diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index af175539..64d1f811 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -15,6 +15,7 @@ pub mod corporate_actions; pub mod events; pub mod fx; pub mod mongo_safety; +pub mod mongo_stream; pub mod parquet_adj; pub mod parquet_bars; pub mod parquet_corporate_actions; @@ -101,6 +102,12 @@ pub use mongo_safety::{ MongoSafetyError, MongoScheme, MongoTarget, MongoTargetHost, ReadOnlyPolicy, ValidatedReadOnlyMongoUri, DEFAULT_ALLOWED_READ_USER, FORBIDDEN_ADMIN_USER, QA_MONGO_PORT, }; +pub use mongo_stream::{ + build_filter_document, FilterDateValue, MongoDateRange, MongoDriverStage, + MongoRawDocumentSource, MongoReadSpec, MongoStreamError, RawBsonCursorReader, + RawDocumentSource, SliceRawDocumentSource, SourceCollection, VecRawDocumentSource, + DEFAULT_MONGO_BATCH_SIZE, MAX_MONGO_BATCH_SIZE, +}; pub use parquet_adj::{ adj_factors_parquet_schema, write_adj_factors_dataset, AdjFactorsParquetRow, AdjFactorsWriteOptions, AdjFactorsWriteStats, ParquetAdjError, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index e60629d7..448dd422 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -11,7 +11,8 @@ use curate_etl::bench::{ run_curate_corporate_actions_cmd_benchmark, run_curate_events_benchmark, run_curate_events_cmd_benchmark, run_curate_fx_benchmark, run_curate_fx_cmd_benchmark, run_curate_shorts_benchmark, run_curate_shorts_command_benchmark, run_events_benchmark, - run_fx_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark, + run_fx_benchmark, run_mongo_stream_benchmark, run_parquet_adj_benchmark, + run_parquet_bars_benchmark, run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark, @@ -656,6 +657,42 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchMongoStream(rows)) => { + let report = match run_mongo_stream_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: mongo-stream benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-mongo-stream"); + println!(" input: rows={} bytes={}", report.rows, report.bytes); + println!( + " decode: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={}) checksum=0x{:016x}", + report.stats.decoded, + report.stats.rejected_total(), + report.stats.rejected_missing_field, + report.stats.rejected_empty_field, + report.stats.rejected_wrong_type, + report.stats.rejected_malformed_date, + report.stats.rejected_invalid_number, + report.stats.rejected_corrupt_document, + report.checksum + ); + println!( + " plain: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MB/s", + report.plain_elapsed_ms, report.plain_docs_per_sec, report.plain_mb_per_sec + ); + println!( + " cursor: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MB/s ratio={:.3}x peak_pending_capacity={} bytes", + report.cursor_elapsed_ms, + report.cursor_docs_per_sec, + report.cursor_mb_per_sec, + report.cursor_to_plain_ratio, + report.peak_pending_capacity + ); + ExitCode::SUCCESS + } Ok(CliAction::BenchCurateBars(rows)) => { let report = match run_curate_bars_benchmark(rows) { Ok(report) => report, diff --git a/tools/curate-etl/src/mongo_safety.rs b/tools/curate-etl/src/mongo_safety.rs index bfca5d75..32ead4fc 100644 --- a/tools/curate-etl/src/mongo_safety.rs +++ b/tools/curate-etl/src/mongo_safety.rs @@ -548,7 +548,7 @@ pub fn assert_read_only_mongo_uri( }) } -fn redact_mongo_uri_password(uri: &str) -> String { +pub(crate) fn redact_mongo_uri_password(uri: &str) -> String { let Some(scheme_end) = uri.find("://") else { return uri.to_owned(); }; diff --git a/tools/curate-etl/src/mongo_stream.rs b/tools/curate-etl/src/mongo_stream.rs new file mode 100644 index 00000000..b0830247 --- /dev/null +++ b/tools/curate-etl/src/mongo_stream.rs @@ -0,0 +1,964 @@ +//! Sealed, read-only MongoDB raw-BSON cursor adapter (`M1.2al`). +//! +//! Bridges [`ValidatedReadOnlyMongoUri`] (from [`crate::mongo_safety`]) to the +//! existing zero-copy [`crate::bson_stream`] decoders via a driver-independent +//! [`RawDocumentSource`] trait and a bounded-memory [`RawBsonCursorReader`] +//! implementing [`std::io::Read`]. +//! +//! # Safety & Sealing Guarantees +//! - Closed [`SourceCollection`] allowlist matching the 8 M1 collections in +//! `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`. No API +//! accepts a free-form collection name string. +//! - The only public constructor for [`MongoRawDocumentSource`] requires a +//! `&ValidatedReadOnlyMongoUri` proof token. +//! - Exposes no MongoDB client, database, or collection handle and performs +//! only read-only `find` cursor iteration. +//! - Lazy connection: [`MongoRawDocumentSource::open`] validates the database +//! name, read spec, and filter document upfront without opening any network +//! connection until the first [`RawDocumentSource::next_raw_document`] call. +//! - Password redaction: [`MongoStreamError`] never stores raw URIs, passwords, +//! or raw driver errors; all driver error text is sanitized at the boundary. + +use std::error::Error; +use std::fmt; +use std::io; + +use bson::raw::RawDocumentBuf; +use bson::{Bson, DateTime, Document}; + +use crate::bson_stream::{DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES}; +use crate::mongo_safety::{redact_mongo_uri_password, ValidatedReadOnlyMongoUri}; + +/// Default MongoDB cursor batch size (matches `DEFAULT_RAW_BSON_BATCH_SIZE`). +pub const DEFAULT_MONGO_BATCH_SIZE: u32 = 4_096; + +/// Maximum permitted MongoDB cursor batch size (matches `MAX_RAW_BSON_BATCH_SIZE`). +pub const MAX_MONGO_BATCH_SIZE: u32 = 100_000; + +/// Default MongoDB `appName` attached to read-only ETL cursor connections when +/// the validated URI does not already specify `appName`. +const DEFAULT_APP_NAME: &str = "curate-etl-ro"; + +/// Closed allowlist of the 8 M1 MongoDB source collections consumed by `curate-etl`. +/// +/// Order and names match `RAW_BSON_EXPORT_COLLECTIONS` in +/// `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum SourceCollection { + EodPrices, + QmSplits, + QmDividends, + QmPrices, + TeMarketData, + CeoShorts, + QmFilings, + QmEarnings, +} + +impl SourceCollection { + /// All 8 allowlisted M1 source collections in canonical order. + pub const ALL: [SourceCollection; 8] = [ + Self::EodPrices, + Self::QmSplits, + Self::QmDividends, + Self::QmPrices, + Self::TeMarketData, + Self::CeoShorts, + Self::QmFilings, + Self::QmEarnings, + ]; + + /// Exact MongoDB collection name. + pub const fn as_str(self) -> &'static str { + match self { + Self::EodPrices => "eodPrices", + Self::QmSplits => "qmSplits", + Self::QmDividends => "qmDividends", + Self::QmPrices => "qmPrices", + Self::TeMarketData => "teMarketData", + Self::CeoShorts => "ceoShorts", + Self::QmFilings => "qmFilings", + Self::QmEarnings => "qmEarnings", + } + } + + /// Primary provider key field used for exact equality filters (`key_eq`). + pub const fn key_field(self) -> &'static str { + match self { + Self::EodPrices => "eodSearchCode", + Self::QmSplits => "qmSearchCode", + Self::QmDividends => "qmSearchCode", + Self::QmPrices => "qmSearchCode", + Self::TeMarketData => "teSymbol", + Self::CeoShorts => "symbol", + Self::QmFilings => "symbol", + Self::QmEarnings => "qmSearchCode", + } + } + + /// Date/timestamp field used for range filters (`date_range`), or `None` + /// for document-per-symbol collections (`teMarketData`). + pub const fn date_field(self) -> Option<&'static str> { + match self { + Self::EodPrices => Some("date"), + Self::QmSplits => Some("date"), + Self::QmDividends => Some("date"), + Self::QmPrices => Some("date"), + Self::TeMarketData => None, + Self::CeoShorts => Some("timestamp"), + Self::QmFilings => Some("timefiled"), + Self::QmEarnings => Some("reportDate"), + } + } +} + +impl fmt::Display for SourceCollection { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// Typed date bound value for [`MongoDateRange`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FilterDateValue { + /// Lexicographically ordered ISO-8601 date/timestamp string (e.g. `"2024-01-01"`). + IsoString(String), + /// BSON UTC `DateTime` expressed as milliseconds since the Unix epoch. + BsonDateTimeMillis(i64), +} + +impl FilterDateValue { + fn to_bson(&self) -> Bson { + match self { + Self::IsoString(s) => Bson::String(s.clone()), + Self::BsonDateTimeMillis(ms) => Bson::DateTime(DateTime::from_millis(*ms)), + } + } +} + +/// Half-open `[gte, lt)` date filter for a [`SourceCollection`] with a date field. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MongoDateRange { + pub gte: Option, + pub lt: Option, +} + +/// Typed read specification for a read-only MongoDB cursor query. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MongoReadSpec { + /// Optional exact match on [`SourceCollection::key_field`]. + pub key_eq: Option, + /// Optional `[gte, lt)` range on [`SourceCollection::date_field`]. + pub date_range: Option, + /// MongoDB cursor `batchSize` (in `1..=MAX_MONGO_BATCH_SIZE`). + pub batch_size: u32, + /// Optional maximum number of documents to return (in `1..=i64::MAX`). + pub limit: Option, + /// Maximum allowed single raw BSON document length in bytes (`>= MIN_BSON_DOC_BYTES`). + pub max_doc_bytes: usize, +} + +impl Default for MongoReadSpec { + fn default() -> Self { + Self { + key_eq: None, + date_range: None, + batch_size: DEFAULT_MONGO_BATCH_SIZE, + limit: None, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + } + } +} + +impl MongoReadSpec { + /// Validates all read specification invariants for `collection`. + pub fn validate(&self, collection: SourceCollection) -> Result<(), MongoStreamError> { + if self.batch_size == 0 || self.batch_size > MAX_MONGO_BATCH_SIZE { + return Err(MongoStreamError::InvalidBatchSize { + batch_size: self.batch_size, + max_batch_size: MAX_MONGO_BATCH_SIZE, + }); + } + if let Some(limit) = self.limit { + if limit == 0 || limit > i64::MAX as u64 { + return Err(MongoStreamError::InvalidLimit { limit }); + } + } + if self.max_doc_bytes < MIN_BSON_DOC_BYTES { + return Err(MongoStreamError::InvalidMaxDocBytes { + max_doc_bytes: self.max_doc_bytes, + min_doc_bytes: MIN_BSON_DOC_BYTES, + }); + } + if let Some(key) = &self.key_eq { + if key.trim().is_empty() { + return Err(MongoStreamError::InvalidKeyFilter { collection }); + } + } + if let Some(range) = &self.date_range { + if collection.date_field().is_none() { + return Err(MongoStreamError::DateRangeNotSupported { collection }); + } + if range.gte.is_none() && range.lt.is_none() { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: "at least one of gte or lt must be set".to_owned(), + }); + } + if let Some(FilterDateValue::IsoString(s)) = &range.gte { + if s.trim().is_empty() { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: "gte ISO string must not be empty or blank".to_owned(), + }); + } + } + if let Some(FilterDateValue::IsoString(s)) = &range.lt { + if s.trim().is_empty() { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: "lt ISO string must not be empty or blank".to_owned(), + }); + } + } + if let (Some(gte), Some(lt)) = (&range.gte, &range.lt) { + match (gte, lt) { + (FilterDateValue::IsoString(a), FilterDateValue::IsoString(b)) => { + if a >= b { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: format!("gte ({a:?}) must be strictly less than lt ({b:?})"), + }); + } + } + ( + FilterDateValue::BsonDateTimeMillis(a), + FilterDateValue::BsonDateTimeMillis(b), + ) => { + if a >= b { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: format!("gte ({a}) must be strictly less than lt ({b})"), + }); + } + } + _ => { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: "gte and lt must use the same FilterDateValue variant" + .to_owned(), + }); + } + } + } + } + Ok(()) + } +} + +/// Validates `spec` and constructs the corresponding MongoDB `find` filter [`Document`]. +pub fn build_filter_document( + collection: SourceCollection, + spec: &MongoReadSpec, +) -> Result { + spec.validate(collection)?; + + let mut entries: Vec<(String, Bson)> = Vec::with_capacity(2); + if let Some(key) = &spec.key_eq { + entries.push((collection.key_field().to_owned(), Bson::String(key.clone()))); + } + if let Some(range) = &spec.date_range { + if let Some(date_field) = collection.date_field() { + let mut range_entries: Vec<(String, Bson)> = Vec::with_capacity(2); + if let Some(gte) = &range.gte { + range_entries.push(("$gte".to_owned(), gte.to_bson())); + } + if let Some(lt) = &range.lt { + range_entries.push(("$lt".to_owned(), lt.to_bson())); + } + entries.push(( + date_field.to_owned(), + Bson::Document(Document::from_iter(range_entries)), + )); + } + } + + Ok(Document::from_iter(entries)) +} + +/// Operation stage for a sanitized MongoDB driver error. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MongoDriverStage { + Connect, + Find, + CursorAdvance, +} + +impl MongoDriverStage { + pub const fn as_str(self) -> &'static str { + match self { + Self::Connect => "connect", + Self::Find => "find", + Self::CursorAdvance => "cursor_advance", + } + } +} + +impl fmt::Display for MongoDriverStage { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// Redacted error type for MongoDB raw-BSON cursor streaming. +/// +/// Intentionally never stores raw URIs, passwords, or raw driver error objects. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MongoStreamError { + MissingDatabaseName { + redacted_uri: String, + }, + InvalidBatchSize { + batch_size: u32, + max_batch_size: u32, + }, + InvalidLimit { + limit: u64, + }, + InvalidMaxDocBytes { + max_doc_bytes: usize, + min_doc_bytes: usize, + }, + InvalidKeyFilter { + collection: SourceCollection, + }, + DateRangeNotSupported { + collection: SourceCollection, + }, + InvalidDateRange { + collection: SourceCollection, + detail: String, + }, + InvalidBsonFrame { + doc_index: u64, + detail: String, + }, + Driver { + collection: SourceCollection, + stage: MongoDriverStage, + redacted_uri: String, + message: String, + }, + Source { + detail: String, + }, +} + +impl fmt::Display for MongoStreamError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MissingDatabaseName { redacted_uri } => write!( + f, + "MongoDB URI {redacted_uri} must include a non-empty database name" + ), + Self::InvalidBatchSize { + batch_size, + max_batch_size, + } => write!( + f, + "invalid MongoDB batch_size {batch_size}: must be in 1..={max_batch_size}" + ), + Self::InvalidLimit { limit } => write!( + f, + "invalid MongoDB limit {limit}: must be in 1..={}", + i64::MAX + ), + Self::InvalidMaxDocBytes { + max_doc_bytes, + min_doc_bytes, + } => write!( + f, + "invalid max_doc_bytes {max_doc_bytes}: must be >= {min_doc_bytes}" + ), + Self::InvalidKeyFilter { collection } => write!( + f, + "invalid key_eq filter for collection {collection}: must not be empty or blank" + ), + Self::DateRangeNotSupported { collection } => write!( + f, + "date_range filter is not supported for collection {collection}" + ), + Self::InvalidDateRange { collection, detail } => { + write!(f, "invalid date_range for collection {collection}: {detail}") + } + Self::InvalidBsonFrame { doc_index, detail } => { + write!(f, "invalid raw BSON frame at doc #{doc_index}: {detail}") + } + Self::Driver { + collection, + stage, + redacted_uri, + message, + } => write!( + f, + "MongoDB driver error during {stage} on {collection} ({redacted_uri}): {message}" + ), + Self::Source { detail } => write!(f, "raw BSON source error: {detail}"), + } + } +} + +impl Error for MongoStreamError {} + +/// Driver-independent seam yielding one raw length-prefixed BSON document at a time. +pub trait RawDocumentSource { + /// Advances to the next raw BSON document and returns its byte slice, + /// or `Ok(None)` when the source is exhausted. + fn next_raw_document(&mut self) -> Result, MongoStreamError>; +} + +/// Zero-copy in-memory [`RawDocumentSource`] over a slice of borrowed raw BSON frames. +#[derive(Debug, Clone)] +pub struct SliceRawDocumentSource<'a> { + docs: &'a [&'a [u8]], + index: usize, +} + +impl<'a> SliceRawDocumentSource<'a> { + pub fn new(docs: &'a [&'a [u8]]) -> Self { + Self { docs, index: 0 } + } +} + +impl<'a> RawDocumentSource for SliceRawDocumentSource<'a> { + #[inline] + fn next_raw_document(&mut self) -> Result, MongoStreamError> { + let Some(&doc) = self.docs.get(self.index) else { + return Ok(None); + }; + self.index += 1; + Ok(Some(doc)) + } +} + +/// Owned in-memory [`RawDocumentSource`] over a `Vec>` of raw BSON frames. +#[derive(Debug, Clone)] +pub struct VecRawDocumentSource { + docs: Vec>, + index: usize, +} + +impl VecRawDocumentSource { + pub fn new(docs: Vec>) -> Self { + Self { docs, index: 0 } + } +} + +impl RawDocumentSource for VecRawDocumentSource { + #[inline] + fn next_raw_document(&mut self) -> Result, MongoStreamError> { + if self.index >= self.docs.len() { + return Ok(None); + } + let doc = self.docs[self.index].as_slice(); + self.index += 1; + Ok(Some(doc)) + } +} + +fn validate_raw_bson_frame( + doc: &[u8], + doc_index: u64, + max_doc_bytes: usize, +) -> Result<(), MongoStreamError> { + if doc.len() < MIN_BSON_DOC_BYTES { + return Err(MongoStreamError::InvalidBsonFrame { + doc_index, + detail: format!( + "frame length {} is below minimum BSON document size ({MIN_BSON_DOC_BYTES})", + doc.len() + ), + }); + } + if doc.len() > max_doc_bytes { + return Err(MongoStreamError::InvalidBsonFrame { + doc_index, + detail: format!( + "frame length {} exceeds max_doc_bytes ({max_doc_bytes})", + doc.len() + ), + }); + } + let declared_len = i32::from_le_bytes([doc[0], doc[1], doc[2], doc[3]]); + if declared_len < MIN_BSON_DOC_BYTES as i32 || (declared_len as usize) != doc.len() { + return Err(MongoStreamError::InvalidBsonFrame { + doc_index, + detail: format!( + "4-byte LE length prefix ({declared_len}) disagrees with byte length ({})", + doc.len() + ), + }); + } + let last_byte = doc[doc.len() - 1]; + if last_byte != 0x00 { + return Err(MongoStreamError::InvalidBsonFrame { + doc_index, + detail: format!("missing trailing 0x00 terminator (got 0x{last_byte:02x})"), + }); + } + Ok(()) +} + +/// Bounded-memory [`io::Read`] adapter that turns any [`RawDocumentSource`] +/// into a concatenated raw BSON byte stream for [`crate::bson_stream::RawBsonChunkReader`] +/// and `decode_*_stream`. +/// +/// Copies documents directly into the caller's buffer whenever they fit, +/// spilling only the unread tail of a single current document into a reused +/// `pending` buffer when the caller's buffer is smaller. +pub struct RawBsonCursorReader { + source: S, + max_doc_bytes: usize, + pending: Vec, + pending_pos: usize, + docs_read: u64, + bytes_read: u64, + eof: bool, + stashed_error: Option, + sticky_error: Option, +} + +impl RawBsonCursorReader { + /// Wraps `source` with the default maximum BSON document size ([`DEFAULT_MAX_DOC_BYTES`]). + pub fn new(source: S) -> Self { + Self { + source, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + pending: Vec::new(), + pending_pos: 0, + docs_read: 0, + bytes_read: 0, + eof: false, + stashed_error: None, + sticky_error: None, + } + } + + /// Wraps `source` with an explicit `max_doc_bytes` ceiling (`>= MIN_BSON_DOC_BYTES`). + pub fn with_max_doc_bytes(source: S, max_doc_bytes: usize) -> Result { + if max_doc_bytes < MIN_BSON_DOC_BYTES { + return Err(MongoStreamError::InvalidMaxDocBytes { + max_doc_bytes, + min_doc_bytes: MIN_BSON_DOC_BYTES, + }); + } + Ok(Self { + source, + max_doc_bytes, + pending: Vec::new(), + pending_pos: 0, + docs_read: 0, + bytes_read: 0, + eof: false, + stashed_error: None, + sticky_error: None, + }) + } + + /// Number of valid raw BSON documents accepted from the underlying source. + #[inline] + pub fn docs_read(&self) -> u64 { + self.docs_read + } + + /// Total bytes across all valid raw BSON documents accepted from the underlying source. + #[inline] + pub fn bytes_read(&self) -> u64 { + self.bytes_read + } + + /// Current allocated capacity of the single-document tail spill buffer. + #[inline] + pub fn pending_capacity(&self) -> usize { + self.pending.capacity() + } + + /// Consumes the adapter and returns the underlying source. + pub fn into_inner(self) -> S { + self.source + } +} + +impl io::Read for RawBsonCursorReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if buf.is_empty() { + return Ok(0); + } + if let Some(err) = &self.sticky_error { + return Err(io::Error::other(err.clone())); + } + if let Some(err) = self.stashed_error.take() { + self.sticky_error = Some(err.clone()); + return Err(io::Error::other(err)); + } + + let mut written = 0usize; + while written < buf.len() { + if self.pending_pos < self.pending.len() { + let avail = self.pending.len() - self.pending_pos; + let take = avail.min(buf.len() - written); + buf[written..written + take] + .copy_from_slice(&self.pending[self.pending_pos..self.pending_pos + take]); + self.pending_pos += take; + written += take; + if self.pending_pos == self.pending.len() { + self.pending.clear(); + self.pending_pos = 0; + } + continue; + } + + if self.eof { + break; + } + + match self.source.next_raw_document() { + Ok(None) => { + self.eof = true; + break; + } + Ok(Some(doc)) => { + if let Err(err) = + validate_raw_bson_frame(doc, self.docs_read, self.max_doc_bytes) + { + if written > 0 { + self.stashed_error = Some(err); + return Ok(written); + } + self.sticky_error = Some(err.clone()); + return Err(io::Error::other(err)); + } + + self.docs_read += 1; + self.bytes_read += doc.len() as u64; + + let remaining = buf.len() - written; + if doc.len() <= remaining { + buf[written..written + doc.len()].copy_from_slice(doc); + written += doc.len(); + } else { + buf[written..written + remaining].copy_from_slice(&doc[..remaining]); + written += remaining; + let tail = &doc[remaining..]; + self.pending.clear(); + if self.pending.capacity() < tail.len() { + self.pending.reserve_exact(tail.len()); + } + self.pending.extend_from_slice(tail); + self.pending_pos = 0; + break; + } + } + Err(err) => { + if written > 0 { + self.stashed_error = Some(err); + return Ok(written); + } + self.sticky_error = Some(err.clone()); + return Err(io::Error::other(err)); + } + } + } + + Ok(written) + } +} + +fn extract_raw_uri_password(uri: &str) -> Option<&str> { + let scheme_end = uri.find("://")?; + let rest = &uri[scheme_end + 3..]; + let authority_end = rest.find(['/', '?']).unwrap_or(rest.len()); + let authority = &rest[..authority_end]; + let at_idx = authority.find('@')?; + let userinfo = &authority[..at_idx]; + let colon_idx = userinfo.find(':')?; + let pass = &userinfo[colon_idx + 1..]; + if pass.is_empty() { + None + } else { + Some(pass) + } +} + +fn percent_decode_best_effort(input: &str) -> Option { + let bytes = input.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' && i + 2 < bytes.len() { + let hi = hex_nibble(bytes[i + 1])?; + let lo = hex_nibble(bytes[i + 2])?; + out.push((hi << 4) | lo); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8(out).ok() +} + +fn hex_nibble(b: u8) -> Option { + match b { + b'0'..=b'9' => Some(b - b'0'), + b'a'..=b'f' => Some(b - b'a' + 10), + b'A'..=b'F' => Some(b - b'A' + 10), + _ => None, + } +} + +fn redact_embedded_mongo_uris(text: &str) -> String { + let mut result = String::with_capacity(text.len()); + let mut cursor = 0usize; + let lower = text.to_ascii_lowercase(); + + while cursor < text.len() { + let rem = &lower[cursor..]; + let next_std = rem.find("mongodb://"); + let next_srv = rem.find("mongodb+srv://"); + let next = match (next_std, next_srv) { + (Some(a), Some(b)) => Some(a.min(b)), + (Some(a), None) => Some(a), + (None, Some(b)) => Some(b), + (None, None) => None, + }; + let Some(rel_start) = next else { + result.push_str(&text[cursor..]); + break; + }; + + let start = cursor + rel_start; + result.push_str(&text[cursor..start]); + + let tail = &text[start..]; + let uri_len = tail + .find(|c: char| { + c.is_whitespace() || matches!(c, '"' | '\'' | ')' | ']' | '}' | ',' | ';') + }) + .unwrap_or(tail.len()); + let candidate = &tail[..uri_len]; + result.push_str(&redact_mongo_uri_password(candidate)); + cursor = start + uri_len; + } + + result +} + +/// Strips raw URI, raw password, percent-decoded password, and any embedded +/// `mongodb://` / `mongodb+srv://` userinfo passwords from driver error text. +pub(crate) fn sanitize_driver_error_message( + raw_message: &str, + uri: &ValidatedReadOnlyMongoUri, +) -> String { + let redacted_uri = uri.redacted(); + let mut sanitized = raw_message.split(uri.as_str()).collect::>().join(&redacted_uri); + + if let Some(raw_pass) = extract_raw_uri_password(uri.as_str()) { + sanitized = sanitized.split(raw_pass).collect::>().join("[REDACTED]"); + if let Some(decoded_pass) = percent_decode_best_effort(raw_pass) { + if !decoded_pass.is_empty() && decoded_pass != raw_pass { + sanitized = sanitized + .split(&decoded_pass) + .collect::>() + .join("[REDACTED]"); + } + } + } + + redact_embedded_mongo_uris(&sanitized) +} + +pub(crate) fn build_driver_error( + collection: SourceCollection, + stage: MongoDriverStage, + uri: &ValidatedReadOnlyMongoUri, + raw_message: &str, +) -> MongoStreamError { + MongoStreamError::Driver { + collection, + stage, + redacted_uri: uri.redacted(), + message: sanitize_driver_error_message(raw_message, uri), + } +} + +fn append_default_app_name(uri: &str) -> String { + let query_part = uri.split_once('?').map(|(_, q)| q).unwrap_or(""); + let has_app_name = query_part.split('&').any(|pair| { + pair.split_once('=') + .map(|(k, _)| k.eq_ignore_ascii_case("appname")) + .unwrap_or(false) + }); + if has_app_name { + return uri.to_owned(); + } + if uri.contains('?') { + if uri.ends_with('?') || uri.ends_with('&') { + format!("{uri}appName={DEFAULT_APP_NAME}") + } else { + format!("{uri}&appName={DEFAULT_APP_NAME}") + } + } else { + format!("{uri}?appName={DEFAULT_APP_NAME}") + } +} + +enum DriverCursorState { + Unopened, + Open(Box>), + Exhausted, +} + +/// Sealed, read-only MongoDB raw-BSON cursor source. +/// +/// The only public constructor is [`MongoRawDocumentSource::open`], which +/// requires a [`ValidatedReadOnlyMongoUri`] proof token and a closed +/// [`SourceCollection`] allowlist variant. No client, database, collection, +/// or mutating/admin operation is exposed. +pub struct MongoRawDocumentSource { + uri: ValidatedReadOnlyMongoUri, + database: String, + collection: SourceCollection, + filter: Document, + batch_size: u32, + limit: Option, + state: DriverCursorState, +} + +impl MongoRawDocumentSource { + /// Validates the target database name, `spec`, and filter document without + /// opening any network connection. The underlying read-only MongoDB cursor + /// is opened lazily on the first [`RawDocumentSource::next_raw_document`] call. + pub fn open( + uri: &ValidatedReadOnlyMongoUri, + collection: SourceCollection, + spec: MongoReadSpec, + ) -> Result { + let Some(database) = uri + .target() + .database + .as_deref() + .filter(|db| !db.trim().is_empty()) + else { + return Err(MongoStreamError::MissingDatabaseName { + redacted_uri: uri.redacted(), + }); + }; + + let filter = build_filter_document(collection, &spec)?; + let limit = spec.limit.map(|v| v as i64); + + Ok(Self { + uri: uri.clone(), + database: database.to_owned(), + collection, + filter, + batch_size: spec.batch_size, + limit, + state: DriverCursorState::Unopened, + }) + } + + pub fn collection(&self) -> SourceCollection { + self.collection + } + + pub fn database(&self) -> &str { + &self.database + } + + pub fn redacted_uri(&self) -> String { + self.uri.redacted() + } + + pub fn batch_size(&self) -> u32 { + self.batch_size + } + + pub fn limit(&self) -> Option { + self.limit.map(|v| v as u64) + } + + pub fn filter(&self) -> &Document { + &self.filter + } +} + +impl RawDocumentSource for MongoRawDocumentSource { + fn next_raw_document(&mut self) -> Result, MongoStreamError> { + if let DriverCursorState::Unopened = self.state { + let connect_uri = append_default_app_name(self.uri.as_str()); + let client = match mongodb::sync::Client::with_uri_str(&connect_uri) { + Ok(client) => client, + Err(err) => { + self.state = DriverCursorState::Exhausted; + return Err(build_driver_error( + self.collection, + MongoDriverStage::Connect, + &self.uri, + &err.to_string(), + )); + } + }; + let coll = client + .database(&self.database) + .collection::(self.collection.as_str()); + let mut find_action = coll.find(self.filter.clone()).batch_size(self.batch_size); + if let Some(limit) = self.limit { + find_action = find_action.limit(limit); + } + let cursor = match find_action.run() { + Ok(cursor) => cursor, + Err(err) => { + self.state = DriverCursorState::Exhausted; + return Err(build_driver_error( + self.collection, + MongoDriverStage::Find, + &self.uri, + &err.to_string(), + )); + } + }; + self.state = DriverCursorState::Open(Box::new(cursor)); + } + + let advance_res = match &mut self.state { + DriverCursorState::Open(cursor) => cursor.advance(), + DriverCursorState::Exhausted | DriverCursorState::Unopened => return Ok(None), + }; + + match advance_res { + Ok(true) => match &self.state { + DriverCursorState::Open(cursor) => Ok(Some(cursor.current().as_bytes())), + DriverCursorState::Exhausted | DriverCursorState::Unopened => Ok(None), + }, + Ok(false) => { + self.state = DriverCursorState::Exhausted; + Ok(None) + } + Err(err) => { + self.state = DriverCursorState::Exhausted; + Err(build_driver_error( + self.collection, + MongoDriverStage::CursorAdvance, + &self.uri, + &err.to_string(), + )) + } + } + } +} + +#[cfg(test)] +#[path = "mongo_stream_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/mongo_stream_tests.rs b/tools/curate-etl/src/mongo_stream_tests.rs new file mode 100644 index 00000000..20f49949 --- /dev/null +++ b/tools/curate-etl/src/mongo_stream_tests.rs @@ -0,0 +1,1151 @@ +use std::fs; +use std::io::{self, Cursor, Read}; +use std::path::PathBuf; + +use bson::raw::{cstr, RawDocumentBuf}; +use bson::{Bson, DateTime}; + +use crate::bson_qm_events::QmFilingsFieldNames; +use crate::bson_stream::{ + decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_filings_stream, + decode_qm_split_stream, BsonStreamError, BsonStreamOptions, MIN_BSON_DOC_BYTES, +}; +use crate::mongo_safety::{ + assert_read_only_mongo_uri, LocalHosts, ReadOnlyPolicy, ValidatedReadOnlyMongoUri, +}; +use crate::mongo_stream::{ + append_default_app_name, build_driver_error, build_filter_document, + sanitize_driver_error_message, FilterDateValue, MongoDateRange, MongoDriverStage, + MongoRawDocumentSource, MongoReadSpec, MongoStreamError, RawBsonCursorReader, + RawDocumentSource, SliceRawDocumentSource, SourceCollection, VecRawDocumentSource, + DEFAULT_MONGO_BATCH_SIZE, MAX_MONGO_BATCH_SIZE, +}; + +fn build_eod_doc(code: &str, date: &str, close: f64, volume: f64) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("open"), close); + doc.append(cstr!("high"), close + 1.0); + doc.append(cstr!("low"), (close - 1.0).max(0.1)); + doc.append(cstr!("close"), close); + doc.append(cstr!("volume"), volume); + doc.into_bytes() +} + +fn build_eod_reject_doc(code: &str) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("date"), "not-a-date"); + doc.append(cstr!("open"), 10.0); + doc.append(cstr!("high"), 11.0); + doc.append(cstr!("low"), 9.0); + doc.append(cstr!("close"), 10.5); + doc.append(cstr!("volume"), 100.0); + doc.into_bytes() +} + +fn build_qm_split_doc(code: &str, date: &str, ratio: f64) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("splitRatio"), ratio); + doc.into_bytes() +} + +fn build_qm_split_reject_doc(code: &str) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("splitRatio"), "bad-type"); + doc.into_bytes() +} + +fn build_qm_dividend_doc(code: &str, date: &str, cash: f64, currency: &str) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("dividendCash"), cash); + doc.append(cstr!("dividendCurrency"), currency); + doc.into_bytes() +} + +fn build_qm_dividend_reject_doc(code: &str) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("dividendCash"), -1.0); + doc.append(cstr!("dividendCurrency"), "USD"); + doc.into_bytes() +} + +fn build_qm_filing_doc( + symbol: &str, + timefiled: &str, + form_type: &str, + filing_id: Option<&str>, +) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("symbol"), symbol); + doc.append(cstr!("timefiled"), timefiled); + doc.append(cstr!("formtype"), form_type); + if let Some(id) = filing_id { + doc.append(cstr!("filingid"), id); + } + doc.into_bytes() +} + +fn build_qm_filing_reject_doc(symbol: &str) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("symbol"), symbol); + doc.append(cstr!("timefiled"), "2024-06-10T16:30:00 EDT"); + // Missing required formtype -> semantic skip + doc.into_bytes() +} + +fn concat_docs(docs: &[Vec]) -> Vec { + let total: usize = docs.iter().map(Vec::len).sum(); + let mut out = Vec::with_capacity(total); + for doc in docs { + out.extend_from_slice(doc); + } + out +} + +/// Wraps any `io::Read` and caps every single `read()` call to `max_step` bytes, +/// exercising tiny (1-byte) and odd-sized (`3`, `7`, `13`, `37` B) read buffers. +struct CappedRead { + inner: R, + max_step: usize, +} + +impl CappedRead { + fn new(inner: R, max_step: usize) -> Self { + Self { inner, max_step } + } +} + +impl Read for CappedRead { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let cap = buf.len().min(self.max_step); + self.inner.read(&mut buf[..cap]) + } +} + +fn read_all_with_step(reader: &mut R, step: usize) -> io::Result> { + let mut out = Vec::new(); + let mut buf = vec![0u8; step]; + loop { + let n = reader.read(&mut buf)?; + if n == 0 { + break; + } + out.extend_from_slice(&buf[..n]); + } + Ok(out) +} + +fn validate_uri(raw: &str) -> ValidatedReadOnlyMongoUri { + assert_read_only_mongo_uri(raw, &ReadOnlyPolicy::default(), &LocalHosts::empty()) + .expect("test URI must pass read-only safety guard") +} + +struct FailingSource { + docs: Vec>, + index: usize, + fail_at: usize, + err: MongoStreamError, +} + +impl RawDocumentSource for FailingSource { + fn next_raw_document(&mut self) -> Result, MongoStreamError> { + if self.index == self.fail_at { + return Err(self.err.clone()); + } + if self.index >= self.docs.len() { + return Ok(None); + } + let doc = self.docs[self.index].as_slice(); + self.index += 1; + Ok(Some(doc)) + } +} + +// --------------------------------------------------------------------------- +// 1. Allowlist parity against export-raw-bson.ts +// --------------------------------------------------------------------------- + +#[test] +fn source_collection_allowlist_matches_export_raw_bson_ts_exactly() { + let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let ts_path = manifest_dir + .join("..") + .join("..") + .join("apps") + .join("stock") + .join("data-pipeline") + .join("src") + .join("security-master") + .join("export-raw-bson.ts"); + + let contents = fs::read_to_string(&ts_path) + .unwrap_or_else(|err| panic!("failed to read {}: {err}", ts_path.display())); + + let anchor = "export const RAW_BSON_EXPORT_COLLECTIONS = Object.freeze(["; + let start = contents + .find(anchor) + .expect("RAW_BSON_EXPORT_COLLECTIONS declaration not found in export-raw-bson.ts") + + anchor.len(); + let rest = &contents[start..]; + let end = rest + .find("] as const") + .expect("closing `] as const` not found for RAW_BSON_EXPORT_COLLECTIONS"); + let block = &rest[..end]; + + let ts_names: Vec = block + .lines() + .filter_map(|line| { + let trimmed = line.trim(); + let first_quote = trimmed.find('\'')?; + let after_first = &trimmed[first_quote + 1..]; + let second_quote = after_first.find('\'')?; + Some(after_first[..second_quote].to_owned()) + }) + .collect(); + + let rust_names: Vec<&str> = SourceCollection::ALL.iter().map(|c| c.as_str()).collect(); + let expected = vec![ + "eodPrices", + "qmSplits", + "qmDividends", + "qmPrices", + "teMarketData", + "ceoShorts", + "qmFilings", + "qmEarnings", + ]; + + assert_eq!(rust_names, expected); + assert_eq!( + ts_names, + rust_names + .iter() + .map(|s| (*s).to_owned()) + .collect::>(), + "SourceCollection::ALL must match RAW_BSON_EXPORT_COLLECTIONS in exact names and order" + ); + assert_eq!(SourceCollection::ALL.len(), 8); +} + +// --------------------------------------------------------------------------- +// 2. Decoder parity across 4 collections + 1-byte and odd-sized buffers +// --------------------------------------------------------------------------- + +#[test] +fn parity_eod_prices_stream_across_default_and_odd_buffers() { + let docs = vec![ + build_eod_doc("AAPL.US", "2024-01-02", 185.5, 1000.0), + build_eod_reject_doc("BAD.US"), + build_eod_doc("NVDA.US", "2024-06-10", 121.75, 50_000.0), + build_eod_doc("RY.TO", "2024-12-31", 173.25, 250_000.0), + ]; + let concat = concat_docs(&docs); + let total_bytes = concat.len() as u64; + + let mut expected_rows = Vec::new(); + let mut expected_errs = Vec::new(); + let expected_stats = decode_eod_price_stream( + Cursor::new(&concat), + BsonStreamOptions::default(), + |bar| { + expected_rows.push(( + bar.eod_search_code.to_owned(), + bar.session_date, + bar.open.to_bits(), + bar.high.to_bits(), + bar.low.to_bits(), + bar.close.to_bits(), + bar.adj_volume.to_bits(), + )); + }, + |offset, err| expected_errs.push((offset, err)), + ) + .expect("baseline cursor decode must succeed"); + + for step in [usize::MAX, 1, 3, 7, 13, 37] { + let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); + let mut rows = Vec::new(); + let mut errs = Vec::new(); + let stats = if step == usize::MAX { + decode_eod_price_stream( + &mut cursor_reader, + BsonStreamOptions::default(), + |bar| { + rows.push(( + bar.eod_search_code.to_owned(), + bar.session_date, + bar.open.to_bits(), + bar.high.to_bits(), + bar.low.to_bits(), + bar.close.to_bits(), + bar.adj_volume.to_bits(), + )); + }, + |offset, err| errs.push((offset, err)), + ) + .expect("stream decode must succeed") + } else { + decode_eod_price_stream( + CappedRead::new(&mut cursor_reader, step), + BsonStreamOptions::default(), + |bar| { + rows.push(( + bar.eod_search_code.to_owned(), + bar.session_date, + bar.open.to_bits(), + bar.high.to_bits(), + bar.low.to_bits(), + bar.close.to_bits(), + bar.adj_volume.to_bits(), + )); + }, + |offset, err| errs.push((offset, err)), + ) + .expect("capped stream decode must succeed") + }; + + assert_eq!(stats, expected_stats, "eodPrices stats mismatch at step={step}"); + assert_eq!(rows, expected_rows, "eodPrices rows mismatch at step={step}"); + assert_eq!(errs, expected_errs, "eodPrices errors mismatch at step={step}"); + assert_eq!(cursor_reader.docs_read(), docs.len() as u64); + assert_eq!(cursor_reader.bytes_read(), total_bytes); + } +} + +#[test] +fn parity_qm_splits_stream_across_default_and_odd_buffers() { + let docs = vec![ + build_qm_split_doc("NVDA:US", "2024-06-10", 10.0), + build_qm_split_reject_doc("BAD:US"), + build_qm_split_doc("NEXM:CA", "2025-06-18", 0.05), + ]; + let concat = concat_docs(&docs); + + let mut expected_rows = Vec::new(); + let mut expected_errs = Vec::new(); + let expected_stats = decode_qm_split_stream( + Cursor::new(&concat), + BsonStreamOptions::default(), + |row| { + expected_rows.push(( + row.qm_search_code.to_owned(), + row.ex_date, + row.ratio.to_bits(), + row.declared_date, + )); + }, + |offset, err| expected_errs.push((offset, err)), + ) + .expect("baseline qmSplits decode must succeed"); + + for step in [usize::MAX, 1, 3, 7, 13, 37] { + let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); + let mut rows = Vec::new(); + let mut errs = Vec::new(); + let stats = if step == usize::MAX { + decode_qm_split_stream( + &mut cursor_reader, + BsonStreamOptions::default(), + |row| { + rows.push(( + row.qm_search_code.to_owned(), + row.ex_date, + row.ratio.to_bits(), + row.declared_date, + )); + }, + |offset, err| errs.push((offset, err)), + ) + .expect("qmSplits stream decode must succeed") + } else { + decode_qm_split_stream( + CappedRead::new(&mut cursor_reader, step), + BsonStreamOptions::default(), + |row| { + rows.push(( + row.qm_search_code.to_owned(), + row.ex_date, + row.ratio.to_bits(), + row.declared_date, + )); + }, + |offset, err| errs.push((offset, err)), + ) + .expect("capped qmSplits stream decode must succeed") + }; + + assert_eq!(stats, expected_stats, "qmSplits stats mismatch at step={step}"); + assert_eq!(rows, expected_rows, "qmSplits rows mismatch at step={step}"); + assert_eq!(errs, expected_errs, "qmSplits errors mismatch at step={step}"); + assert_eq!(cursor_reader.docs_read(), docs.len() as u64); + assert_eq!(cursor_reader.bytes_read(), concat.len() as u64); + } +} + +#[test] +fn parity_qm_dividends_stream_across_default_and_odd_buffers() { + let docs = vec![ + build_qm_dividend_doc("AAPL:US", "2024-05-10", 0.25, "USD"), + build_qm_dividend_reject_doc("BAD:US"), + build_qm_dividend_doc("RY:CA", "2024-07-25", 1.42, "CAD"), + ]; + let concat = concat_docs(&docs); + + let mut expected_rows = Vec::new(); + let mut expected_errs = Vec::new(); + let expected_stats = decode_qm_dividend_stream( + Cursor::new(&concat), + BsonStreamOptions::default(), + |row| { + expected_rows.push(( + row.qm_search_code.to_owned(), + row.ex_date, + row.cash.to_bits(), + row.currency.to_owned(), + row.declared_date, + )); + }, + |offset, err| expected_errs.push((offset, err)), + ) + .expect("baseline qmDividends decode must succeed"); + + for step in [usize::MAX, 1, 3, 7, 13, 37] { + let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); + let mut rows = Vec::new(); + let mut errs = Vec::new(); + let stats = if step == usize::MAX { + decode_qm_dividend_stream( + &mut cursor_reader, + BsonStreamOptions::default(), + |row| { + rows.push(( + row.qm_search_code.to_owned(), + row.ex_date, + row.cash.to_bits(), + row.currency.to_owned(), + row.declared_date, + )); + }, + |offset, err| errs.push((offset, err)), + ) + .expect("qmDividends stream decode must succeed") + } else { + decode_qm_dividend_stream( + CappedRead::new(&mut cursor_reader, step), + BsonStreamOptions::default(), + |row| { + rows.push(( + row.qm_search_code.to_owned(), + row.ex_date, + row.cash.to_bits(), + row.currency.to_owned(), + row.declared_date, + )); + }, + |offset, err| errs.push((offset, err)), + ) + .expect("capped qmDividends stream decode must succeed") + }; + + assert_eq!(stats, expected_stats, "qmDividends stats mismatch at step={step}"); + assert_eq!(rows, expected_rows, "qmDividends rows mismatch at step={step}"); + assert_eq!(errs, expected_errs, "qmDividends errors mismatch at step={step}"); + assert_eq!(cursor_reader.docs_read(), docs.len() as u64); + assert_eq!(cursor_reader.bytes_read(), concat.len() as u64); + } +} + +#[test] +fn parity_qm_filings_stream_across_default_and_odd_buffers() { + let docs = vec![ + build_qm_filing_doc("AAPL:US", "2024-05-03T16:30:00 EDT", "10-Q", Some("F-101")), + build_qm_filing_reject_doc("BAD:US"), + build_qm_filing_doc("RY:CA", "2024-12-04T08:05:00 EST", "Annual financial statements", None), + ]; + let concat = concat_docs(&docs); + let fields = QmFilingsFieldNames { + key: "symbol", + timefiled: "timefiled", + form_type: "formtype", + filing_id: Some("filingid"), + url: None, + }; + + let mut expected_rows = Vec::new(); + let expected_stats = decode_qm_filings_stream( + Cursor::new(&concat), + BsonStreamOptions::default(), + &fields, + |row| { + expected_rows.push(( + row.key.to_owned(), + row.timefiled.to_owned(), + row.form_type.to_owned(), + row.filing_id.map(str::to_owned), + row.url.map(str::to_owned), + )); + }, + ) + .expect("baseline qmFilings decode must succeed"); + + for step in [usize::MAX, 1, 3, 7, 13, 37] { + let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); + let mut rows = Vec::new(); + let stats = if step == usize::MAX { + decode_qm_filings_stream( + &mut cursor_reader, + BsonStreamOptions::default(), + &fields, + |row| { + rows.push(( + row.key.to_owned(), + row.timefiled.to_owned(), + row.form_type.to_owned(), + row.filing_id.map(str::to_owned), + row.url.map(str::to_owned), + )); + }, + ) + .expect("qmFilings stream decode must succeed") + } else { + decode_qm_filings_stream( + CappedRead::new(&mut cursor_reader, step), + BsonStreamOptions::default(), + &fields, + |row| { + rows.push(( + row.key.to_owned(), + row.timefiled.to_owned(), + row.form_type.to_owned(), + row.filing_id.map(str::to_owned), + row.url.map(str::to_owned), + )); + }, + ) + .expect("capped qmFilings stream decode must succeed") + }; + + assert_eq!(stats, expected_stats, "qmFilings stats mismatch at step={step}"); + assert_eq!(rows, expected_rows, "qmFilings rows mismatch at step={step}"); + assert_eq!(cursor_reader.docs_read(), docs.len() as u64); + assert_eq!(cursor_reader.bytes_read(), concat.len() as u64); + } +} + +// --------------------------------------------------------------------------- +// 3. Bounded memory, counters, framing validation & error handling +// --------------------------------------------------------------------------- + +#[test] +fn empty_source_yields_eof_with_zero_counts() { + let empty: [&[u8]; 0] = []; + let mut reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&empty)); + let mut buf = [0u8; 64]; + assert_eq!(reader.read(&mut buf).expect("empty read must succeed"), 0); + assert_eq!(reader.read(&mut buf).expect("repeated EOF must succeed"), 0); + assert_eq!(reader.docs_read(), 0); + assert_eq!(reader.bytes_read(), 0); + assert_eq!(reader.pending_capacity(), 0); +} + +#[test] +fn zero_length_read_buffer_returns_zero_without_advancing() { + let docs = vec![build_eod_doc("AAPL.US", "2024-01-02", 100.0, 50.0)]; + let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone())); + assert_eq!(reader.read(&mut []).expect("empty buf read must succeed"), 0); + assert_eq!(reader.docs_read(), 0); + assert_eq!(reader.bytes_read(), 0); + + let got = read_all_with_step(&mut reader, 64).expect("full read must succeed"); + assert_eq!(got, docs[0]); + assert_eq!(reader.docs_read(), 1); + assert_eq!(reader.bytes_read(), docs[0].len() as u64); +} + +#[test] +fn pending_capacity_stays_bounded_to_single_document_under_one_byte_reads() { + let docs: Vec> = (0..50) + .map(|i| build_eod_doc(&format!("SYM{i:03}.US"), "2024-01-02", 10.0 + i as f64, 100.0)) + .collect(); + let max_doc_len = docs.iter().map(Vec::len).max().unwrap(); + let expected = concat_docs(&docs); + + let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs)); + let got = read_all_with_step(&mut reader, 1).expect("1-byte read must succeed"); + + assert_eq!(got, expected); + assert_eq!(reader.docs_read(), 50); + assert_eq!(reader.bytes_read(), expected.len() as u64); + assert!( + reader.pending_capacity() <= max_doc_len, + "pending_capacity ({}) exceeded max single doc length ({max_doc_len})", + reader.pending_capacity() + ); +} + +#[test] +fn mid_stream_source_error_delivers_prior_docs_then_surfaces_sticky_mongo_stream_error() { + let doc0 = build_eod_doc("AAPL.US", "2024-01-02", 100.0, 10.0); + let doc1 = build_eod_doc("MSFT.US", "2024-01-03", 200.0, 20.0); + let expected_err = MongoStreamError::Source { + detail: "simulated cursor drop mid-stream".to_owned(), + }; + let source = FailingSource { + docs: vec![doc0.clone(), doc1.clone()], + index: 0, + fail_at: 2, + err: expected_err.clone(), + }; + + let mut reader = RawBsonCursorReader::new(source); + let mut big_buf = vec![0u8; 4096]; + let n = reader + .read(&mut big_buf) + .expect("first read must return bytes from prior valid docs"); + assert_eq!(n, doc0.len() + doc1.len()); + assert_eq!(&big_buf[..doc0.len()], doc0.as_slice()); + assert_eq!(&big_buf[doc0.len()..n], doc1.as_slice()); + assert_eq!(reader.docs_read(), 2); + assert_eq!(reader.bytes_read(), (doc0.len() + doc1.len()) as u64); + + // Next read surfaces the stashed MongoStreamError wrapped in io::Error. + let io_err = reader + .read(&mut big_buf) + .expect_err("next read must surface stashed error"); + let downcast = io_err + .get_ref() + .and_then(|e| e.downcast_ref::()) + .expect("io::Error must carry MongoStreamError"); + assert_eq!(downcast, &expected_err); + + // Subsequent reads stay sticky with the same MongoStreamError. + let io_err2 = reader + .read(&mut big_buf) + .expect_err("reader must remain in sticky error state"); + let downcast2 = io_err2 + .get_ref() + .and_then(|e| e.downcast_ref::()) + .expect("sticky io::Error must carry MongoStreamError"); + assert_eq!(downcast2, &expected_err); +} + +#[test] +fn first_doc_source_error_surfaces_through_bson_stream_error_io() { + let expected_err = MongoStreamError::Source { + detail: "initial cursor failure".to_owned(), + }; + let source = FailingSource { + docs: vec![], + index: 0, + fail_at: 0, + err: expected_err.clone(), + }; + let reader = RawBsonCursorReader::new(source); + let err = decode_eod_price_stream(reader, BsonStreamOptions::default(), |_| {}, |_, _| {}) + .expect_err("decode_eod_price_stream must propagate source error"); + + match err { + BsonStreamError::Io { offset, source } => { + assert_eq!(offset, 0); + let inner = source + .get_ref() + .and_then(|e| e.downcast_ref::()) + .expect("BsonStreamError::Io must wrap MongoStreamError"); + assert_eq!(inner, &expected_err); + } + other => panic!("expected BsonStreamError::Io, got {other:?}"), + } +} + +#[test] +fn malformed_bson_frames_are_rejected_without_incrementing_counters() { + let valid_doc = build_eod_doc("AAPL.US", "2024-01-02", 100.0, 10.0); + + // 1. Shorter than MIN_BSON_DOC_BYTES (5) + let too_short = vec![4u8, 0, 0, 0]; + // 2. Negative declared length + let negative_len = vec![0xff, 0xff, 0xff, 0xff, 0x00]; + // 3. Declared length < actual byte length + let mut declared_lt_actual = valid_doc.clone(); + declared_lt_actual.push(0x00); + // 4. Declared length > actual byte length + let mut declared_gt_actual = valid_doc.clone(); + let bad_len = (valid_doc.len() as i32 + 4).to_le_bytes(); + declared_gt_actual[..4].copy_from_slice(&bad_len); + // 5. Missing trailing 0x00 terminator + let mut missing_null = valid_doc.clone(); + *missing_null.last_mut().unwrap() = 0x7f; + + let bad_cases = [ + ("too_short", too_short), + ("negative_len", negative_len), + ("declared_lt_actual", declared_lt_actual), + ("declared_gt_actual", declared_gt_actual), + ("missing_null", missing_null), + ]; + + for (label, bad_frame) in bad_cases { + let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(vec![ + valid_doc.clone(), + bad_frame, + ])); + let mut buf = vec![0u8; 4096]; + let n = reader + .read(&mut buf) + .unwrap_or_else(|e| panic!("{label}: first doc should succeed, got {e}")); + assert_eq!(n, valid_doc.len(), "{label}"); + assert_eq!(reader.docs_read(), 1, "{label}"); + assert_eq!(reader.bytes_read(), valid_doc.len() as u64, "{label}"); + + let err = reader + .read(&mut buf) + .expect_err(&format!("{label}: bad frame must fail")); + let mongo_err = err + .get_ref() + .and_then(|e| e.downcast_ref::()) + .expect("must downcast to MongoStreamError"); + match mongo_err { + MongoStreamError::InvalidBsonFrame { doc_index, .. } => { + assert_eq!(*doc_index, 1, "{label}: doc_index must be 1"); + } + other => panic!("{label}: expected InvalidBsonFrame, got {other:?}"), + } + assert_eq!(reader.docs_read(), 1, "{label}: counters must not advance"); + assert_eq!(reader.bytes_read(), valid_doc.len() as u64, "{label}"); + } + + // 6. Exceeds max_doc_bytes + let mut reader = RawBsonCursorReader::with_max_doc_bytes( + VecRawDocumentSource::new(vec![valid_doc.clone()]), + valid_doc.len() - 1, + ) + .expect("with_max_doc_bytes >= 5 must succeed"); + let mut buf = vec![0u8; 4096]; + let err = reader.read(&mut buf).expect_err("oversized doc must fail"); + let mongo_err = err + .get_ref() + .and_then(|e| e.downcast_ref::()) + .expect("must downcast to MongoStreamError"); + assert!(matches!( + mongo_err, + MongoStreamError::InvalidBsonFrame { doc_index: 0, .. } + )); + assert_eq!(reader.docs_read(), 0); + assert_eq!(reader.bytes_read(), 0); + + // 7. with_max_doc_bytes < MIN_BSON_DOC_BYTES rejected + let err = RawBsonCursorReader::with_max_doc_bytes( + VecRawDocumentSource::new(vec![]), + MIN_BSON_DOC_BYTES - 1, + ) + .err() + .expect("max_doc_bytes < 5 must fail"); + assert!(matches!(err, MongoStreamError::InvalidMaxDocBytes { .. })); +} + +// --------------------------------------------------------------------------- +// 4. Filter & spec validation + lazy non-connecting open() +// --------------------------------------------------------------------------- + +#[test] +fn build_filter_document_and_spec_validation() { + // Empty spec -> empty filter document + let empty_filter = + build_filter_document(SourceCollection::EodPrices, &MongoReadSpec::default()) + .expect("default spec must be valid"); + assert!(empty_filter.is_empty()); + + // Key + ISO date range + let spec = MongoReadSpec { + key_eq: Some("AAPL.US".to_owned()), + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), + lt: Some(FilterDateValue::IsoString("2025-01-01".to_owned())), + }), + batch_size: DEFAULT_MONGO_BATCH_SIZE, + limit: Some(500), + ..MongoReadSpec::default() + }; + let doc = build_filter_document(SourceCollection::EodPrices, &spec) + .expect("valid key + date_range spec must succeed"); + assert_eq!( + doc.get("eodSearchCode"), + Some(&Bson::String("AAPL.US".to_owned())) + ); + let date_sub = doc + .get_document("date") + .expect("date range subdocument must exist"); + assert_eq!( + date_sub.get("$gte"), + Some(&Bson::String("2024-01-01".to_owned())) + ); + assert_eq!( + date_sub.get("$lt"), + Some(&Bson::String("2025-01-01".to_owned())) + ); + + // BSON DateTime millis range + let dt_spec = MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::BsonDateTimeMillis(1_704_067_200_000)), + lt: Some(FilterDateValue::BsonDateTimeMillis(1_735_689_600_000)), + }), + ..MongoReadSpec::default() + }; + let dt_doc = build_filter_document(SourceCollection::QmEarnings, &dt_spec) + .expect("valid DateTime range must succeed"); + let rd = dt_doc + .get_document("reportDate") + .expect("reportDate subdocument must exist"); + assert_eq!( + rd.get("$gte"), + Some(&Bson::DateTime(DateTime::from_millis(1_704_067_200_000))) + ); + + // Invalid batch_size == 0 and > MAX_MONGO_BATCH_SIZE + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + batch_size: 0, + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidBatchSize { batch_size: 0, .. }) + )); + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + batch_size: MAX_MONGO_BATCH_SIZE + 1, + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidBatchSize { .. }) + )); + + // Invalid limit == Some(0) and > i64::MAX + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + limit: Some(0), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidLimit { limit: 0 }) + )); + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + limit: Some(i64::MAX as u64 + 1), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidLimit { .. }) + )); + + // Blank key_eq + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + key_eq: Some(" ".to_owned()), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidKeyFilter { + collection: SourceCollection::EodPrices + }) + )); + + // date_range on TeMarketData + assert!(matches!( + build_filter_document( + SourceCollection::TeMarketData, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), + lt: None, + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::DateRangeNotSupported { + collection: SourceCollection::TeMarketData + }) + )); + + // Empty date_range (neither gte nor lt) + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: None, + lt: None, + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { .. }) + )); + + // Inverted date_range (gte >= lt) + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::IsoString("2025-01-01".to_owned())), + lt: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { .. }) + )); + + // Mismatched FilterDateValue variants + assert!(matches!( + build_filter_document( + SourceCollection::EodPrices, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())), + lt: Some(FilterDateValue::BsonDateTimeMillis(1_735_689_600_000)), + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { .. }) + )); +} + +#[test] +fn mongo_raw_document_source_open_validates_database_and_is_strictly_lazy() { + // Missing database name fails closed offline + let uri_no_db = validate_uri("mongodb://studio_stock_bot_read:s3cr3t@localhost:27017/"); + let err = MongoRawDocumentSource::open( + &uri_no_db, + SourceCollection::EodPrices, + MongoReadSpec::default(), + ) + .err() + .expect("missing database name must fail closed"); + assert!(matches!(err, MongoStreamError::MissingDatabaseName { .. })); + assert!(!format!("{err}").contains("s3cr3t")); + assert!(format!("{err}").contains("[REDACTED]")); + + // Valid URI with unreachable host succeeds lazily without touching the network + let uri_ok = validate_uri( + "mongodb://studio_stock_bot_read:s3cr3t@192.0.2.1:27017/stock?authSource=stock", + ); + let source = MongoRawDocumentSource::open( + &uri_ok, + SourceCollection::QmSplits, + MongoReadSpec { + batch_size: 1024, + limit: Some(10), + ..MongoReadSpec::default() + }, + ) + .expect("lazy open must succeed offline without connecting"); + + assert_eq!(source.collection(), SourceCollection::QmSplits); + assert_eq!(source.database(), "stock"); + assert_eq!(source.batch_size(), 1024); + assert_eq!(source.limit(), Some(10)); + assert!(!source.redacted_uri().contains("s3cr3t")); + assert!(source.redacted_uri().contains("[REDACTED]")); + // Dropped here without calling next_raw_document() -> zero network I/O. +} + +#[test] +fn append_default_app_name_preserves_existing_and_adds_when_missing() { + assert_eq!( + append_default_app_name("mongodb://u:p@host:27017/stock"), + "mongodb://u:p@host:27017/stock?appName=curate-etl-ro" + ); + assert_eq!( + append_default_app_name("mongodb://u:p@host:27017/stock?authSource=stock"), + "mongodb://u:p@host:27017/stock?authSource=stock&appName=curate-etl-ro" + ); + assert_eq!( + append_default_app_name("mongodb://u:p@host:27017/stock?appName=custom"), + "mongodb://u:p@host:27017/stock?appName=custom" + ); +} + +// --------------------------------------------------------------------------- +// 5. Password redaction (plain and percent-encoded sentinel passwords) +// --------------------------------------------------------------------------- + +#[test] +fn error_display_and_debug_never_leak_plain_or_percent_encoded_passwords() { + // Plain sentinel password + let plain_sentinel = "SENTINEL_PLAIN_PASS_998877"; + let plain_uri_str = format!( + "mongodb://studio_stock_bot_read:{plain_sentinel}@localhost:27017/stock?authSource=stock" + ); + let plain_uri = validate_uri(&plain_uri_str); + let simulated_raw = format!( + "connection failed for {plain_uri_str} (auth token {plain_sentinel}) secondary mongodb://other:{plain_sentinel}@10.0.0.51:27017/stock" + ); + let err = build_driver_error( + SourceCollection::EodPrices, + MongoDriverStage::Connect, + &plain_uri, + &simulated_raw, + ); + let display_out = format!("{err}"); + let debug_out = format!("{err:?}"); + assert!(!display_out.contains(plain_sentinel), "Display leaked plain password: {display_out}"); + assert!(!debug_out.contains(plain_sentinel), "Debug leaked plain password: {debug_out}"); + assert!(display_out.contains("[REDACTED]")); + assert!(debug_out.contains("[REDACTED]")); + + // Percent-encoded sentinel password (contains %40 -> @ and %21 -> !) + let encoded_sentinel = "SENTINEL%40ENC%21PASS_554433"; + let decoded_sentinel = "SENTINEL@ENC!PASS_554433"; + let enc_uri_str = format!( + "mongodb://studio_stock_bot_read:{encoded_sentinel}@localhost:27017/stock" + ); + let enc_uri = validate_uri(&enc_uri_str); + let simulated_enc_raw = format!( + "failed parsing {enc_uri_str}; raw={encoded_sentinel}; decoded={decoded_sentinel}" + ); + let sanitized = sanitize_driver_error_message(&simulated_enc_raw, &enc_uri); + assert!(!sanitized.contains(encoded_sentinel), "leaked encoded password: {sanitized}"); + assert!(!sanitized.contains(decoded_sentinel), "leaked decoded password: {sanitized}"); + assert!(sanitized.contains("[REDACTED]")); + + let enc_err = build_driver_error( + SourceCollection::QmFilings, + MongoDriverStage::Find, + &enc_uri, + &simulated_enc_raw, + ); + let enc_display = format!("{enc_err}"); + let enc_debug = format!("{enc_err:?}"); + assert!(!enc_display.contains(encoded_sentinel)); + assert!(!enc_display.contains(decoded_sentinel)); + assert!(!enc_debug.contains(encoded_sentinel)); + assert!(!enc_debug.contains(decoded_sentinel)); + assert!(enc_display.contains("[REDACTED]")); +} + +// --------------------------------------------------------------------------- +// 6. Sealed-surface checks (compile-time signature + source scan) +// --------------------------------------------------------------------------- + +#[test] +fn sealed_surface_compile_time_signature_and_source_scan() { + // Compile-time function pointer check: MongoRawDocumentSource::open MUST take + // `&ValidatedReadOnlyMongoUri` and `SourceCollection`. + let _open_fn: fn( + &ValidatedReadOnlyMongoUri, + SourceCollection, + MongoReadSpec, + ) -> Result = MongoRawDocumentSource::open; + + let src_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("mongo_stream.rs"); + let raw_src = fs::read_to_string(&src_path) + .unwrap_or_else(|err| panic!("failed to read {}: {err}", src_path.display())); + + // Strip line comments (`//...`) so documentation prose does not produce false positives, + // while keeping all code lines verbatim. + let code_only: String = raw_src + .lines() + .map(|line| match line.find("//") { + Some(idx) => &line[..idx], + None => line, + }) + .collect::>() + .join("\n"); + + let forbidden_calls = [ + "insert", + "update", + "delete", + "replace", + "drop", + "aggregate", + "create_index", + "run_command", + "bulk_write", + ]; + + for word in forbidden_calls { + // Check for `.word(` or `word(` identifier calls in code. + let method_pat = format!(".{word}"); + let call_pat = format!("{word}("); + assert!( + !code_only.contains(&method_pat) && !code_only.contains(&call_pat), + "forbidden driver/mutation call `{word}` found in mongo_stream.rs" + ); + } + + // Check that no `pub` item exposes `mongodb::Client`, `Database`, or `Collection`, + // and every `pub fn` returning `MongoRawDocumentSource` or `Result = code_only.lines().collect(); + for (idx, line) in lines.iter().enumerate() { + let trimmed = line.trim(); + if trimmed.starts_with("pub ") && !trimmed.starts_with("pub(crate)") { + // Gather signature up to `{` or `;` + let mut sig = String::new(); + for next_line in &lines[idx..] { + sig.push_str(next_line.trim()); + sig.push(' '); + if next_line.contains('{') || next_line.contains(';') { + break; + } + } + for forbidden_type in [ + "mongodb::Client", + "mongodb::sync::Client", + "mongodb::Database", + "mongodb::sync::Database", + "mongodb::Collection", + "mongodb::sync::Collection", + "-> Client", + "-> Database", + "-> Collection", + ] { + assert!( + !sig.contains(forbidden_type), + "public item exposes forbidden MongoDB handle `{forbidden_type}`: {sig}" + ); + } + + if trimmed.starts_with("pub fn ") + && (sig.contains("-> Result Self") + || sig.contains("-> MongoRawDocumentSource") + || sig.contains("-> Result