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

1227 lines
41 KiB
Rust

//! Bounded-memory streaming reader for concatenated raw BSON (`M1.2y`).
//!
//! Reads length-prefixed raw BSON documents from any [`std::io::Read`] source (files, stdin pipes,
//! or future cursor adapters) into a single reused byte buffer with a fixed memory ceiling,
//! framing only complete documents into [`RawBsonChunk`] slices that can be passed directly to the
//! existing zero-copy decoders (`decode_eod_price_buffer`, `decode_qm_split_buffer`,
//! `decode_qm_dividend_buffer`).
//!
//! # Callback Lifetime Bound (`for<'a>`)
//!
//! Because [`RawBsonChunkReader`] reuses one internal byte buffer across chunks, borrowed zero-copy
//! document views ([`RawEodDailyBar<'a>`], [`RawQmSplit<'a>`], [`RawQmDividend<'a>`]) only remain
//! valid for the duration of the chunk in which they were decoded. The streaming decode helpers
//! ([`decode_eod_price_stream`], [`decode_qm_split_stream`], [`decode_qm_dividend_stream`], and
//! their `*_chunks` counterparts) therefore require higher-ranked callbacks
//! (`F: for<'a> FnMut(RawEodDailyBar<'a>)`, etc.) so closures cannot escape borrowed slices past a
//! chunk boundary. Callers should map or intern borrowed keys (e.g. via
//! `ProviderMappingTable::resolve`) or copy only the retained fields inside the callback.
use std::error::Error;
use std::fmt;
use std::io;
use crate::bson_ceo_shorts::{
decode_ceo_shorts_buffer, BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames,
};
use crate::bson_eod_intraday::{
decode_eod_intraday_buffer, BsonEodIntradayDecodeStats, BsonEodIntradayError,
RawEodIntradayBar,
};
use crate::bson_eod_prices::{
decode_eod_price_buffer, BsonEodDecodeStats, BsonEodPriceError, RawEodDailyBar,
};
use crate::bson_qm_actions::{
decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, BsonQmActionError,
RawQmDividend, RawQmSplit,
};
use crate::bson_qm_events::{
decode_qm_earning_buffer, decode_qm_filing_buffer, BsonQmEarningsDecodeStats,
BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames, QmFilingsFieldNames,
RawQmEarning, RawQmFiling,
};
use crate::bson_qm_intraday::{
decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError, RawQmIntradayBar,
};
use crate::bson_qm_prices::{
decode_qm_price_buffer, BsonQmPriceDecodeStats, BsonQmPriceError, RawQmPrice,
};
use crate::bson_te_market_data::{
decode_te_market_data_buffer, BsonTeMarketDataDecodeStats, BsonTeMarketDataError,
};
use crate::fx::FxDailyBar;
use crate::shorts::CeoShortReport;
/// Default chunk buffer capacity: 8 MiB.
pub const DEFAULT_CHUNK_CAPACITY_BYTES: usize = 8 * 1024 * 1024;
/// Default maximum allowed BSON document size: 16 MiB (MongoDB limit) + 16 KiB headroom.
pub const DEFAULT_MAX_DOC_BYTES: usize = 16 * 1024 * 1024 + 16 * 1024;
/// Minimum valid length-prefixed BSON document size (4-byte length prefix + trailing `0x00`).
pub const MIN_BSON_DOC_BYTES: usize = 5;
/// Configuration options for [`RawBsonChunkReader`] and the `decode_*_stream` helpers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BsonStreamOptions {
/// Initial reusable buffer size in bytes (capped at `max_doc_bytes`). Must be `> 0`.
pub chunk_capacity_bytes: usize,
/// Hard upper bound on any single BSON document's declared byte length. Must be `>= 5`.
pub max_doc_bytes: usize,
}
impl Default for BsonStreamOptions {
#[inline]
fn default() -> Self {
Self {
chunk_capacity_bytes: DEFAULT_CHUNK_CAPACITY_BYTES,
max_doc_bytes: DEFAULT_MAX_DOC_BYTES,
}
}
}
impl BsonStreamOptions {
/// Validates option invariants, rejecting `chunk_capacity_bytes == 0` and `max_doc_bytes < 5`.
#[inline]
pub fn validate(&self) -> Result<(), BsonStreamError> {
if self.chunk_capacity_bytes == 0 {
return Err(BsonStreamError::InvalidChunkCapacity);
}
if self.max_doc_bytes < MIN_BSON_DOC_BYTES {
return Err(BsonStreamError::InvalidMaxDocBytes);
}
Ok(())
}
}
/// Terminal errors returned by [`RawBsonChunkReader`] and the `decode_*_stream` helpers.
///
/// Every stream-level framing or I/O error carries the absolute byte `offset` of the offending
/// document in the underlying stream.
#[derive(Debug)]
pub enum BsonStreamError {
/// `BsonStreamOptions::chunk_capacity_bytes` was `0`.
InvalidChunkCapacity,
/// `BsonStreamOptions::max_doc_bytes` was `< 5`.
InvalidMaxDocBytes,
/// Declared 4-byte little-endian BSON document length was `< 5` or `> max_doc_bytes`.
CorruptDocumentLength {
offset: u64,
declared_len: i32,
max_doc_bytes: usize,
},
/// Stream reached EOF mid-header (`declared_len == None`) or mid-document (`Some(len)`).
TruncatedDocument {
offset: u64,
remaining: usize,
declared_len: Option<i32>,
},
/// Underlying [`std::io::Read`] failed with a non-`Interrupted` error.
Io { offset: u64, source: io::Error },
}
impl fmt::Display for BsonStreamError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidChunkCapacity => {
write!(f, "invalid BSON stream chunk_capacity_bytes: must be > 0")
}
Self::InvalidMaxDocBytes => {
write!(
f,
"invalid BSON stream max_doc_bytes: must be >= {MIN_BSON_DOC_BYTES}"
)
}
Self::CorruptDocumentLength {
offset,
declared_len,
max_doc_bytes,
} => write!(
f,
"corrupt BSON document length {declared_len} at stream offset {offset} (valid range: {MIN_BSON_DOC_BYTES}..={max_doc_bytes})"
),
Self::TruncatedDocument {
offset,
remaining,
declared_len,
} => match declared_len {
Some(len) => write!(
f,
"truncated BSON document at stream offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
),
None => write!(
f,
"truncated BSON document header at stream offset {offset}: only {remaining} bytes remaining"
),
},
Self::Io { offset, source } => {
write!(
f,
"I/O error reading BSON stream at offset {offset}: {source}"
)
}
}
}
}
impl Error for BsonStreamError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
_ => None,
}
}
}
/// A borrowed chunk of complete, length-prefixed raw BSON documents from [`RawBsonChunkReader`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RawBsonChunk<'a> {
/// Contiguous bytes containing one or more complete length-prefixed BSON documents.
pub bytes: &'a [u8],
/// Absolute byte offset of `bytes[0]` from the start of the underlying stream.
pub start_offset: u64,
}
#[derive(Debug, Clone)]
enum StickyError {
CorruptDocumentLength {
offset: u64,
declared_len: i32,
max_doc_bytes: usize,
},
TruncatedDocument {
offset: u64,
remaining: usize,
declared_len: Option<i32>,
},
Io {
offset: u64,
kind: io::ErrorKind,
message: String,
},
}
impl StickyError {
fn to_error(&self) -> BsonStreamError {
match self {
Self::CorruptDocumentLength {
offset,
declared_len,
max_doc_bytes,
} => BsonStreamError::CorruptDocumentLength {
offset: *offset,
declared_len: *declared_len,
max_doc_bytes: *max_doc_bytes,
},
Self::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonStreamError::TruncatedDocument {
offset: *offset,
remaining: *remaining,
declared_len: *declared_len,
},
Self::Io {
offset,
kind,
message,
} => BsonStreamError::Io {
offset: *offset,
source: io::Error::new(*kind, message.clone()),
},
}
}
}
#[derive(Debug)]
enum TerminalState {
Active,
Eof,
Failed(StickyError),
}
#[inline]
fn read_i32_le(bytes: &[u8]) -> i32 {
i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
}
/// Bounded-memory chunked reader for concatenated length-prefixed raw BSON documents.
///
/// Reuses a single internal byte buffer across all calls to [`Self::next_chunk`], carrying any
/// trailing partial document to the front of the buffer before the next fill. The initial
/// allocation is capped at `min(options.chunk_capacity_bytes, options.max_doc_bytes)`; the buffer
/// grows only when a single document exceeds the current buffer length (or to 4 bytes when
/// `chunk_capacity_bytes < 4`), and never beyond `options.max_doc_bytes`.
pub struct RawBsonChunkReader<R: io::Read> {
reader: R,
options: BsonStreamOptions,
buf: Vec<u8>,
filled: usize,
consumed: usize,
buf_start_offset: u64,
bytes_read: u64,
docs_framed: u64,
eof_reached: bool,
pending_io_err: Option<io::Error>,
terminal: TerminalState,
}
impl<R: io::Read> RawBsonChunkReader<R> {
/// Creates a new chunk reader with [`BsonStreamOptions::default`].
pub fn new(reader: R) -> Self {
let options = BsonStreamOptions::default();
let initial_cap = options.chunk_capacity_bytes.min(options.max_doc_bytes);
Self {
reader,
options,
buf: vec![0u8; initial_cap],
filled: 0,
consumed: 0,
buf_start_offset: 0,
bytes_read: 0,
docs_framed: 0,
eof_reached: false,
pending_io_err: None,
terminal: TerminalState::Active,
}
}
/// Creates a new chunk reader with explicit [`BsonStreamOptions`], validating them up front.
pub fn with_options(reader: R, options: BsonStreamOptions) -> Result<Self, BsonStreamError> {
options.validate()?;
let initial_cap = options.chunk_capacity_bytes.min(options.max_doc_bytes);
Ok(Self {
reader,
options,
buf: vec![0u8; initial_cap],
filled: 0,
consumed: 0,
buf_start_offset: 0,
bytes_read: 0,
docs_framed: 0,
eof_reached: false,
pending_io_err: None,
terminal: TerminalState::Active,
})
}
/// Returns the configured stream options.
#[inline]
pub fn options(&self) -> BsonStreamOptions {
self.options
}
/// Returns the current allocated capacity of the reusable internal buffer in bytes.
#[inline]
pub fn buffer_capacity(&self) -> usize {
self.buf.capacity()
}
/// Returns the total number of bytes read from the underlying reader so far.
#[inline]
pub fn bytes_read(&self) -> u64 {
self.bytes_read
}
/// Returns the total number of complete length-prefixed documents framed and yielded so far.
#[inline]
pub fn docs_framed(&self) -> u64 {
self.docs_framed
}
/// Consumes the chunk reader, returning the underlying [`std::io::Read`] source.
#[inline]
pub fn into_inner(self) -> R {
self.reader
}
/// Grows `self.buf` to exactly `target_len` without doubling past `max_doc_bytes`.
fn grow_buf_exact(&mut self, target_len: usize) {
debug_assert!(target_len <= self.options.max_doc_bytes);
if target_len > self.buf.len() {
if target_len > self.buf.capacity() {
self.buf.reserve_exact(target_len - self.buf.len());
}
self.buf.resize(target_len, 0);
}
}
/// Reads and frames the next chunk of complete length-prefixed BSON documents.
///
/// Returns `Ok(None)` at clean EOF. Any terminal framing or I/O error locks the reader into a
/// failed state so subsequent calls continue returning an error without panicking or looping.
pub fn next_chunk(&mut self) -> Result<Option<RawBsonChunk<'_>>, BsonStreamError> {
match &self.terminal {
TerminalState::Active => {}
TerminalState::Eof => return Ok(None),
TerminalState::Failed(err) => return Err(err.to_error()),
}
// Compact bytes already yielded by the previous chunk.
if self.consumed > 0 {
if self.consumed < self.filled {
self.buf.copy_within(self.consumed..self.filled, 0);
}
self.filled -= self.consumed;
self.buf_start_offset += self.consumed as u64;
self.consumed = 0;
}
let mut chunk_end = 0usize;
let mut chunk_docs = 0u64;
loop {
// Incrementally frame complete documents as bytes arrive so a corrupt length prefix
// stops the fill loop immediately without issuing further reads.
let mut saw_corrupt_len = false;
while self.filled - chunk_end >= 4 {
let declared_len = read_i32_le(&self.buf[chunk_end..chunk_end + 4]);
if declared_len < MIN_BSON_DOC_BYTES as i32
|| (declared_len as usize) > self.options.max_doc_bytes
{
if chunk_end == 0 {
let err = StickyError::CorruptDocumentLength {
offset: self.buf_start_offset,
declared_len,
max_doc_bytes: self.options.max_doc_bytes,
};
self.terminal = TerminalState::Failed(err.clone());
return Err(err.to_error());
}
// Yield any complete preceding documents first; the next call will compact
// this corrupt header to index 0 and surface `CorruptDocumentLength`.
saw_corrupt_len = true;
break;
}
let doc_len = declared_len as usize;
if chunk_end == 0
&& doc_len > self.buf.len()
&& !self.eof_reached
&& self.pending_io_err.is_none()
{
self.grow_buf_exact(doc_len);
}
if doc_len > self.filled - chunk_end {
break;
}
chunk_end += doc_len;
chunk_docs += 1;
}
if saw_corrupt_len || self.eof_reached || self.pending_io_err.is_some() {
break;
}
if self.filled == self.buf.len() {
if self.filled < 4 {
// `chunk_capacity_bytes` was in `1..=3`; grow to 4 bytes (always <= max_doc_bytes).
self.grow_buf_exact(4);
} else {
// Buffer is full and the leading document fit in `self.buf.len()`, so at least
// one complete document is ready to yield.
break;
}
}
match self.reader.read(&mut self.buf[self.filled..]) {
Ok(0) => {
self.eof_reached = true;
break;
}
Ok(n) => {
self.filled += n;
self.bytes_read += n as u64;
}
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
Err(err) => {
self.pending_io_err = Some(err);
break;
}
}
}
if chunk_end > 0 {
self.consumed = chunk_end;
self.docs_framed += chunk_docs;
return Ok(Some(RawBsonChunk {
bytes: &self.buf[..chunk_end],
start_offset: self.buf_start_offset,
}));
}
// No complete document could be framed; surface pending I/O error, clean EOF, or truncation.
if let Some(source) = self.pending_io_err.take() {
let offset = self.buf_start_offset;
self.terminal = TerminalState::Failed(StickyError::Io {
offset,
kind: source.kind(),
message: source.to_string(),
});
return Err(BsonStreamError::Io { offset, source });
}
if self.filled == 0 {
self.terminal = TerminalState::Eof;
return Ok(None);
}
let declared_len = if self.filled >= 4 {
Some(read_i32_le(&self.buf[0..4]))
} else {
None
};
let err = StickyError::TruncatedDocument {
offset: self.buf_start_offset,
remaining: self.filled,
declared_len,
};
self.terminal = TerminalState::Failed(err.clone());
Err(err.to_error())
}
}
#[inline]
fn rebase_offset(base: u64, local: usize) -> usize {
let abs = base.saturating_add(local as u64);
usize::try_from(abs).unwrap_or(usize::MAX)
}
#[inline]
fn rebase_eod_error(base: u64, err: BsonEodPriceError) -> BsonEodPriceError {
match err {
BsonEodPriceError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonEodPriceError::TruncatedDocument {
offset: rebase_offset(base, offset),
remaining,
declared_len,
},
BsonEodPriceError::CorruptDocumentLength {
offset,
declared_len,
} => BsonEodPriceError::CorruptDocumentLength {
offset: rebase_offset(base, offset),
declared_len,
},
BsonEodPriceError::CorruptBson { offset, detail } => BsonEodPriceError::CorruptBson {
offset: rebase_offset(base, offset),
detail,
},
other => other,
}
}
#[inline]
fn rebase_qm_error(base: u64, err: BsonQmActionError) -> BsonQmActionError {
match err {
BsonQmActionError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonQmActionError::TruncatedDocument {
offset: rebase_offset(base, offset),
remaining,
declared_len,
},
BsonQmActionError::CorruptDocumentLength {
offset,
declared_len,
} => BsonQmActionError::CorruptDocumentLength {
offset: rebase_offset(base, offset),
declared_len,
},
BsonQmActionError::CorruptBson { offset, detail } => BsonQmActionError::CorruptBson {
offset: rebase_offset(base, offset),
detail,
},
other => other,
}
}
#[inline]
fn rebase_eod_intraday_error(base: u64, err: BsonEodIntradayError) -> BsonEodIntradayError {
match err {
BsonEodIntradayError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonEodIntradayError::TruncatedDocument {
offset: rebase_offset(base, offset),
remaining,
declared_len,
},
BsonEodIntradayError::CorruptDocumentLength {
offset,
declared_len,
} => BsonEodIntradayError::CorruptDocumentLength {
offset: rebase_offset(base, offset),
declared_len,
},
BsonEodIntradayError::CorruptBson { offset, detail } => {
BsonEodIntradayError::CorruptBson {
offset: rebase_offset(base, offset),
detail,
}
}
other => other,
}
}
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_intraday_buffer`],
/// accumulating [`BsonEodIntradayDecodeStats`] and rebasing per-document error offsets to
/// absolute stream byte offsets.
pub fn decode_eod_intraday_chunks<R, F, E>(
reader: &mut RawBsonChunkReader<R>,
mut on_bar: F,
mut on_error: E,
) -> Result<BsonEodIntradayDecodeStats, BsonStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawEodIntradayBar<'a>),
E: FnMut(u64, BsonEodIntradayError),
{
let mut total = BsonEodIntradayDecodeStats::default();
while let Some(chunk) = reader.next_chunk()? {
let base = chunk.start_offset;
let chunk_stats = decode_eod_intraday_buffer(
chunk.bytes,
&mut on_bar,
|local_offset, err| {
let abs_offset = base + local_offset as u64;
on_error(abs_offset, rebase_eod_intraday_error(base, err));
},
);
total += chunk_stats;
}
Ok(total)
}
/// Streams a concatenated raw BSON `eodIntraday1M` [`std::io::Read`] source through
/// [`decode_eod_intraday_buffer`] with bounded memory.
///
/// Per-document decode errors are reported to `on_error` with their absolute stream byte offset
/// and skipped; stream-level framing or I/O errors return `Err(BsonStreamError)`.
pub fn decode_eod_intraday_stream<R, F, E>(
reader: R,
options: BsonStreamOptions,
on_bar: F,
on_error: E,
) -> Result<BsonEodIntradayDecodeStats, BsonStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawEodIntradayBar<'a>),
E: FnMut(u64, BsonEodIntradayError),
{
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
decode_eod_intraday_chunks(&mut chunk_reader, on_bar, on_error)
}
#[inline]
fn rebase_qm_intraday_error(base: u64, err: BsonQmIntradayError) -> BsonQmIntradayError {
match err {
BsonQmIntradayError::CorruptBson { offset, detail } => BsonQmIntradayError::CorruptBson {
offset: rebase_offset(base, offset),
detail,
},
other => other,
}
}
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_intraday_buffer`],
/// accumulating [`BsonQmIntradayDecodeStats`] and rebasing per-document error offsets to
/// absolute stream byte offsets.
pub fn decode_qm_intraday_chunks<R, F, E>(
reader: &mut RawBsonChunkReader<R>,
mut on_bar: F,
mut on_error: E,
) -> Result<BsonQmIntradayDecodeStats, BsonStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawQmIntradayBar<'a>),
E: FnMut(u64, BsonQmIntradayError),
{
let mut total = BsonQmIntradayDecodeStats::default();
while let Some(chunk) = reader.next_chunk()? {
let base = chunk.start_offset;
let chunk_stats = decode_qm_intraday_buffer(
chunk.bytes,
&mut on_bar,
|local_offset, err| {
let abs_offset = base + local_offset as u64;
on_error(abs_offset, rebase_qm_intraday_error(base, err));
},
);
total += chunk_stats;
}
Ok(total)
}
/// Streams a concatenated raw BSON `qmIntraday` [`std::io::Read`] source through
/// [`decode_qm_intraday_buffer`] with bounded memory.
///
/// Per-document decode errors are reported to `on_error` with their absolute stream byte offset
/// and skipped; stream-level framing or I/O errors return `Err(BsonStreamError)`.
pub fn decode_qm_intraday_stream<R, F, E>(
reader: R,
options: BsonStreamOptions,
on_bar: F,
on_error: E,
) -> Result<BsonQmIntradayDecodeStats, BsonStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawQmIntradayBar<'a>),
E: FnMut(u64, BsonQmIntradayError),
{
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
decode_qm_intraday_chunks(&mut chunk_reader, on_bar, on_error)
}
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_price_buffer`],
/// accumulating [`BsonEodDecodeStats`] and rebasing per-document error offsets to absolute stream
/// byte offsets.
pub fn decode_eod_price_chunks<R, F, E>(
reader: &mut RawBsonChunkReader<R>,
mut on_bar: F,
mut on_error: E,
) -> Result<BsonEodDecodeStats, BsonStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawEodDailyBar<'a>),
E: FnMut(u64, BsonEodPriceError),
{
let mut total = BsonEodDecodeStats::default();
while let Some(chunk) = reader.next_chunk()? {
let base = chunk.start_offset;
let chunk_stats = decode_eod_price_buffer(
chunk.bytes,
&mut on_bar,
|local_offset, err| {
let abs_offset = base + local_offset as u64;
on_error(abs_offset, rebase_eod_error(base, err));
},
);
total += chunk_stats;
}
Ok(total)
}
/// Streams a concatenated raw BSON `eodPrices` [`std::io::Read`] source through
/// [`decode_eod_price_buffer`] with bounded memory.
///
/// Per-document decode errors are reported to `on_error` with their absolute stream byte offset
/// and skipped; stream-level framing or I/O errors return `Err(BsonStreamError)`.
pub fn decode_eod_price_stream<R, F, E>(
reader: R,
options: BsonStreamOptions,
on_bar: F,
on_error: E,
) -> Result<BsonEodDecodeStats, BsonStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawEodDailyBar<'a>),
E: FnMut(u64, BsonEodPriceError),
{
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
decode_eod_price_chunks(&mut chunk_reader, on_bar, on_error)
}
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_split_buffer`],
/// accumulating [`BsonQmActionDecodeStats`] and rebasing per-document error offsets to absolute
/// stream byte offsets.
pub fn decode_qm_split_chunks<R, F, E>(
reader: &mut RawBsonChunkReader<R>,
mut on_split: F,
mut on_error: E,
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawQmSplit<'a>),
E: FnMut(u64, BsonQmActionError),
{
let mut total = BsonQmActionDecodeStats::default();
while let Some(chunk) = reader.next_chunk()? {
let base = chunk.start_offset;
let chunk_stats = decode_qm_split_buffer(
chunk.bytes,
&mut on_split,
|local_offset, err| {
let abs_offset = base + local_offset as u64;
on_error(abs_offset, rebase_qm_error(base, err));
},
);
total += chunk_stats;
}
Ok(total)
}
/// Streams a concatenated raw BSON `qmSplits` [`std::io::Read`] source through
/// [`decode_qm_split_buffer`] with bounded memory.
pub fn decode_qm_split_stream<R, F, E>(
reader: R,
options: BsonStreamOptions,
on_split: F,
on_error: E,
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawQmSplit<'a>),
E: FnMut(u64, BsonQmActionError),
{
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
decode_qm_split_chunks(&mut chunk_reader, on_split, on_error)
}
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_dividend_buffer`],
/// accumulating [`BsonQmActionDecodeStats`] and rebasing per-document error offsets to absolute
/// stream byte offsets.
pub fn decode_qm_dividend_chunks<R, F, E>(
reader: &mut RawBsonChunkReader<R>,
mut on_dividend: F,
mut on_error: E,
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawQmDividend<'a>),
E: FnMut(u64, BsonQmActionError),
{
let mut total = BsonQmActionDecodeStats::default();
while let Some(chunk) = reader.next_chunk()? {
let base = chunk.start_offset;
let chunk_stats = decode_qm_dividend_buffer(
chunk.bytes,
&mut on_dividend,
|local_offset, err| {
let abs_offset = base + local_offset as u64;
on_error(abs_offset, rebase_qm_error(base, err));
},
);
total += chunk_stats;
}
Ok(total)
}
/// Streams a concatenated raw BSON `qmDividends` [`std::io::Read`] source through
/// [`decode_qm_dividend_buffer`] with bounded memory.
pub fn decode_qm_dividend_stream<R, F, E>(
reader: R,
options: BsonStreamOptions,
on_dividend: F,
on_error: E,
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawQmDividend<'a>),
E: FnMut(u64, BsonQmActionError),
{
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
decode_qm_dividend_chunks(&mut chunk_reader, on_dividend, on_error)
}
#[inline]
fn rebase_qm_price_error(base: u64, err: BsonQmPriceError) -> BsonQmPriceError {
match err {
BsonQmPriceError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonQmPriceError::TruncatedDocument {
offset: rebase_offset(base, offset),
remaining,
declared_len,
},
BsonQmPriceError::CorruptDocumentLength {
offset,
declared_len,
} => BsonQmPriceError::CorruptDocumentLength {
offset: rebase_offset(base, offset),
declared_len,
},
BsonQmPriceError::CorruptBson { offset, detail } => BsonQmPriceError::CorruptBson {
offset: rebase_offset(base, offset),
detail,
},
other => other,
}
}
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_price_buffer`],
/// accumulating [`BsonQmPriceDecodeStats`] and rebasing per-document error offsets to absolute
/// stream byte offsets.
pub fn decode_qm_price_chunks<R, F, E>(
reader: &mut RawBsonChunkReader<R>,
mut on_price: F,
mut on_error: E,
) -> Result<BsonQmPriceDecodeStats, BsonStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawQmPrice<'a>),
E: FnMut(u64, BsonQmPriceError),
{
let mut total = BsonQmPriceDecodeStats::default();
while let Some(chunk) = reader.next_chunk()? {
let base = chunk.start_offset;
let chunk_stats = decode_qm_price_buffer(chunk.bytes, &mut on_price, |local_offset, err| {
let abs_offset = base + local_offset as u64;
on_error(abs_offset, rebase_qm_price_error(base, err));
});
total += chunk_stats;
}
Ok(total)
}
/// Streams a concatenated raw BSON `qmPrices` [`std::io::Read`] source through
/// [`decode_qm_price_buffer`] with bounded memory.
pub fn decode_qm_price_stream<R, F, E>(
reader: R,
options: BsonStreamOptions,
on_price: F,
on_error: E,
) -> Result<BsonQmPriceDecodeStats, BsonStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawQmPrice<'a>),
E: FnMut(u64, BsonQmPriceError),
{
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
decode_qm_price_chunks(&mut chunk_reader, on_price, on_error)
}
#[inline]
fn rebase_te_error(base: u64, err: BsonTeMarketDataError) -> BsonTeMarketDataError {
match err {
BsonTeMarketDataError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonTeMarketDataError::TruncatedDocument {
offset: rebase_offset(base, offset),
remaining,
declared_len,
},
BsonTeMarketDataError::CorruptDocumentLength {
offset,
declared_len,
} => BsonTeMarketDataError::CorruptDocumentLength {
offset: rebase_offset(base, offset),
declared_len,
},
BsonTeMarketDataError::CorruptBson { offset, detail } => {
BsonTeMarketDataError::CorruptBson {
offset: rebase_offset(base, offset),
detail,
}
}
BsonTeMarketDataError::CorruptPointBson {
offset,
point_index,
detail,
} => BsonTeMarketDataError::CorruptPointBson {
offset: rebase_offset(base, offset),
point_index,
detail,
},
other => other,
}
}
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_te_market_data_buffer`],
/// accumulating [`BsonTeMarketDataDecodeStats`] and rebasing per-document and per-point error
/// offsets to absolute stream byte offsets.
pub fn decode_te_market_data_chunks<R, F, E>(
reader: &mut RawBsonChunkReader<R>,
target_symbol: &str,
mut on_bar: F,
mut on_error: E,
) -> Result<BsonTeMarketDataDecodeStats, BsonStreamError>
where
R: io::Read,
F: FnMut(FxDailyBar),
E: FnMut(u64, BsonTeMarketDataError),
{
let mut total = BsonTeMarketDataDecodeStats::default();
while let Some(chunk) = reader.next_chunk()? {
let base = chunk.start_offset;
let chunk_stats = decode_te_market_data_buffer(
chunk.bytes,
target_symbol,
&mut on_bar,
|local_offset, err| {
let abs_offset = base + local_offset as u64;
on_error(abs_offset, rebase_te_error(base, err));
},
);
total += chunk_stats;
}
Ok(total)
}
/// Streams a concatenated raw BSON `teMarketData` [`std::io::Read`] source through
/// [`decode_te_market_data_buffer`] with bounded memory.
pub fn decode_te_market_data_stream<R, F, E>(
reader: R,
options: BsonStreamOptions,
target_symbol: &str,
on_bar: F,
on_error: E,
) -> Result<BsonTeMarketDataDecodeStats, BsonStreamError>
where
R: io::Read,
F: FnMut(FxDailyBar),
E: FnMut(u64, BsonTeMarketDataError),
{
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
decode_te_market_data_chunks(&mut chunk_reader, target_symbol, on_bar, on_error)
}
/// Terminal error returned by [`decode_ceo_shorts_chunks`] and [`decode_ceo_shorts_stream`].
#[derive(Debug)]
pub enum BsonCeoShortsStreamError {
Stream(BsonStreamError),
Decode(BsonCeoShortsError),
}
impl fmt::Display for BsonCeoShortsStreamError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Stream(err) => write!(f, "{err}"),
Self::Decode(err) => write!(f, "{err}"),
}
}
}
impl Error for BsonCeoShortsStreamError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Stream(err) => Some(err),
Self::Decode(err) => Some(err),
}
}
}
impl From<BsonStreamError> for BsonCeoShortsStreamError {
fn from(err: BsonStreamError) -> Self {
Self::Stream(err)
}
}
impl From<BsonCeoShortsError> for BsonCeoShortsStreamError {
fn from(err: BsonCeoShortsError) -> Self {
Self::Decode(err)
}
}
#[inline]
fn rebase_ceo_shorts_error(base: u64, err: BsonCeoShortsError) -> BsonCeoShortsError {
match err {
BsonCeoShortsError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonCeoShortsError::TruncatedDocument {
offset: base.saturating_add(offset),
remaining,
declared_len,
},
BsonCeoShortsError::CorruptDocumentLength {
offset,
declared_len,
} => BsonCeoShortsError::CorruptDocumentLength {
offset: base.saturating_add(offset),
declared_len,
},
BsonCeoShortsError::CorruptBson { offset, detail } => BsonCeoShortsError::CorruptBson {
offset: base.saturating_add(offset),
detail,
},
other => other,
}
}
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_ceo_shorts_buffer`],
/// accumulating [`BsonCeoShortsDecodeStats`] and rebasing structural BSON error offsets to
/// absolute stream byte offsets.
pub fn decode_ceo_shorts_chunks<R, F>(
reader: &mut RawBsonChunkReader<R>,
fields: &CeoShortsFieldNames<'_>,
mut on_row: F,
) -> Result<BsonCeoShortsDecodeStats, BsonCeoShortsStreamError>
where
R: io::Read,
F: for<'a> FnMut(CeoShortReport<&'a str>),
{
fields.validate()?;
let mut total = BsonCeoShortsDecodeStats::default();
while let Some(chunk) = reader.next_chunk()? {
let base = chunk.start_offset;
let chunk_stats = decode_ceo_shorts_buffer(chunk.bytes, fields, &mut on_row)
.map_err(|err| BsonCeoShortsStreamError::Decode(rebase_ceo_shorts_error(base, err)))?;
total += chunk_stats;
}
Ok(total)
}
/// Streams a concatenated raw BSON `ceoShorts` [`std::io::Read`] source through
/// [`decode_ceo_shorts_buffer`] with bounded memory.
pub fn decode_ceo_shorts_stream<R, F>(
reader: R,
options: BsonStreamOptions,
fields: &CeoShortsFieldNames<'_>,
on_row: F,
) -> Result<BsonCeoShortsDecodeStats, BsonCeoShortsStreamError>
where
R: io::Read,
F: for<'a> FnMut(CeoShortReport<&'a str>),
{
fields.validate()?;
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
decode_ceo_shorts_chunks(&mut chunk_reader, fields, on_row)
}
/// Terminal error returned by [`decode_qm_filings_chunks`], [`decode_qm_filings_stream`],
/// [`decode_qm_earnings_chunks`], and [`decode_qm_earnings_stream`].
#[derive(Debug)]
pub enum BsonQmEventsStreamError {
Stream(BsonStreamError),
Decode(BsonQmEventsError),
}
impl fmt::Display for BsonQmEventsStreamError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Stream(err) => write!(f, "{err}"),
Self::Decode(err) => write!(f, "{err}"),
}
}
}
impl Error for BsonQmEventsStreamError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Stream(err) => Some(err),
Self::Decode(err) => Some(err),
}
}
}
impl From<BsonStreamError> for BsonQmEventsStreamError {
fn from(err: BsonStreamError) -> Self {
Self::Stream(err)
}
}
impl From<BsonQmEventsError> for BsonQmEventsStreamError {
fn from(err: BsonQmEventsError) -> Self {
Self::Decode(err)
}
}
#[inline]
fn rebase_qm_events_error(base: u64, err: BsonQmEventsError) -> BsonQmEventsError {
match err {
BsonQmEventsError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonQmEventsError::TruncatedDocument {
offset: base.saturating_add(offset),
remaining,
declared_len,
},
BsonQmEventsError::CorruptDocumentLength {
offset,
declared_len,
} => BsonQmEventsError::CorruptDocumentLength {
offset: base.saturating_add(offset),
declared_len,
},
BsonQmEventsError::CorruptBson { offset, detail } => BsonQmEventsError::CorruptBson {
offset: base.saturating_add(offset),
detail,
},
other => other,
}
}
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_filing_buffer`],
/// accumulating [`BsonQmFilingsDecodeStats`] and rebasing structural BSON error offsets to
/// absolute stream byte offsets.
pub fn decode_qm_filings_chunks<R, F>(
reader: &mut RawBsonChunkReader<R>,
fields: &QmFilingsFieldNames<'_>,
mut on_row: F,
) -> Result<BsonQmFilingsDecodeStats, BsonQmEventsStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawQmFiling<'a>),
{
fields.validate()?;
let mut total = BsonQmFilingsDecodeStats::default();
while let Some(chunk) = reader.next_chunk()? {
let base = chunk.start_offset;
let chunk_stats = decode_qm_filing_buffer(chunk.bytes, fields, &mut on_row)
.map_err(|err| BsonQmEventsStreamError::Decode(rebase_qm_events_error(base, err)))?;
total += chunk_stats;
}
Ok(total)
}
/// Streams a concatenated raw BSON `qmFilings` [`std::io::Read`] source through
/// [`decode_qm_filing_buffer`] with bounded memory.
pub fn decode_qm_filings_stream<R, F>(
reader: R,
options: BsonStreamOptions,
fields: &QmFilingsFieldNames<'_>,
on_row: F,
) -> Result<BsonQmFilingsDecodeStats, BsonQmEventsStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawQmFiling<'a>),
{
fields.validate()?;
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
decode_qm_filings_chunks(&mut chunk_reader, fields, on_row)
}
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_earning_buffer`],
/// accumulating [`BsonQmEarningsDecodeStats`] and rebasing structural BSON error offsets to
/// absolute stream byte offsets.
pub fn decode_qm_earnings_chunks<R, F>(
reader: &mut RawBsonChunkReader<R>,
fields: &QmEarningsFieldNames<'_>,
mut on_row: F,
) -> Result<BsonQmEarningsDecodeStats, BsonQmEventsStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawQmEarning<'a>),
{
fields.validate()?;
let mut total = BsonQmEarningsDecodeStats::default();
while let Some(chunk) = reader.next_chunk()? {
let base = chunk.start_offset;
let chunk_stats = decode_qm_earning_buffer(chunk.bytes, fields, &mut on_row)
.map_err(|err| BsonQmEventsStreamError::Decode(rebase_qm_events_error(base, err)))?;
total += chunk_stats;
}
Ok(total)
}
/// Streams a concatenated raw BSON `qmEarnings` [`std::io::Read`] source through
/// [`decode_qm_earning_buffer`] with bounded memory.
pub fn decode_qm_earnings_stream<R, F>(
reader: R,
options: BsonStreamOptions,
fields: &QmEarningsFieldNames<'_>,
on_row: F,
) -> Result<BsonQmEarningsDecodeStats, BsonQmEventsStreamError>
where
R: io::Read,
F: for<'a> FnMut(RawQmEarning<'a>),
{
fields.validate()?;
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
decode_qm_earnings_chunks(&mut chunk_reader, fields, on_row)
}
#[cfg(test)]
#[path = "bson_stream_tests.rs"]
mod tests;