1941 lines
68 KiB
Rust
1941 lines
68 KiB
Rust
use std::fs;
|
||
use std::io::{self, Cursor, Read};
|
||
use std::path::PathBuf;
|
||
|
||
use bson::raw::{cstr, RawDocumentBuf};
|
||
use bson::{Bson, DateTime};
|
||
|
||
use crate::bson_qm_events::QmFilingsFieldNames;
|
||
use crate::bson_stream::{
|
||
decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_filings_stream,
|
||
decode_qm_split_stream, BsonStreamError, BsonStreamOptions, MIN_BSON_DOC_BYTES,
|
||
};
|
||
use crate::mongo_safety::{
|
||
assert_read_only_mongo_uri, LocalHosts, ReadOnlyPolicy, ValidatedReadOnlyMongoUri,
|
||
};
|
||
use crate::mongo_stream::{
|
||
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> {
|
||
let mut doc = RawDocumentBuf::new();
|
||
doc.append(cstr!("eodSearchCode"), code);
|
||
doc.append(cstr!("date"), date);
|
||
doc.append(cstr!("open"), close);
|
||
doc.append(cstr!("high"), close + 1.0);
|
||
doc.append(cstr!("low"), (close - 1.0).max(0.1));
|
||
doc.append(cstr!("close"), close);
|
||
doc.append(cstr!("volume"), volume);
|
||
doc.into_bytes()
|
||
}
|
||
|
||
fn build_eod_reject_doc(code: &str) -> Vec<u8> {
|
||
let mut doc = RawDocumentBuf::new();
|
||
doc.append(cstr!("eodSearchCode"), code);
|
||
doc.append(cstr!("date"), "not-a-date");
|
||
doc.append(cstr!("open"), 10.0);
|
||
doc.append(cstr!("high"), 11.0);
|
||
doc.append(cstr!("low"), 9.0);
|
||
doc.append(cstr!("close"), 10.5);
|
||
doc.append(cstr!("volume"), 100.0);
|
||
doc.into_bytes()
|
||
}
|
||
|
||
fn build_qm_split_doc(code: &str, date: &str, ratio: f64) -> Vec<u8> {
|
||
let mut doc = RawDocumentBuf::new();
|
||
doc.append(cstr!("qmSearchCode"), code);
|
||
doc.append(cstr!("date"), date);
|
||
doc.append(cstr!("splitratio"), ratio);
|
||
doc.into_bytes()
|
||
}
|
||
|
||
fn build_qm_split_reject_doc(code: &str) -> Vec<u8> {
|
||
let mut doc = RawDocumentBuf::new();
|
||
doc.append(cstr!("qmSearchCode"), code);
|
||
doc.append(cstr!("date"), "2024-06-10");
|
||
doc.append(cstr!("splitratio"), "bad-type");
|
||
doc.into_bytes()
|
||
}
|
||
|
||
fn build_qm_dividend_doc(code: &str, date: &str, cash: f64, currency: &str) -> Vec<u8> {
|
||
let mut doc = RawDocumentBuf::new();
|
||
doc.append(cstr!("qmSearchCode"), code);
|
||
doc.append(cstr!("date"), date);
|
||
doc.append(cstr!("amount"), cash);
|
||
doc.append(cstr!("currency"), currency);
|
||
doc.into_bytes()
|
||
}
|
||
|
||
fn build_qm_dividend_reject_doc(code: &str) -> Vec<u8> {
|
||
let mut doc = RawDocumentBuf::new();
|
||
doc.append(cstr!("qmSearchCode"), code);
|
||
doc.append(cstr!("date"), "2024-06-10");
|
||
doc.append(cstr!("amount"), -1.0);
|
||
doc.append(cstr!("currency"), "USD");
|
||
doc.into_bytes()
|
||
}
|
||
|
||
fn build_qm_filing_doc(
|
||
symbol: &str,
|
||
timefiled: &str,
|
||
form_type: &str,
|
||
filing_id: Option<&str>,
|
||
) -> Vec<u8> {
|
||
let mut doc = RawDocumentBuf::new();
|
||
doc.append(cstr!("symbol"), symbol);
|
||
doc.append(cstr!("timefiled"), timefiled);
|
||
doc.append(cstr!("formtype"), form_type);
|
||
if let Some(id) = filing_id {
|
||
doc.append(cstr!("filingid"), id);
|
||
}
|
||
doc.into_bytes()
|
||
}
|
||
|
||
fn build_qm_filing_reject_doc(symbol: &str) -> Vec<u8> {
|
||
let mut doc = RawDocumentBuf::new();
|
||
doc.append(cstr!("symbol"), symbol);
|
||
doc.append(cstr!("timefiled"), "2024-06-10T16:30:00 EDT");
|
||
// Missing required formtype -> semantic skip
|
||
doc.into_bytes()
|
||
}
|
||
|
||
fn concat_docs(docs: &[Vec<u8>]) -> Vec<u8> {
|
||
let total: usize = docs.iter().map(Vec::len).sum();
|
||
let mut out = Vec::with_capacity(total);
|
||
for doc in docs {
|
||
out.extend_from_slice(doc);
|
||
}
|
||
out
|
||
}
|
||
|
||
/// Wraps any `io::Read` and caps every single `read()` call to `max_step` bytes,
|
||
/// exercising tiny (1-byte) and odd-sized (`3`, `7`, `13`, `37` B) read buffers.
|
||
struct CappedRead<R> {
|
||
inner: R,
|
||
max_step: usize,
|
||
}
|
||
|
||
impl<R> CappedRead<R> {
|
||
fn new(inner: R, max_step: usize) -> Self {
|
||
Self { inner, max_step }
|
||
}
|
||
}
|
||
|
||
impl<R: Read> Read for CappedRead<R> {
|
||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||
let cap = buf.len().min(self.max_step);
|
||
self.inner.read(&mut buf[..cap])
|
||
}
|
||
}
|
||
|
||
fn read_all_with_step<R: Read>(reader: &mut R, step: usize) -> io::Result<Vec<u8>> {
|
||
let mut out = Vec::new();
|
||
let mut buf = vec![0u8; step];
|
||
loop {
|
||
let n = reader.read(&mut buf)?;
|
||
if n == 0 {
|
||
break;
|
||
}
|
||
out.extend_from_slice(&buf[..n]);
|
||
}
|
||
Ok(out)
|
||
}
|
||
|
||
fn validate_uri(raw: &str) -> ValidatedReadOnlyMongoUri {
|
||
assert_read_only_mongo_uri(raw, &ReadOnlyPolicy::default(), &LocalHosts::empty())
|
||
.expect("test URI must pass read-only safety guard")
|
||
}
|
||
|
||
struct FailingSource {
|
||
docs: Vec<Vec<u8>>,
|
||
index: usize,
|
||
fail_at: usize,
|
||
err: MongoStreamError,
|
||
}
|
||
|
||
impl RawDocumentSource for FailingSource {
|
||
fn next_raw_document(&mut self) -> Result<Option<&[u8]>, MongoStreamError> {
|
||
if self.index == self.fail_at {
|
||
return Err(self.err.clone());
|
||
}
|
||
if self.index >= self.docs.len() {
|
||
return Ok(None);
|
||
}
|
||
let doc = self.docs[self.index].as_slice();
|
||
self.index += 1;
|
||
Ok(Some(doc))
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 1. Allowlist parity against export-raw-bson.ts
|
||
// ---------------------------------------------------------------------------
|
||
|
||
#[test]
|
||
fn source_collection_allowlist_matches_export_raw_bson_ts_exactly() {
|
||
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||
let ts_path = manifest_dir
|
||
.join("..")
|
||
.join("..")
|
||
.join("apps")
|
||
.join("stock")
|
||
.join("data-pipeline")
|
||
.join("src")
|
||
.join("security-master")
|
||
.join("export-raw-bson.ts");
|
||
|
||
let contents = fs::read_to_string(&ts_path)
|
||
.unwrap_or_else(|err| panic!("failed to read {}: {err}", ts_path.display()));
|
||
|
||
let anchor = "export const RAW_BSON_EXPORT_COLLECTIONS = Object.freeze([";
|
||
let start = contents
|
||
.find(anchor)
|
||
.expect("RAW_BSON_EXPORT_COLLECTIONS declaration not found in export-raw-bson.ts")
|
||
+ anchor.len();
|
||
let rest = &contents[start..];
|
||
let end = rest
|
||
.find("] as const")
|
||
.expect("closing `] as const` not found for RAW_BSON_EXPORT_COLLECTIONS");
|
||
let block = &rest[..end];
|
||
|
||
let ts_names: Vec<String> = block
|
||
.lines()
|
||
.filter_map(|line| {
|
||
let trimmed = line.trim();
|
||
let first_quote = trimmed.find('\'')?;
|
||
let after_first = &trimmed[first_quote + 1..];
|
||
let second_quote = after_first.find('\'')?;
|
||
Some(after_first[..second_quote].to_owned())
|
||
})
|
||
.collect();
|
||
|
||
let rust_names: Vec<&str> = SourceCollection::ALL.iter().map(|c| c.as_str()).collect();
|
||
let expected = vec![
|
||
"eodPrices",
|
||
"qmSplits",
|
||
"qmDividends",
|
||
"qmPrices",
|
||
"teMarketData",
|
||
"ceoShorts",
|
||
"qmFilings",
|
||
"qmEarnings",
|
||
];
|
||
|
||
assert_eq!(rust_names, expected);
|
||
assert_eq!(
|
||
ts_names,
|
||
rust_names
|
||
.iter()
|
||
.map(|s| (*s).to_owned())
|
||
.collect::<Vec<_>>(),
|
||
"SourceCollection::ALL must match RAW_BSON_EXPORT_COLLECTIONS in exact names and order"
|
||
);
|
||
assert_eq!(SourceCollection::ALL.len(), 8);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 2. Decoder parity across 4 collections + 1-byte and odd-sized buffers
|
||
// ---------------------------------------------------------------------------
|
||
|
||
#[test]
|
||
fn parity_eod_prices_stream_across_default_and_odd_buffers() {
|
||
let docs = vec![
|
||
build_eod_doc("AAPL.US", "2024-01-02", 185.5, 1000.0),
|
||
build_eod_reject_doc("BAD.US"),
|
||
build_eod_doc("NVDA.US", "2024-06-10", 121.75, 50_000.0),
|
||
build_eod_doc("RY.TO", "2024-12-31", 173.25, 250_000.0),
|
||
];
|
||
let concat = concat_docs(&docs);
|
||
let total_bytes = concat.len() as u64;
|
||
|
||
let mut expected_rows = Vec::new();
|
||
let mut expected_errs = Vec::new();
|
||
let expected_stats = decode_eod_price_stream(
|
||
Cursor::new(&concat),
|
||
BsonStreamOptions::default(),
|
||
|bar| {
|
||
expected_rows.push((
|
||
bar.eod_search_code.to_owned(),
|
||
bar.session_date,
|
||
bar.open.to_bits(),
|
||
bar.high.to_bits(),
|
||
bar.low.to_bits(),
|
||
bar.close.to_bits(),
|
||
bar.adj_volume.to_bits(),
|
||
));
|
||
},
|
||
|offset, err| expected_errs.push((offset, err)),
|
||
)
|
||
.expect("baseline cursor decode must succeed");
|
||
assert_eq!(expected_rows.len(), 3, "baseline eodPrices must decode 3 valid rows");
|
||
assert_eq!(expected_errs.len(), 1, "baseline eodPrices must reject 1 invalid doc");
|
||
assert_eq!(expected_stats.decoded, 3);
|
||
assert_eq!(expected_stats.rejected_total(), 1);
|
||
|
||
for step in [usize::MAX, 1, 3, 7, 13, 37] {
|
||
let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone()));
|
||
let mut rows = Vec::new();
|
||
let mut errs = Vec::new();
|
||
let stats = if step == usize::MAX {
|
||
decode_eod_price_stream(
|
||
&mut cursor_reader,
|
||
BsonStreamOptions::default(),
|
||
|bar| {
|
||
rows.push((
|
||
bar.eod_search_code.to_owned(),
|
||
bar.session_date,
|
||
bar.open.to_bits(),
|
||
bar.high.to_bits(),
|
||
bar.low.to_bits(),
|
||
bar.close.to_bits(),
|
||
bar.adj_volume.to_bits(),
|
||
));
|
||
},
|
||
|offset, err| errs.push((offset, err)),
|
||
)
|
||
.expect("stream decode must succeed")
|
||
} else {
|
||
decode_eod_price_stream(
|
||
CappedRead::new(&mut cursor_reader, step),
|
||
BsonStreamOptions::default(),
|
||
|bar| {
|
||
rows.push((
|
||
bar.eod_search_code.to_owned(),
|
||
bar.session_date,
|
||
bar.open.to_bits(),
|
||
bar.high.to_bits(),
|
||
bar.low.to_bits(),
|
||
bar.close.to_bits(),
|
||
bar.adj_volume.to_bits(),
|
||
));
|
||
},
|
||
|offset, err| errs.push((offset, err)),
|
||
)
|
||
.expect("capped stream decode must succeed")
|
||
};
|
||
|
||
assert_eq!(stats, expected_stats, "eodPrices stats mismatch at step={step}");
|
||
assert_eq!(rows, expected_rows, "eodPrices rows mismatch at step={step}");
|
||
assert_eq!(errs, expected_errs, "eodPrices errors mismatch at step={step}");
|
||
assert_eq!(cursor_reader.docs_read(), docs.len() as u64);
|
||
assert_eq!(cursor_reader.bytes_read(), total_bytes);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn parity_qm_splits_stream_across_default_and_odd_buffers() {
|
||
let docs = vec![
|
||
build_qm_split_doc("NVDA:US", "2024-06-10", 10.0),
|
||
build_qm_split_reject_doc("BAD:US"),
|
||
build_qm_split_doc("NEXM:CA", "2025-06-18", 0.05),
|
||
];
|
||
let concat = concat_docs(&docs);
|
||
|
||
let mut expected_rows = Vec::new();
|
||
let mut expected_errs = Vec::new();
|
||
let expected_stats = decode_qm_split_stream(
|
||
Cursor::new(&concat),
|
||
BsonStreamOptions::default(),
|
||
|row| {
|
||
expected_rows.push((
|
||
row.qm_search_code.to_owned(),
|
||
row.ex_date,
|
||
row.ratio.to_bits(),
|
||
row.declared_date,
|
||
));
|
||
},
|
||
|offset, err| expected_errs.push((offset, err)),
|
||
)
|
||
.expect("baseline qmSplits decode must succeed");
|
||
assert_eq!(expected_rows.len(), 2, "baseline qmSplits must decode 2 valid rows");
|
||
assert_eq!(expected_errs.len(), 1, "baseline qmSplits must reject 1 invalid doc");
|
||
assert_eq!(expected_stats.decoded, 2);
|
||
assert_eq!(expected_stats.rejected_total(), 1);
|
||
|
||
for step in [usize::MAX, 1, 3, 7, 13, 37] {
|
||
let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone()));
|
||
let mut rows = Vec::new();
|
||
let mut errs = Vec::new();
|
||
let stats = if step == usize::MAX {
|
||
decode_qm_split_stream(
|
||
&mut cursor_reader,
|
||
BsonStreamOptions::default(),
|
||
|row| {
|
||
rows.push((
|
||
row.qm_search_code.to_owned(),
|
||
row.ex_date,
|
||
row.ratio.to_bits(),
|
||
row.declared_date,
|
||
));
|
||
},
|
||
|offset, err| errs.push((offset, err)),
|
||
)
|
||
.expect("qmSplits stream decode must succeed")
|
||
} else {
|
||
decode_qm_split_stream(
|
||
CappedRead::new(&mut cursor_reader, step),
|
||
BsonStreamOptions::default(),
|
||
|row| {
|
||
rows.push((
|
||
row.qm_search_code.to_owned(),
|
||
row.ex_date,
|
||
row.ratio.to_bits(),
|
||
row.declared_date,
|
||
));
|
||
},
|
||
|offset, err| errs.push((offset, err)),
|
||
)
|
||
.expect("capped qmSplits stream decode must succeed")
|
||
};
|
||
|
||
assert_eq!(stats, expected_stats, "qmSplits stats mismatch at step={step}");
|
||
assert_eq!(rows, expected_rows, "qmSplits rows mismatch at step={step}");
|
||
assert_eq!(errs, expected_errs, "qmSplits errors mismatch at step={step}");
|
||
assert_eq!(cursor_reader.docs_read(), docs.len() as u64);
|
||
assert_eq!(cursor_reader.bytes_read(), concat.len() as u64);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn parity_qm_dividends_stream_across_default_and_odd_buffers() {
|
||
let docs = vec![
|
||
build_qm_dividend_doc("AAPL:US", "2024-05-10", 0.25, "USD"),
|
||
build_qm_dividend_reject_doc("BAD:US"),
|
||
build_qm_dividend_doc("RY:CA", "2024-07-25", 1.42, "CAD"),
|
||
];
|
||
let concat = concat_docs(&docs);
|
||
|
||
let mut expected_rows = Vec::new();
|
||
let mut expected_errs = Vec::new();
|
||
let expected_stats = decode_qm_dividend_stream(
|
||
Cursor::new(&concat),
|
||
BsonStreamOptions::default(),
|
||
|row| {
|
||
expected_rows.push((
|
||
row.qm_search_code.to_owned(),
|
||
row.ex_date,
|
||
row.cash.to_bits(),
|
||
row.currency.to_owned(),
|
||
row.declared_date,
|
||
));
|
||
},
|
||
|offset, err| expected_errs.push((offset, err)),
|
||
)
|
||
.expect("baseline qmDividends decode must succeed");
|
||
assert_eq!(expected_rows.len(), 2, "baseline qmDividends must decode 2 valid rows");
|
||
assert_eq!(expected_errs.len(), 1, "baseline qmDividends must reject 1 invalid doc");
|
||
assert_eq!(expected_stats.decoded, 2);
|
||
assert_eq!(expected_stats.rejected_total(), 1);
|
||
|
||
for step in [usize::MAX, 1, 3, 7, 13, 37] {
|
||
let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone()));
|
||
let mut rows = Vec::new();
|
||
let mut errs = Vec::new();
|
||
let stats = if step == usize::MAX {
|
||
decode_qm_dividend_stream(
|
||
&mut cursor_reader,
|
||
BsonStreamOptions::default(),
|
||
|row| {
|
||
rows.push((
|
||
row.qm_search_code.to_owned(),
|
||
row.ex_date,
|
||
row.cash.to_bits(),
|
||
row.currency.to_owned(),
|
||
row.declared_date,
|
||
));
|
||
},
|
||
|offset, err| errs.push((offset, err)),
|
||
)
|
||
.expect("qmDividends stream decode must succeed")
|
||
} else {
|
||
decode_qm_dividend_stream(
|
||
CappedRead::new(&mut cursor_reader, step),
|
||
BsonStreamOptions::default(),
|
||
|row| {
|
||
rows.push((
|
||
row.qm_search_code.to_owned(),
|
||
row.ex_date,
|
||
row.cash.to_bits(),
|
||
row.currency.to_owned(),
|
||
row.declared_date,
|
||
));
|
||
},
|
||
|offset, err| errs.push((offset, err)),
|
||
)
|
||
.expect("capped qmDividends stream decode must succeed")
|
||
};
|
||
|
||
assert_eq!(stats, expected_stats, "qmDividends stats mismatch at step={step}");
|
||
assert_eq!(rows, expected_rows, "qmDividends rows mismatch at step={step}");
|
||
assert_eq!(errs, expected_errs, "qmDividends errors mismatch at step={step}");
|
||
assert_eq!(cursor_reader.docs_read(), docs.len() as u64);
|
||
assert_eq!(cursor_reader.bytes_read(), concat.len() as u64);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn parity_qm_filings_stream_across_default_and_odd_buffers() {
|
||
let docs = vec![
|
||
build_qm_filing_doc("AAPL:US", "2024-05-03T16:30:00 EDT", "10-Q", Some("F-101")),
|
||
build_qm_filing_reject_doc("BAD:US"),
|
||
build_qm_filing_doc("RY:CA", "2024-12-04T08:05:00 EST", "Annual financial statements", None),
|
||
];
|
||
let concat = concat_docs(&docs);
|
||
let fields = QmFilingsFieldNames {
|
||
key: "symbol",
|
||
timefiled: "timefiled",
|
||
form_type: "formtype",
|
||
filing_id: Some("filingid"),
|
||
url: None,
|
||
};
|
||
|
||
let mut expected_rows = Vec::new();
|
||
let expected_stats = decode_qm_filings_stream(
|
||
Cursor::new(&concat),
|
||
BsonStreamOptions::default(),
|
||
&fields,
|
||
|row| {
|
||
expected_rows.push((
|
||
row.key.to_owned(),
|
||
row.timefiled.to_owned(),
|
||
row.form_type.to_owned(),
|
||
row.filing_id.map(str::to_owned),
|
||
row.url.map(str::to_owned),
|
||
));
|
||
},
|
||
)
|
||
.expect("baseline qmFilings decode must succeed");
|
||
assert_eq!(expected_rows.len(), 2, "baseline qmFilings must decode 2 valid rows");
|
||
assert_eq!(expected_stats.rows_out, 2);
|
||
assert_eq!(expected_stats.skipped_total(), 1);
|
||
|
||
for step in [usize::MAX, 1, 3, 7, 13, 37] {
|
||
let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone()));
|
||
let mut rows = Vec::new();
|
||
let stats = if step == usize::MAX {
|
||
decode_qm_filings_stream(
|
||
&mut cursor_reader,
|
||
BsonStreamOptions::default(),
|
||
&fields,
|
||
|row| {
|
||
rows.push((
|
||
row.key.to_owned(),
|
||
row.timefiled.to_owned(),
|
||
row.form_type.to_owned(),
|
||
row.filing_id.map(str::to_owned),
|
||
row.url.map(str::to_owned),
|
||
));
|
||
},
|
||
)
|
||
.expect("qmFilings stream decode must succeed")
|
||
} else {
|
||
decode_qm_filings_stream(
|
||
CappedRead::new(&mut cursor_reader, step),
|
||
BsonStreamOptions::default(),
|
||
&fields,
|
||
|row| {
|
||
rows.push((
|
||
row.key.to_owned(),
|
||
row.timefiled.to_owned(),
|
||
row.form_type.to_owned(),
|
||
row.filing_id.map(str::to_owned),
|
||
row.url.map(str::to_owned),
|
||
));
|
||
},
|
||
)
|
||
.expect("capped qmFilings stream decode must succeed")
|
||
};
|
||
|
||
assert_eq!(stats, expected_stats, "qmFilings stats mismatch at step={step}");
|
||
assert_eq!(rows, expected_rows, "qmFilings rows mismatch at step={step}");
|
||
assert_eq!(cursor_reader.docs_read(), docs.len() as u64);
|
||
assert_eq!(cursor_reader.bytes_read(), concat.len() as u64);
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 3. Bounded memory, counters, framing validation & error handling
|
||
// ---------------------------------------------------------------------------
|
||
|
||
#[test]
|
||
fn empty_source_yields_eof_with_zero_counts() {
|
||
let empty: [&[u8]; 0] = [];
|
||
let mut reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&empty));
|
||
let mut buf = [0u8; 64];
|
||
assert_eq!(reader.read(&mut buf).expect("empty read must succeed"), 0);
|
||
assert_eq!(reader.read(&mut buf).expect("repeated EOF must succeed"), 0);
|
||
assert_eq!(reader.docs_read(), 0);
|
||
assert_eq!(reader.bytes_read(), 0);
|
||
assert_eq!(reader.pending_capacity(), 0);
|
||
}
|
||
|
||
#[test]
|
||
fn zero_length_read_buffer_returns_zero_without_advancing() {
|
||
let docs = vec![build_eod_doc("AAPL.US", "2024-01-02", 100.0, 50.0)];
|
||
let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone()));
|
||
assert_eq!(reader.read(&mut []).expect("empty buf read must succeed"), 0);
|
||
assert_eq!(reader.docs_read(), 0);
|
||
assert_eq!(reader.bytes_read(), 0);
|
||
|
||
let got = read_all_with_step(&mut reader, 64).expect("full read must succeed");
|
||
assert_eq!(got, docs[0]);
|
||
assert_eq!(reader.docs_read(), 1);
|
||
assert_eq!(reader.bytes_read(), docs[0].len() as u64);
|
||
}
|
||
|
||
#[test]
|
||
fn pending_capacity_stays_bounded_to_single_document_under_one_byte_reads() {
|
||
let docs: Vec<Vec<u8>> = (0..50)
|
||
.map(|i| build_eod_doc(&format!("SYM{i:03}.US"), "2024-01-02", 10.0 + i as f64, 100.0))
|
||
.collect();
|
||
let max_doc_len = docs.iter().map(Vec::len).max().unwrap();
|
||
let expected = concat_docs(&docs);
|
||
|
||
let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs));
|
||
let got = read_all_with_step(&mut reader, 1).expect("1-byte read must succeed");
|
||
|
||
assert_eq!(got, expected);
|
||
assert_eq!(reader.docs_read(), 50);
|
||
assert_eq!(reader.bytes_read(), expected.len() as u64);
|
||
assert!(
|
||
reader.pending_capacity() <= max_doc_len,
|
||
"pending_capacity ({}) exceeded max single doc length ({max_doc_len})",
|
||
reader.pending_capacity()
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn mid_stream_source_error_delivers_prior_docs_then_surfaces_sticky_mongo_stream_error() {
|
||
let doc0 = build_eod_doc("AAPL.US", "2024-01-02", 100.0, 10.0);
|
||
let doc1 = build_eod_doc("MSFT.US", "2024-01-03", 200.0, 20.0);
|
||
let expected_err = MongoStreamError::Source {
|
||
detail: "simulated cursor drop mid-stream".to_owned(),
|
||
};
|
||
let source = FailingSource {
|
||
docs: vec![doc0.clone(), doc1.clone()],
|
||
index: 0,
|
||
fail_at: 2,
|
||
err: expected_err.clone(),
|
||
};
|
||
|
||
let mut reader = RawBsonCursorReader::new(source);
|
||
let mut big_buf = vec![0u8; 4096];
|
||
let n = reader
|
||
.read(&mut big_buf)
|
||
.expect("first read must return bytes from prior valid docs");
|
||
assert_eq!(n, doc0.len() + doc1.len());
|
||
assert_eq!(&big_buf[..doc0.len()], doc0.as_slice());
|
||
assert_eq!(&big_buf[doc0.len()..n], doc1.as_slice());
|
||
assert_eq!(reader.docs_read(), 2);
|
||
assert_eq!(reader.bytes_read(), (doc0.len() + doc1.len()) as u64);
|
||
|
||
// Next read surfaces the stashed MongoStreamError wrapped in io::Error.
|
||
let io_err = reader
|
||
.read(&mut big_buf)
|
||
.expect_err("next read must surface stashed error");
|
||
let downcast = io_err
|
||
.get_ref()
|
||
.and_then(|e| e.downcast_ref::<MongoStreamError>())
|
||
.expect("io::Error must carry MongoStreamError");
|
||
assert_eq!(downcast, &expected_err);
|
||
|
||
// Subsequent reads stay sticky with the same MongoStreamError.
|
||
let io_err2 = reader
|
||
.read(&mut big_buf)
|
||
.expect_err("reader must remain in sticky error state");
|
||
let downcast2 = io_err2
|
||
.get_ref()
|
||
.and_then(|e| e.downcast_ref::<MongoStreamError>())
|
||
.expect("sticky io::Error must carry MongoStreamError");
|
||
assert_eq!(downcast2, &expected_err);
|
||
}
|
||
|
||
#[test]
|
||
fn first_doc_source_error_surfaces_through_bson_stream_error_io() {
|
||
let expected_err = MongoStreamError::Source {
|
||
detail: "initial cursor failure".to_owned(),
|
||
};
|
||
let source = FailingSource {
|
||
docs: vec![],
|
||
index: 0,
|
||
fail_at: 0,
|
||
err: expected_err.clone(),
|
||
};
|
||
let reader = RawBsonCursorReader::new(source);
|
||
let err = decode_eod_price_stream(reader, BsonStreamOptions::default(), |_| {}, |_, _| {})
|
||
.expect_err("decode_eod_price_stream must propagate source error");
|
||
|
||
match err {
|
||
BsonStreamError::Io { offset, source } => {
|
||
assert_eq!(offset, 0);
|
||
let inner = source
|
||
.get_ref()
|
||
.and_then(|e| e.downcast_ref::<MongoStreamError>())
|
||
.expect("BsonStreamError::Io must wrap MongoStreamError");
|
||
assert_eq!(inner, &expected_err);
|
||
}
|
||
other => panic!("expected BsonStreamError::Io, got {other:?}"),
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn malformed_bson_frames_are_rejected_without_incrementing_counters() {
|
||
let valid_doc = build_eod_doc("AAPL.US", "2024-01-02", 100.0, 10.0);
|
||
|
||
// 1. Shorter than MIN_BSON_DOC_BYTES (5)
|
||
let too_short = vec![4u8, 0, 0, 0];
|
||
// 2. Negative declared length
|
||
let negative_len = vec![0xff, 0xff, 0xff, 0xff, 0x00];
|
||
// 3. Declared length < actual byte length
|
||
let mut declared_lt_actual = valid_doc.clone();
|
||
declared_lt_actual.push(0x00);
|
||
// 4. Declared length > actual byte length
|
||
let mut declared_gt_actual = valid_doc.clone();
|
||
let bad_len = (valid_doc.len() as i32 + 4).to_le_bytes();
|
||
declared_gt_actual[..4].copy_from_slice(&bad_len);
|
||
// 5. Missing trailing 0x00 terminator
|
||
let mut missing_null = valid_doc.clone();
|
||
*missing_null.last_mut().unwrap() = 0x7f;
|
||
|
||
let bad_cases = [
|
||
("too_short", too_short),
|
||
("negative_len", negative_len),
|
||
("declared_lt_actual", declared_lt_actual),
|
||
("declared_gt_actual", declared_gt_actual),
|
||
("missing_null", missing_null),
|
||
];
|
||
|
||
for (label, bad_frame) in bad_cases {
|
||
let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(vec![
|
||
valid_doc.clone(),
|
||
bad_frame,
|
||
]));
|
||
let mut buf = vec![0u8; 4096];
|
||
let n = reader
|
||
.read(&mut buf)
|
||
.unwrap_or_else(|e| panic!("{label}: first doc should succeed, got {e}"));
|
||
assert_eq!(n, valid_doc.len(), "{label}");
|
||
assert_eq!(reader.docs_read(), 1, "{label}");
|
||
assert_eq!(reader.bytes_read(), valid_doc.len() as u64, "{label}");
|
||
|
||
let err = reader
|
||
.read(&mut buf)
|
||
.expect_err(&format!("{label}: bad frame must fail"));
|
||
let mongo_err = err
|
||
.get_ref()
|
||
.and_then(|e| e.downcast_ref::<MongoStreamError>())
|
||
.expect("must downcast to MongoStreamError");
|
||
match mongo_err {
|
||
MongoStreamError::InvalidBsonFrame { doc_index, .. } => {
|
||
assert_eq!(*doc_index, 1, "{label}: doc_index must be 1");
|
||
}
|
||
other => panic!("{label}: expected InvalidBsonFrame, got {other:?}"),
|
||
}
|
||
assert_eq!(reader.docs_read(), 1, "{label}: counters must not advance");
|
||
assert_eq!(reader.bytes_read(), valid_doc.len() as u64, "{label}");
|
||
}
|
||
|
||
// 6. Exceeds max_doc_bytes
|
||
let mut reader = RawBsonCursorReader::with_max_doc_bytes(
|
||
VecRawDocumentSource::new(vec![valid_doc.clone()]),
|
||
valid_doc.len() - 1,
|
||
)
|
||
.expect("with_max_doc_bytes >= 5 must succeed");
|
||
let mut buf = vec![0u8; 4096];
|
||
let err = reader.read(&mut buf).expect_err("oversized doc must fail");
|
||
let mongo_err = err
|
||
.get_ref()
|
||
.and_then(|e| e.downcast_ref::<MongoStreamError>())
|
||
.expect("must downcast to MongoStreamError");
|
||
assert!(matches!(
|
||
mongo_err,
|
||
MongoStreamError::InvalidBsonFrame { doc_index: 0, .. }
|
||
));
|
||
assert_eq!(reader.docs_read(), 0);
|
||
assert_eq!(reader.bytes_read(), 0);
|
||
|
||
// 7. with_max_doc_bytes < MIN_BSON_DOC_BYTES rejected
|
||
let err = RawBsonCursorReader::with_max_doc_bytes(
|
||
VecRawDocumentSource::new(vec![]),
|
||
MIN_BSON_DOC_BYTES - 1,
|
||
)
|
||
.err()
|
||
.expect("max_doc_bytes < 5 must fail");
|
||
assert!(matches!(err, MongoStreamError::InvalidMaxDocBytes { .. }));
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 4. Filter & spec validation + lazy non-connecting open()
|
||
// ---------------------------------------------------------------------------
|
||
|
||
#[test]
|
||
fn build_filter_document_and_spec_validation() {
|
||
// Empty spec -> empty filter document
|
||
let empty_filter =
|
||
build_filter_document(SourceCollection::EodPrices, &MongoReadSpec::default())
|
||
.expect("default spec must be valid");
|
||
assert!(empty_filter.is_empty());
|
||
|
||
// Key + ISO date range
|
||
let spec = MongoReadSpec {
|
||
key_eq: Some("AAPL.US".to_owned()),
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())),
|
||
lt: Some(FilterDateValue::IsoString("2025-01-01".to_owned())),
|
||
}),
|
||
batch_size: DEFAULT_MONGO_BATCH_SIZE,
|
||
limit: Some(500),
|
||
..MongoReadSpec::default()
|
||
};
|
||
let doc = build_filter_document(SourceCollection::EodPrices, &spec)
|
||
.expect("valid key + date_range spec must succeed");
|
||
assert_eq!(
|
||
doc.get("eodSearchCode"),
|
||
Some(&Bson::String("AAPL.US".to_owned()))
|
||
);
|
||
let date_sub = doc
|
||
.get_document("date")
|
||
.expect("date range subdocument must exist");
|
||
assert_eq!(
|
||
date_sub.get("$gte"),
|
||
Some(&Bson::String("2024-01-01".to_owned()))
|
||
);
|
||
assert_eq!(
|
||
date_sub.get("$lt"),
|
||
Some(&Bson::String("2025-01-01".to_owned()))
|
||
);
|
||
|
||
// BSON DateTime millis range
|
||
let dt_spec = MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::BsonDateTimeMillis(1_704_067_200_000)),
|
||
lt: Some(FilterDateValue::BsonDateTimeMillis(1_735_689_600_000)),
|
||
}),
|
||
..MongoReadSpec::default()
|
||
};
|
||
let dt_doc = build_filter_document(SourceCollection::QmEarnings, &dt_spec)
|
||
.expect("valid DateTime range must succeed");
|
||
let rd = dt_doc
|
||
.get_document("reportDate")
|
||
.expect("reportDate subdocument must exist");
|
||
assert_eq!(
|
||
rd.get("$gte"),
|
||
Some(&Bson::DateTime(DateTime::from_millis(1_704_067_200_000)))
|
||
);
|
||
|
||
// Invalid batch_size == 0 and > MAX_MONGO_BATCH_SIZE
|
||
assert!(matches!(
|
||
build_filter_document(
|
||
SourceCollection::EodPrices,
|
||
&MongoReadSpec {
|
||
batch_size: 0,
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidBatchSize { batch_size: 0, .. })
|
||
));
|
||
assert!(matches!(
|
||
build_filter_document(
|
||
SourceCollection::EodPrices,
|
||
&MongoReadSpec {
|
||
batch_size: MAX_MONGO_BATCH_SIZE + 1,
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidBatchSize { .. })
|
||
));
|
||
|
||
// Invalid limit == Some(0) and > i64::MAX
|
||
assert!(matches!(
|
||
build_filter_document(
|
||
SourceCollection::EodPrices,
|
||
&MongoReadSpec {
|
||
limit: Some(0),
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidLimit { limit: 0 })
|
||
));
|
||
assert!(matches!(
|
||
build_filter_document(
|
||
SourceCollection::EodPrices,
|
||
&MongoReadSpec {
|
||
limit: Some(i64::MAX as u64 + 1),
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidLimit { .. })
|
||
));
|
||
|
||
// Blank key_eq
|
||
assert!(matches!(
|
||
build_filter_document(
|
||
SourceCollection::EodPrices,
|
||
&MongoReadSpec {
|
||
key_eq: Some(" ".to_owned()),
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidKeyFilter {
|
||
collection: SourceCollection::EodPrices
|
||
})
|
||
));
|
||
|
||
// date_range on TeMarketData
|
||
assert!(matches!(
|
||
build_filter_document(
|
||
SourceCollection::TeMarketData,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())),
|
||
lt: None,
|
||
}),
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::DateRangeNotSupported {
|
||
collection: SourceCollection::TeMarketData
|
||
})
|
||
));
|
||
|
||
// Empty date_range (neither gte nor lt)
|
||
assert!(matches!(
|
||
build_filter_document(
|
||
SourceCollection::EodPrices,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: None,
|
||
lt: None,
|
||
}),
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidDateRange { .. })
|
||
));
|
||
|
||
// Inverted date_range (gte >= lt)
|
||
assert!(matches!(
|
||
build_filter_document(
|
||
SourceCollection::EodPrices,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::IsoString("2025-01-01".to_owned())),
|
||
lt: Some(FilterDateValue::IsoString("2024-01-01".to_owned())),
|
||
}),
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidDateRange { .. })
|
||
));
|
||
|
||
// Mismatched FilterDateValue variants
|
||
assert!(matches!(
|
||
build_filter_document(
|
||
SourceCollection::EodPrices,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())),
|
||
lt: Some(FilterDateValue::BsonDateTimeMillis(1_735_689_600_000)),
|
||
}),
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidDateRange { .. })
|
||
));
|
||
}
|
||
|
||
#[test]
|
||
fn qm_filings_date_range_requires_eastern_calendar_day_boundaries_and_handles_fall_back_dst() {
|
||
// UTC ISO string must be rejected: a filing stored as "2024-12-31T21:30:00 EST"
|
||
// (= 2025-01-01T02:30:00Z) would lexicographically sort before "2025-01-01T00:00:00Z".
|
||
assert!(matches!(
|
||
build_filter_document(
|
||
SourceCollection::QmFilings,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::IsoString("2025-01-01T00:00:00Z".to_owned())),
|
||
lt: Some(FilterDateValue::IsoString("2025-01-02T00:00:00Z".to_owned())),
|
||
}),
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidDateRange {
|
||
collection: SourceCollection::QmFilings,
|
||
..
|
||
})
|
||
));
|
||
|
||
// Intra-day Eastern timestamps must also be rejected for server-side string ranges:
|
||
// on fall-back DST day (2024-11-03), "2024-11-03T01:15:00 EST" occurred 45 minutes
|
||
// AFTER "2024-11-03T01:30:00 EDT" but sorts lexicographically BEFORE it.
|
||
assert!(matches!(
|
||
build_filter_document(
|
||
SourceCollection::QmFilings,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::IsoString(
|
||
"2024-11-03T01:30:00 EDT".to_owned()
|
||
)),
|
||
lt: Some(FilterDateValue::IsoString(
|
||
"2024-11-03T02:00:00 EST".to_owned()
|
||
)),
|
||
}),
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidDateRange {
|
||
collection: SourceCollection::QmFilings,
|
||
..
|
||
})
|
||
));
|
||
|
||
// Invalid calendar dates and BsonDateTimeMillis bounds must be rejected.
|
||
assert!(matches!(
|
||
build_filter_document(
|
||
SourceCollection::QmFilings,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::IsoString("2024-02-30".to_owned())),
|
||
lt: None,
|
||
}),
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidDateRange {
|
||
collection: SourceCollection::QmFilings,
|
||
..
|
||
})
|
||
));
|
||
assert!(matches!(
|
||
build_filter_document(
|
||
SourceCollection::QmFilings,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::BsonDateTimeMillis(1_735_689_600_000)),
|
||
lt: None,
|
||
}),
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidDateRange {
|
||
collection: SourceCollection::QmFilings,
|
||
..
|
||
})
|
||
));
|
||
|
||
// Eastern calendar-day boundaries (YYYY-MM-DD) are monotonic even across fall-back DST
|
||
// (2024-11-03): both 01:30:00 EDT and 01:15:00 EST fall inside ["2024-11-03", "2024-11-04"),
|
||
// while the previous and next days stay cleanly outside.
|
||
let gte_day = "2024-11-03";
|
||
let lt_day = "2024-11-04";
|
||
let filter = build_filter_document(
|
||
SourceCollection::QmFilings,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::IsoString(gte_day.to_owned())),
|
||
lt: Some(FilterDateValue::IsoString(lt_day.to_owned())),
|
||
}),
|
||
..MongoReadSpec::default()
|
||
},
|
||
)
|
||
.expect("valid Eastern calendar-day bounds for qmFilings must succeed");
|
||
|
||
let tf = filter
|
||
.get_document("timefiled")
|
||
.expect("timefiled range subdocument must exist");
|
||
assert_eq!(tf.get("$gte"), Some(&Bson::String(gte_day.to_owned())));
|
||
assert_eq!(tf.get("$lt"), Some(&Bson::String(lt_day.to_owned())));
|
||
|
||
let before_day = "2024-11-02T23:59:59 EDT";
|
||
let dst_first_pass = "2024-11-03T01:30:00 EDT";
|
||
let dst_second_pass = "2024-11-03T01:15:00 EST";
|
||
let next_day_midnight = "2024-11-04T00:00:00 EST";
|
||
|
||
assert!(before_day < gte_day);
|
||
assert!(dst_first_pass >= gte_day && dst_first_pass < lt_day);
|
||
assert!(dst_second_pass >= gte_day && dst_second_pass < lt_day);
|
||
assert!(next_day_midnight >= lt_day);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 5. Password redaction (plain and percent-encoded sentinel passwords)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
#[test]
|
||
fn error_display_and_debug_never_leak_plain_or_percent_encoded_passwords() {
|
||
// Plain sentinel password
|
||
let plain_sentinel = "SENTINEL_PLAIN_PASS_998877";
|
||
let plain_uri_str = format!(
|
||
"mongodb://studio_stock_bot_read:{plain_sentinel}@localhost:27017/stock?authSource=stock"
|
||
);
|
||
let plain_uri = validate_uri(&plain_uri_str);
|
||
let simulated_raw = format!(
|
||
"connection failed for {plain_uri_str} (auth token {plain_sentinel}) secondary mongodb://other:{plain_sentinel}@10.0.0.51:27017/stock"
|
||
);
|
||
let err = 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("[REDACTED]"));
|
||
assert!(debug_out.contains("[REDACTED]"));
|
||
|
||
// Percent-encoded sentinel password (contains %40 -> @ and %21 -> !)
|
||
let encoded_sentinel = "SENTINEL%40ENC%21PASS_554433";
|
||
let decoded_sentinel = "SENTINEL@ENC!PASS_554433";
|
||
let enc_uri_str = format!(
|
||
"mongodb://studio_stock_bot_read:{encoded_sentinel}@localhost:27017/stock"
|
||
);
|
||
let enc_uri = validate_uri(&enc_uri_str);
|
||
let simulated_enc_raw = format!(
|
||
"failed parsing {enc_uri_str}; raw={encoded_sentinel}; decoded={decoded_sentinel}"
|
||
);
|
||
let sanitized = sanitize_driver_error_message(&simulated_enc_raw, &enc_uri);
|
||
assert!(
|
||
!sanitized.contains(encoded_sentinel),
|
||
"leaked encoded password: {sanitized}"
|
||
);
|
||
assert!(
|
||
!sanitized.contains(decoded_sentinel),
|
||
"leaked decoded password: {sanitized}"
|
||
);
|
||
assert!(sanitized.contains("[REDACTED]"));
|
||
|
||
let enc_err = 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));
|
||
assert!(!enc_display.contains(decoded_sentinel));
|
||
assert!(!enc_debug.contains(encoded_sentinel));
|
||
assert!(!enc_debug.contains(decoded_sentinel));
|
||
assert!(enc_display.contains("[REDACTED]"));
|
||
}
|
||
|
||
#[test]
|
||
fn error_redaction_covers_distinct_secondary_uri_passwords_with_punctuation() {
|
||
let primary_uri = validate_uri(
|
||
"mongodb://studio_stock_bot_read:PRIMARY_PASS_111@localhost:27017/stock?authSource=stock",
|
||
);
|
||
let secondary_pass_comma = "SEC_ALPHA,BETA;GAMMA)DELTA";
|
||
let secondary_pass_srv = "SRV_PASS\"QUOTE]BRACKET@AT";
|
||
let diagnostic = format!(
|
||
"primary timed out; fallback mongodb://secondary:{secondary_pass_comma}@10.0.0.51:27017,10.0.0.52:27017/stock, \
|
||
and srv \"mongodb+srv://reader:{secondary_pass_srv}@cluster.internal/stock?retryReads=true\""
|
||
);
|
||
|
||
let err = MongoStreamError::redacted_source(&diagnostic, &primary_uri);
|
||
let display_out = format!("{err}");
|
||
let debug_out = format!("{err:?}");
|
||
|
||
for secret in [
|
||
"PRIMARY_PASS_111",
|
||
secondary_pass_comma,
|
||
"SEC_ALPHA",
|
||
"BETA",
|
||
"GAMMA",
|
||
"DELTA",
|
||
secondary_pass_srv,
|
||
"SRV_PASS",
|
||
"QUOTE",
|
||
"BRACKET",
|
||
] {
|
||
assert!(
|
||
!display_out.contains(secret),
|
||
"Display leaked secondary password fragment `{secret}`: {display_out}"
|
||
);
|
||
assert!(
|
||
!debug_out.contains(secret),
|
||
"Debug leaked secondary password fragment `{secret}`: {debug_out}"
|
||
);
|
||
}
|
||
|
||
assert!(
|
||
display_out.contains("mongodb://secondary:[REDACTED]@10.0.0.51:27017,10.0.0.52:27017/stock"),
|
||
"unexpected redacted secondary URI in Display: {display_out}"
|
||
);
|
||
assert!(
|
||
display_out.contains("mongodb+srv://reader:[REDACTED]@cluster.internal/stock?retryReads=true"),
|
||
"unexpected redacted srv URI in Display: {display_out}"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn error_redaction_covers_adjacent_uris_in_compact_json_list() {
|
||
let primary_uri = validate_uri(
|
||
"mongodb://studio_stock_bot_read:PRIMARY_PASS_222@localhost:27017/stock?authSource=stock",
|
||
);
|
||
let second_pass = "ADJACENT_JSON_SECRET_999";
|
||
let third_pass = "ADJACENT_SRV_SECRET,COMMA;SEMI";
|
||
// Compact JSON array with no whitespace between an unauthenticated URI lacking a `/db` path
|
||
// and subsequent authenticated URIs carrying distinct passwords.
|
||
let diagnostic = format!(
|
||
r#"{{"uris":["mongodb://localhost:27017","mongodb://secondary:{second_pass}@10.0.0.51:27017/stock","mongodb+srv://reader:{third_pass}@cluster.internal"]}}"#
|
||
);
|
||
|
||
let err = MongoStreamError::redacted_source(&diagnostic, &primary_uri);
|
||
let display_out = format!("{err}");
|
||
let debug_out = format!("{err:?}");
|
||
|
||
for secret in [
|
||
"PRIMARY_PASS_222",
|
||
second_pass,
|
||
third_pass,
|
||
"ADJACENT_SRV_SECRET",
|
||
"COMMA",
|
||
"SEMI",
|
||
] {
|
||
assert!(
|
||
!display_out.contains(secret),
|
||
"Display leaked adjacent JSON URI secret `{secret}`: {display_out}"
|
||
);
|
||
assert!(
|
||
!debug_out.contains(secret),
|
||
"Debug leaked adjacent JSON URI secret `{secret}`: {debug_out}"
|
||
);
|
||
}
|
||
|
||
assert!(
|
||
display_out.contains(
|
||
r#"["mongodb://localhost:27017","mongodb://secondary:[REDACTED]@10.0.0.51:27017/stock","mongodb+srv://reader:[REDACTED]@cluster.internal"]"#
|
||
),
|
||
"unexpected redacted compact JSON list in Display: {display_out}"
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 6. Sealed-surface source scan (zero driver paths or mutating calls)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
#[test]
|
||
fn sealed_surface_source_scan() {
|
||
let src_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||
.join("src")
|
||
.join("mongo_stream.rs");
|
||
let raw_src = fs::read_to_string(&src_path)
|
||
.unwrap_or_else(|err| panic!("failed to read {}: {err}", src_path.display()));
|
||
|
||
// Strip line comments (`//...`) so documentation prose does not produce false positives,
|
||
// while keeping all code lines verbatim.
|
||
let code_only: String = raw_src
|
||
.lines()
|
||
.map(|line| match line.find("//") {
|
||
Some(idx) => &line[..idx],
|
||
None => line,
|
||
})
|
||
.collect::<Vec<_>>()
|
||
.join("\n");
|
||
|
||
// Driver usage in `mongo_stream.rs` is sealed to `mongodb::sync::` read-only cursor operations.
|
||
assert!(
|
||
code_only.contains("mongodb::sync::Client") && code_only.contains("mongodb::sync::Cursor"),
|
||
"mongo_stream.rs must wire the sealed mongodb::sync driver adapter"
|
||
);
|
||
|
||
let forbidden_calls = [
|
||
"insert",
|
||
"update",
|
||
"delete",
|
||
"replace",
|
||
"drop",
|
||
"aggregate",
|
||
"create_index",
|
||
"run_command",
|
||
"bulk_write",
|
||
];
|
||
|
||
for word in forbidden_calls {
|
||
// Check for `.word(` or `word(` identifier calls in code.
|
||
let method_pat = format!(".{word}");
|
||
let call_pat = format!("{word}(");
|
||
assert!(
|
||
!code_only.contains(&method_pat) && !code_only.contains(&call_pat),
|
||
"forbidden driver/mutation call `{word}` found in mongo_stream.rs"
|
||
);
|
||
}
|
||
|
||
// Check that no `pub` item exposes `mongodb::Client`, `Database`, or `Collection`.
|
||
let lines: Vec<&str> = code_only.lines().collect();
|
||
for (idx, line) in lines.iter().enumerate() {
|
||
let trimmed = line.trim();
|
||
if trimmed.starts_with("pub ") && !trimmed.starts_with("pub(crate)") {
|
||
// Gather signature up to `{` or `;`
|
||
let mut sig = String::new();
|
||
for next_line in &lines[idx..] {
|
||
sig.push_str(next_line.trim());
|
||
sig.push(' ');
|
||
if next_line.contains('{') || next_line.contains(';') {
|
||
break;
|
||
}
|
||
}
|
||
for forbidden_type in [
|
||
"mongodb::Client",
|
||
"mongodb::sync::Client",
|
||
"mongodb::Database",
|
||
"mongodb::sync::Database",
|
||
"mongodb::Collection",
|
||
"mongodb::sync::Collection",
|
||
"-> Client",
|
||
"-> Database",
|
||
"-> Collection",
|
||
] {
|
||
assert!(
|
||
!sig.contains(forbidden_type),
|
||
"public item exposes forbidden MongoDB handle `{forbidden_type}`: {sig}"
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 7. Additional edge-case coverage
|
||
// ---------------------------------------------------------------------------
|
||
|
||
struct CountingSource {
|
||
docs: Vec<Vec<u8>>,
|
||
index: usize,
|
||
polls: usize,
|
||
}
|
||
|
||
impl CountingSource {
|
||
fn new(docs: Vec<Vec<u8>>) -> Self {
|
||
Self {
|
||
docs,
|
||
index: 0,
|
||
polls: 0,
|
||
}
|
||
}
|
||
}
|
||
|
||
impl RawDocumentSource for CountingSource {
|
||
fn next_raw_document(&mut self) -> Result<Option<&[u8]>, MongoStreamError> {
|
||
self.polls += 1;
|
||
if self.index >= self.docs.len() {
|
||
return Ok(None);
|
||
}
|
||
let doc = self.docs[self.index].as_slice();
|
||
self.index += 1;
|
||
Ok(Some(doc))
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn source_is_not_polled_again_after_eof_across_repeated_reads() {
|
||
let docs = vec![
|
||
build_eod_doc("AAPL.US", "2024-01-02", 185.5, 1000.0),
|
||
build_eod_doc("MSFT.US", "2024-01-03", 370.0, 2000.0),
|
||
];
|
||
let expected = concat_docs(&docs);
|
||
let mut reader = RawBsonCursorReader::new(CountingSource::new(docs));
|
||
|
||
let got = read_all_with_step(&mut reader, 64).expect("initial read must succeed");
|
||
assert_eq!(got, expected);
|
||
assert_eq!(reader.docs_read(), 2);
|
||
assert_eq!(reader.bytes_read(), expected.len() as u64);
|
||
|
||
let mut buf = [0u8; 32];
|
||
for _ in 0..5 {
|
||
assert_eq!(
|
||
reader.read(&mut buf).expect("post-EOF read must return Ok(0)"),
|
||
0
|
||
);
|
||
}
|
||
|
||
let inner = reader.into_inner();
|
||
assert_eq!(
|
||
inner.polls, 3,
|
||
"source must be polled only once per doc plus one EOF poll"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn source_error_after_split_document_delivers_all_doc_bytes_then_sticky_error() {
|
||
let doc0 = build_eod_doc("AAPL.US", "2024-01-02", 185.5, 1000.0);
|
||
assert!(doc0.len() > 25, "test doc must span multiple small reads");
|
||
let expected_err = MongoStreamError::Source {
|
||
detail: "cursor dropped after split doc".to_owned(),
|
||
};
|
||
let source = FailingSource {
|
||
docs: vec![doc0.clone()],
|
||
index: 0,
|
||
fail_at: 1,
|
||
err: expected_err.clone(),
|
||
};
|
||
|
||
let mut reader = RawBsonCursorReader::new(source);
|
||
let mut received = Vec::new();
|
||
let mut buf = [0u8; 13];
|
||
|
||
let first_err = loop {
|
||
match reader.read(&mut buf) {
|
||
Ok(0) => panic!("expected source error after split document, got EOF"),
|
||
Ok(n) => received.extend_from_slice(&buf[..n]),
|
||
Err(err) => break err,
|
||
}
|
||
};
|
||
|
||
assert_eq!(received, doc0, "all split document bytes must be delivered before error");
|
||
assert_eq!(reader.docs_read(), 1);
|
||
assert_eq!(reader.bytes_read(), doc0.len() as u64);
|
||
|
||
let downcast = first_err
|
||
.get_ref()
|
||
.and_then(|e| e.downcast_ref::<MongoStreamError>())
|
||
.expect("io::Error must wrap MongoStreamError");
|
||
assert_eq!(downcast, &expected_err);
|
||
|
||
// Subsequent reads stay sticky with the same error.
|
||
let second_err = reader
|
||
.read(&mut buf)
|
||
.expect_err("reader must remain in sticky error state");
|
||
let downcast2 = second_err
|
||
.get_ref()
|
||
.and_then(|e| e.downcast_ref::<MongoStreamError>())
|
||
.expect("sticky io::Error must wrap MongoStreamError");
|
||
assert_eq!(downcast2, &expected_err);
|
||
}
|
||
|
||
#[test]
|
||
fn malformed_first_document_fails_immediately_with_zero_counts_and_stays_sticky() {
|
||
let valid_doc = build_eod_doc("AAPL.US", "2024-01-02", 100.0, 10.0);
|
||
let mut bad_first = valid_doc.clone();
|
||
*bad_first.last_mut().unwrap() = 0x42; // missing trailing 0x00
|
||
|
||
let mut reader =
|
||
RawBsonCursorReader::new(VecRawDocumentSource::new(vec![bad_first, valid_doc]));
|
||
let mut buf = [0u8; 256];
|
||
|
||
let first_err = reader
|
||
.read(&mut buf)
|
||
.expect_err("malformed doc #0 must fail on first read");
|
||
let first_mongo_err = first_err
|
||
.get_ref()
|
||
.and_then(|e| e.downcast_ref::<MongoStreamError>())
|
||
.expect("must downcast to MongoStreamError")
|
||
.clone();
|
||
assert!(
|
||
matches!(
|
||
first_mongo_err,
|
||
MongoStreamError::InvalidBsonFrame { doc_index: 0, .. }
|
||
),
|
||
"expected InvalidBsonFrame at doc_index 0, got {first_mongo_err:?}"
|
||
);
|
||
assert_eq!(reader.docs_read(), 0);
|
||
assert_eq!(reader.bytes_read(), 0);
|
||
|
||
for _ in 0..3 {
|
||
let sticky_err = reader
|
||
.read(&mut buf)
|
||
.expect_err("subsequent reads must stay sticky after malformed doc #0");
|
||
let sticky_mongo_err = sticky_err
|
||
.get_ref()
|
||
.and_then(|e| e.downcast_ref::<MongoStreamError>())
|
||
.expect("sticky error must downcast to MongoStreamError");
|
||
assert_eq!(sticky_mongo_err, &first_mongo_err);
|
||
assert_eq!(reader.docs_read(), 0);
|
||
assert_eq!(reader.bytes_read(), 0);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn boundary_document_sizes_min_five_bytes_and_exact_max_doc_bytes() {
|
||
// Minimum valid 5-byte empty BSON document succeeds at max_doc_bytes == MIN_BSON_DOC_BYTES.
|
||
let empty_bson = vec![5u8, 0, 0, 0, 0];
|
||
assert_eq!(empty_bson.len(), MIN_BSON_DOC_BYTES);
|
||
let mut min_reader = RawBsonCursorReader::with_max_doc_bytes(
|
||
VecRawDocumentSource::new(vec![empty_bson.clone()]),
|
||
MIN_BSON_DOC_BYTES,
|
||
)
|
||
.expect("MIN_BSON_DOC_BYTES must be accepted");
|
||
let min_out = read_all_with_step(&mut min_reader, 2).expect("5-byte doc must succeed");
|
||
assert_eq!(min_out, empty_bson);
|
||
assert_eq!(min_reader.docs_read(), 1);
|
||
assert_eq!(min_reader.bytes_read(), MIN_BSON_DOC_BYTES as u64);
|
||
|
||
// Exact max_doc_bytes succeeds while max_doc_bytes + 1 fails with InvalidBsonFrame.
|
||
let exact_doc = build_eod_doc("AAPL.US", "2024-01-02", 185.5, 1000.0);
|
||
let one_byte_larger = build_eod_doc("AAPLX.US", "2024-01-02", 185.5, 1000.0);
|
||
assert_eq!(one_byte_larger.len(), exact_doc.len() + 1);
|
||
let ceiling = exact_doc.len();
|
||
|
||
let mut exact_reader = RawBsonCursorReader::with_max_doc_bytes(
|
||
VecRawDocumentSource::new(vec![exact_doc.clone()]),
|
||
ceiling,
|
||
)
|
||
.expect("exact ceiling must be valid");
|
||
let exact_out = read_all_with_step(&mut exact_reader, 37).expect("exact-size doc must succeed");
|
||
assert_eq!(exact_out, exact_doc);
|
||
assert_eq!(exact_reader.docs_read(), 1);
|
||
assert_eq!(exact_reader.bytes_read(), ceiling as u64);
|
||
|
||
let mut over_reader = RawBsonCursorReader::with_max_doc_bytes(
|
||
VecRawDocumentSource::new(vec![one_byte_larger]),
|
||
ceiling,
|
||
)
|
||
.expect("ceiling must be valid");
|
||
let mut buf = [0u8; 512];
|
||
let err = over_reader
|
||
.read(&mut buf)
|
||
.expect_err("max_doc_bytes + 1 must fail");
|
||
let mongo_err = err
|
||
.get_ref()
|
||
.and_then(|e| e.downcast_ref::<MongoStreamError>())
|
||
.expect("must downcast to MongoStreamError");
|
||
assert!(matches!(
|
||
mongo_err,
|
||
MongoStreamError::InvalidBsonFrame { doc_index: 0, .. }
|
||
));
|
||
assert_eq!(over_reader.docs_read(), 0);
|
||
assert_eq!(over_reader.bytes_read(), 0);
|
||
}
|
||
|
||
#[test]
|
||
fn large_200kib_document_parity_and_bounded_pending_capacity() {
|
||
let payload = "X".repeat(200 * 1024);
|
||
let mut large_doc = RawDocumentBuf::new();
|
||
large_doc.append(cstr!("eodSearchCode"), "BIG.US");
|
||
large_doc.append(cstr!("date"), "2024-08-15");
|
||
large_doc.append(cstr!("open"), 42.0_f64);
|
||
large_doc.append(cstr!("high"), 43.0_f64);
|
||
large_doc.append(cstr!("low"), 41.0_f64);
|
||
large_doc.append(cstr!("close"), 42.5_f64);
|
||
large_doc.append(cstr!("volume"), 999.0_f64);
|
||
large_doc.append(cstr!("padding"), payload.as_str());
|
||
let large_bytes = large_doc.into_bytes();
|
||
assert!(large_bytes.len() > 200 * 1024);
|
||
|
||
let small_doc = build_eod_doc("SMALL.US", "2024-08-16", 12.25, 50.0);
|
||
let docs = vec![large_bytes.clone(), small_doc];
|
||
let concat = concat_docs(&docs);
|
||
let max_doc_len = docs.iter().map(Vec::len).max().unwrap();
|
||
|
||
let mut expected_rows = Vec::new();
|
||
let expected_stats = decode_eod_price_stream(
|
||
Cursor::new(&concat),
|
||
BsonStreamOptions::default(),
|
||
|bar| {
|
||
expected_rows.push((
|
||
bar.eod_search_code.to_owned(),
|
||
bar.session_date,
|
||
bar.close.to_bits(),
|
||
));
|
||
},
|
||
|offset, err| panic!("unexpected baseline error at {offset}: {err:?}"),
|
||
)
|
||
.expect("baseline large-doc decode must succeed");
|
||
assert_eq!(expected_rows.len(), 2);
|
||
|
||
for step in [13usize, 37, 4099] {
|
||
let mut cursor_reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone()));
|
||
let mut rows = Vec::new();
|
||
let stats = decode_eod_price_stream(
|
||
CappedRead::new(&mut cursor_reader, step),
|
||
BsonStreamOptions::default(),
|
||
|bar| {
|
||
rows.push((
|
||
bar.eod_search_code.to_owned(),
|
||
bar.session_date,
|
||
bar.close.to_bits(),
|
||
));
|
||
},
|
||
|offset, err| panic!("unexpected stream error at {offset} (step={step}): {err:?}"),
|
||
)
|
||
.expect("large-doc stream decode must succeed");
|
||
|
||
assert_eq!(stats, expected_stats, "stats mismatch at step={step}");
|
||
assert_eq!(rows, expected_rows, "rows mismatch at step={step}");
|
||
assert_eq!(cursor_reader.docs_read(), 2);
|
||
assert_eq!(cursor_reader.bytes_read(), concat.len() as u64);
|
||
assert!(
|
||
cursor_reader.pending_capacity() <= max_doc_len,
|
||
"pending_capacity ({}) exceeded single large doc length ({max_doc_len}) at step={step}",
|
||
cursor_reader.pending_capacity()
|
||
);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn read_spec_validate_accepts_all_boundary_limits() {
|
||
let min_spec = MongoReadSpec {
|
||
batch_size: 1,
|
||
limit: Some(1),
|
||
max_doc_bytes: MIN_BSON_DOC_BYTES,
|
||
..MongoReadSpec::default()
|
||
};
|
||
min_spec
|
||
.validate(SourceCollection::EodPrices)
|
||
.expect("min boundary spec must validate");
|
||
assert!(
|
||
build_filter_document(SourceCollection::EodPrices, &min_spec)
|
||
.expect("min boundary filter must succeed")
|
||
.is_empty()
|
||
);
|
||
|
||
let max_spec = MongoReadSpec {
|
||
batch_size: MAX_MONGO_BATCH_SIZE,
|
||
limit: Some(i64::MAX as u64),
|
||
max_doc_bytes: MIN_BSON_DOC_BYTES,
|
||
..MongoReadSpec::default()
|
||
};
|
||
max_spec
|
||
.validate(SourceCollection::EodPrices)
|
||
.expect("max boundary spec must validate");
|
||
assert!(
|
||
build_filter_document(SourceCollection::EodPrices, &max_spec)
|
||
.expect("max boundary filter must succeed")
|
||
.is_empty()
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn one_sided_date_range_bounds_and_equal_bound_rejection() {
|
||
// ISO string: gte-only
|
||
let iso_gte = build_filter_document(
|
||
SourceCollection::EodPrices,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())),
|
||
lt: None,
|
||
}),
|
||
..MongoReadSpec::default()
|
||
},
|
||
)
|
||
.expect("ISO gte-only must succeed");
|
||
let sub = iso_gte.get_document("date").unwrap();
|
||
assert_eq!(sub.get("$gte"), Some(&Bson::String("2024-01-01".to_owned())));
|
||
assert_eq!(sub.get("$lt"), None);
|
||
|
||
// ISO string: lt-only
|
||
let iso_lt = build_filter_document(
|
||
SourceCollection::EodPrices,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: None,
|
||
lt: Some(FilterDateValue::IsoString("2025-01-01".to_owned())),
|
||
}),
|
||
..MongoReadSpec::default()
|
||
},
|
||
)
|
||
.expect("ISO lt-only must succeed");
|
||
let sub = iso_lt.get_document("date").unwrap();
|
||
assert_eq!(sub.get("$gte"), None);
|
||
assert_eq!(sub.get("$lt"), Some(&Bson::String("2025-01-01".to_owned())));
|
||
|
||
// BSON DateTime millis: gte-only
|
||
let dt_gte = build_filter_document(
|
||
SourceCollection::CeoShorts,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::BsonDateTimeMillis(1_704_067_200_000)),
|
||
lt: None,
|
||
}),
|
||
..MongoReadSpec::default()
|
||
},
|
||
)
|
||
.expect("DateTime gte-only must succeed");
|
||
let sub = dt_gte.get_document("timestamp").unwrap();
|
||
assert_eq!(
|
||
sub.get("$gte"),
|
||
Some(&Bson::DateTime(DateTime::from_millis(1_704_067_200_000)))
|
||
);
|
||
assert_eq!(sub.get("$lt"), None);
|
||
|
||
// BSON DateTime millis: lt-only
|
||
let dt_lt = build_filter_document(
|
||
SourceCollection::CeoShorts,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: None,
|
||
lt: Some(FilterDateValue::BsonDateTimeMillis(1_735_689_600_000)),
|
||
}),
|
||
..MongoReadSpec::default()
|
||
},
|
||
)
|
||
.expect("DateTime lt-only must succeed");
|
||
let sub = dt_lt.get_document("timestamp").unwrap();
|
||
assert_eq!(sub.get("$gte"), None);
|
||
assert_eq!(
|
||
sub.get("$lt"),
|
||
Some(&Bson::DateTime(DateTime::from_millis(1_735_689_600_000)))
|
||
);
|
||
|
||
// Equal bounds (gte == lt) must be rejected for both variants.
|
||
assert!(matches!(
|
||
build_filter_document(
|
||
SourceCollection::EodPrices,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::IsoString("2024-06-01".to_owned())),
|
||
lt: Some(FilterDateValue::IsoString("2024-06-01".to_owned())),
|
||
}),
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidDateRange {
|
||
collection: SourceCollection::EodPrices,
|
||
..
|
||
})
|
||
));
|
||
assert!(matches!(
|
||
build_filter_document(
|
||
SourceCollection::CeoShorts,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::BsonDateTimeMillis(1_704_067_200_000)),
|
||
lt: Some(FilterDateValue::BsonDateTimeMillis(1_704_067_200_000)),
|
||
}),
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidDateRange {
|
||
collection: SourceCollection::CeoShorts,
|
||
..
|
||
})
|
||
));
|
||
}
|
||
|
||
#[test]
|
||
fn qm_filings_rejects_invalid_eastern_calendar_day_bounds() {
|
||
let invalid_days = [
|
||
"2023-02-29", // non-leap year Feb 29
|
||
"2024-13-01", // month > 12
|
||
"2024-00-10", // month == 0
|
||
"2024-01-00", // day == 0
|
||
"2024-04-31", // April has 30 days
|
||
"2024-01-01 ", // trailing space
|
||
"2024-01-01Z", // trailing UTC marker
|
||
"2024-01-0é", // non-ASCII byte
|
||
"2024-01-01", // fullwidth digits (non-ASCII)
|
||
];
|
||
|
||
for bad in invalid_days {
|
||
assert!(
|
||
matches!(
|
||
build_filter_document(
|
||
SourceCollection::QmFilings,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::IsoString(bad.to_owned())),
|
||
lt: None,
|
||
}),
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidDateRange {
|
||
collection: SourceCollection::QmFilings,
|
||
..
|
||
})
|
||
),
|
||
"expected gte={bad:?} to be rejected for qmFilings"
|
||
);
|
||
assert!(
|
||
matches!(
|
||
build_filter_document(
|
||
SourceCollection::QmFilings,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: None,
|
||
lt: Some(FilterDateValue::IsoString(bad.to_owned())),
|
||
}),
|
||
..MongoReadSpec::default()
|
||
}
|
||
),
|
||
Err(MongoStreamError::InvalidDateRange {
|
||
collection: SourceCollection::QmFilings,
|
||
..
|
||
})
|
||
),
|
||
"expected lt={bad:?} to be rejected for qmFilings"
|
||
);
|
||
}
|
||
|
||
// Leap-year Feb 29 is valid.
|
||
build_filter_document(
|
||
SourceCollection::QmFilings,
|
||
&MongoReadSpec {
|
||
date_range: Some(MongoDateRange {
|
||
gte: Some(FilterDateValue::IsoString("2024-02-29".to_owned())),
|
||
lt: Some(FilterDateValue::IsoString("2024-03-01".to_owned())),
|
||
}),
|
||
..MongoReadSpec::default()
|
||
},
|
||
)
|
||
.expect("valid leap-year calendar day 2024-02-29 must succeed");
|
||
}
|
||
|
||
#[test]
|
||
fn source_collection_exhaustive_key_date_and_display_mappings() {
|
||
let expected: [(SourceCollection, &str, &str, Option<&str>); 8] = [
|
||
(
|
||
SourceCollection::EodPrices,
|
||
"eodPrices",
|
||
"eodSearchCode",
|
||
Some("date"),
|
||
),
|
||
(
|
||
SourceCollection::QmSplits,
|
||
"qmSplits",
|
||
"qmSearchCode",
|
||
Some("date"),
|
||
),
|
||
(
|
||
SourceCollection::QmDividends,
|
||
"qmDividends",
|
||
"qmSearchCode",
|
||
Some("date"),
|
||
),
|
||
(
|
||
SourceCollection::QmPrices,
|
||
"qmPrices",
|
||
"qmSearchCode",
|
||
Some("date"),
|
||
),
|
||
(
|
||
SourceCollection::TeMarketData,
|
||
"teMarketData",
|
||
"teSymbol",
|
||
None,
|
||
),
|
||
(
|
||
SourceCollection::CeoShorts,
|
||
"ceoShorts",
|
||
"symbol",
|
||
Some("timestamp"),
|
||
),
|
||
(
|
||
SourceCollection::QmFilings,
|
||
"qmFilings",
|
||
"symbol",
|
||
Some("timefiled"),
|
||
),
|
||
(
|
||
SourceCollection::QmEarnings,
|
||
"qmEarnings",
|
||
"qmSearchCode",
|
||
Some("reportDate"),
|
||
),
|
||
];
|
||
|
||
assert_eq!(SourceCollection::ALL.len(), expected.len());
|
||
for (actual, (exp_variant, exp_name, exp_key, exp_date)) in
|
||
SourceCollection::ALL.into_iter().zip(expected)
|
||
{
|
||
assert_eq!(actual, exp_variant);
|
||
assert_eq!(actual.as_str(), exp_name);
|
||
assert_eq!(format!("{actual}"), exp_name);
|
||
assert_eq!(actual.key_field(), exp_key);
|
||
assert_eq!(actual.date_field(), exp_date);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn error_redaction_handles_uppercase_and_mixed_case_mongo_schemes() {
|
||
let primary_uri = validate_uri(
|
||
"mongodb://studio_stock_bot_read:PRIMARY_CASE_PASS@localhost:27017/stock?authSource=stock",
|
||
);
|
||
let upper_secret = "UPPER_SCHEME_SECRET_777";
|
||
let mixed_secret = "MIXED_SRV_SECRET_888";
|
||
let diagnostic = format!(
|
||
"tried MONGODB://reader:{upper_secret}@10.0.0.51:27017/stock then MongoDB+SRV://srvuser:{mixed_secret}@cluster.internal/stock"
|
||
);
|
||
|
||
let err = MongoStreamError::redacted_source(&diagnostic, &primary_uri);
|
||
let display_out = format!("{err}");
|
||
let debug_out = format!("{err:?}");
|
||
|
||
for secret in ["PRIMARY_CASE_PASS", upper_secret, mixed_secret] {
|
||
assert!(
|
||
!display_out.contains(secret),
|
||
"Display leaked `{secret}` under uppercase/mixed-case scheme: {display_out}"
|
||
);
|
||
assert!(
|
||
!debug_out.contains(secret),
|
||
"Debug leaked `{secret}` under uppercase/mixed-case scheme: {debug_out}"
|
||
);
|
||
}
|
||
assert!(
|
||
display_out.contains("[REDACTED]@10.0.0.51:27017/stock"),
|
||
"expected redacted MONGODB:// URI in Display: {display_out}"
|
||
);
|
||
assert!(
|
||
display_out.contains("[REDACTED]@cluster.internal/stock"),
|
||
"expected redacted MongoDB+SRV:// URI in Display: {display_out}"
|
||
);
|
||
assert!(debug_out.contains("[REDACTED]"));
|
||
}
|
||
|
||
#[test]
|
||
fn error_redaction_scrubs_repeated_password_occurrences_across_message() {
|
||
let repeated_pass = "REPEATED_SENTINEL_PASS_4242";
|
||
let primary_uri_str = format!(
|
||
"mongodb://studio_stock_bot_read:{repeated_pass}@localhost:27017/stock?authSource=stock"
|
||
);
|
||
let primary_uri = validate_uri(&primary_uri_str);
|
||
let diagnostic = format!(
|
||
"attempt1={primary_uri_str}; raw1={repeated_pass}; fallback=mongodb://alt:{repeated_pass}@10.0.0.51:27017/stock; raw2={repeated_pass}; attempt2={primary_uri_str}"
|
||
);
|
||
|
||
let err = MongoStreamError::redacted_source(&diagnostic, &primary_uri);
|
||
let display_out = format!("{err}");
|
||
let debug_out = format!("{err:?}");
|
||
|
||
assert!(
|
||
!display_out.contains(repeated_pass),
|
||
"Display leaked repeated password: {display_out}"
|
||
);
|
||
assert!(
|
||
!debug_out.contains(repeated_pass),
|
||
"Debug leaked repeated password: {debug_out}"
|
||
);
|
||
assert!(
|
||
display_out.matches("[REDACTED]").count() >= 5,
|
||
"expected every occurrence to be redacted in Display: {display_out}"
|
||
);
|
||
assert!(
|
||
debug_out.matches("[REDACTED]").count() >= 5,
|
||
"expected every occurrence to be redacted in Debug: {debug_out}"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn cli_to_read_spec_for_collection_uses_bson_datetime_for_qm_earnings_and_iso_string_for_filings() {
|
||
let opts = super::MongoCliOptions {
|
||
date_gte: Some("2017-01-01".to_owned()),
|
||
date_lt: Some("2025-02-13".to_owned()),
|
||
..super::MongoCliOptions::default()
|
||
};
|
||
|
||
let filings_spec = opts.to_read_spec_for_collection(SourceCollection::QmFilings, None, true);
|
||
let filings_doc = build_filter_document(SourceCollection::QmFilings, &filings_spec)
|
||
.expect("qmFilings string filter must succeed");
|
||
let tf = filings_doc
|
||
.get_document("timefiled")
|
||
.expect("timefiled subdocument");
|
||
assert_eq!(tf.get("$gte"), Some(&Bson::String("2017-01-01".to_owned())));
|
||
assert_eq!(tf.get("$lt"), Some(&Bson::String("2025-02-13".to_owned())));
|
||
|
||
let earnings_spec = opts.to_read_spec_for_collection(SourceCollection::QmEarnings, None, true);
|
||
let earnings_doc = build_filter_document(SourceCollection::QmEarnings, &earnings_spec)
|
||
.expect("qmEarnings DateTime filter must succeed");
|
||
let rd = earnings_doc
|
||
.get_document("reportDate")
|
||
.expect("reportDate subdocument");
|
||
// 2017-01-01T00:00:00Z = 1483228800000 ms; 2025-02-13T00:00:00Z = 1739404800000 ms
|
||
assert_eq!(
|
||
rd.get("$gte"),
|
||
Some(&Bson::DateTime(DateTime::from_millis(1_483_228_800_000)))
|
||
);
|
||
assert_eq!(
|
||
rd.get("$lt"),
|
||
Some(&Bson::DateTime(DateTime::from_millis(1_739_404_800_000)))
|
||
);
|
||
}
|