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:
parent
d998115dcf
commit
97fad30fd0
5 changed files with 68 additions and 370 deletions
|
|
@ -7,7 +7,6 @@ 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"
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# `curate-etl`
|
||||
|
||||
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`).
|
||||
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`, 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` driver-independent read-only MongoDB raw-BSON cursor seam (`mongo_stream`).
|
||||
|
||||
## Scope & Sign Conventions
|
||||
|
||||
|
|
@ -1520,23 +1520,20 @@ 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`)
|
||||
## Driver-Independent MongoDB Raw-BSON Cursor Seam (`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.
|
||||
Library-only, driver-independent read-only MongoDB raw-BSON cursor seam (`src/mongo_stream.rs`, tested offline in `src/mongo_stream_tests.rs`) bridging the read-only safety model (`src/mongo_safety.rs`) into the existing `bson_stream` zero-copy decoders (`RawBsonChunkReader` and `decode_*_stream`) with zero new dependencies and zero CLI/command wiring yet.
|
||||
|
||||
### Dependency & Build Impact
|
||||
### Dependencies
|
||||
|
||||
- **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).
|
||||
- **No new dependency added:** `tools/curate-etl/Cargo.toml` and `Cargo.lock` are unchanged (still three exact-pinned direct dependencies: `bson = "=3.1.0"`, `parquet = "=60.2.0"`, and `rayon = "=1.12.0"`). `src/mongo_stream.rs` contains no `mongodb::` driver paths yet.
|
||||
|
||||
### 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]`.
|
||||
- **Error redaction (`MongoStreamError`, `MongoStreamError::redacted_source`):** never stores raw URIs or passwords; sanitizes raw URI, raw password, percent-decoded password, and embedded `mongodb://` / `mongodb+srv://` userinfo passwords to `[REDACTED]` (reusing `mongo_safety::redact_mongo_uri_password`).
|
||||
|
||||
### `bench-mongo-stream`
|
||||
|
||||
|
|
@ -1546,14 +1543,15 @@ Offline fixed-seed benchmark comparing decoding `1,000,000` synthetic `eodPrices
|
|||
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`):
|
||||
Measured locally (`2026-11-30`, two back-to-back offline runs on the final code 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`)
|
||||
- **Run 1:** plain `273.98 ms` (`3,649,838 docs/s`, `994.24 MB/s`) vs. `RawBsonCursorReader` `275.41 ms` (`3,630,978 docs/s`, `989.10 MB/s`, ratio `0.995x`, `peak_pending_capacity=271 bytes`)
|
||||
- **Run 2:** plain `265.00 ms` (`3,773,617 docs/s`, `1,027.96 MB/s`) vs. `RawBsonCursorReader` `270.05 ms` (`3,703,016 docs/s`, `1,008.73 MB/s`, ratio `0.981x`, `peak_pending_capacity=271 bytes`)
|
||||
|
||||
### Not Verified
|
||||
### Not Done / 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).
|
||||
- **Deferred `mongodb`-backed `MongoRawDocumentSource`:** the `mongodb` crate could not be fetched into the offline Cargo cache from the sandbox (`cargo fetch` failed with `failed to download from https://index.crates.io/config.json: [6] Could not resolve hostname (Could not resolve host: index.crates.io)`), and its driver-backed code has never been compiled. Adding exact-pinned `mongodb` (`Cargo.toml` / `Cargo.lock`) and `MongoRawDocumentSource::open(&ValidatedReadOnlyMongoUri, ...)` is deferred to a follow-up task once `mongodb` and its transitive crates are cached via a host-side `cargo fetch` or working crates.io egress.
|
||||
- **Live QA MongoDB cursor throughput on `quant`:** not run (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 driver/CLI wiring and live-host verification tasks).
|
||||
|
||||
## Exporting Input Files (`data-pipeline`)
|
||||
|
||||
|
|
|
|||
|
|
@ -103,10 +103,9 @@ pub use mongo_safety::{
|
|||
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,
|
||||
build_filter_document, FilterDateValue, MongoDateRange, 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,
|
||||
|
|
|
|||
|
|
@ -1,29 +1,25 @@
|
|||
//! Sealed, read-only MongoDB raw-BSON cursor adapter (`M1.2al`).
|
||||
//! Driver-independent read-only MongoDB raw-BSON cursor seam (`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`].
|
||||
//! Provides the closed [`SourceCollection`] allowlist, typed [`MongoReadSpec`]
|
||||
//! filter validation/builder, driver-independent [`RawDocumentSource`] trait,
|
||||
//! bounded-memory [`RawBsonCursorReader`] implementing [`std::io::Read`] for
|
||||
//! the existing zero-copy [`crate::bson_stream`] decoders, and password-redacted
|
||||
//! [`MongoStreamError`] sanitization reusing [`crate::mongo_safety`].
|
||||
//!
|
||||
//! # 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.
|
||||
//! - Zero MongoDB driver surface in this module yet (no `mongodb::` imports,
|
||||
//! client/database/collection handles, or write/admin/aggregation calls).
|
||||
//! - Password redaction: [`MongoStreamError`] never stores raw URIs or
|
||||
//! passwords; error text is sanitized at the boundary via
|
||||
//! [`crate::mongo_safety::redact_mongo_uri_password`].
|
||||
|
||||
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};
|
||||
|
|
@ -35,10 +31,6 @@ 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
|
||||
|
|
@ -286,38 +278,11 @@ pub fn build_filter_document(
|
|||
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.
|
||||
/// Intentionally never stores raw URIs or passwords.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum MongoStreamError {
|
||||
MissingDatabaseName {
|
||||
redacted_uri: String,
|
||||
},
|
||||
InvalidBatchSize {
|
||||
batch_size: u32,
|
||||
max_batch_size: u32,
|
||||
|
|
@ -343,24 +308,25 @@ pub enum MongoStreamError {
|
|||
doc_index: u64,
|
||||
detail: String,
|
||||
},
|
||||
Driver {
|
||||
collection: SourceCollection,
|
||||
stage: MongoDriverStage,
|
||||
redacted_uri: String,
|
||||
message: String,
|
||||
},
|
||||
Source {
|
||||
detail: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl MongoStreamError {
|
||||
/// Constructs a [`MongoStreamError::Source`] after stripping any raw URI,
|
||||
/// raw password, percent-decoded password, or embedded MongoDB userinfo
|
||||
/// password from `raw_message`.
|
||||
pub fn redacted_source(raw_message: &str, uri: &ValidatedReadOnlyMongoUri) -> Self {
|
||||
Self::Source {
|
||||
detail: sanitize_driver_error_message(raw_message, uri),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
|
|
@ -394,15 +360,6 @@ impl fmt::Display for MongoStreamError {
|
|||
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}"),
|
||||
}
|
||||
}
|
||||
|
|
@ -778,187 +735,6 @@ pub(crate) fn sanitize_driver_error_message(
|
|||
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;
|
||||
|
|
|
|||
|
|
@ -14,11 +14,10 @@ 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,
|
||||
build_filter_document, sanitize_driver_error_message, FilterDateValue, MongoDateRange,
|
||||
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<u8> {
|
||||
|
|
@ -933,61 +932,6 @@ fn build_filter_document_and_spec_validation() {
|
|||
));
|
||||
}
|
||||
|
||||
#[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)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
@ -1003,16 +947,17 @@ fn error_display_and_debug_never_leak_plain_or_percent_encoded_passwords() {
|
|||
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 err = MongoStreamError::redacted_source(&simulated_raw, &plain_uri);
|
||||
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(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]"));
|
||||
|
||||
|
|
@ -1027,16 +972,17 @@ fn error_display_and_debug_never_leak_plain_or_percent_encoded_passwords() {
|
|||
"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(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_err = MongoStreamError::redacted_source(&simulated_enc_raw, &enc_uri);
|
||||
let enc_display = format!("{enc_err}");
|
||||
let enc_debug = format!("{enc_err:?}");
|
||||
assert!(!enc_display.contains(encoded_sentinel));
|
||||
|
|
@ -1047,19 +993,11 @@ fn error_display_and_debug_never_leak_plain_or_percent_encoded_passwords() {
|
|||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 6. Sealed-surface checks (compile-time signature + source scan)
|
||||
// 6. Sealed-surface source scan (zero driver paths or mutating calls)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[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, MongoStreamError> = MongoRawDocumentSource::open;
|
||||
|
||||
fn sealed_surface_source_scan() {
|
||||
let src_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("src")
|
||||
.join("mongo_stream.rs");
|
||||
|
|
@ -1077,6 +1015,11 @@ fn sealed_surface_compile_time_signature_and_source_scan() {
|
|||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
|
||||
assert!(
|
||||
!code_only.contains("mongodb::"),
|
||||
"mongo_stream.rs must not contain any `mongodb::` driver path yet"
|
||||
);
|
||||
|
||||
let forbidden_calls = [
|
||||
"insert",
|
||||
"update",
|
||||
|
|
@ -1099,9 +1042,7 @@ fn sealed_surface_compile_time_signature_and_source_scan() {
|
|||
);
|
||||
}
|
||||
|
||||
// Check that no `pub` item exposes `mongodb::Client`, `Database`, or `Collection`,
|
||||
// and every `pub fn` returning `MongoRawDocumentSource` or `Result<Self` takes
|
||||
// `&ValidatedReadOnlyMongoUri`.
|
||||
// Check that no `pub` item exposes `mongodb::Client`, `Database`, or `Collection`.
|
||||
let lines: Vec<&str> = code_only.lines().collect();
|
||||
for (idx, line) in lines.iter().enumerate() {
|
||||
let trimmed = line.trim();
|
||||
|
|
@ -1131,21 +1072,6 @@ fn sealed_surface_compile_time_signature_and_source_scan() {
|
|||
"public item exposes forbidden MongoDB handle `{forbidden_type}`: {sig}"
|
||||
);
|
||||
}
|
||||
|
||||
if trimmed.starts_with("pub fn ")
|
||||
&& (sig.contains("-> Result<Self")
|
||||
|| sig.contains("-> Self")
|
||||
|| sig.contains("-> MongoRawDocumentSource")
|
||||
|| sig.contains("-> Result<MongoRawDocumentSource"))
|
||||
{
|
||||
// Only applies to constructors of MongoRawDocumentSource (not MongoReadSpec::default, etc.)
|
||||
if sig.contains("open(") || sig.contains("MongoRawDocumentSource") {
|
||||
assert!(
|
||||
sig.contains("&ValidatedReadOnlyMongoUri"),
|
||||
"public MongoRawDocumentSource constructor must require &ValidatedReadOnlyMongoUri: {sig}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue