T-126: M1.2al — tools/curate-etl: sealed read-only MongoDB raw-BSON cursor adapter (mongo_stream.rs: ValidatedReadOnlyMongoUri → allowlisted find → impl io::Read feeding the existing bson_stream decoders) with offline tests and local benchmark (adds the mongodb crate only; no live MongoDB in tests)

This commit is contained in:
Studio 2026-11-30 02:01:43 -05:00
parent 88b7a5d141
commit d998115dcf
9 changed files with 2408 additions and 6 deletions

View file

@ -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"

View file

@ -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<S>`):** 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<RawDocumentBuf>::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`:

View file

@ -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<BsonStreamBenchReport, B
})
}
/// Summary metrics produced by [`run_mongo_stream_benchmark`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MongoStreamBenchReport {
pub rows: usize,
pub bytes: usize,
pub plain_elapsed_ms: f64,
pub plain_docs_per_sec: f64,
pub plain_mb_per_sec: f64,
pub cursor_elapsed_ms: f64,
pub cursor_docs_per_sec: f64,
pub cursor_mb_per_sec: f64,
pub cursor_to_plain_ratio: f64,
pub peak_pending_capacity: usize,
pub checksum: u64,
pub stats: BsonEodDecodeStats,
}
/// Runs the offline fixed-seed `RawBsonCursorReader` vs plain in-memory `io::Cursor<&[u8]>`
/// decode benchmark for `rows` synthetic `eodPrices` documents.
pub fn run_mongo_stream_benchmark(rows: usize) -> Result<MongoStreamBenchReport, BsonStreamError> {
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);

View file

@ -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<CliAction, String> {
["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::<usize>() {
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::<usize>() {
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");

View file

@ -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,

View file

@ -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,

View file

@ -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();
};

View file

@ -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<FilterDateValue>,
pub lt: Option<FilterDateValue>,
}
/// 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<String>,
/// Optional `[gte, lt)` range on [`SourceCollection::date_field`].
pub date_range: Option<MongoDateRange>,
/// 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<u64>,
/// 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<Document, MongoStreamError> {
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<Option<&[u8]>, 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<Option<&[u8]>, 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<Vec<u8>>` of raw BSON frames.
#[derive(Debug, Clone)]
pub struct VecRawDocumentSource {
docs: Vec<Vec<u8>>,
index: usize,
}
impl VecRawDocumentSource {
pub fn new(docs: Vec<Vec<u8>>) -> Self {
Self { docs, index: 0 }
}
}
impl RawDocumentSource for VecRawDocumentSource {
#[inline]
fn next_raw_document(&mut self) -> Result<Option<&[u8]>, 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<S: RawDocumentSource> {
source: S,
max_doc_bytes: usize,
pending: Vec<u8>,
pending_pos: usize,
docs_read: u64,
bytes_read: u64,
eof: bool,
stashed_error: Option<MongoStreamError>,
sticky_error: Option<MongoStreamError>,
}
impl<S: RawDocumentSource> RawBsonCursorReader<S> {
/// 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<Self, MongoStreamError> {
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<S: RawDocumentSource> io::Read for RawBsonCursorReader<S> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
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<String> {
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<u8> {
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::<Vec<_>>().join(&redacted_uri);
if let Some(raw_pass) = extract_raw_uri_password(uri.as_str()) {
sanitized = sanitized.split(raw_pass).collect::<Vec<_>>().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::<Vec<_>>()
.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<mongodb::sync::Cursor<RawDocumentBuf>>),
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<i64>,
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<Self, MongoStreamError> {
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<u64> {
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<Option<&[u8]>, 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::<RawDocumentBuf>(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;

File diff suppressed because it is too large Load diff