322 lines
12 KiB
Rust
322 lines
12 KiB
Rust
//! QA contract tests for the public `mongo_stream` API (T-126 / M1.2al).
|
|
//!
|
|
//! Covers gaps left by `src/mongo_stream_tests.rs`, using only the public crate API and
|
|
//! in-memory sources (no MongoDB, no network):
|
|
//! - a source that fails exactly once is never polled again; the reader replays the same
|
|
//! sticky error (stashed-after-partial-write path and split-document path);
|
|
//! - an invalid frame after a valid one in the same `read()` is deferred, then sticky, and
|
|
//! never counted;
|
|
//! - seeded random documents + random read sizes: concatenated output is byte-identical to
|
|
//! the inputs, counters match, and `pending` never exceeds the largest single document;
|
|
//! - `RawBsonChunkReader` frames the adapter's output with the same chunks as a plain cursor;
|
|
//! - `with_max_doc_bytes` rejects ceilings below the BSON minimum; `into_inner` returns the
|
|
//! source at its current position;
|
|
//! - `build_filter_document` emits the exact key / `$gte` / `$lt` shape, and an empty spec
|
|
//! yields an empty filter;
|
|
//! - `MongoStreamError::redacted_source` (public path) hides the validated URI's password in
|
|
//! `Display` and `Debug` even when the raw URI is absent from the message.
|
|
|
|
use std::io::{self, Cursor, Read};
|
|
|
|
use bson::raw::{cstr, RawDocumentBuf};
|
|
use bson::{doc, Bson, DateTime};
|
|
use curate_etl::{
|
|
assert_read_only_mongo_uri, build_filter_document, FilterDateValue, LocalHosts, MongoDateRange,
|
|
MongoReadSpec, MongoStreamError, RawBsonChunkReader, RawBsonCursorReader, RawDocumentSource,
|
|
ReadOnlyPolicy, SliceRawDocumentSource, SourceCollection, VecRawDocumentSource,
|
|
MIN_BSON_DOC_BYTES,
|
|
};
|
|
|
|
struct SplitMix64(u64);
|
|
|
|
impl SplitMix64 {
|
|
fn next_u64(&mut self) -> u64 {
|
|
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
|
let mut z = self.0;
|
|
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
|
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
|
z ^ (z >> 31)
|
|
}
|
|
|
|
fn below(&mut self, n: u64) -> u64 {
|
|
self.next_u64() % n
|
|
}
|
|
}
|
|
|
|
fn doc_with_payload(tag: u64, payload_len: usize) -> Vec<u8> {
|
|
let mut doc = RawDocumentBuf::new();
|
|
doc.append(cstr!("tag"), tag as i64);
|
|
doc.append(cstr!("payload"), "x".repeat(payload_len));
|
|
doc.into_bytes()
|
|
}
|
|
|
|
/// Yields `docs`, fails exactly once at `fail_at`, and counts every poll.
|
|
struct FailOnceSource {
|
|
docs: Vec<Vec<u8>>,
|
|
index: usize,
|
|
fail_at: usize,
|
|
failed: bool,
|
|
polls: usize,
|
|
}
|
|
|
|
impl FailOnceSource {
|
|
fn new(docs: Vec<Vec<u8>>, fail_at: usize) -> Self {
|
|
Self {
|
|
docs,
|
|
index: 0,
|
|
fail_at,
|
|
failed: false,
|
|
polls: 0,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl RawDocumentSource for FailOnceSource {
|
|
fn next_raw_document(&mut self) -> Result<Option<&[u8]>, MongoStreamError> {
|
|
self.polls += 1;
|
|
if self.index == self.fail_at && !self.failed {
|
|
self.failed = true;
|
|
return Err(MongoStreamError::Source {
|
|
detail: "simulated cursor failure".to_owned(),
|
|
});
|
|
}
|
|
if self.index >= self.docs.len() {
|
|
return Ok(None);
|
|
}
|
|
let doc = self.docs[self.index].as_slice();
|
|
self.index += 1;
|
|
Ok(Some(doc))
|
|
}
|
|
}
|
|
|
|
fn downcast_stream_err(err: &io::Error) -> MongoStreamError {
|
|
err.get_ref()
|
|
.and_then(|e| e.downcast_ref::<MongoStreamError>())
|
|
.cloned()
|
|
.expect("io::Error must carry MongoStreamError")
|
|
}
|
|
|
|
#[test]
|
|
fn fail_once_source_after_split_document_is_not_repolled_and_error_is_sticky() {
|
|
let doc0 = doc_with_payload(0, 40);
|
|
let docs = vec![doc0.clone(), doc_with_payload(1, 40)];
|
|
let mut reader = RawBsonCursorReader::new(FailOnceSource::new(docs, 1));
|
|
|
|
let mut out = Vec::new();
|
|
let mut buf = [0u8; 7];
|
|
let err = loop {
|
|
match reader.read(&mut buf) {
|
|
Ok(0) => panic!("reader must not report EOF after a source failure"),
|
|
Ok(n) => out.extend_from_slice(&buf[..n]),
|
|
Err(err) => break err,
|
|
}
|
|
};
|
|
assert_eq!(
|
|
out, doc0,
|
|
"split document must be fully delivered before the error"
|
|
);
|
|
let first = downcast_stream_err(&err);
|
|
assert!(matches!(first, MongoStreamError::Source { .. }));
|
|
|
|
for _ in 0..3 {
|
|
let again = reader.read(&mut buf).expect_err("error must stay sticky");
|
|
assert_eq!(downcast_stream_err(&again), first);
|
|
}
|
|
assert_eq!(reader.docs_read(), 1);
|
|
assert_eq!(reader.bytes_read(), doc0.len() as u64);
|
|
assert_eq!(
|
|
reader.into_inner().polls,
|
|
2,
|
|
"sticky error must be replayed without polling the source again"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn fail_once_source_after_whole_document_returns_partial_then_sticky_without_repoll() {
|
|
let doc0 = doc_with_payload(0, 10);
|
|
let mut reader = RawBsonCursorReader::new(FailOnceSource::new(vec![doc0.clone()], 1));
|
|
|
|
let mut buf = [0u8; 4096];
|
|
let n = reader
|
|
.read(&mut buf)
|
|
.expect("first read returns the bytes already written");
|
|
assert_eq!(&buf[..n], doc0.as_slice());
|
|
|
|
let err = reader
|
|
.read(&mut buf)
|
|
.expect_err("stashed error surfaces on the next read");
|
|
let first = downcast_stream_err(&err);
|
|
let err2 = reader.read(&mut buf).expect_err("error stays sticky");
|
|
assert_eq!(downcast_stream_err(&err2), first);
|
|
assert_eq!(reader.docs_read(), 1);
|
|
assert_eq!(reader.into_inner().polls, 2);
|
|
}
|
|
|
|
#[test]
|
|
fn invalid_frame_after_valid_frame_is_deferred_sticky_and_uncounted() {
|
|
let good = doc_with_payload(7, 3);
|
|
let mut bad = doc_with_payload(8, 3);
|
|
let last = bad.len() - 1;
|
|
bad[last] = 0x01;
|
|
let docs: Vec<&[u8]> = vec![&good, &bad, &good];
|
|
let mut reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&docs));
|
|
|
|
let mut buf = [0u8; 4096];
|
|
let n = reader.read(&mut buf).expect("valid prefix delivered first");
|
|
assert_eq!(&buf[..n], good.as_slice());
|
|
|
|
let err = reader.read(&mut buf).expect_err("bad frame surfaces next");
|
|
match downcast_stream_err(&err) {
|
|
MongoStreamError::InvalidBsonFrame { doc_index, .. } => assert_eq!(doc_index, 1),
|
|
other => panic!("unexpected error: {other:?}"),
|
|
}
|
|
assert!(reader.read(&mut buf).is_err(), "error must stay sticky");
|
|
assert_eq!(reader.docs_read(), 1);
|
|
assert_eq!(reader.bytes_read(), good.len() as u64);
|
|
}
|
|
|
|
#[test]
|
|
fn seeded_random_documents_and_read_sizes_round_trip_byte_identically() {
|
|
let mut rng = SplitMix64(0x5EED_126A);
|
|
for _round in 0..40 {
|
|
let doc_count = rng.below(12) as usize;
|
|
let docs: Vec<Vec<u8>> = (0..doc_count)
|
|
.map(|i| doc_with_payload(i as u64, rng.below(600) as usize))
|
|
.collect();
|
|
let expected: Vec<u8> = docs.concat();
|
|
let largest = docs.iter().map(Vec::len).max().unwrap_or(0);
|
|
|
|
let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone()));
|
|
let mut out = Vec::new();
|
|
loop {
|
|
let step = 1 + rng.below(700) as usize;
|
|
let mut buf = vec![0u8; step];
|
|
let n = reader.read(&mut buf).expect("valid stream must read");
|
|
if n == 0 {
|
|
break;
|
|
}
|
|
out.extend_from_slice(&buf[..n]);
|
|
assert!(
|
|
reader.pending_capacity() <= largest,
|
|
"pending {} exceeds largest doc {largest}",
|
|
reader.pending_capacity()
|
|
);
|
|
}
|
|
assert_eq!(out, expected);
|
|
assert_eq!(reader.docs_read(), doc_count as u64);
|
|
assert_eq!(reader.bytes_read(), expected.len() as u64);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn chunk_reader_frames_cursor_output_identically_to_plain_cursor() {
|
|
let docs: Vec<Vec<u8>> = (0..50)
|
|
.map(|i| doc_with_payload(i, (i as usize * 37) % 900))
|
|
.collect();
|
|
let concat = docs.concat();
|
|
|
|
let collect = |mut chunker: RawBsonChunkReader<Box<dyn Read>>| {
|
|
let mut chunks = Vec::new();
|
|
while let Some(chunk) = chunker.next_chunk().expect("framing must succeed") {
|
|
chunks.push((chunk.start_offset, chunk.bytes.to_vec()));
|
|
}
|
|
chunks
|
|
};
|
|
let plain = collect(RawBsonChunkReader::new(Box::new(Cursor::new(
|
|
concat.clone(),
|
|
))));
|
|
let via_cursor = collect(RawBsonChunkReader::new(Box::new(RawBsonCursorReader::new(
|
|
VecRawDocumentSource::new(docs),
|
|
))));
|
|
|
|
let flatten =
|
|
|chunks: &[(u64, Vec<u8>)]| chunks.iter().flat_map(|c| c.1.clone()).collect::<Vec<u8>>();
|
|
assert_eq!(flatten(&plain), concat);
|
|
assert_eq!(flatten(&via_cursor), concat);
|
|
assert_eq!(via_cursor.first().map(|c| c.0), Some(0));
|
|
}
|
|
|
|
#[test]
|
|
fn with_max_doc_bytes_rejects_ceiling_below_bson_minimum() {
|
|
let empty: [&[u8]; 0] = [];
|
|
let err = RawBsonCursorReader::with_max_doc_bytes(
|
|
SliceRawDocumentSource::new(&empty),
|
|
MIN_BSON_DOC_BYTES - 1,
|
|
)
|
|
.err()
|
|
.expect("ceiling below minimum must be rejected");
|
|
assert!(matches!(err, MongoStreamError::InvalidMaxDocBytes { .. }));
|
|
assert!(RawBsonCursorReader::with_max_doc_bytes(
|
|
SliceRawDocumentSource::new(&empty),
|
|
MIN_BSON_DOC_BYTES
|
|
)
|
|
.is_ok());
|
|
}
|
|
|
|
#[test]
|
|
fn into_inner_returns_source_at_current_position() {
|
|
let docs = vec![doc_with_payload(0, 1), doc_with_payload(1, 1)];
|
|
let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone()));
|
|
let mut buf = vec![0u8; docs[0].len()];
|
|
reader.read_exact(&mut buf).expect("first doc");
|
|
let mut source = reader.into_inner();
|
|
let next = source
|
|
.next_raw_document()
|
|
.expect("source ok")
|
|
.map(<[u8]>::to_vec);
|
|
assert_eq!(next, Some(docs[1].clone()));
|
|
assert!(source.next_raw_document().expect("source ok").is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn build_filter_document_emits_exact_key_and_range_shape() {
|
|
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())),
|
|
}),
|
|
..MongoReadSpec::default()
|
|
};
|
|
let filter = build_filter_document(SourceCollection::EodPrices, &spec).expect("valid spec");
|
|
assert_eq!(
|
|
filter,
|
|
doc! { "eodSearchCode": "AAPL.US", "date": { "$gte": "2024-01-01", "$lt": "2025-01-01" } }
|
|
);
|
|
|
|
let ms_spec = MongoReadSpec {
|
|
date_range: Some(MongoDateRange {
|
|
gte: None,
|
|
lt: Some(FilterDateValue::BsonDateTimeMillis(1_700_000_000_000)),
|
|
}),
|
|
..MongoReadSpec::default()
|
|
};
|
|
let ms_filter = build_filter_document(SourceCollection::CeoShorts, &ms_spec).expect("valid");
|
|
assert_eq!(
|
|
ms_filter.get("timestamp"),
|
|
Some(&Bson::Document(
|
|
doc! { "$lt": DateTime::from_millis(1_700_000_000_000) }
|
|
))
|
|
);
|
|
|
|
let empty = build_filter_document(SourceCollection::TeMarketData, &MongoReadSpec::default())
|
|
.expect("default spec is valid");
|
|
assert!(empty.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn redacted_source_hides_validated_password_even_without_full_uri_in_message() {
|
|
let sentinel = "QA_SENTINEL_PW_4242";
|
|
let uri = assert_read_only_mongo_uri(
|
|
&format!("mongodb://studio_stock_bot_read:{sentinel}@localhost:27017/stock"),
|
|
&ReadOnlyPolicy::default(),
|
|
&LocalHosts::empty(),
|
|
)
|
|
.expect("valid read-only URI");
|
|
let raw = format!("SCRAM failure: password={sentinel}; retry with '{sentinel}'");
|
|
let err = MongoStreamError::redacted_source(&raw, &uri);
|
|
for rendered in [format!("{err}"), format!("{err:?}")] {
|
|
assert!(!rendered.contains(sentinel), "leaked: {rendered}");
|
|
assert!(rendered.contains("[REDACTED]"));
|
|
}
|
|
}
|