diff --git a/tools/curate-etl/src/bson_ceo_posts.rs b/tools/curate-etl/src/bson_ceo_posts.rs new file mode 100644 index 00000000..046ec0f9 --- /dev/null +++ b/tools/curate-etl/src/bson_ceo_posts.rs @@ -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, + }, + /// 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 +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 +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 +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 +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; diff --git a/tools/curate-etl/src/bson_ceo_posts_tests.rs b/tools/curate-etl/src/bson_ceo_posts_tests.rs new file mode 100644 index 00000000..b80fd2b0 --- /dev/null +++ b/tools/curate-etl/src/bson_ceo_posts_tests.rs @@ -0,0 +1,1070 @@ +use bson::raw::{cstr, RawArrayBuf, RawBson, RawDocument, RawDocumentBuf}; +use bson::DateTime as BsonDateTime; + +use super::*; +use crate::posts::build_posts; + +fn assert_conservation(stats: &BsonCeoPostsDecodeStats) { + assert_eq!( + stats.docs_in, + stats.rows_out + stats.skipped_total(), + "conservation invariant failed: {stats:?}" + ); +} + +fn make_base_doc(key: &str, spiel_id: &str, ts_secs: i64) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("ceoId"), key); + doc.append(cstr!("spielId"), spiel_id); + doc.append(cstr!("timestamp"), ts_secs); + doc.append(cstr!("spiel"), "hello world"); + doc +} + +#[test] +fn validates_field_names_rejecting_empty_blank_and_duplicates() { + let defaults = CeoPostsFieldNames::default(); + assert_eq!(defaults.key, DEFAULT_KEY_FIELD); + assert_eq!(defaults.spiel_id, DEFAULT_SPIEL_ID_FIELD); + assert_eq!(defaults.timestamp, DEFAULT_TIMESTAMP_FIELD); + assert_eq!(defaults.edited, DEFAULT_EDITED_FIELD); + assert_eq!(defaults.bot, DEFAULT_BOT_FIELD); + assert_eq!(defaults.user_id, DEFAULT_USER_ID_FIELD); + assert_eq!(defaults.text, DEFAULT_TEXT_FIELD); + assert!(defaults.validate().is_ok()); + + let custom = CeoPostsFieldNames { + key: "channel", + spiel_id: "postId", + timestamp: "createdAt", + edited: "updatedAt", + bot: "isBot", + user_id: "authorId", + text: "body", + }; + assert!(custom.validate().is_ok()); + + let bad_configs = [ + CeoPostsFieldNames { + key: "", + ..defaults + }, + CeoPostsFieldNames { + key: " \t ", + ..defaults + }, + CeoPostsFieldNames { + spiel_id: "", + ..defaults + }, + CeoPostsFieldNames { + timestamp: " ", + ..defaults + }, + CeoPostsFieldNames { + edited: "", + ..defaults + }, + CeoPostsFieldNames { + bot: " ", + ..defaults + }, + CeoPostsFieldNames { + user_id: "", + ..defaults + }, + CeoPostsFieldNames { + text: "\t", + ..defaults + }, + // Duplicate role mappings + CeoPostsFieldNames { + key: "dup", + spiel_id: "dup", + ..defaults + }, + CeoPostsFieldNames { + timestamp: "edited", + ..defaults + }, + CeoPostsFieldNames { + bot: "userId", + ..defaults + }, + CeoPostsFieldNames { + text: "ceoId", + ..defaults + }, + ]; + + let empty_doc = RawDocumentBuf::new(); + + for cfg in bad_configs { + let err = cfg.validate().unwrap_err(); + assert!( + matches!(err, BsonCeoPostsError::InvalidFieldNames { .. }), + "expected InvalidFieldNames for {cfg:?}, got {err:?}" + ); + let msg = err.to_string(); + assert!(!msg.contains('\n'), "single-line display expected: {msg}"); + + // All three entry points validate config before touching bytes/docs. + assert!(matches!( + decode_ceo_posts_buffer(&[], &cfg, CeoPostsTimestampUnit::Seconds, |_| {}), + Err(BsonCeoPostsError::InvalidFieldNames { .. }) + )); + assert!(matches!( + decode_ceo_posts_bytes(&[], &cfg, CeoPostsTimestampUnit::Millis, |_| {}), + Err(BsonCeoPostsError::InvalidFieldNames { .. }) + )); + assert!(matches!( + decode_ceo_posts_doc( + empty_doc.as_ref(), + &cfg, + CeoPostsTimestampUnit::Seconds, + |_| {} + ), + Err(BsonCeoPostsError::InvalidFieldNames { .. }) + )); + } +} + +#[test] +fn decodes_timestamp_and_edited_across_types_under_seconds_and_millis() { + let fields = CeoPostsFieldNames::default(); + let ts_sec_i32: i32 = 1_710_460_800; // 2024-03-15T00:00:00Z + let ed_sec_i32: i32 = 1_710_461_400; // +600s + let ts_sec_i64: i64 = 1_710_460_900; + let ed_sec_i64: i64 = 1_710_461_900; + let ts_dt_ms: i64 = 1_710_460_800_123; + let ed_dt_ms: i64 = 1_710_461_400_456; + + // --- Seconds unit --- + let mut sec_buf = Vec::new(); + + // 1. Int32 timestamp + Int32 edited + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("ceoId"), " CH-1 "); // verbatim + d1.append(cstr!("spielId"), "s1"); + d1.append(cstr!("timestamp"), ts_sec_i32); + d1.append(cstr!("edited"), ed_sec_i32); + d1.append(cstr!("spiel"), "int32"); + sec_buf.extend_from_slice(d1.as_bytes()); + + // 2. Int64 timestamp + Int64 edited + let mut d2 = RawDocumentBuf::new(); + d2.append(cstr!("ceoId"), "CH-2"); + d2.append(cstr!("spielId"), 200_i32); + d2.append(cstr!("timestamp"), ts_sec_i64); + d2.append(cstr!("edited"), ed_sec_i64); + d2.append(cstr!("spiel"), "int64"); + sec_buf.extend_from_slice(d2.as_bytes()); + + // 3. Integral Double timestamp + integral Double edited + let mut d3 = RawDocumentBuf::new(); + d3.append(cstr!("ceoId"), "CH-3"); + d3.append(cstr!("spielId"), 300_i64); + d3.append(cstr!("timestamp"), ts_sec_i64 as f64); + d3.append(cstr!("edited"), ed_sec_i64 as f64); + d3.append(cstr!("spiel"), "double"); + sec_buf.extend_from_slice(d3.as_bytes()); + + // 4. BSON DateTime (already ms; unit ignored) + let mut d4 = RawDocumentBuf::new(); + d4.append(cstr!("ceoId"), "CH-4"); + d4.append(cstr!("spielId"), "s4"); + d4.append(cstr!("timestamp"), BsonDateTime::from_millis(ts_dt_ms)); + d4.append(cstr!("edited"), BsonDateTime::from_millis(ed_dt_ms)); + d4.append(cstr!("spiel"), "datetime"); + sec_buf.extend_from_slice(d4.as_bytes()); + + // 5. Non-positive creation times (<= 0) passed through verbatim (build_posts rejects them) + let mut d5 = RawDocumentBuf::new(); + d5.append(cstr!("ceoId"), "CH-5"); + d5.append(cstr!("spielId"), "s5"); + d5.append(cstr!("timestamp"), 0_i32); + d5.append(cstr!("spiel"), "zero"); + sec_buf.extend_from_slice(d5.as_bytes()); + + let mut d6 = RawDocumentBuf::new(); + d6.append(cstr!("ceoId"), "CH-6"); + d6.append(cstr!("spielId"), "s6"); + d6.append(cstr!("timestamp"), -10_i64); + d6.append(cstr!("spiel"), "neg"); + sec_buf.extend_from_slice(d6.as_bytes()); + + let mut d7 = RawDocumentBuf::new(); + d7.append(cstr!("ceoId"), "CH-7"); + d7.append(cstr!("spielId"), "s7"); + d7.append(cstr!("timestamp"), -0.0_f64); + d7.append(cstr!("spiel"), "negzero"); + sec_buf.extend_from_slice(d7.as_bytes()); + + let buf_start = sec_buf.as_ptr() as usize; + let buf_end = buf_start + sec_buf.len(); + + let mut sec_rows = Vec::new(); + let stats = decode_ceo_posts_buffer(&sec_buf, &fields, CeoPostsTimestampUnit::Seconds, |r| { + // Verify zero-copy borrow: `key` points directly into `sec_buf`. + let key_ptr = r.key.as_ptr() as usize; + assert!( + key_ptr >= buf_start && key_ptr + r.key.len() <= buf_end, + "decoded key must borrow directly from input buffer" + ); + sec_rows.push(( + r.key.to_owned(), + r.spiel_id, + r.timestamp_ms, + r.edited_ms, + r.text, + )); + }) + .expect("decode seconds buffer"); + + assert_conservation(&stats); + assert_eq!(stats.docs_in, 7); + assert_eq!(stats.rows_out, 7); + assert_eq!( + sec_rows, + vec![ + ( + " CH-1 ".to_string(), + "s1".to_string(), + i64::from(ts_sec_i32) * 1_000, + Some(i64::from(ed_sec_i32) * 1_000), + "int32".to_string() + ), + ( + "CH-2".to_string(), + "200".to_string(), + ts_sec_i64 * 1_000, + Some(ed_sec_i64 * 1_000), + "int64".to_string() + ), + ( + "CH-3".to_string(), + "300".to_string(), + ts_sec_i64 * 1_000, + Some(ed_sec_i64 * 1_000), + "double".to_string() + ), + ( + "CH-4".to_string(), + "s4".to_string(), + ts_dt_ms, + Some(ed_dt_ms), + "datetime".to_string() + ), + ( + "CH-5".to_string(), + "s5".to_string(), + 0, + None, + "zero".to_string() + ), + ( + "CH-6".to_string(), + "s6".to_string(), + -10_000, + None, + "neg".to_string() + ), + ( + "CH-7".to_string(), + "s7".to_string(), + 0, + None, + "negzero".to_string() + ), + ] + ); + + // --- Millis unit --- + let mut ms_buf = Vec::new(); + + // Int32 millis + let mut m1 = RawDocumentBuf::new(); + m1.append(cstr!("ceoId"), "M1"); + m1.append(cstr!("spielId"), "m1"); + m1.append(cstr!("timestamp"), 1_000_000_i32); + m1.append(cstr!("edited"), 1_000_500_i32); + m1.append(cstr!("spiel"), "m1"); + ms_buf.extend_from_slice(m1.as_bytes()); + + // Int64 millis + let mut m2 = RawDocumentBuf::new(); + m2.append(cstr!("ceoId"), "M2"); + m2.append(cstr!("spielId"), "m2"); + m2.append(cstr!("timestamp"), ts_dt_ms); + m2.append(cstr!("edited"), ed_dt_ms); + m2.append(cstr!("spiel"), "m2"); + ms_buf.extend_from_slice(m2.as_bytes()); + + // Integral Double millis (including exact -2^63 and 2^63 - 1024 boundaries) + let mut m3 = RawDocumentBuf::new(); + m3.append(cstr!("ceoId"), "M3"); + m3.append(cstr!("spielId"), "m3"); + m3.append(cstr!("timestamp"), -9_223_372_036_854_775_808.0_f64); + m3.append(cstr!("edited"), 9_223_372_036_854_774_784.0_f64); + m3.append(cstr!("spiel"), "m3"); + ms_buf.extend_from_slice(m3.as_bytes()); + + // BSON DateTime under Millis (unchanged) + let mut m4 = RawDocumentBuf::new(); + m4.append(cstr!("ceoId"), "M4"); + m4.append(cstr!("spielId"), "m4"); + m4.append(cstr!("timestamp"), BsonDateTime::from_millis(ts_dt_ms)); + m4.append(cstr!("edited"), BsonDateTime::from_millis(ed_dt_ms)); + m4.append(cstr!("spiel"), "m4"); + ms_buf.extend_from_slice(m4.as_bytes()); + + let mut ms_rows = Vec::new(); + let ms_stats = decode_ceo_posts_buffer(&ms_buf, &fields, CeoPostsTimestampUnit::Millis, |r| { + ms_rows.push((r.spiel_id, r.timestamp_ms, r.edited_ms)); + }) + .expect("decode millis buffer"); + + assert_conservation(&ms_stats); + assert_eq!(ms_stats.docs_in, 4); + assert_eq!(ms_stats.rows_out, 4); + assert_eq!( + ms_rows, + vec![ + ("m1".to_string(), 1_000_000, Some(1_000_500)), + ("m2".to_string(), ts_dt_ms, Some(ed_dt_ms)), + ( + "m3".to_string(), + i64::MIN, + Some(9_223_372_036_854_774_784_i64) + ), + ("m4".to_string(), ts_dt_ms, Some(ed_dt_ms)), + ] + ); +} + +#[test] +fn skips_timestamp_seconds_overflow_and_double_range_boundaries() { + let fields = CeoPostsFieldNames::default(); + let mut buf = Vec::new(); + + // 1. Positive Int64 seconds overflow (i64::MAX / 1_000 + 1) + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("ceoId"), "CH"); + d1.append(cstr!("spielId"), "ovf_pos"); + d1.append(cstr!("timestamp"), (i64::MAX / 1_000) + 1); + buf.extend_from_slice(d1.as_bytes()); + + // 2. Negative Int64 seconds overflow (i64::MIN / 1_000 - 1) + let mut d2 = RawDocumentBuf::new(); + d2.append(cstr!("ceoId"), "CH"); + d2.append(cstr!("spielId"), "ovf_neg"); + d2.append(cstr!("timestamp"), (i64::MIN / 1_000) - 1); + buf.extend_from_slice(d2.as_bytes()); + + // 3. Double exactly at 2^63 (outside half-open [-2^63, 2^63)) + let mut d3 = RawDocumentBuf::new(); + d3.append(cstr!("ceoId"), "CH"); + d3.append(cstr!("spielId"), "dbl_2p63"); + d3.append(cstr!("timestamp"), 9_223_372_036_854_775_808.0_f64); + buf.extend_from_slice(d3.as_bytes()); + + // 4. Double below -2^63 + let mut d4 = RawDocumentBuf::new(); + d4.append(cstr!("ceoId"), "CH"); + d4.append(cstr!("spielId"), "dbl_neg_oob"); + d4.append(cstr!("timestamp"), -1e20_f64); + buf.extend_from_slice(d4.as_bytes()); + + // 5. Double in i64 range but overflows when multiplied by 1_000 + let mut d5 = RawDocumentBuf::new(); + d5.append(cstr!("ceoId"), "CH"); + d5.append(cstr!("spielId"), "dbl_sec_ovf"); + d5.append(cstr!("timestamp"), 9_223_372_036_854_774_784.0_f64); + buf.extend_from_slice(d5.as_bytes()); + + let mut emitted = 0usize; + let stats = decode_ceo_posts_buffer(&buf, &fields, CeoPostsTimestampUnit::Seconds, |_| { + emitted += 1; + }) + .expect("decode overflow buffer"); + + assert_conservation(&stats); + assert_eq!(emitted, 0); + assert_eq!(stats.docs_in, 5); + assert_eq!(stats.skipped_timestamp_out_of_range, 5); + + // Under Millis, 2^63 is still out of range. + let stats_2p63 = + decode_ceo_posts_bytes(d3.as_bytes(), &fields, CeoPostsTimestampUnit::Millis, |_| { + panic!("2^63 double must not emit") + }) + .expect("decode 2^63 under millis"); + assert_eq!(stats_2p63.skipped_timestamp_out_of_range, 1); +} + +#[test] +fn edited_fail_closed_rule_and_sentinel_accounting() { + let fields = CeoPostsFieldNames::default(); + let ts_sec: i64 = 1_710_460_800; + + // --- Unedited & valid cases --- + let mut valid_buf = Vec::new(); + + // 1. Absent edited -> None (not counted in edited_zero_or_false) + valid_buf.extend_from_slice(make_base_doc("CH", "e_absent", ts_sec).as_bytes()); + + // 2. Null edited -> None (not counted in edited_zero_or_false) + let mut d = make_base_doc("CH", "e_null", ts_sec); + d.append(cstr!("edited"), RawBson::Null); + valid_buf.extend_from_slice(d.as_bytes()); + + // 3. Int32(0) -> None + edited_zero_or_false + let mut d = make_base_doc("CH", "e_i32_zero", ts_sec); + d.append(cstr!("edited"), 0_i32); + valid_buf.extend_from_slice(d.as_bytes()); + + // 4. Int64(0) -> None + edited_zero_or_false + let mut d = make_base_doc("CH", "e_i64_zero", ts_sec); + d.append(cstr!("edited"), 0_i64); + valid_buf.extend_from_slice(d.as_bytes()); + + // 5. Double(0.0) -> None + edited_zero_or_false + let mut d = make_base_doc("CH", "e_f64_zero", ts_sec); + d.append(cstr!("edited"), 0.0_f64); + valid_buf.extend_from_slice(d.as_bytes()); + + // 6. Double(-0.0) -> None + edited_zero_or_false + let mut d = make_base_doc("CH", "e_f64_neg_zero", ts_sec); + d.append(cstr!("edited"), -0.0_f64); + valid_buf.extend_from_slice(d.as_bytes()); + + // 7. Boolean(false) -> None + edited_zero_or_false + let mut d = make_base_doc("CH", "e_bool_false", ts_sec); + d.append(cstr!("edited"), false); + valid_buf.extend_from_slice(d.as_bytes()); + + // 8. Epoch-zero BSON DateTime -> Some(0) (not numeric zero sentinel) + let mut d = make_base_doc("CH", "e_dt_zero", ts_sec); + d.append(cstr!("edited"), BsonDateTime::from_millis(0)); + valid_buf.extend_from_slice(d.as_bytes()); + + let mut valid_out = Vec::new(); + let valid_stats = + decode_ceo_posts_buffer(&valid_buf, &fields, CeoPostsTimestampUnit::Seconds, |r| { + valid_out.push((r.spiel_id, r.edited_ms)); + }) + .expect("decode valid edited buffer"); + + assert_conservation(&valid_stats); + assert_eq!(valid_stats.docs_in, 8); + assert_eq!(valid_stats.rows_out, 8); + assert_eq!(valid_stats.skipped_invalid_edited, 0); + assert_eq!(valid_stats.edited_zero_or_false, 5); + assert_eq!( + valid_out, + vec![ + ("e_absent".to_string(), None), + ("e_null".to_string(), None), + ("e_i32_zero".to_string(), None), + ("e_i64_zero".to_string(), None), + ("e_f64_zero".to_string(), None), + ("e_f64_neg_zero".to_string(), None), + ("e_bool_false".to_string(), None), + ("e_dt_zero".to_string(), Some(0)), + ] + ); + + // --- Fail-closed rejected cases (must NEVER invoke on_row) --- + let mut bad_buf = Vec::new(); + + // 1. Negative Int32 + let mut d = make_base_doc("CH", "bad_neg_i32", ts_sec); + d.append(cstr!("edited"), -1_i32); + bad_buf.extend_from_slice(d.as_bytes()); + + // 2. Negative Int64 + let mut d = make_base_doc("CH", "bad_neg_i64", ts_sec); + d.append(cstr!("edited"), -5_000_i64); + bad_buf.extend_from_slice(d.as_bytes()); + + // 3. Negative Double + let mut d = make_base_doc("CH", "bad_neg_f64", ts_sec); + d.append(cstr!("edited"), -1.0_f64); + bad_buf.extend_from_slice(d.as_bytes()); + + // 4. Negative DateTime + let mut d = make_base_doc("CH", "bad_neg_dt", ts_sec); + d.append(cstr!("edited"), BsonDateTime::from_millis(-1)); + bad_buf.extend_from_slice(d.as_bytes()); + + // 5. Fractional Double + let mut d = make_base_doc("CH", "bad_frac", ts_sec); + d.append(cstr!("edited"), 1_710_461_400.5_f64); + bad_buf.extend_from_slice(d.as_bytes()); + + // 6. NaN Double + let mut d = make_base_doc("CH", "bad_nan", ts_sec); + d.append(cstr!("edited"), f64::NAN); + bad_buf.extend_from_slice(d.as_bytes()); + + // 7. +Inf Double + let mut d = make_base_doc("CH", "bad_inf", ts_sec); + d.append(cstr!("edited"), f64::INFINITY); + bad_buf.extend_from_slice(d.as_bytes()); + + // 8. Boolean(true) + let mut d = make_base_doc("CH", "bad_true", ts_sec); + d.append(cstr!("edited"), true); + bad_buf.extend_from_slice(d.as_bytes()); + + // 9. String + let mut d = make_base_doc("CH", "bad_str", ts_sec); + d.append(cstr!("edited"), "1710461400"); + bad_buf.extend_from_slice(d.as_bytes()); + + // 10. Unsupported type (embedded document) + let mut d = make_base_doc("CH", "bad_doc", ts_sec); + d.append(cstr!("edited"), RawDocumentBuf::new()); + bad_buf.extend_from_slice(d.as_bytes()); + + // 11. Seconds overflow + let mut d = make_base_doc("CH", "bad_ovf", ts_sec); + d.append(cstr!("edited"), (i64::MAX / 1_000) + 1); + bad_buf.extend_from_slice(d.as_bytes()); + + // 12. Repeated `edited` with unreadable value followed by Null (must fail closed!) + let mut d = make_base_doc("CH", "bad_dup_unreadable_then_null", ts_sec); + d.append(cstr!("edited"), "unreadable"); + d.append(cstr!("edited"), RawBson::Null); + bad_buf.extend_from_slice(d.as_bytes()); + + // 13. Repeated `edited` with valid timestamp followed by Null + let mut d = make_base_doc("CH", "bad_dup_valid_then_null", ts_sec); + d.append(cstr!("edited"), ts_sec + 60); + d.append(cstr!("edited"), RawBson::Null); + bad_buf.extend_from_slice(d.as_bytes()); + + // 14. Repeated `edited` with Null followed by valid timestamp + let mut d = make_base_doc("CH", "bad_dup_null_then_valid", ts_sec); + d.append(cstr!("edited"), RawBson::Null); + d.append(cstr!("edited"), ts_sec + 60); + bad_buf.extend_from_slice(d.as_bytes()); + + let mut bad_emitted = 0usize; + let bad_stats = + decode_ceo_posts_buffer(&bad_buf, &fields, CeoPostsTimestampUnit::Seconds, |_| { + bad_emitted += 1; + }) + .expect("decode bad edited buffer"); + + assert_conservation(&bad_stats); + assert_eq!(bad_emitted, 0); + assert_eq!(bad_stats.docs_in, 14); + assert_eq!(bad_stats.rows_out, 0); + assert_eq!(bad_stats.skipped_invalid_edited, 14); + assert_eq!(bad_stats.edited_zero_or_false, 0); +} + +#[test] +fn skips_every_counter_respects_priority_and_matches_single_doc_sum() { + let fields = CeoPostsFieldNames::default(); + let ts_sec: i64 = 1_710_460_800; + + let mut docs: Vec = Vec::new(); + + // 1. skipped_missing_key (also missing spiel_id, timestamp, bad edited, bad text -> key wins) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("spiel"), 123_i32); + d.append(cstr!("edited"), true); + docs.push(d); + + // 2. skipped_wrong_key_type (fields in reverse priority order -> key still wins) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("spiel"), 123_i32); + d.append(cstr!("edited"), "bad"); + d.append(cstr!("timestamp"), "bad"); + d.append(cstr!("spielId"), true); + d.append(cstr!("ceoId"), 42_i32); + docs.push(d); + + // 3. skipped_empty_key (with wrong-type optionals & zero edited -> emitted-row counters stay 0) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), " "); + d.append(cstr!("spielId"), "s3"); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("edited"), 0_i32); + d.append(cstr!("bot"), 1.5_f64); + d.append(cstr!("userId"), true); + docs.push(d); + + // 4. skipped_missing_spiel_id (also bad timestamp, edited, text -> spiel_id wins) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("spiel"), false); + d.append(cstr!("edited"), true); + d.append(cstr!("timestamp"), f64::NAN); + d.append(cstr!("ceoId"), "CH"); + docs.push(d); + + // 5. skipped_wrong_spiel_id_type + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), true); + d.append(cstr!("timestamp"), ts_sec); + docs.push(d); + + // 6. skipped_empty_spiel_id + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), " "); + d.append(cstr!("timestamp"), ts_sec); + docs.push(d); + + // 7. skipped_missing_timestamp (also bad edited & bad text -> timestamp wins) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("spiel"), 99_i32); + d.append(cstr!("edited"), "bad"); + d.append(cstr!("spielId"), "s7"); + d.append(cstr!("ceoId"), "CH"); + docs.push(d); + + // 8. skipped_wrong_timestamp_type + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "s8"); + d.append(cstr!("timestamp"), "2024-03-15"); + docs.push(d); + + // 9. skipped_invalid_timestamp (fractional Double) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "s9"); + d.append(cstr!("timestamp"), 1_710_460_800.25_f64); + docs.push(d); + + // 10. skipped_timestamp_out_of_range (Seconds overflow) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "s10"); + d.append(cstr!("timestamp"), i64::MAX); + docs.push(d); + + // 11. skipped_invalid_edited (also bad text -> edited wins over text) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("spiel"), 99_i32); + d.append(cstr!("edited"), true); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("spielId"), "s11"); + d.append(cstr!("ceoId"), "CH"); + docs.push(d); + + // 12. skipped_wrong_text_type (with valid edited=0 and wrong-type bot/userId -> emitted counters stay 0) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "s12"); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("edited"), false); + d.append(cstr!("bot"), 2.5_f64); + d.append(cstr!("userId"), true); + d.append(cstr!("spiel"), 123_i32); + docs.push(d); + + // 13. Valid emitted row with missing text, wrong-type bot & userId, edited=false + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "ok1"); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("edited"), false); + d.append(cstr!("bot"), 2.5_f64); + d.append(cstr!("userId"), false); + docs.push(d); + + // 14. Valid emitted row with Null text, Int32 userId, String bot + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "ok2"); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("bot"), "1"); + d.append(cstr!("userId"), 777_i32); + d.append(cstr!("spiel"), RawBson::Null); + docs.push(d); + + // 15. Valid emitted row with explicit empty string text (not counted in empty_text) and Int64 userId + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "ok3"); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("bot"), 0_i64); + d.append(cstr!("userId"), 9_000_000_000_i64); + d.append(cstr!("spiel"), ""); + docs.push(d); + + let mut combined = Vec::new(); + let mut summed = BsonCeoPostsDecodeStats::default(); + for doc in &docs { + combined.extend_from_slice(doc.as_bytes()); + let single = + decode_ceo_posts_doc(doc.as_ref(), &fields, CeoPostsTimestampUnit::Seconds, |_| {}) + .expect("decode single doc"); + assert_conservation(&single); + summed += single; + } + + let mut emitted = Vec::new(); + let buf_stats = decode_ceo_posts_buffer( + &combined, + &fields, + CeoPostsTimestampUnit::Seconds, + |r| emitted.push((r.spiel_id, r.bot, r.user_id, r.text)), + ) + .expect("decode combined buffer"); + + assert_conservation(&buf_stats); + assert_eq!(buf_stats, summed); + assert_eq!(buf_stats.docs_in, 15); + assert_eq!(buf_stats.rows_out, 3); + assert_eq!(buf_stats.skipped_total(), 12); + assert_eq!(buf_stats.skipped_missing_key, 1); + assert_eq!(buf_stats.skipped_wrong_key_type, 1); + assert_eq!(buf_stats.skipped_empty_key, 1); + assert_eq!(buf_stats.skipped_missing_spiel_id, 1); + assert_eq!(buf_stats.skipped_wrong_spiel_id_type, 1); + assert_eq!(buf_stats.skipped_empty_spiel_id, 1); + assert_eq!(buf_stats.skipped_missing_timestamp, 1); + assert_eq!(buf_stats.skipped_wrong_timestamp_type, 1); + assert_eq!(buf_stats.skipped_invalid_timestamp, 1); + assert_eq!(buf_stats.skipped_timestamp_out_of_range, 1); + assert_eq!(buf_stats.skipped_invalid_edited, 1); + assert_eq!(buf_stats.skipped_wrong_text_type, 1); + assert_eq!(buf_stats.edited_zero_or_false, 1); + assert_eq!(buf_stats.nulled_wrong_type_bot, 1); + assert_eq!(buf_stats.nulled_wrong_type_user_id, 1); + assert_eq!(buf_stats.empty_text, 2); + + assert_eq!( + emitted, + vec![ + ("ok1".to_string(), None, None, String::new()), + ( + "ok2".to_string(), + Some("1".to_string()), + Some("777".to_string()), + String::new() + ), + ( + "ok3".to_string(), + Some("0".to_string()), + Some("9000000000".to_string()), + String::new() + ), + ] + ); +} + +#[test] +fn decodes_custom_field_names_and_feeds_build_posts_deterministically() { + let fields = CeoPostsFieldNames { + key: "channelId", + spiel_id: "postId", + timestamp: "postedSec", + edited: "editedSec", + bot: "botFlag", + user_id: "author", + text: "body", + }; + + let t0_sec: i64 = 1_710_460_800; // 2024-03-15T00:00:00Z + let t_edit_sec: i64 = t0_sec + 900; // +15m + + let mut raw_docs: Vec = Vec::new(); + + // 1. bot = "1" (newswire, unedited baseline) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "nw_str_1"); + d.append(cstr!("postedSec"), t0_sec); + d.append(cstr!("botFlag"), "1"); + d.append(cstr!("author"), "wire"); + d.append(cstr!("body"), "Press release"); + raw_docs.push(d); + + // 2. bot = Int32(1) (newswire, edited later -> known_at == edited_ms * 1_000) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "nw_i32_1"); + d.append(cstr!("postedSec"), t0_sec + 10); + d.append(cstr!("editedSec"), t_edit_sec); + d.append(cstr!("botFlag"), 1_i32); + d.append(cstr!("author"), 42_i32); + d.append(cstr!("body"), "Corrected release"); + raw_docs.push(d); + + // 3. bot = Boolean(true) (newswire) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "nw_bool_true"); + d.append(cstr!("postedSec"), t0_sec + 20); + d.append(cstr!("botFlag"), true); + d.append(cstr!("body"), "Auto alert"); + raw_docs.push(d); + + // 4. bot = "0" (retail) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "ret_str_0"); + d.append(cstr!("postedSec"), t0_sec + 30); + d.append(cstr!("botFlag"), "0"); + d.append(cstr!("body"), "Retail chatter"); + raw_docs.push(d); + + // 5. bot absent (retail) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "ret_absent"); + d.append(cstr!("postedSec"), t0_sec + 40); + d.append(cstr!("body"), "No bot field"); + raw_docs.push(d); + + // 6. bot wrong type (Double -> nulled -> retail) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "ret_wrong_type"); + d.append(cstr!("postedSec"), t0_sec + 50); + d.append(cstr!("botFlag"), 1.0_f64); + d.append(cstr!("body"), "Wrong type bot"); + raw_docs.push(d); + + // 7. Non-positive creation time passed through by decoder, rejected by build_posts + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "zero_ts"); + d.append(cstr!("postedSec"), 0_i64); + d.append(cstr!("body"), "Zero ts"); + raw_docs.push(d); + + let mut buf = Vec::new(); + for d in &raw_docs { + buf.extend_from_slice(d.as_bytes()); + } + + // Run through all three entry points and confirm identical decoded rows. + let mut rows_from_buffer = Vec::new(); + let stats_buf = decode_ceo_posts_buffer(&buf, &fields, CeoPostsTimestampUnit::Seconds, |r| { + rows_from_buffer.push(r); + }) + .expect("decode buffer"); + + let mut rows_from_bytes = Vec::new(); + let mut stats_bytes = BsonCeoPostsDecodeStats::default(); + for d in &raw_docs { + stats_bytes += decode_ceo_posts_bytes( + d.as_bytes(), + &fields, + CeoPostsTimestampUnit::Seconds, + |r| rows_from_bytes.push(r), + ) + .expect("decode bytes"); + } + + let mut rows_from_doc = Vec::new(); + let mut stats_doc = BsonCeoPostsDecodeStats::default(); + for d in &raw_docs { + let raw_doc = RawDocument::from_bytes(d.as_bytes()).expect("valid raw doc"); + stats_doc += decode_ceo_posts_doc(raw_doc, &fields, CeoPostsTimestampUnit::Seconds, |r| { + rows_from_doc.push(r) + }) + .expect("decode doc"); + } + + assert_eq!(stats_buf, stats_bytes); + assert_eq!(stats_buf, stats_doc); + assert_eq!(stats_buf.nulled_wrong_type_bot, 1); + assert_eq!(rows_from_buffer, rows_from_bytes); + assert_eq!(rows_from_buffer, rows_from_doc); + + // Feed into `build_posts` twice and verify exact classification, known_at, and determinism. + let build1 = build_posts(rows_from_buffer.clone()).expect("build_posts run 1"); + let build2 = build_posts(rows_from_buffer).expect("build_posts run 2"); + assert_eq!(build1, build2); + + let newswire_ids: Vec<&str> = build1 + .newswire + .iter() + .map(|r| r.spiel_id.as_str()) + .collect(); + let retail_ids: Vec<&str> = build1.retail.iter().map(|r| r.spiel_id.as_str()).collect(); + assert_eq!(newswire_ids, vec!["nw_str_1", "nw_bool_true", "nw_i32_1"]); + assert_eq!(retail_ids, vec!["ret_str_0", "ret_absent", "ret_wrong_type"]); + assert_eq!(build1.stats.rejected_invalid, 1); + + // Baseline unedited post: known_at == posted_at. + let baseline = build1 + .newswire + .iter() + .find(|r| r.spiel_id == "nw_str_1") + .expect("baseline row"); + assert_eq!(baseline.posted_at, t0_sec * 1_000_000); + assert_eq!(baseline.known_at, baseline.posted_at); + assert!(!baseline.is_edited); + + // Edited post: known_at == edited_ms * 1_000 (UTC microseconds). + let edited = build1 + .newswire + .iter() + .find(|r| r.spiel_id == "nw_i32_1") + .expect("edited row"); + assert_eq!(edited.posted_at, (t0_sec + 10) * 1_000_000); + assert_eq!(edited.known_at, (t_edit_sec * 1_000) * 1_000); + assert!(edited.is_edited); + assert_eq!(edited.user_id.as_deref(), Some("42")); +} + +#[test] +fn framing_and_structural_corruption_fail_closed_with_exact_offsets() { + let fields = CeoPostsFieldNames::default(); + let ts_sec: i64 = 1_710_460_800; + + let good = make_base_doc("CH-OK", "ok_first", ts_sec); + let good_len = good.as_bytes().len() as u64; + + // 1. Truncated header (< 4 bytes) after one valid doc + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&[0x10, 0x00]); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert_eq!( + err, + BsonCeoPostsError::TruncatedDocument { + offset: good_len, + remaining: 2, + declared_len: None, + } + ); + assert!(!err.to_string().contains('\n')); + + // 2. Truncated body after one valid doc + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&[20, 0, 0, 0, 0, 0]); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert_eq!( + err, + BsonCeoPostsError::TruncatedDocument { + offset: good_len, + remaining: 6, + declared_len: Some(20), + } + ); + assert!(!err.to_string().contains('\n')); + + // 3. Declared length < 5 after one valid doc + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&[3, 0, 0, 0, 0]); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert_eq!( + err, + BsonCeoPostsError::CorruptDocumentLength { + offset: good_len, + declared_len: 3, + } + ); + assert!(!err.to_string().contains('\n')); + + // 4. Malformed element AFTER a semantically invalid field (must not be masked by skip) + let mut bad_after_skip = RawDocumentBuf::new(); + bad_after_skip.append(cstr!("ceoId"), ""); // would be skipped_empty_key + bad_after_skip.append(cstr!("z"), 1_i32); + let mut bad_bytes = bad_after_skip.into_bytes(); + let z_pos = bad_bytes + .windows(3) + .position(|w| w == [0x10, b'z', 0x00]) + .expect("locate z element"); + bad_bytes[z_pos] = 0x7e; + + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&bad_bytes); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert!( + matches!(err, BsonCeoPostsError::CorruptBson { offset, .. } if offset == good_len), + "expected CorruptBson at offset {good_len}, got {err:?}" + ); + assert!(!err.to_string().contains('\n')); + + // 5. Corruption inside an unused nested embedded document after one valid doc + let mut inner = RawDocumentBuf::new(); + inner.append(cstr!("nestedText"), "INNER!"); + let mut nested_bad = make_base_doc("CH-2", "nested_bad", ts_sec); + nested_bad.append(cstr!("poll"), inner); + let mut nested_bytes = nested_bad.into_bytes(); + let pos = nested_bytes + .windows(6) + .position(|w| w == b"INNER!") + .expect("locate INNER!"); + nested_bytes[pos] = 0xff; + + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&nested_bytes); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert!( + matches!(err, BsonCeoPostsError::CorruptBson { offset, .. } if offset == good_len), + "expected CorruptBson for nested embedded doc at offset {good_len}, got {err:?}" + ); + + // 6. Corrupt array index inside an unused array after one valid doc + let mut arr = RawArrayBuf::new(); + arr.push(10_i32); + arr.push(20_i32); + let mut arr_bad = make_base_doc("CH-3", "arr_bad", ts_sec); + arr_bad.append(cstr!("votes"), arr); + let mut arr_bytes = arr_bad.into_bytes(); + let idx1 = arr_bytes + .windows(3) + .position(|w| w == [0x10, b'1', 0x00]) + .expect("locate index 1"); + arr_bytes[idx1 + 1] = b'2'; + + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&arr_bytes); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert!( + matches!(err, BsonCeoPostsError::CorruptBson { offset, .. } if offset == good_len), + "expected CorruptBson for corrupt array index at offset {good_len}, got {err:?}" + ); + + // 7. Trailing bytes on decode_ceo_posts_bytes -> CorruptDocumentLength + let mut extra = good.as_bytes().to_vec(); + extra.push(0x00); + let err = decode_ceo_posts_bytes(&extra, &fields, CeoPostsTimestampUnit::Seconds, |_| {}) + .unwrap_err(); + assert!(matches!( + err, + BsonCeoPostsError::CorruptDocumentLength { .. } + )); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 3e6ac6f0..ad00e80b 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -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,