T-160: M2.2g — tools/curate-etl: zero-copy raw BSON decoder for MongoDB ceoPosts (bson_ceo_posts.rs → CeoPost<&str>, explicit timestamp unit, fail-closed edited handling) with tests (no new crates, no CLI/bench changes, no live Mongo)

This commit is contained in:
Studio 2026-12-02 09:28:42 -05:00
parent 75a7c16e32
commit 061d593085
3 changed files with 1935 additions and 0 deletions

View file

@ -0,0 +1,860 @@
//! Zero-copy raw BSON decoder for MongoDB `ceoPosts` documents (`M2.2g`).
//!
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without
//! allocating a `bson::Document`, emitting [`CeoPost<&str>`] rows (borrowing `key` directly from
//! the input buffer and allocating owned `String`s only for rows that will be emitted) via a
//! caller-supplied callback.
//!
//! # Unverified Live Schema & Explicit Timestamp Unit
//!
//! `apps/stock/data-ingestion/src/handlers/ceo/actions/get-posts.action.ts` establishes the
//! default stored field names (`ceoId`, `spielId`, `timestamp`, `edited`, `bot`, `userId`,
//! `spiel`), but the live MongoDB BSON types and whether `timestamp` / `edited` are stored in
//! epoch seconds or epoch milliseconds are **not verified** in the repository. Callers must
//! therefore supply [`CeoPostsTimestampUnit`] explicitly (there is intentionally no default).
//!
//! # Decoding & Validation Rules
//! - Every element and nested subdocument/array/JS-with-scope (up to depth `128`) of each
//! [`RawDocument`] is scanned and structurally validated to completion before applying semantic
//! skip rules, so structural BSON corruption always returns
//! `Err(BsonCeoPostsError::CorruptBson)` rather than being masked by an earlier semantic skip.
//! - `key` (`ceoId`): required non-blank UTF-8 BSON `String`, passed through verbatim (no
//! trimming). Missing, wrong type, or empty/whitespace-only strings skip the row under
//! `skipped_missing_key`, `skipped_wrong_key_type`, or `skipped_empty_key`.
//! - `spiel_id` (`spielId`): required UTF-8 BSON `String` (verbatim, non-blank) or `Int32` /
//! `Int64` rendered as decimal. Missing, wrong type, or empty/whitespace-only strings skip the
//! row under `skipped_missing_spiel_id`, `skipped_wrong_spiel_id_type`, or
//! `skipped_empty_spiel_id`.
//! - `timestamp` (`timestamp`): required `Int32`, `Int64`, finite integral `Double` in the
//! half-open `[-2^63, 2^63)` range, or BSON `DateTime` (already epoch milliseconds; unit
//! ignored). Under [`CeoPostsTimestampUnit::Seconds`], numeric values are multiplied by `1_000`
//! using `checked_mul`; overflow or out-of-range doubles skip under
//! `skipped_timestamp_out_of_range`. Non-finite or fractional doubles skip under
//! `skipped_invalid_timestamp`. Missing or other BSON types skip under
//! `skipped_missing_timestamp` or `skipped_wrong_timestamp_type`. Values `<= 0` are passed
//! through so [`crate::posts::build_posts`] remains the single place rejecting non-positive
//! creation timestamps.
//! - `edited` (`edited`, **point-in-time guard, fail closed**):
//! - Absent or BSON `Null` yields `edited_ms = None`.
//! - Numeric `0` (`Int32(0)`, `Int64(0)`, `Double(0.0)`, `Double(-0.0)`) or `Boolean(false)`
//! yields `edited_ms = None` and increments `edited_zero_or_false` (on emitted rows).
//! - Positive integral numeric values (`Int32`, `Int64`, finite integral `Double` in
//! `[-2^63, 2^63)`) converted with `unit` (checked multiply for seconds), or non-negative BSON
//! `DateTime` (including epoch-zero `DateTime(0)` -> `Some(0)` because the zero sentinel is
//! numeric), yield `edited_ms = Some(ms)`.
//! - Anything else — negative values, fractional or non-finite doubles, `Boolean(true)`,
//! `String`, other BSON types, seconds overflow, or repeated `edited` fields in the same
//! document — skips the row under `skipped_invalid_edited`. A row with a present but
//! unreadable `edited` field is never emitted as unedited.
//! - `text` (`spiel`): UTF-8 BSON `String` (verbatim); absent or BSON `Null` emits `String::new()`
//! and increments `empty_text` (on emitted rows); any other BSON type skips under
//! `skipped_wrong_text_type`.
//! - `bot` (`bot`): normalized only for emitted rows. UTF-8 `String` (verbatim), `Int32`/`Int64`
//! rendered as decimal, `Boolean` mapped to `"1"` / `"0"`, absent or `Null` -> `None`; any
//! other BSON type -> `None` and increments `nulled_wrong_type_bot`.
//! - `user_id` (`userId`): normalized only for emitted rows. UTF-8 `String` (verbatim),
//! `Int32`/`Int64` rendered as decimal, absent or `Null` -> `None`; any other BSON type ->
//! `None` and increments `nulled_wrong_type_user_id`.
//! - Deterministic semantic skip priority: `key` → `spiel_id` → `timestamp` → `edited` → `text`.
//! - Emitted-row counters (`edited_zero_or_false`, `nulled_wrong_type_bot`,
//! `nulled_wrong_type_user_id`, `empty_text`) are incremented only on rows that pass all skip
//! checks and are emitted to `on_row`.
//! - Conservation invariant: `docs_in == rows_out + skipped_total()`.
use std::error::Error;
use std::fmt;
use bson::raw::{RawBsonRef, RawDocument};
use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError};
use crate::posts::CeoPost;
/// Default BSON field name for the `ceoPosts` channel / security key (`get-posts.action.ts`).
pub const DEFAULT_KEY_FIELD: &str = "ceoId";
/// Default BSON field name for the `ceoPosts` post identifier (`get-posts.action.ts`).
pub const DEFAULT_SPIEL_ID_FIELD: &str = "spielId";
/// Default BSON field name for the `ceoPosts` creation timestamp (`get-posts.action.ts`).
pub const DEFAULT_TIMESTAMP_FIELD: &str = "timestamp";
/// Default BSON field name for the `ceoPosts` last-edit timestamp (`get-posts.action.ts`).
pub const DEFAULT_EDITED_FIELD: &str = "edited";
/// Default BSON field name for the `ceoPosts` bot/newswire flag (`get-posts.action.ts`).
pub const DEFAULT_BOT_FIELD: &str = "bot";
/// Default BSON field name for the `ceoPosts` author identifier (`get-posts.action.ts`).
pub const DEFAULT_USER_ID_FIELD: &str = "userId";
/// Default BSON field name for the `ceoPosts` post body (`get-posts.action.ts`).
pub const DEFAULT_TEXT_FIELD: &str = "spiel";
/// Explicit numeric timestamp unit for `ceoPosts` `timestamp` and `edited` fields.
///
/// Intentionally has no `Default`: the live MongoDB unit is unverified in the repository, so
/// callers must choose explicitly. BSON `DateTime` values are always epoch milliseconds and ignore
/// this setting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CeoPostsTimestampUnit {
/// Numeric `timestamp` / `edited` values are Unix epoch seconds (multiplied by `1_000`).
Seconds,
/// Numeric `timestamp` / `edited` values are Unix epoch milliseconds.
Millis,
}
/// Borrowed BSON field-name configuration for decoding `ceoPosts` documents.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CeoPostsFieldNames<'a> {
pub key: &'a str,
pub spiel_id: &'a str,
pub timestamp: &'a str,
pub edited: &'a str,
pub bot: &'a str,
pub user_id: &'a str,
pub text: &'a str,
}
impl Default for CeoPostsFieldNames<'static> {
fn default() -> Self {
Self {
key: DEFAULT_KEY_FIELD,
spiel_id: DEFAULT_SPIEL_ID_FIELD,
timestamp: DEFAULT_TIMESTAMP_FIELD,
edited: DEFAULT_EDITED_FIELD,
bot: DEFAULT_BOT_FIELD,
user_id: DEFAULT_USER_ID_FIELD,
text: DEFAULT_TEXT_FIELD,
}
}
}
impl<'a> CeoPostsFieldNames<'a> {
/// Validates that every configured field name is non-empty/non-blank and that no two
/// configured roles point to the same BSON field name.
pub fn validate(&self) -> Result<(), BsonCeoPostsError> {
let roles: [(&'static str, &str); 7] = [
("key", self.key),
("spiel_id", self.spiel_id),
("timestamp", self.timestamp),
("edited", self.edited),
("bot", self.bot),
("user_id", self.user_id),
("text", self.text),
];
for &(role, name) in &roles {
if name.trim().is_empty() {
return Err(BsonCeoPostsError::InvalidFieldNames {
detail: format!("field name for '{role}' must not be empty or blank"),
});
}
}
for i in 0..roles.len() {
let (role_a, name_a) = roles[i];
for &(role_b, name_b) in &roles[i + 1..] {
if name_a == name_b {
return Err(BsonCeoPostsError::InvalidFieldNames {
detail: format!(
"roles '{role_a}' and '{role_b}' cannot share BSON field '{name_a}'"
),
});
}
}
}
Ok(())
}
}
/// Typed errors returned while validating field configuration or decoding raw `ceoPosts` BSON.
///
/// Structural BSON framing or element errors fail closed and carry a `u64` byte offset;
/// every variant's `Display` output is a single line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BsonCeoPostsError {
/// Invalid [`CeoPostsFieldNames`] configuration (empty/blank name or duplicate role mapping).
InvalidFieldNames { detail: String },
/// Buffer ended before a complete 4-byte length prefix or declared document body.
TruncatedDocument {
offset: u64,
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: u64, declared_len: i32 },
/// Underlying BSON framing or element bytes were malformed.
CorruptBson { offset: u64, detail: String },
}
impl fmt::Display for BsonCeoPostsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidFieldNames { detail } => {
write!(f, "invalid ceoPosts field configuration: {detail}")
}
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}")
}
}
}
}
impl Error for BsonCeoPostsError {}
#[inline]
fn map_framing_error(err: BsonEodPriceError) -> BsonCeoPostsError {
match err {
BsonEodPriceError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonCeoPostsError::TruncatedDocument {
offset: offset as u64,
remaining,
declared_len,
},
BsonEodPriceError::CorruptDocumentLength {
offset,
declared_len,
} => BsonCeoPostsError::CorruptDocumentLength {
offset: offset as u64,
declared_len,
},
BsonEodPriceError::CorruptBson { offset, detail } => BsonCeoPostsError::CorruptBson {
offset: offset as u64,
detail,
},
other => BsonCeoPostsError::CorruptBson {
offset: 0,
detail: other.to_string(),
},
}
}
/// Per-batch decode accounting for `ceoPosts`.
///
/// Conservation invariant:
/// `docs_in == rows_out + skipped_total()`
///
/// Emitted-row counters (`edited_zero_or_false`, `nulled_wrong_type_bot`,
/// `nulled_wrong_type_user_id`, `empty_text`) are incremented only for emitted rows and are
/// excluded from [`Self::skipped_total`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BsonCeoPostsDecodeStats {
pub docs_in: usize,
pub rows_out: usize,
pub skipped_missing_key: usize,
pub skipped_wrong_key_type: usize,
pub skipped_empty_key: usize,
pub skipped_missing_spiel_id: usize,
pub skipped_wrong_spiel_id_type: usize,
pub skipped_empty_spiel_id: usize,
pub skipped_missing_timestamp: usize,
pub skipped_wrong_timestamp_type: usize,
pub skipped_invalid_timestamp: usize,
pub skipped_timestamp_out_of_range: usize,
pub skipped_invalid_edited: usize,
pub skipped_wrong_text_type: usize,
pub edited_zero_or_false: usize,
pub nulled_wrong_type_bot: usize,
pub nulled_wrong_type_user_id: usize,
pub empty_text: usize,
}
impl BsonCeoPostsDecodeStats {
/// Total number of semantically skipped documents across all skip categories.
#[inline]
pub fn skipped_total(&self) -> usize {
self.skipped_missing_key
+ self.skipped_wrong_key_type
+ self.skipped_empty_key
+ self.skipped_missing_spiel_id
+ self.skipped_wrong_spiel_id_type
+ self.skipped_empty_spiel_id
+ self.skipped_missing_timestamp
+ self.skipped_wrong_timestamp_type
+ self.skipped_invalid_timestamp
+ self.skipped_timestamp_out_of_range
+ self.skipped_invalid_edited
+ self.skipped_wrong_text_type
}
/// Accumulates counters from another batch into `self`.
#[inline]
pub fn merge(&mut self, other: &Self) {
self.docs_in += other.docs_in;
self.rows_out += other.rows_out;
self.skipped_missing_key += other.skipped_missing_key;
self.skipped_wrong_key_type += other.skipped_wrong_key_type;
self.skipped_empty_key += other.skipped_empty_key;
self.skipped_missing_spiel_id += other.skipped_missing_spiel_id;
self.skipped_wrong_spiel_id_type += other.skipped_wrong_spiel_id_type;
self.skipped_empty_spiel_id += other.skipped_empty_spiel_id;
self.skipped_missing_timestamp += other.skipped_missing_timestamp;
self.skipped_wrong_timestamp_type += other.skipped_wrong_timestamp_type;
self.skipped_invalid_timestamp += other.skipped_invalid_timestamp;
self.skipped_timestamp_out_of_range += other.skipped_timestamp_out_of_range;
self.skipped_invalid_edited += other.skipped_invalid_edited;
self.skipped_wrong_text_type += other.skipped_wrong_text_type;
self.edited_zero_or_false += other.edited_zero_or_false;
self.nulled_wrong_type_bot += other.nulled_wrong_type_bot;
self.nulled_wrong_type_user_id += other.nulled_wrong_type_user_id;
self.empty_text += other.empty_text;
}
}
impl std::ops::AddAssign for BsonCeoPostsDecodeStats {
#[inline]
fn add_assign(&mut self, rhs: Self) {
self.merge(&rhs);
}
}
enum KeyState<'a> {
Missing,
WrongType,
Empty,
Valid(&'a str),
}
enum SpielIdState<'a> {
Missing,
WrongType,
Empty,
Str(&'a str),
Int32(i32),
Int64(i64),
}
enum TimestampState {
Missing,
WrongType,
Invalid,
OutOfRange,
Valid(i64),
}
enum EditedState {
Absent,
Null,
ZeroOrFalse,
Valid(i64),
Invalid,
}
enum TextState<'a> {
MissingOrNull,
WrongType,
Str(&'a str),
}
enum BotState<'a> {
None,
WrongType,
Str(&'a str),
Int32(i32),
Int64(i64),
Bool(bool),
}
enum UserIdState<'a> {
None,
WrongType,
Str(&'a str),
Int32(i32),
Int64(i64),
}
#[inline]
fn scale_numeric_timestamp(raw: i64, unit: CeoPostsTimestampUnit) -> TimestampState {
match unit {
CeoPostsTimestampUnit::Millis => TimestampState::Valid(raw),
CeoPostsTimestampUnit::Seconds => match raw.checked_mul(1_000) {
Some(ms) => TimestampState::Valid(ms),
None => TimestampState::OutOfRange,
},
}
}
#[inline]
fn decode_timestamp_val(val: RawBsonRef<'_>, unit: CeoPostsTimestampUnit) -> TimestampState {
match val {
RawBsonRef::DateTime(dt) => TimestampState::Valid(dt.timestamp_millis()),
RawBsonRef::Int32(v) => scale_numeric_timestamp(i64::from(v), unit),
RawBsonRef::Int64(v) => scale_numeric_timestamp(v, unit),
RawBsonRef::Double(v) => {
if !v.is_finite() || v.fract() != 0.0 {
return TimestampState::Invalid;
}
// 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(&v) {
return TimestampState::OutOfRange;
}
scale_numeric_timestamp(v as i64, unit)
}
_ => TimestampState::WrongType,
}
}
#[inline]
fn decode_edited_val(val: RawBsonRef<'_>, unit: CeoPostsTimestampUnit) -> EditedState {
match val {
RawBsonRef::Null => EditedState::Null,
RawBsonRef::Boolean(false) => EditedState::ZeroOrFalse,
RawBsonRef::Boolean(true) => EditedState::Invalid,
RawBsonRef::DateTime(dt) => {
let ms = dt.timestamp_millis();
if ms < 0 {
EditedState::Invalid
} else {
// Epoch-zero BSON DateTime is a timestamp, not the numeric `0` sentinel.
EditedState::Valid(ms)
}
}
RawBsonRef::Int32(_) | RawBsonRef::Int64(_) | RawBsonRef::Double(_) => {
match decode_timestamp_val(val, unit) {
TimestampState::Valid(0) => EditedState::ZeroOrFalse,
TimestampState::Valid(ms) if ms > 0 => EditedState::Valid(ms),
TimestampState::Valid(_)
| TimestampState::Invalid
| TimestampState::OutOfRange
| TimestampState::WrongType
| TimestampState::Missing => EditedState::Invalid,
}
}
_ => EditedState::Invalid,
}
}
#[inline]
fn decode_spiel_id_val(val: RawBsonRef<'_>) -> SpielIdState<'_> {
match val {
RawBsonRef::String(s) => {
if s.trim().is_empty() {
SpielIdState::Empty
} else {
SpielIdState::Str(s)
}
}
RawBsonRef::Int32(v) => SpielIdState::Int32(v),
RawBsonRef::Int64(v) => SpielIdState::Int64(v),
_ => SpielIdState::WrongType,
}
}
#[inline]
fn decode_bot_val(val: RawBsonRef<'_>) -> BotState<'_> {
match val {
RawBsonRef::Null => BotState::None,
RawBsonRef::String(s) => BotState::Str(s),
RawBsonRef::Int32(v) => BotState::Int32(v),
RawBsonRef::Int64(v) => BotState::Int64(v),
RawBsonRef::Boolean(b) => BotState::Bool(b),
_ => BotState::WrongType,
}
}
#[inline]
fn decode_user_id_val(val: RawBsonRef<'_>) -> UserIdState<'_> {
match val {
RawBsonRef::Null => UserIdState::None,
RawBsonRef::String(s) => UserIdState::Str(s),
RawBsonRef::Int32(v) => UserIdState::Int32(v),
RawBsonRef::Int64(v) => UserIdState::Int64(v),
_ => UserIdState::WrongType,
}
}
#[inline]
fn decode_text_val(val: RawBsonRef<'_>) -> TextState<'_> {
match val {
RawBsonRef::Null => TextState::MissingOrNull,
RawBsonRef::String(s) => TextState::Str(s),
_ => TextState::WrongType,
}
}
/// Maximum recursive nesting depth accepted while validating raw BSON documents and arrays.
const MAX_BSON_VALIDATION_DEPTH: usize = 128;
#[inline]
fn is_exact_array_index(key: &str, expected: usize) -> bool {
let bytes = key.as_bytes();
if bytes.is_empty() || (bytes.len() > 1 && bytes[0] == b'0') {
return false;
}
let mut parsed: usize = 0;
for &b in bytes {
if !b.is_ascii_digit() {
return false;
}
let digit = usize::from(b - b'0');
match parsed.checked_mul(10).and_then(|n| n.checked_add(digit)) {
Some(next) => parsed = next,
None => return false,
}
}
parsed == expected
}
fn validate_raw_bson_value(
val: RawBsonRef<'_>,
doc_offset: u64,
field_name: &str,
depth: usize,
) -> Result<(), BsonCeoPostsError> {
match val {
RawBsonRef::Document(subdoc) => {
validate_raw_document(subdoc, doc_offset, field_name, depth + 1)
}
RawBsonRef::Array(arr) => {
if depth >= MAX_BSON_VALIDATION_DEPTH {
return Err(BsonCeoPostsError::CorruptBson {
offset: doc_offset,
detail: format!(
"field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}"
),
});
}
for (expected_idx, elem_res) in arr.iter_elements().enumerate() {
let elem = elem_res.map_err(|err| BsonCeoPostsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{field_name}': {err}"),
})?;
let key = elem.key().as_str();
if !is_exact_array_index(key, expected_idx) {
return Err(BsonCeoPostsError::CorruptBson {
offset: doc_offset,
detail: format!(
"field '{field_name}': invalid BSON array index '{key}' at position {expected_idx}"
),
});
}
let item = elem.value().map_err(|err| BsonCeoPostsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{field_name}': {err}"),
})?;
validate_raw_bson_value(item, doc_offset, field_name, depth + 1)?;
}
Ok(())
}
RawBsonRef::JavaScriptCodeWithScope(code_with_scope) => {
validate_raw_document(code_with_scope.scope, doc_offset, field_name, depth + 1)
}
_ => Ok(()),
}
}
fn validate_raw_document(
doc: &RawDocument,
doc_offset: u64,
field_name: &str,
depth: usize,
) -> Result<(), BsonCeoPostsError> {
if depth > MAX_BSON_VALIDATION_DEPTH {
return Err(BsonCeoPostsError::CorruptBson {
offset: doc_offset,
detail: format!(
"field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}"
),
});
}
for elem_res in doc.iter_elements() {
let elem = elem_res.map_err(|err| BsonCeoPostsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{field_name}': {err}"),
})?;
let val = elem.value().map_err(|err| BsonCeoPostsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{field_name}': {err}"),
})?;
validate_raw_bson_value(val, doc_offset, field_name, depth)?;
}
Ok(())
}
fn decode_ceo_posts_doc_at<'a, F>(
doc: &'a RawDocument,
doc_offset: u64,
fields: &CeoPostsFieldNames<'_>,
unit: CeoPostsTimestampUnit,
mut on_row: F,
) -> Result<BsonCeoPostsDecodeStats, BsonCeoPostsError>
where
F: FnMut(CeoPost<&'a str>),
{
let mut stats = BsonCeoPostsDecodeStats {
docs_in: 1,
..BsonCeoPostsDecodeStats::default()
};
let mut key_state = KeyState::Missing;
let mut spiel_id_state = SpielIdState::Missing;
let mut timestamp_state = TimestampState::Missing;
let mut edited_state = EditedState::Absent;
let mut bot_state = BotState::None;
let mut user_id_state = UserIdState::None;
let mut text_state = TextState::MissingOrNull;
// Scan and validate every element and nested raw value to completion so structural BSON
// corruption (including invalid UTF-8 in unused fields or malformed nested documents/arrays)
// always fails closed and is never masked by an earlier semantic skip.
for elem_res in doc.iter_elements() {
let elem = elem_res.map_err(|err| BsonCeoPostsError::CorruptBson {
offset: doc_offset,
detail: err.to_string(),
})?;
let name = elem.key().as_str();
let val = elem.value().map_err(|err| BsonCeoPostsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{name}': {err}"),
})?;
validate_raw_bson_value(val, doc_offset, name, 0)?;
if name == fields.key {
key_state = match val {
RawBsonRef::String(s) => {
if s.trim().is_empty() {
KeyState::Empty
} else {
KeyState::Valid(s)
}
}
_ => KeyState::WrongType,
};
} else if name == fields.spiel_id {
spiel_id_state = decode_spiel_id_val(val);
} else if name == fields.timestamp {
timestamp_state = decode_timestamp_val(val, unit);
} else if name == fields.edited {
// Fail closed on repeated `edited` fields so a later value (e.g. Null) can never
// mask an earlier unreadable or later edit timestamp.
edited_state = if matches!(edited_state, EditedState::Absent) {
decode_edited_val(val, unit)
} else {
EditedState::Invalid
};
} else if name == fields.bot {
bot_state = decode_bot_val(val);
} else if name == fields.user_id {
user_id_state = decode_user_id_val(val);
} else if name == fields.text {
text_state = decode_text_val(val);
}
}
// Apply deterministic semantic skip priority: key -> spiel_id -> timestamp -> edited -> text.
let key = match key_state {
KeyState::Valid(s) => s,
KeyState::Missing => {
stats.skipped_missing_key += 1;
return Ok(stats);
}
KeyState::WrongType => {
stats.skipped_wrong_key_type += 1;
return Ok(stats);
}
KeyState::Empty => {
stats.skipped_empty_key += 1;
return Ok(stats);
}
};
match spiel_id_state {
SpielIdState::Str(_) | SpielIdState::Int32(_) | SpielIdState::Int64(_) => {}
SpielIdState::Missing => {
stats.skipped_missing_spiel_id += 1;
return Ok(stats);
}
SpielIdState::WrongType => {
stats.skipped_wrong_spiel_id_type += 1;
return Ok(stats);
}
SpielIdState::Empty => {
stats.skipped_empty_spiel_id += 1;
return Ok(stats);
}
}
let timestamp_ms = match timestamp_state {
TimestampState::Valid(ms) => ms,
TimestampState::Missing => {
stats.skipped_missing_timestamp += 1;
return Ok(stats);
}
TimestampState::WrongType => {
stats.skipped_wrong_timestamp_type += 1;
return Ok(stats);
}
TimestampState::Invalid => {
stats.skipped_invalid_timestamp += 1;
return Ok(stats);
}
TimestampState::OutOfRange => {
stats.skipped_timestamp_out_of_range += 1;
return Ok(stats);
}
};
let (edited_ms, edited_is_zero_or_false) = match edited_state {
EditedState::Absent | EditedState::Null => (None, false),
EditedState::ZeroOrFalse => (None, true),
EditedState::Valid(ms) => (Some(ms), false),
EditedState::Invalid => {
stats.skipped_invalid_edited += 1;
return Ok(stats);
}
};
let (text, text_is_empty) = match text_state {
TextState::Str(s) => (s.to_owned(), false),
TextState::MissingOrNull => (String::new(), true),
TextState::WrongType => {
stats.skipped_wrong_text_type += 1;
return Ok(stats);
}
};
// Row passed all skip checks: record emitted-row counters and allocate owned fields.
if edited_is_zero_or_false {
stats.edited_zero_or_false += 1;
}
if text_is_empty {
stats.empty_text += 1;
}
let spiel_id = match spiel_id_state {
SpielIdState::Str(s) => s.to_owned(),
SpielIdState::Int32(v) => v.to_string(),
SpielIdState::Int64(v) => v.to_string(),
SpielIdState::Missing | SpielIdState::WrongType | SpielIdState::Empty => {
unreachable!("validated above")
}
};
let bot = match bot_state {
BotState::None => None,
BotState::Str(s) => Some(s.to_owned()),
BotState::Int32(v) => Some(v.to_string()),
BotState::Int64(v) => Some(v.to_string()),
BotState::Bool(true) => Some("1".to_owned()),
BotState::Bool(false) => Some("0".to_owned()),
BotState::WrongType => {
stats.nulled_wrong_type_bot += 1;
None
}
};
let user_id = match user_id_state {
UserIdState::None => None,
UserIdState::Str(s) => Some(s.to_owned()),
UserIdState::Int32(v) => Some(v.to_string()),
UserIdState::Int64(v) => Some(v.to_string()),
UserIdState::WrongType => {
stats.nulled_wrong_type_user_id += 1;
None
}
};
stats.rows_out += 1;
on_row(CeoPost {
key,
spiel_id,
timestamp_ms,
edited_ms,
bot,
user_id,
text,
});
Ok(stats)
}
/// Decodes a single `&RawDocument` representing a `ceoPosts` MongoDB document in one forward pass
/// without allocating a `bson::Document`.
///
/// Validates `fields` before inspecting the document.
pub fn decode_ceo_posts_doc<'a, F>(
doc: &'a RawDocument,
fields: &CeoPostsFieldNames<'_>,
unit: CeoPostsTimestampUnit,
on_row: F,
) -> Result<BsonCeoPostsDecodeStats, BsonCeoPostsError>
where
F: FnMut(CeoPost<&'a str>),
{
fields.validate()?;
decode_ceo_posts_doc_at(doc, 0, fields, unit, on_row)
}
/// Decodes a single length-prefixed raw BSON document byte slice representing a `ceoPosts`
/// document.
///
/// Validates `fields` before inspecting the bytes.
pub fn decode_ceo_posts_bytes<'a, F>(
bytes: &'a [u8],
fields: &CeoPostsFieldNames<'_>,
unit: CeoPostsTimestampUnit,
on_row: F,
) -> Result<BsonCeoPostsDecodeStats, BsonCeoPostsError>
where
F: FnMut(CeoPost<&'a str>),
{
fields.validate()?;
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
decode_ceo_posts_doc_at(doc, 0, fields, unit, on_row)
}
/// Streams a concatenated length-prefixed BSON buffer through [`decode_ceo_posts_doc`],
/// emitting every valid [`CeoPost<&str>`] to `on_row` and failing closed on the first structural
/// BSON framing or element corruption.
///
/// Validates `fields` once before reading the buffer. If an error occurs after one or more valid
/// documents, `on_row` has already been invoked for those earlier documents.
///
/// Always maintains `stats.docs_in == stats.rows_out + stats.skipped_total()`.
pub fn decode_ceo_posts_buffer<'a, F>(
buf: &'a [u8],
fields: &CeoPostsFieldNames<'_>,
unit: CeoPostsTimestampUnit,
mut on_row: F,
) -> Result<BsonCeoPostsDecodeStats, BsonCeoPostsError>
where
F: FnMut(CeoPost<&'a str>),
{
fields.validate()?;
let mut total = BsonCeoPostsDecodeStats::default();
let mut iter = iter_raw_bson_docs(buf);
while let Some(item) = iter.next_with_offset() {
match item {
Ok((offset, doc)) => {
let doc_stats =
decode_ceo_posts_doc_at(doc, offset as u64, fields, unit, &mut on_row)?;
total += doc_stats;
}
Err((_, err)) => return Err(map_framing_error(err)),
}
}
Ok(total)
}
#[cfg(test)]
#[path = "bson_ceo_posts_tests.rs"]
mod tests;

File diff suppressed because it is too large Load diff

View file

@ -4,6 +4,7 @@ pub mod adj;
pub mod bars;
pub mod bars_1m;
pub mod bench;
pub mod bson_ceo_posts;
pub mod bson_ceo_shorts;
pub mod bson_eod_intraday;
pub mod bson_eod_prices;
@ -50,6 +51,10 @@ pub use bars_1m::{
SessionCloseCheck, SessionCloseCutoffPolicy, SessionCloseMismatchSample, SessionCloseStats,
BARS_1M_SOURCE_EOD, BARS_1M_SOURCE_QM, RTH_END_MINUTE_ET, RTH_START_MINUTE_ET,
};
pub use bson_ceo_posts::{
decode_ceo_posts_buffer, decode_ceo_posts_bytes, decode_ceo_posts_doc,
BsonCeoPostsDecodeStats, BsonCeoPostsError, CeoPostsFieldNames, CeoPostsTimestampUnit,
};
pub use bson_ceo_shorts::{
decode_ceo_shorts_buffer, decode_ceo_shorts_bytes, decode_ceo_shorts_doc,
BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, DEFAULT_KEY_FIELD,