stock-bot/tools/curate-etl/src/mongo_stream.rs

1237 lines
44 KiB
Rust

//! Sealed read-only MongoDB raw-BSON cursor adapter (`M1.2al`).
//!
//! 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, password-redacted
//! [`MongoStreamError`] sanitization reusing [`crate::mongo_safety`], and the
//! sealed [`ReadOnlyMongoClient`] / [`MongoRawDocumentSource`] driver adapter
//! backed by `mongodb::sync`.
//!
//! # 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.
//! - Sealed read-only driver surface: [`ReadOnlyMongoClient`] requires a
//! [`ValidatedReadOnlyMongoUri`] proof token and exposes strictly
//! [`ReadOnlyMongoClient::open_raw_cursor`] (`find` returning raw BSON bytes).
//! No `mongodb::sync::Client`, `Database`, `Collection`, write, index, admin,
//! or aggregation handle is ever exposed outside this module.
//! - Password redaction: [`MongoStreamError`] never stores raw URIs or
//! passwords; every driver error is sanitized at the boundary via
//! [`MongoStreamError::redacted_source`].
use std::error::Error;
use std::fmt;
use std::io;
use bson::raw::RawDocumentBuf;
use bson::{Bson, DateTime, Document};
use crate::bson_eod_prices::{parse_ymd_strict_days, MILLIS_PER_DAY};
use crate::bson_stream::{DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES};
use crate::events::parse_filing_timefiled;
use crate::mongo_safety::{
assert_read_only_mongo_uri, redact_mongo_uri_password, LocalHosts, ReadOnlyPolicy,
ValidatedReadOnlyMongoUri,
};
/// Default environment variable name holding the read-only MongoDB connection URI.
pub const DEFAULT_MONGO_URI_ENV: &str = "MONGODB_READ_URI";
/// 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;
/// 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"),
}
}
/// Returns `true` when the collection's [`Self::date_field`] is stored as a
/// BSON `DateTime` rather than a `YYYY-MM-DD` / ISO UTF-8 string.
///
/// Verified empirically against live QA MongoDB (`m1-source-field-shapes.md`):
/// `qmEarnings.reportDate` (100% BSON `DateTime`) and `ceoShorts.timestamp`
/// (BSON `DateTime`), while `eodPrices.date`, `qmPrices.date`, `qmSplits.date`,
/// `qmDividends.date`, and `qmFilings.timefiled` are UTF-8 strings.
pub const fn date_field_is_bson_datetime(self) -> bool {
matches!(self, Self::QmEarnings | Self::CeoShorts)
}
}
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 collection == SourceCollection::QmFilings {
let validate_et_calendar_day =
|bound: Option<&FilterDateValue>, label: &str| match bound {
Some(FilterDateValue::IsoString(s)) => {
let is_calendar_day = s.len() == 10
&& s.is_ascii()
&& parse_filing_timefiled(&format!("{s}T00:00:00 EST")).is_ok();
if !is_calendar_day {
return Err(MongoStreamError::InvalidDateRange {
collection,
detail: format!(
"qmFilings.timefiled {label} must be an Eastern \
calendar-day boundary (YYYY-MM-DD); intra-day local \
timestamps are not monotonic across the fall-back DST \
transition and UTC strings do not match stored Eastern \
Time strings"
),
});
}
Ok(())
}
Some(FilterDateValue::BsonDateTimeMillis(_)) => {
Err(MongoStreamError::InvalidDateRange {
collection,
detail: "qmFilings.timefiled is stored as an Eastern Time string; \
only Eastern calendar-day boundaries (YYYY-MM-DD) are \
supported for server-side ranges"
.to_owned(),
})
}
None => Ok(()),
};
validate_et_calendar_day(range.gte.as_ref(), "gte")?;
validate_et_calendar_day(range.lt.as_ref(), "lt")?;
}
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))
}
/// Redacted error type for MongoDB raw-BSON cursor streaming.
///
/// Intentionally never stores raw URIs or passwords.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MongoStreamError {
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,
},
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::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::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 find_next_mongo_scheme(lower_slice: &str) -> Option<(usize, usize)> {
let next_std = lower_slice
.find("mongodb://")
.map(|i| (i, "mongodb://".len()));
let next_srv = lower_slice
.find("mongodb+srv://")
.map(|i| (i, "mongodb+srv://".len()));
match (next_std, next_srv) {
(Some(a), Some(b)) => Some(if a.0 <= b.0 { a } else { b }),
(Some(a), None) => Some(a),
(None, Some(b)) => Some(b),
(None, None) => 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 Some((rel_start, scheme_len)) = find_next_mongo_scheme(&lower[cursor..]) else {
result.push_str(&text[cursor..]);
break;
};
let start = cursor + rel_start;
result.push_str(&text[cursor..start]);
let tail = &text[start..];
let after_scheme = &tail[scheme_len..];
let after_scheme_lower = &lower[start + scheme_len..];
// Authority ends at `/`, `?`, whitespace, or the start of a subsequent
// MongoDB URI scheme (e.g., compact JSON `["mongodb://host","mongodb://u:p@host"]`).
// Do not stop on punctuation such as `,`, `;`, `)`, `]`, `}`, `"`, `'` before
// locating `@`, because embedded passwords (or replica-set host lists) may contain them.
let delim_end = after_scheme
.find(|c: char| c.is_whitespace() || matches!(c, '/' | '?'))
.unwrap_or(after_scheme.len());
let next_scheme_end = find_next_mongo_scheme(after_scheme_lower)
.map(|(idx, _)| idx)
.unwrap_or(after_scheme.len());
let authority_end = delim_end.min(next_scheme_end);
let authority_region = &after_scheme[..authority_end];
if let Some(at_idx) = authority_region.rfind('@') {
let userinfo = &authority_region[..at_idx];
if let Some(colon_idx) = userinfo.find(':') {
let prefix_with_at = &tail[..scheme_len + at_idx + 1];
if !userinfo.contains('@') {
result.push_str(&redact_mongo_uri_password(prefix_with_at));
} else {
result.push_str(&tail[..scheme_len + colon_idx + 1]);
result.push_str("[REDACTED]@");
}
cursor = start + scheme_len + at_idx + 1;
continue;
}
}
let advance = scheme_len + authority_end;
result.push_str(&tail[..advance]);
cursor = start + advance;
}
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)
}
/// Sealed read-only raw-BSON document source backed by a `mongodb::sync::Cursor`.
///
/// Advances one document at a time directly over the driver's wire batch buffer
/// (`cursor.current().as_bytes()`) with zero per-document heap allocation or
/// BSON object deserialization. Exposes no write, admin, or underlying driver
/// handle.
pub struct MongoRawDocumentSource {
cursor: mongodb::sync::Cursor<RawDocumentBuf>,
uri: ValidatedReadOnlyMongoUri,
exhausted: bool,
}
impl fmt::Debug for MongoRawDocumentSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MongoRawDocumentSource")
.field("uri", &self.uri.redacted())
.field("exhausted", &self.exhausted)
.finish()
}
}
impl RawDocumentSource for MongoRawDocumentSource {
fn next_raw_document(&mut self) -> Result<Option<&[u8]>, MongoStreamError> {
if self.exhausted {
return Ok(None);
}
match self.cursor.advance() {
Ok(true) => Ok(Some(self.cursor.current().as_bytes())),
Ok(false) => {
self.exhausted = true;
Ok(None)
}
Err(err) => {
self.exhausted = true;
Err(MongoStreamError::redacted_source(
&err.to_string(),
&self.uri,
))
}
}
}
}
/// Sealed read-only raw-BSON document source that streams a sequence of
/// key-partitioned `$in` queries over an allowlisted collection so indexed
/// per-symbol scans (`eodSearchCode`, `qmSearchCode`) skip out-of-scope global
/// symbols and avoid random-I/O date-index fetches.
pub struct ChunkedMongoRawDocumentSource {
coll: mongodb::sync::Collection<RawDocumentBuf>,
uri: ValidatedReadOnlyMongoUri,
key_field: &'static str,
date_filter: Option<(String, Bson)>,
batch_size: u32,
chunks: std::vec::IntoIter<Vec<Bson>>,
current: Option<mongodb::sync::Cursor<RawDocumentBuf>>,
exhausted: bool,
}
impl fmt::Debug for ChunkedMongoRawDocumentSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ChunkedMongoRawDocumentSource")
.field("uri", &self.uri.redacted())
.field("key_field", &self.key_field)
.field("exhausted", &self.exhausted)
.finish()
}
}
impl RawDocumentSource for ChunkedMongoRawDocumentSource {
fn next_raw_document(&mut self) -> Result<Option<&[u8]>, MongoStreamError> {
if self.exhausted {
return Ok(None);
}
loop {
if self.current.is_some() {
let advanced = {
let cursor = self.current.as_mut().expect("checked is_some");
cursor.advance()
};
match advanced {
Ok(true) => {
let cursor = self.current.as_ref().expect("checked is_some");
return Ok(Some(cursor.current().as_bytes()));
}
Ok(false) => {
self.current = None;
}
Err(err) => {
self.exhausted = true;
self.current = None;
return Err(MongoStreamError::redacted_source(
&err.to_string(),
&self.uri,
));
}
}
}
let Some(chunk) = self.chunks.next() else {
self.exhausted = true;
return Ok(None);
};
let mut entries: Vec<(String, Bson)> = Vec::with_capacity(2);
entries.push((
self.key_field.to_owned(),
Bson::Document(Document::from_iter([("$in".to_owned(), Bson::Array(chunk))])),
));
if let Some((df, dv)) = &self.date_filter {
entries.push((df.clone(), dv.clone()));
}
let filter = Document::from_iter(entries);
let cursor = self
.coll
.find(filter)
.batch_size(self.batch_size)
.run()
.map_err(|err| {
self.exhausted = true;
MongoStreamError::redacted_source(&err.to_string(), &self.uri)
})?;
self.current = Some(cursor);
}
}
}
/// Sealed read-only MongoDB client constructed exclusively from a
/// [`ValidatedReadOnlyMongoUri`] proof token.
///
/// Intentionally exposes **only** allowlisted raw-BSON `find` cursor opening
/// via [`Self::open_raw_cursor`] and clean shutdown via [`Self::shutdown`].
/// No `mongodb::sync::Client`, `Database`, `Collection`, write, index, admin,
/// or aggregation surface is accessible outside this module.
pub struct ReadOnlyMongoClient {
client: mongodb::sync::Client,
uri: ValidatedReadOnlyMongoUri,
database_name: String,
}
impl fmt::Debug for ReadOnlyMongoClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ReadOnlyMongoClient")
.field("uri", &self.uri.redacted())
.field("database", &self.database_name)
.finish()
}
}
impl ReadOnlyMongoClient {
/// Connects a sealed read-only MongoDB client using a pre-validated
/// [`ValidatedReadOnlyMongoUri`] proof token.
///
/// Fails closed if the URI omits a database name in its path.
pub fn connect(uri: ValidatedReadOnlyMongoUri) -> Result<Self, MongoStreamError> {
let Some(database_name) = uri.target().database.clone() else {
return Err(MongoStreamError::Source {
detail: "validated MongoDB URI must specify a database name in its path (e.g. /stock)"
.to_owned(),
});
};
let client = mongodb::sync::Client::with_uri_str(uri.as_str())
.map_err(|err| MongoStreamError::redacted_source(&err.to_string(), &uri))?;
Ok(Self {
client,
uri,
database_name,
})
}
/// Returns the target database name parsed from the validated URI.
#[inline]
pub fn database_name(&self) -> &str {
&self.database_name
}
/// Returns the validated URI with its password replaced by `[REDACTED]`.
#[inline]
pub fn redacted_uri(&self) -> String {
self.uri.redacted()
}
/// Opens a read-only raw-BSON `find` cursor over an allowlisted
/// [`SourceCollection`] and wraps it in a bounded-memory
/// [`RawBsonCursorReader`] implementing [`io::Read`].
pub fn open_raw_cursor(
&self,
collection: SourceCollection,
spec: &MongoReadSpec,
) -> Result<RawBsonCursorReader<MongoRawDocumentSource>, MongoStreamError> {
let filter = build_filter_document(collection, spec)?;
let coll = self
.client
.database(&self.database_name)
.collection::<RawDocumentBuf>(collection.as_str());
let mut find = coll.find(filter).batch_size(spec.batch_size);
if let Some(limit) = spec.limit {
find = find.limit(limit as i64);
}
let cursor = find
.run()
.map_err(|err| MongoStreamError::redacted_source(&err.to_string(), &self.uri))?;
let source = MongoRawDocumentSource {
cursor,
uri: self.uri.clone(),
exhausted: false,
};
RawBsonCursorReader::with_max_doc_bytes(source, spec.max_doc_bytes)
}
/// Opens a read-only raw-BSON stream partitioned into `$in` chunks over
/// `keys` on `collection.key_field()`, avoiding random-I/O date-index
/// scans when reading a known security-master key universe (e.g. US+CA
/// `eodPrices` / `qmPrices`).
pub fn open_raw_cursor_for_keys(
&self,
collection: SourceCollection,
spec: &MongoReadSpec,
keys: &[String],
chunk_size: usize,
) -> Result<RawBsonCursorReader<ChunkedMongoRawDocumentSource>, MongoStreamError> {
spec.validate(collection)?;
let effective_chunk = chunk_size.clamp(1, 2000);
let date_filter = if let (Some(range), Some(date_field)) =
(&spec.date_range, 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()));
}
if range_entries.is_empty() {
None
} else {
Some((
date_field.to_owned(),
Bson::Document(Document::from_iter(range_entries)),
))
}
} else {
None
};
let chunks: Vec<Vec<Bson>> = keys
.chunks(effective_chunk)
.map(|c| c.iter().cloned().map(Bson::String).collect())
.collect();
let coll = self
.client
.database(&self.database_name)
.collection::<RawDocumentBuf>(collection.as_str());
let source = ChunkedMongoRawDocumentSource {
coll,
uri: self.uri.clone(),
key_field: collection.key_field(),
date_filter,
batch_size: spec.batch_size,
chunks: chunks.into_iter(),
current: None,
exhausted: false,
};
RawBsonCursorReader::with_max_doc_bytes(source, spec.max_doc_bytes)
}
/// Cleanly terminates background driver tasks once all open cursors have
/// been dropped.
pub fn shutdown(self) {
self.client.shutdown().run();
}
}
/// Validates `raw_uri` against [`ReadOnlyPolicy::default`] and `local_hosts`
/// and opens a sealed [`ReadOnlyMongoClient`].
pub fn open_read_only_mongo_uri(
raw_uri: &str,
local_hosts: &LocalHosts,
) -> Result<ReadOnlyMongoClient, MongoStreamError> {
let validated = assert_read_only_mongo_uri(raw_uri, &ReadOnlyPolicy::default(), local_hosts)
.map_err(|err| MongoStreamError::Source {
detail: err.to_string(),
})?;
ReadOnlyMongoClient::connect(validated)
}
/// Reads a MongoDB URI from environment variable `env_var`, validates it
/// against [`ReadOnlyPolicy::default`] and `local_hosts`, and opens a sealed
/// [`ReadOnlyMongoClient`].
pub fn open_read_only_mongo_from_env(
env_var: &str,
local_hosts: &LocalHosts,
) -> Result<ReadOnlyMongoClient, MongoStreamError> {
if env_var.trim().is_empty() {
return Err(MongoStreamError::Source {
detail: "MongoDB URI environment variable name must not be empty".to_owned(),
});
}
let raw_uri = std::env::var(env_var).map_err(|_| MongoStreamError::Source {
detail: format!("environment variable '{env_var}' is not set or not valid UTF-8"),
})?;
open_read_only_mongo_uri(&raw_uri, local_hosts)
}
/// Configured source for a read-only MongoDB URI in CLI invocations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MongoUriSource {
/// Read URI from an environment variable (default [`DEFAULT_MONGO_URI_ENV`]).
EnvVar(String),
/// Explicit URI passed via `--mongo-uri`.
Literal(String),
}
impl MongoUriSource {
/// Validates and connects a sealed [`ReadOnlyMongoClient`] using
/// [`LocalHosts::detect`].
pub fn connect(&self) -> Result<ReadOnlyMongoClient, MongoStreamError> {
let local_hosts = LocalHosts::detect();
match self {
Self::EnvVar(var) => open_read_only_mongo_from_env(var, &local_hosts),
Self::Literal(raw) => open_read_only_mongo_uri(raw, &local_hosts),
}
}
}
/// Shared MongoDB streaming options parsed by `--from-mongo` CLI commands.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MongoCliOptions {
pub uri_source: MongoUriSource,
pub batch_size: u32,
pub limit: Option<u64>,
pub date_gte: Option<String>,
pub date_lt: Option<String>,
}
impl Default for MongoCliOptions {
fn default() -> Self {
Self {
uri_source: MongoUriSource::EnvVar(DEFAULT_MONGO_URI_ENV.to_owned()),
batch_size: DEFAULT_MONGO_BATCH_SIZE,
limit: None,
date_gte: None,
date_lt: None,
}
}
}
impl MongoCliOptions {
/// Builds a [`MongoReadSpec`] for string-dated collections, attaching `key_eq`
/// and optional ISO string date bounds when `apply_date_range` is `true`.
pub fn to_read_spec(&self, key_eq: Option<String>, apply_date_range: bool) -> MongoReadSpec {
let date_range = if apply_date_range && (self.date_gte.is_some() || self.date_lt.is_some())
{
Some(MongoDateRange {
gte: self.date_gte.clone().map(FilterDateValue::IsoString),
lt: self.date_lt.clone().map(FilterDateValue::IsoString),
})
} else {
None
};
MongoReadSpec {
key_eq,
date_range,
batch_size: self.batch_size,
limit: self.limit,
max_doc_bytes: DEFAULT_MAX_DOC_BYTES,
}
}
/// Builds a [`MongoReadSpec`] using the collection's native BSON date representation:
/// `BsonDateTimeMillis` (UTC midnight) for BSON `DateTime` collections (`qmEarnings`,
/// `ceoShorts`) and `IsoString` for string-dated collections (`eodPrices`, `qmPrices`,
/// `qmSplits`, `qmDividends`, `qmFilings`).
pub fn to_read_spec_for_collection(
&self,
collection: SourceCollection,
key_eq: Option<String>,
apply_date_range: bool,
) -> MongoReadSpec {
if !apply_date_range || (self.date_gte.is_none() && self.date_lt.is_none()) {
return self.to_read_spec(key_eq, false);
}
if !collection.date_field_is_bson_datetime() {
return self.to_read_spec(key_eq, true);
}
let to_dt = |raw: &String| -> FilterDateValue {
match parse_ymd_strict_days(raw) {
Some(days) => FilterDateValue::BsonDateTimeMillis(i64::from(days) * MILLIS_PER_DAY),
None => FilterDateValue::IsoString(raw.clone()),
}
};
MongoReadSpec {
key_eq,
date_range: Some(MongoDateRange {
gte: self.date_gte.as_ref().map(to_dt),
lt: self.date_lt.as_ref().map(to_dt),
}),
batch_size: self.batch_size,
limit: self.limit,
max_doc_bytes: DEFAULT_MAX_DOC_BYTES,
}
}
}
#[cfg(test)]
#[path = "mongo_stream_tests.rs"]
mod tests;