839 lines
30 KiB
Rust
839 lines
30 KiB
Rust
//! Zero-copy raw BSON decoder for MongoDB `teMarketData` documents (`M1.2ac`).
|
|
//!
|
|
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without
|
|
//! allocating a `bson::Document` or per-point heap memory, emitting [`FxDailyBar`] values via a
|
|
//! caller-supplied callback.
|
|
//!
|
|
//! # Empirical Field Contract & Unverified Assumptions
|
|
//!
|
|
//! - Field names are derived from the ingestion writer in
|
|
//! `apps/stock/data-ingestion/src/handlers/te/actions/market-data-fetch.action.ts`
|
|
//! (`teSymbol`, `daily: [{ t, o, h, l, c, pc, ac }]`, `monthly`), and isolated in the
|
|
//! `pub const FIELD_*` constants below. They have **not** yet been verified against a live
|
|
//! `mongodump` of `teMarketData`.
|
|
//! - **`t` epoch unit rule (unverified in repo):** TradingEconomics CDN series timestamps may be
|
|
//! stored in either Unix seconds or Unix milliseconds. This decoder converts numeric `t` via
|
|
//! [`TE_EPOCH_MILLIS_THRESHOLD`] (`100_000_000_000`):
|
|
//! - `|t| >= 100_000_000_000` → treated as Unix **milliseconds**
|
|
//! (`session_date = floor(t / 86_400_000)` UTC).
|
|
//! - `|t| < 100_000_000_000` → treated as Unix **seconds**
|
|
//! (`session_date = floor(t / 86_400)` UTC).
|
|
//! - Floor division (`div_euclid`) ensures pre-1970 negative timestamps round down to the
|
|
//! earlier UTC calendar day rather than truncating toward zero.
|
|
//! - `monthly`, `pc`, `ac`, and all unknown fields are skipped without calling `elem.value()`.
|
|
//! - `daily` is captured lazily as a raw [`RawElement`] during the top-level scan and only decoded
|
|
//! after `teSymbol` matches `target_symbol` (ASCII case-insensitive), so non-target symbols pay
|
|
//! zero array-scan cost and never emit false `daily` errors even when `daily` precedes `teSymbol`
|
|
//! in raw BSON field order.
|
|
|
|
use std::error::Error;
|
|
use std::fmt;
|
|
|
|
use bson::raw::{RawBsonRef, RawDocument, RawElement};
|
|
use bson::spec::ElementType;
|
|
|
|
use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError};
|
|
use crate::fx::FxDailyBar;
|
|
|
|
/// MongoDB field name for the TradingEconomics symbol key (`market-data-fetch.action.ts:133`).
|
|
pub const FIELD_TE_SYMBOL: &str = "teSymbol";
|
|
/// MongoDB field name for the daily OHLC array (`market-data-fetch.action.ts:144`).
|
|
pub const FIELD_DAILY: &str = "daily";
|
|
/// MongoDB field name for the monthly OHLC array, explicitly ignored (`market-data-fetch.action.ts:145`).
|
|
pub const FIELD_MONTHLY: &str = "monthly";
|
|
/// Point field name for the Unix epoch timestamp (`market-data-fetch.action.ts:15`).
|
|
pub const FIELD_POINT_T: &str = "t";
|
|
/// Point field name for open price (`market-data-fetch.action.ts:16`).
|
|
pub const FIELD_POINT_O: &str = "o";
|
|
/// Point field name for high price (`market-data-fetch.action.ts:17`).
|
|
pub const FIELD_POINT_H: &str = "h";
|
|
/// Point field name for low price (`market-data-fetch.action.ts:18`).
|
|
pub const FIELD_POINT_L: &str = "l";
|
|
/// Point field name for close price (`market-data-fetch.action.ts:19`).
|
|
pub const FIELD_POINT_C: &str = "c";
|
|
|
|
/// Magnitude threshold distinguishing Unix milliseconds (`|t| >= 100_000_000_000`) from Unix
|
|
/// seconds (`|t| < 100_000_000_000`).
|
|
pub const TE_EPOCH_MILLIS_THRESHOLD: i64 = 100_000_000_000;
|
|
/// Number of seconds in one UTC calendar day.
|
|
pub const SECONDS_PER_DAY: i64 = 86_400;
|
|
/// Number of milliseconds in one UTC calendar day.
|
|
pub const MILLIS_PER_DAY: i64 = 86_400_000;
|
|
|
|
/// Converts an integer Unix epoch timestamp `t` (seconds or milliseconds per
|
|
/// [`TE_EPOCH_MILLIS_THRESHOLD`]) into UTC `session_date` (days since `1970-01-01`).
|
|
///
|
|
/// Uses `unsigned_abs()` (avoiding `i64::MIN.abs()` overflow), `div_euclid` (flooring negative
|
|
/// pre-1970 timestamps to the earlier UTC calendar day), and checked `i32::try_from`.
|
|
#[inline]
|
|
pub fn te_epoch_i64_to_session_date(t: i64) -> Option<i32> {
|
|
let days = if t.unsigned_abs() >= TE_EPOCH_MILLIS_THRESHOLD as u64 {
|
|
t.div_euclid(MILLIS_PER_DAY)
|
|
} else {
|
|
t.div_euclid(SECONDS_PER_DAY)
|
|
};
|
|
i32::try_from(days).ok()
|
|
}
|
|
|
|
#[inline]
|
|
fn te_epoch_f64_to_session_date(point_index: usize, v: f64) -> Result<i32, BsonTeMarketDataError> {
|
|
if !v.is_finite() {
|
|
return Err(BsonTeMarketDataError::NonFiniteValue {
|
|
point_index,
|
|
field: FIELD_POINT_T,
|
|
value: v,
|
|
});
|
|
}
|
|
let is_millis = v.abs() >= TE_EPOCH_MILLIS_THRESHOLD as f64;
|
|
let t_floor = v.floor();
|
|
// Exact half-open range of `f64` values representable as `i64` (`[-2^63, 2^63)`).
|
|
if !(-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&t_floor) {
|
|
return Err(BsonTeMarketDataError::DateOutOfRange { point_index });
|
|
}
|
|
let t_i64 = t_floor as i64;
|
|
let days = if is_millis {
|
|
t_i64.div_euclid(MILLIS_PER_DAY)
|
|
} else {
|
|
t_i64.div_euclid(SECONDS_PER_DAY)
|
|
};
|
|
i32::try_from(days).map_err(|_| BsonTeMarketDataError::DateOutOfRange { point_index })
|
|
}
|
|
|
|
/// Typed errors returned while decoding raw `teMarketData` BSON documents or length-prefixed
|
|
/// buffers.
|
|
///
|
|
/// Every variant's `Display` output is a single line; no input path panics.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub enum BsonTeMarketDataError {
|
|
/// Required top-level `teSymbol` field was absent.
|
|
MissingSymbol,
|
|
/// Top-level `teSymbol` string was empty or whitespace-only.
|
|
EmptySymbol,
|
|
/// Top-level `teSymbol` had an unexpected BSON element type.
|
|
WrongSymbolType { actual: ElementType },
|
|
/// Required `daily` field was absent on a matched `teSymbol` document.
|
|
MissingDaily,
|
|
/// `daily` field on a matched `teSymbol` document was not a BSON array.
|
|
DailyNotArray { actual: ElementType },
|
|
/// An element inside `daily` was not an embedded BSON document.
|
|
PointNotDocument {
|
|
point_index: usize,
|
|
actual: ElementType,
|
|
},
|
|
/// A required field (`t`, `o`, `h`, `l`, or `c`) was absent from a `daily` point document.
|
|
MissingPointField {
|
|
point_index: usize,
|
|
field: &'static str,
|
|
},
|
|
/// A required field in a `daily` point document had an unexpected BSON type.
|
|
WrongPointFieldType {
|
|
point_index: usize,
|
|
field: &'static str,
|
|
actual: ElementType,
|
|
},
|
|
/// A numeric field (`t`, `o`, `h`, `l`, or `c`) in a `daily` point was `NaN` or `±inf`.
|
|
NonFiniteValue {
|
|
point_index: usize,
|
|
field: &'static str,
|
|
value: f64,
|
|
},
|
|
/// Point timestamp `t` mapped outside the `i32` UTC epoch-day range.
|
|
DateOutOfRange { point_index: usize },
|
|
/// Buffer ended before a complete 4-byte length prefix or declared document body.
|
|
TruncatedDocument {
|
|
offset: usize,
|
|
remaining: usize,
|
|
declared_len: Option<i32>,
|
|
},
|
|
/// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single
|
|
/// document slice).
|
|
CorruptDocumentLength { offset: usize, declared_len: i32 },
|
|
/// Underlying top-level BSON framing or element bytes were malformed.
|
|
CorruptBson { offset: usize, detail: String },
|
|
/// Underlying BSON bytes inside a `daily` array or point document were malformed.
|
|
CorruptPointBson {
|
|
offset: usize,
|
|
point_index: usize,
|
|
detail: String,
|
|
},
|
|
}
|
|
|
|
impl fmt::Display for BsonTeMarketDataError {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::MissingSymbol => {
|
|
write!(f, "teMarketData BSON missing required field '{FIELD_TE_SYMBOL}'")
|
|
}
|
|
Self::EmptySymbol => {
|
|
write!(
|
|
f,
|
|
"teMarketData BSON field '{FIELD_TE_SYMBOL}' must not be empty or blank"
|
|
)
|
|
}
|
|
Self::WrongSymbolType { actual } => write!(
|
|
f,
|
|
"teMarketData BSON field '{FIELD_TE_SYMBOL}' has unexpected BSON type {actual:?}"
|
|
),
|
|
Self::MissingDaily => {
|
|
write!(f, "teMarketData BSON missing required field '{FIELD_DAILY}'")
|
|
}
|
|
Self::DailyNotArray { actual } => write!(
|
|
f,
|
|
"teMarketData BSON field '{FIELD_DAILY}' has unexpected BSON type {actual:?} (expected Array)"
|
|
),
|
|
Self::PointNotDocument {
|
|
point_index,
|
|
actual,
|
|
} => write!(
|
|
f,
|
|
"teMarketData BSON '{FIELD_DAILY}[{point_index}]' has unexpected BSON type {actual:?} (expected EmbeddedDocument)"
|
|
),
|
|
Self::MissingPointField { point_index, field } => write!(
|
|
f,
|
|
"teMarketData BSON '{FIELD_DAILY}[{point_index}]' missing required field '{field}'"
|
|
),
|
|
Self::WrongPointFieldType {
|
|
point_index,
|
|
field,
|
|
actual,
|
|
} => write!(
|
|
f,
|
|
"teMarketData BSON '{FIELD_DAILY}[{point_index}].{field}' has unexpected BSON type {actual:?}"
|
|
),
|
|
Self::NonFiniteValue {
|
|
point_index,
|
|
field,
|
|
value,
|
|
} => write!(
|
|
f,
|
|
"teMarketData BSON '{FIELD_DAILY}[{point_index}].{field}' has non-finite value {value}"
|
|
),
|
|
Self::DateOutOfRange { point_index } => write!(
|
|
f,
|
|
"teMarketData BSON '{FIELD_DAILY}[{point_index}].{FIELD_POINT_T}' overflows i32 UTC session_date"
|
|
),
|
|
Self::TruncatedDocument {
|
|
offset,
|
|
remaining,
|
|
declared_len,
|
|
} => match declared_len {
|
|
Some(len) => write!(
|
|
f,
|
|
"truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
|
|
),
|
|
None => write!(
|
|
f,
|
|
"truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining"
|
|
),
|
|
},
|
|
Self::CorruptDocumentLength {
|
|
offset,
|
|
declared_len,
|
|
} => write!(
|
|
f,
|
|
"corrupt BSON document length {declared_len} at byte offset {offset}"
|
|
),
|
|
Self::CorruptBson { offset, detail } => {
|
|
write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}")
|
|
}
|
|
Self::CorruptPointBson {
|
|
offset,
|
|
point_index,
|
|
detail,
|
|
} => write!(
|
|
f,
|
|
"corrupt BSON bytes in '{FIELD_DAILY}[{point_index}]' at byte offset {offset}: {detail}"
|
|
),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Error for BsonTeMarketDataError {}
|
|
|
|
#[inline]
|
|
fn map_framing_error(err: BsonEodPriceError) -> BsonTeMarketDataError {
|
|
match err {
|
|
BsonEodPriceError::TruncatedDocument {
|
|
offset,
|
|
remaining,
|
|
declared_len,
|
|
} => BsonTeMarketDataError::TruncatedDocument {
|
|
offset,
|
|
remaining,
|
|
declared_len,
|
|
},
|
|
BsonEodPriceError::CorruptDocumentLength {
|
|
offset,
|
|
declared_len,
|
|
} => BsonTeMarketDataError::CorruptDocumentLength {
|
|
offset,
|
|
declared_len,
|
|
},
|
|
BsonEodPriceError::CorruptBson { offset, detail } => {
|
|
BsonTeMarketDataError::CorruptBson { offset, detail }
|
|
}
|
|
other => BsonTeMarketDataError::CorruptBson {
|
|
offset: 0,
|
|
detail: other.to_string(),
|
|
},
|
|
}
|
|
}
|
|
|
|
/// Per-batch document and point decode accounting for `teMarketData`.
|
|
///
|
|
/// Conservation invariants:
|
|
/// - `docs_in == docs_matched + docs_other_symbol + docs_rejected_total()`
|
|
/// - `points_in == points_decoded + rejected_total()`
|
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
|
pub struct BsonTeMarketDataDecodeStats {
|
|
pub docs_in: usize,
|
|
pub docs_matched: usize,
|
|
pub docs_other_symbol: usize,
|
|
pub rejected_missing_symbol: usize,
|
|
pub rejected_empty_symbol: usize,
|
|
pub rejected_wrong_symbol_type: usize,
|
|
pub rejected_daily_missing: usize,
|
|
pub rejected_daily_not_array: usize,
|
|
pub rejected_corrupt_document: usize,
|
|
pub points_in: usize,
|
|
pub points_decoded: usize,
|
|
pub rejected_point_not_document: usize,
|
|
pub rejected_missing_field: usize,
|
|
pub rejected_wrong_type: usize,
|
|
pub rejected_non_finite: usize,
|
|
pub rejected_date_out_of_range: usize,
|
|
pub rejected_corrupt_point: usize,
|
|
}
|
|
|
|
impl BsonTeMarketDataDecodeStats {
|
|
/// Total number of document-level rejects across all document error categories.
|
|
#[inline]
|
|
pub fn docs_rejected_total(&self) -> usize {
|
|
self.rejected_missing_symbol
|
|
+ self.rejected_empty_symbol
|
|
+ self.rejected_wrong_symbol_type
|
|
+ self.rejected_daily_missing
|
|
+ self.rejected_daily_not_array
|
|
+ self.rejected_corrupt_document
|
|
}
|
|
|
|
/// Total number of point-level rejects across all point error categories.
|
|
#[inline]
|
|
pub fn rejected_total(&self) -> usize {
|
|
self.rejected_point_not_document
|
|
+ self.rejected_missing_field
|
|
+ self.rejected_wrong_type
|
|
+ self.rejected_non_finite
|
|
+ self.rejected_date_out_of_range
|
|
+ self.rejected_corrupt_point
|
|
}
|
|
|
|
/// Increments the point-level rejection counter corresponding to `err`.
|
|
#[inline]
|
|
fn record_point_error(&mut self, err: &BsonTeMarketDataError) {
|
|
match err {
|
|
BsonTeMarketDataError::PointNotDocument { .. } => {
|
|
self.rejected_point_not_document += 1;
|
|
}
|
|
BsonTeMarketDataError::MissingPointField { .. } => {
|
|
self.rejected_missing_field += 1;
|
|
}
|
|
BsonTeMarketDataError::WrongPointFieldType { .. } => {
|
|
self.rejected_wrong_type += 1;
|
|
}
|
|
BsonTeMarketDataError::NonFiniteValue { .. } => {
|
|
self.rejected_non_finite += 1;
|
|
}
|
|
BsonTeMarketDataError::DateOutOfRange { .. } => {
|
|
self.rejected_date_out_of_range += 1;
|
|
}
|
|
BsonTeMarketDataError::CorruptPointBson { .. } => {
|
|
self.rejected_corrupt_point += 1;
|
|
}
|
|
_ => {
|
|
self.rejected_corrupt_point += 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Accumulates counters from another batch into `self`.
|
|
#[inline]
|
|
pub fn merge(&mut self, other: &Self) {
|
|
self.docs_in += other.docs_in;
|
|
self.docs_matched += other.docs_matched;
|
|
self.docs_other_symbol += other.docs_other_symbol;
|
|
self.rejected_missing_symbol += other.rejected_missing_symbol;
|
|
self.rejected_empty_symbol += other.rejected_empty_symbol;
|
|
self.rejected_wrong_symbol_type += other.rejected_wrong_symbol_type;
|
|
self.rejected_daily_missing += other.rejected_daily_missing;
|
|
self.rejected_daily_not_array += other.rejected_daily_not_array;
|
|
self.rejected_corrupt_document += other.rejected_corrupt_document;
|
|
self.points_in += other.points_in;
|
|
self.points_decoded += other.points_decoded;
|
|
self.rejected_point_not_document += other.rejected_point_not_document;
|
|
self.rejected_missing_field += other.rejected_missing_field;
|
|
self.rejected_wrong_type += other.rejected_wrong_type;
|
|
self.rejected_non_finite += other.rejected_non_finite;
|
|
self.rejected_date_out_of_range += other.rejected_date_out_of_range;
|
|
self.rejected_corrupt_point += other.rejected_corrupt_point;
|
|
}
|
|
}
|
|
|
|
impl std::ops::AddAssign for BsonTeMarketDataDecodeStats {
|
|
#[inline]
|
|
fn add_assign(&mut self, rhs: Self) {
|
|
self.merge(&rhs);
|
|
}
|
|
}
|
|
|
|
#[inline]
|
|
fn decode_point_t(
|
|
point_index: usize,
|
|
val: RawBsonRef<'_>,
|
|
) -> Result<i32, BsonTeMarketDataError> {
|
|
match val {
|
|
RawBsonRef::Int32(v) => te_epoch_i64_to_session_date(i64::from(v))
|
|
.ok_or(BsonTeMarketDataError::DateOutOfRange { point_index }),
|
|
RawBsonRef::Int64(v) => te_epoch_i64_to_session_date(v)
|
|
.ok_or(BsonTeMarketDataError::DateOutOfRange { point_index }),
|
|
RawBsonRef::Double(v) => te_epoch_f64_to_session_date(point_index, v),
|
|
other => Err(BsonTeMarketDataError::WrongPointFieldType {
|
|
point_index,
|
|
field: FIELD_POINT_T,
|
|
actual: other.element_type(),
|
|
}),
|
|
}
|
|
}
|
|
|
|
#[inline]
|
|
fn decode_point_price(
|
|
point_index: usize,
|
|
field: &'static str,
|
|
val: RawBsonRef<'_>,
|
|
) -> Result<f64, BsonTeMarketDataError> {
|
|
match val {
|
|
RawBsonRef::Double(v) => {
|
|
if !v.is_finite() {
|
|
return Err(BsonTeMarketDataError::NonFiniteValue {
|
|
point_index,
|
|
field,
|
|
value: v,
|
|
});
|
|
}
|
|
Ok(v)
|
|
}
|
|
RawBsonRef::Int32(v) => Ok(f64::from(v)),
|
|
RawBsonRef::Int64(v) => Ok(v as f64),
|
|
other => Err(BsonTeMarketDataError::WrongPointFieldType {
|
|
point_index,
|
|
field,
|
|
actual: other.element_type(),
|
|
}),
|
|
}
|
|
}
|
|
|
|
fn decode_point_doc(
|
|
point_doc: &RawDocument,
|
|
doc_offset: usize,
|
|
point_index: usize,
|
|
) -> Result<FxDailyBar, BsonTeMarketDataError> {
|
|
let mut session_date: Option<i32> = None;
|
|
let mut open: Option<f64> = None;
|
|
let mut high: Option<f64> = None;
|
|
let mut low: Option<f64> = None;
|
|
let mut close: Option<f64> = None;
|
|
let mut first_semantic_err: Option<BsonTeMarketDataError> = None;
|
|
|
|
for elem_res in point_doc.iter_elements() {
|
|
let elem = elem_res.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
|
offset: doc_offset,
|
|
point_index,
|
|
detail: err.to_string(),
|
|
})?;
|
|
let key = elem.key().as_str();
|
|
|
|
if key == FIELD_POINT_T {
|
|
let val = elem
|
|
.value()
|
|
.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
|
offset: doc_offset,
|
|
point_index,
|
|
detail: format!("field '{FIELD_POINT_T}': {err}"),
|
|
})?;
|
|
match decode_point_t(point_index, val) {
|
|
Ok(v) => session_date = Some(v),
|
|
Err(err) => {
|
|
if first_semantic_err.is_none() {
|
|
first_semantic_err = Some(err);
|
|
}
|
|
}
|
|
}
|
|
} else if key == FIELD_POINT_O {
|
|
let val = elem
|
|
.value()
|
|
.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
|
offset: doc_offset,
|
|
point_index,
|
|
detail: format!("field '{FIELD_POINT_O}': {err}"),
|
|
})?;
|
|
match decode_point_price(point_index, FIELD_POINT_O, val) {
|
|
Ok(v) => open = Some(v),
|
|
Err(err) => {
|
|
if first_semantic_err.is_none() {
|
|
first_semantic_err = Some(err);
|
|
}
|
|
}
|
|
}
|
|
} else if key == FIELD_POINT_H {
|
|
let val = elem
|
|
.value()
|
|
.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
|
offset: doc_offset,
|
|
point_index,
|
|
detail: format!("field '{FIELD_POINT_H}': {err}"),
|
|
})?;
|
|
match decode_point_price(point_index, FIELD_POINT_H, val) {
|
|
Ok(v) => high = Some(v),
|
|
Err(err) => {
|
|
if first_semantic_err.is_none() {
|
|
first_semantic_err = Some(err);
|
|
}
|
|
}
|
|
}
|
|
} else if key == FIELD_POINT_L {
|
|
let val = elem
|
|
.value()
|
|
.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
|
offset: doc_offset,
|
|
point_index,
|
|
detail: format!("field '{FIELD_POINT_L}': {err}"),
|
|
})?;
|
|
match decode_point_price(point_index, FIELD_POINT_L, val) {
|
|
Ok(v) => low = Some(v),
|
|
Err(err) => {
|
|
if first_semantic_err.is_none() {
|
|
first_semantic_err = Some(err);
|
|
}
|
|
}
|
|
}
|
|
} else if key == FIELD_POINT_C {
|
|
let val = elem
|
|
.value()
|
|
.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
|
offset: doc_offset,
|
|
point_index,
|
|
detail: format!("field '{FIELD_POINT_C}': {err}"),
|
|
})?;
|
|
match decode_point_price(point_index, FIELD_POINT_C, val) {
|
|
Ok(v) => close = Some(v),
|
|
Err(err) => {
|
|
if first_semantic_err.is_none() {
|
|
first_semantic_err = Some(err);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// `pc`, `ac`, and all unknown fields are skipped without calling `elem.value()`.
|
|
}
|
|
|
|
if let Some(err) = first_semantic_err {
|
|
return Err(err);
|
|
}
|
|
|
|
let Some(session_date) = session_date else {
|
|
return Err(BsonTeMarketDataError::MissingPointField {
|
|
point_index,
|
|
field: FIELD_POINT_T,
|
|
});
|
|
};
|
|
let Some(open) = open else {
|
|
return Err(BsonTeMarketDataError::MissingPointField {
|
|
point_index,
|
|
field: FIELD_POINT_O,
|
|
});
|
|
};
|
|
let Some(high) = high else {
|
|
return Err(BsonTeMarketDataError::MissingPointField {
|
|
point_index,
|
|
field: FIELD_POINT_H,
|
|
});
|
|
};
|
|
let Some(low) = low else {
|
|
return Err(BsonTeMarketDataError::MissingPointField {
|
|
point_index,
|
|
field: FIELD_POINT_L,
|
|
});
|
|
};
|
|
let Some(close) = close else {
|
|
return Err(BsonTeMarketDataError::MissingPointField {
|
|
point_index,
|
|
field: FIELD_POINT_C,
|
|
});
|
|
};
|
|
|
|
Ok(FxDailyBar {
|
|
session_date,
|
|
open,
|
|
high,
|
|
low,
|
|
close,
|
|
})
|
|
}
|
|
|
|
fn decode_te_market_data_doc_at<F, E>(
|
|
doc: &RawDocument,
|
|
doc_offset: usize,
|
|
target_symbol: &str,
|
|
mut on_bar: F,
|
|
mut on_error: E,
|
|
) -> BsonTeMarketDataDecodeStats
|
|
where
|
|
F: FnMut(FxDailyBar),
|
|
E: FnMut(BsonTeMarketDataError),
|
|
{
|
|
let mut stats = BsonTeMarketDataDecodeStats {
|
|
docs_in: 1,
|
|
..BsonTeMarketDataDecodeStats::default()
|
|
};
|
|
|
|
let mut te_symbol: Option<&str> = None;
|
|
let mut symbol_err: Option<BsonTeMarketDataError> = None;
|
|
let mut daily_elem: Option<RawElement<'_>> = None;
|
|
|
|
for elem_res in doc.iter_elements() {
|
|
let elem = match elem_res {
|
|
Ok(elem) => elem,
|
|
Err(err) => {
|
|
stats.rejected_corrupt_document += 1;
|
|
on_error(BsonTeMarketDataError::CorruptBson {
|
|
offset: doc_offset,
|
|
detail: err.to_string(),
|
|
});
|
|
return stats;
|
|
}
|
|
};
|
|
let key = elem.key().as_str();
|
|
if key == FIELD_TE_SYMBOL {
|
|
let val = match elem.value() {
|
|
Ok(val) => val,
|
|
Err(err) => {
|
|
stats.rejected_corrupt_document += 1;
|
|
on_error(BsonTeMarketDataError::CorruptBson {
|
|
offset: doc_offset,
|
|
detail: format!("field '{FIELD_TE_SYMBOL}': {err}"),
|
|
});
|
|
return stats;
|
|
}
|
|
};
|
|
match val {
|
|
RawBsonRef::String(s) => {
|
|
if s.trim().is_empty() {
|
|
if symbol_err.is_none() {
|
|
symbol_err = Some(BsonTeMarketDataError::EmptySymbol);
|
|
}
|
|
} else {
|
|
te_symbol = Some(s);
|
|
}
|
|
}
|
|
other => {
|
|
if symbol_err.is_none() {
|
|
symbol_err = Some(BsonTeMarketDataError::WrongSymbolType {
|
|
actual: other.element_type(),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
} else if key == FIELD_DAILY {
|
|
daily_elem = Some(elem);
|
|
}
|
|
// `FIELD_MONTHLY` and all other top-level fields are skipped without calling `elem.value()`.
|
|
}
|
|
|
|
if let Some(err) = symbol_err {
|
|
match &err {
|
|
BsonTeMarketDataError::EmptySymbol => stats.rejected_empty_symbol += 1,
|
|
BsonTeMarketDataError::WrongSymbolType { .. } => stats.rejected_wrong_symbol_type += 1,
|
|
_ => stats.rejected_corrupt_document += 1,
|
|
}
|
|
on_error(err);
|
|
return stats;
|
|
}
|
|
|
|
let Some(symbol) = te_symbol else {
|
|
stats.rejected_missing_symbol += 1;
|
|
on_error(BsonTeMarketDataError::MissingSymbol);
|
|
return stats;
|
|
};
|
|
|
|
if !symbol.eq_ignore_ascii_case(target_symbol) {
|
|
stats.docs_other_symbol += 1;
|
|
return stats;
|
|
}
|
|
|
|
let Some(daily_elem) = daily_elem else {
|
|
stats.rejected_daily_missing += 1;
|
|
on_error(BsonTeMarketDataError::MissingDaily);
|
|
return stats;
|
|
};
|
|
|
|
let daily_val = match daily_elem.value() {
|
|
Ok(val) => val,
|
|
Err(err) => {
|
|
stats.rejected_corrupt_document += 1;
|
|
on_error(BsonTeMarketDataError::CorruptBson {
|
|
offset: doc_offset,
|
|
detail: format!("field '{FIELD_DAILY}': {err}"),
|
|
});
|
|
return stats;
|
|
}
|
|
};
|
|
|
|
let daily_arr = match daily_val {
|
|
RawBsonRef::Array(arr) => arr,
|
|
other => {
|
|
stats.rejected_daily_not_array += 1;
|
|
on_error(BsonTeMarketDataError::DailyNotArray {
|
|
actual: other.element_type(),
|
|
});
|
|
return stats;
|
|
}
|
|
};
|
|
|
|
stats.docs_matched += 1;
|
|
|
|
for (point_index, item_res) in daily_arr.into_iter().enumerate() {
|
|
stats.points_in += 1;
|
|
let item = match item_res {
|
|
Ok(item) => item,
|
|
Err(err) => {
|
|
let err = BsonTeMarketDataError::CorruptPointBson {
|
|
offset: doc_offset,
|
|
point_index,
|
|
detail: err.to_string(),
|
|
};
|
|
stats.record_point_error(&err);
|
|
on_error(err);
|
|
break;
|
|
}
|
|
};
|
|
|
|
let point_doc = match item {
|
|
RawBsonRef::Document(point_doc) => point_doc,
|
|
other => {
|
|
let err = BsonTeMarketDataError::PointNotDocument {
|
|
point_index,
|
|
actual: other.element_type(),
|
|
};
|
|
stats.record_point_error(&err);
|
|
on_error(err);
|
|
continue;
|
|
}
|
|
};
|
|
|
|
match decode_point_doc(point_doc, doc_offset, point_index) {
|
|
Ok(bar) => {
|
|
stats.points_decoded += 1;
|
|
on_bar(bar);
|
|
}
|
|
Err(err) => {
|
|
stats.record_point_error(&err);
|
|
on_error(err);
|
|
}
|
|
}
|
|
}
|
|
|
|
stats
|
|
}
|
|
|
|
/// Decodes a single `&RawDocument` representing a `teMarketData` MongoDB document in one forward
|
|
/// pass without allocating a `bson::Document` or per-point heap memory.
|
|
///
|
|
/// Matches `teSymbol` against `target_symbol` using ASCII case-insensitive comparison. For matched
|
|
/// documents, emits each valid `daily` point as an [`FxDailyBar`] via `on_bar` and reports
|
|
/// document- or point-level errors to `on_error` without panicking.
|
|
#[inline]
|
|
pub fn decode_te_market_data_doc<F, E>(
|
|
doc: &RawDocument,
|
|
target_symbol: &str,
|
|
on_bar: F,
|
|
on_error: E,
|
|
) -> BsonTeMarketDataDecodeStats
|
|
where
|
|
F: FnMut(FxDailyBar),
|
|
E: FnMut(BsonTeMarketDataError),
|
|
{
|
|
decode_te_market_data_doc_at(doc, 0, target_symbol, on_bar, on_error)
|
|
}
|
|
|
|
/// Decodes a single length-prefixed raw BSON document byte slice representing a `teMarketData`
|
|
/// document.
|
|
pub fn decode_te_market_data_bytes<F, E>(
|
|
bytes: &[u8],
|
|
target_symbol: &str,
|
|
on_bar: F,
|
|
mut on_error: E,
|
|
) -> BsonTeMarketDataDecodeStats
|
|
where
|
|
F: FnMut(FxDailyBar),
|
|
E: FnMut(BsonTeMarketDataError),
|
|
{
|
|
match parse_single_raw_doc(bytes) {
|
|
Ok(doc) => decode_te_market_data_doc_at(doc, 0, target_symbol, on_bar, on_error),
|
|
Err(err) => {
|
|
let mut stats = BsonTeMarketDataDecodeStats {
|
|
docs_in: 1,
|
|
..BsonTeMarketDataDecodeStats::default()
|
|
};
|
|
stats.rejected_corrupt_document += 1;
|
|
on_error(map_framing_error(err));
|
|
stats
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Streams a concatenated length-prefixed BSON buffer through [`decode_te_market_data_doc`],
|
|
/// emitting every valid [`FxDailyBar`] for `target_symbol` (ASCII case-insensitive) to `on_bar`
|
|
/// and reporting document- or point-level errors to `on_error(byte_offset, err)` without aborting.
|
|
///
|
|
/// Always maintains:
|
|
/// - `stats.docs_in == stats.docs_matched + stats.docs_other_symbol + stats.docs_rejected_total()`
|
|
/// - `stats.points_in == stats.points_decoded + stats.rejected_total()`
|
|
pub fn decode_te_market_data_buffer<F, E>(
|
|
buf: &[u8],
|
|
target_symbol: &str,
|
|
mut on_bar: F,
|
|
mut on_error: E,
|
|
) -> BsonTeMarketDataDecodeStats
|
|
where
|
|
F: FnMut(FxDailyBar),
|
|
E: FnMut(usize, BsonTeMarketDataError),
|
|
{
|
|
let mut stats = BsonTeMarketDataDecodeStats::default();
|
|
let mut iter = iter_raw_bson_docs(buf);
|
|
|
|
while let Some(item) = iter.next_with_offset() {
|
|
match item {
|
|
Ok((doc_offset, doc)) => {
|
|
let doc_stats = decode_te_market_data_doc_at(
|
|
doc,
|
|
doc_offset,
|
|
target_symbol,
|
|
&mut on_bar,
|
|
|err| on_error(doc_offset, err),
|
|
);
|
|
stats += doc_stats;
|
|
}
|
|
Err((doc_offset, err)) => {
|
|
stats.docs_in += 1;
|
|
stats.rejected_corrupt_document += 1;
|
|
on_error(doc_offset, map_framing_error(err));
|
|
}
|
|
}
|
|
}
|
|
|
|
stats
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "bson_te_market_data_tests.rs"]
|
|
mod tests;
|