T-107: M1.2w — tools/curate-etl: zero-copy raw BSON decoders for qmSplits + qmDividends documents → source-keyed split/dividend events (no new crates, no MongoDB connection) with fixture tests and local benchmark
This commit is contained in:
parent
50a9968e84
commit
6734229022
9 changed files with 2360 additions and 35 deletions
|
|
@ -1,6 +1,6 @@
|
|||
# `curate-etl`
|
||||
|
||||
Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, and the `M1.2o` zero-copy raw BSON decoder for `eodPrices`.
|
||||
Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, and the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`.
|
||||
|
||||
## Scope & Sign Conventions
|
||||
|
||||
|
|
@ -453,7 +453,29 @@ Rules:
|
|||
- `iter_raw_bson_docs` walks concatenated 4-byte little-endian length-prefixed BSON documents (wire / `mongodump` layout), terminating cleanly on unrecoverable framing errors (`TruncatedDocument`, `CorruptDocumentLength`) while skipping validly framed corrupt documents (`CorruptBson`).
|
||||
- `decode_eod_price_buffer` reports and skips per-document errors without aborting the stream, reconciling `BsonEodDecodeStats` with `decoded + rejected_total() == docs_in`.
|
||||
5. **Deferred out of `M1.2o`:**
|
||||
- MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, end-to-end `curate bars_1d` CLI command, and decoders for other collections (`qmPrices`, `qmSplits`, `qmDividends`, `ceoShorts`, `qmFilings`, `qmEarnings`, `eodIntraday1M`).
|
||||
- MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, end-to-end `curate bars_1d` CLI command, and decoders for other collections (`qmPrices`, `ceoShorts`, `qmFilings`, `qmEarnings`, `eodIntraday1M`).
|
||||
|
||||
## `qmSplits` / `qmDividends` Raw BSON Decoders (`M1.2w`)
|
||||
|
||||
`decode_qm_split_doc`, `decode_qm_split_bytes`, `decode_qm_split_buffer`, `decode_qm_dividend_doc`, `decode_qm_dividend_bytes`, and `decode_qm_dividend_buffer` (`src/bson_qm_actions.rs`) decode raw MongoDB `qmSplits` and `qmDividends` BSON documents in a single forward pass over `RawDocument::iter_elements()` into borrowed `RawQmSplit<'a>` and `RawQmDividend<'a>` views without allocating a `String` or `bson::Document` per row, reusing `bson_eod_prices::iter_raw_bson_docs` for concatenated length-prefixed buffers.
|
||||
|
||||
1. **Field contract & cited in-repo sources:**
|
||||
- `qmSearchCode` (`FIELD_QM_SEARCH_CODE`): BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only is rejected). Cited: `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:98,118`.
|
||||
- `date` (`FIELD_DATE`): strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via `split::ymd_to_epoch_days`) or BSON `DateTime` (UTC epoch day via `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check so pre-1970 timestamps floor accurately). Cited: `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:99,119`, `design/DATA-CONTRACTS.md` §1 (line 25).
|
||||
- `declared` (`FIELD_DECLARED`, optional): absent, BSON `Null`, or empty/whitespace-only `String` maps to `None`; strict `YYYY-MM-DD` `String` or BSON `DateTime` maps to `Some(i32)`; malformed strings/out-of-range `DateTime` return `MalformedDate { field: "declared" }` and other types return `WrongType { field: "declared", .. }`. Cited: `design/DATA-CONTRACTS.md` §1 (line 25).
|
||||
- `splitratio` (`FIELD_SPLIT_RATIO`): BSON `Double`, `Int32`, or `Int64`; must be finite and `> 0.0`. `splitratio == 1.0` no-ops are **decoded, not dropped** here (downstream builders drop them) and counted in `BsonQmActionDecodeStats::split_noop_ratio_one` (a subset of `decoded`, never added to `rejected_total()`). Cited: `design/DATA-CONTRACTS.md` §1 (line 25).
|
||||
- `usdFxRate` (`FIELD_USD_FX_RATE`): explicitly ignored without calling `elem.value()` per `design/DATA-CONTRACTS.md` §1 (line 25: bogus `usdFxRate: 1` on CAD dividend rows). All other unknown extra fields (`_id`, `symbol`, `exchange`, `reportDate`, `created_at`, `updated_at`, nested objects/arrays) are likewise skipped without decoding.
|
||||
- `amount` (`FIELD_DIVIDEND_CASH`): BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` (`-0.0` normalized to `+0.0`). See **Unverified field names** below.
|
||||
- `currency` (`FIELD_DIVIDEND_CURRENCY`): BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only is rejected). See **Unverified field names** below.
|
||||
2. **Zero-allocation key mapping & builder conversions:**
|
||||
- `RawQmSplit::to_split_event` → `SplitEvent`, `to_split_action_event` → `SplitActionEvent`; `RawQmDividend::to_dividend_event` → `DividendEvent`, `to_dividend_action_event` → `DividendActionEvent`.
|
||||
- `try_map_key(|code, ex_date| ...)` and `try_into_*` helpers mirror `RawEodDailyBar::try_into_eod_daily_bar` so callers can resolve `("qm", qmSearchCode, ex_date)` through `ProviderMappingTable` before allocating `currency` on dividends.
|
||||
3. **Typed errors & stream accounting policy:**
|
||||
- Never panics on untrusted input. `BsonQmActionError` names the offending field on every field-level error (`MissingField`, `EmptyField`, `WrongType`, `MalformedDate`, `InvalidNumber`, plus framing variants `TruncatedDocument`, `CorruptDocumentLength`, `CorruptBson`).
|
||||
- Buffer decoders report and skip per-document errors without aborting the stream, always reconciling `decoded + rejected_total() == docs_in`.
|
||||
4. **Unverified field names:**
|
||||
- `amount` (`FIELD_DIVIDEND_CASH`) and `currency` (`FIELD_DIVIDEND_CURRENCY`) could not be proven from any in-repo schema or fixture (`events.action.ts` spreads `...dividend` untyped and `design/DATA-CONTRACTS.md` names only `date`, `declared`, and `usdFxRate` for `qmDividends`). Both are isolated in single `pub const` constants so the live MongoDB cursor task can confirm or adjust them in one place before touching QA data.
|
||||
- Numeric strings (e.g. `"10.0"`, `"1.42"`) are currently rejected as `WrongType` because no in-repo source proves QuoteMedia sends `splitratio` or dividend cash as strings; live schema inspection should confirm whether string coercion is needed.
|
||||
|
||||
## Local Benchmarks
|
||||
|
||||
|
|
@ -669,6 +691,22 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x05af9d27
|
|||
- Run 2: `elapsed=217.38 ms`, `throughput=4600307 rows/s`, `scan=1253.15 MB/s`, `latency=217.38 ns/row`, `checksum=0x05af9d2746d1b5e3`
|
||||
- Extrapolation to full `846,000,000` `eodPrices` documents on one core (decode-only, excluding MongoDB cursor I/O and Parquet writes): `183.9 s`–`187.7 s` (`3.07`–`3.13 min`).
|
||||
|
||||
### `bench-bson-qm-actions`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) zero-copy raw BSON decode benchmark over `1,000,000` realistic synthetic QuoteMedia corporate-action documents (~4% `qmSplits`, ~96% `qmDividends`, with extra metadata `_id`, `symbol`, `exchange`, `reportDate`, `created_at`, `updated_at`, bogus `usdFxRate: 1`, `declared` present/missing/`Null`, ~5% BSON `DateTime` dates, mixed `Double`/`Int32`/`Int64` numerics, ~1.5% `splitratio == 1` no-ops, and ~0.5% deterministic rejected rows) pre-encoded into two contiguous length-prefixed buffers up front, timing decode-only via `decode_qm_split_buffer` and `decode_qm_dividend_buffer`:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-bson-qm-actions [rows]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`, two back-to-back runs with identical checksum `0x6d48cd59e46dc9dc`): `cargo run --release -p curate-etl --offline -- bench-bson-qm-actions`
|
||||
|
||||
- Input: `rows=1000000`, `splits=40146`, `dividends=959854`, `bytes=236043886` (~225.1 MiB, ~236.0 bytes/doc)
|
||||
- Splits: `decoded=39937`, `noop_ratio_one=616`, `rejected=209` (`missing=93`, `empty=0`, `wrong_type=45`, `malformed_date=38`, `invalid_number=33`, `corrupt=0`)
|
||||
- Dividends: `decoded=954952`, `rejected=4902` (`missing=1952`, `empty=0`, `wrong_type=1009`, `malformed_date=946`, `invalid_number=995`, `corrupt=0`)
|
||||
- Run 1: `elapsed=275.12 ms`, `throughput=3634828 docs/s`, `scan=818.23 MB/s`, `latency=275.12 ns/doc`, `checksum=0x6d48cd59e46dc9dc`
|
||||
- Run 2: `elapsed=282.92 ms`, `throughput=3534598 docs/s`, `scan=795.67 MB/s`, `latency=282.92 ns/doc`, `checksum=0x6d48cd59e46dc9dc`
|
||||
|
||||
## Deferred Follow-Ups (`M1.3+` / `M2`)
|
||||
|
||||
This crate currently depends only on `bson` (`=3.1.0`, `default-features = false, features = ["compat-3-0-0"]`) and `parquet` (`=60.2.0`, Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline. Follow-up tasks will add:
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
|
|||
use std::time::Instant;
|
||||
|
||||
use bson::oid::ObjectId;
|
||||
use bson::raw::{cstr, RawDocumentBuf};
|
||||
use bson::raw::{cstr, RawBsonRef, RawDocumentBuf};
|
||||
use bson::DateTime;
|
||||
use parquet::errors::ParquetError;
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
|
|
@ -17,6 +17,9 @@ use parquet::file::reader::{FileReader, SerializedFileReader};
|
|||
use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent};
|
||||
use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume};
|
||||
use crate::bson_eod_prices::{decode_eod_price_buffer, BsonEodDecodeStats};
|
||||
use crate::bson_qm_actions::{
|
||||
decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats,
|
||||
};
|
||||
use crate::corporate_actions::{
|
||||
build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats,
|
||||
DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, SplitActionEvent,
|
||||
|
|
@ -79,6 +82,7 @@ pub const DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS: usize = 1_000_000;
|
|||
/// + `known_at` (8) + `known_at_source` (~13) = 72 bytes.
|
||||
pub const PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES: usize = 72;
|
||||
pub const DEFAULT_BSON_EOD_PRICES_BENCH_ROWS: usize = 1_000_000;
|
||||
pub const DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS: usize = 1_000_000;
|
||||
pub const BENCH_KEY_COUNT: usize = 20_000;
|
||||
pub const BENCH_EVENT_COUNT: usize = 19_000;
|
||||
pub const PROVIDER_MAPPING_BENCH_KEY_COUNT: usize = 60_000;
|
||||
|
|
@ -104,6 +108,7 @@ const PARQUET_EVENTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_E7E4;
|
|||
const PARQUET_FX_BENCH_SEED: u64 = 0x570C_4B07_9A49_F81D;
|
||||
const PARQUET_ADJ_BENCH_SEED: u64 = 0x570C_4B07_9A49_AD7F;
|
||||
const BSON_EOD_PRICES_BENCH_SEED: u64 = 0x570C_4B07_B504_E0D1;
|
||||
const BSON_QM_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_B504_AC71;
|
||||
const PARQUET_CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_9A49_C049;
|
||||
const SAMPLE_RATIOS: [f64; 9] = [2.0, 3.0, 4.0, 5.0, 10.0, 0.5, 0.25, 0.1, 0.05];
|
||||
|
||||
|
|
@ -3792,6 +3797,278 @@ pub fn run_bson_eod_prices_benchmark(rows: usize) -> BsonEodPricesBenchReport {
|
|||
}
|
||||
}
|
||||
|
||||
/// Summary metrics produced by [`run_bson_qm_actions_benchmark`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct BsonQmActionsBenchReport {
|
||||
pub rows: usize,
|
||||
pub split_rows: usize,
|
||||
pub dividend_rows: usize,
|
||||
pub bytes: usize,
|
||||
pub elapsed_ms: f64,
|
||||
pub docs_per_sec: f64,
|
||||
pub mb_per_sec: f64,
|
||||
pub ns_per_doc: f64,
|
||||
pub checksum: u64,
|
||||
pub split_stats: BsonQmActionDecodeStats,
|
||||
pub dividend_stats: BsonQmActionDecodeStats,
|
||||
}
|
||||
|
||||
/// Runs the fixed-seed raw BSON `qmSplits` + `qmDividends` zero-copy decode benchmark for `rows`
|
||||
/// synthetic documents (~4% splits, ~96% dividends).
|
||||
///
|
||||
/// Pre-encodes realistic QuoteMedia documents (including extra metadata `_id`, `symbol`,
|
||||
/// `exchange`, `reportDate`, `created_at`, `updated_at`, bogus `usdFxRate: 1`, `declared`
|
||||
/// present/missing/`Null`, ~5% BSON `DateTime` dates, mixed `Double`/`Int32`/`Int64` numerics,
|
||||
/// ~1.5% `splitratio == 1` no-ops, and ~0.5% deterministic rejected rows) into two contiguous
|
||||
/// length-prefixed buffers, then times decode-only via [`decode_qm_split_buffer`] and
|
||||
/// [`decode_qm_dividend_buffer`] and asserts exact stats reconciliation.
|
||||
pub fn run_bson_qm_actions_benchmark(rows: usize) -> BsonQmActionsBenchReport {
|
||||
if rows == 0 {
|
||||
return BsonQmActionsBenchReport {
|
||||
rows: 0,
|
||||
split_rows: 0,
|
||||
dividend_rows: 0,
|
||||
bytes: 0,
|
||||
elapsed_ms: 0.0,
|
||||
docs_per_sec: 0.0,
|
||||
mb_per_sec: 0.0,
|
||||
ns_per_doc: 0.0,
|
||||
checksum: 0,
|
||||
split_stats: BsonQmActionDecodeStats::default(),
|
||||
dividend_stats: BsonQmActionDecodeStats::default(),
|
||||
};
|
||||
}
|
||||
|
||||
const SYMBOL_POOL: usize = 2_000;
|
||||
const EXCHANGES: [&str; 4] = ["NASDAQ", "NYSE", "TSX", "TSXV"];
|
||||
const CURRENCIES: [&str; 4] = ["USD", "USD", "CAD", "CAD"];
|
||||
const MILLIS_PER_DAY: i64 = 86_400_000;
|
||||
|
||||
let min_date = ymd_to_epoch_days(2005, 1, 3).unwrap_or(12_786);
|
||||
let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453);
|
||||
let mut date_days: Vec<i32> = Vec::with_capacity(5_600);
|
||||
let mut date_strings: Vec<String> = Vec::with_capacity(5_600);
|
||||
for d in min_date..=max_date {
|
||||
let dow = (d + 4).rem_euclid(7);
|
||||
if dow == 0 || dow == 6 {
|
||||
continue;
|
||||
}
|
||||
let (y, m, day) = epoch_days_to_ymd(d);
|
||||
date_days.push(d);
|
||||
date_strings.push(format!("{y:04}-{m:02}-{day:02}"));
|
||||
}
|
||||
|
||||
let symbols: Vec<(String, String, &'static str, &'static str)> = (0..SYMBOL_POOL)
|
||||
.map(|i| {
|
||||
let ex_idx = i % EXCHANGES.len();
|
||||
let sym = format!("QM{i:04}");
|
||||
let code = if ex_idx >= 2 {
|
||||
format!("{sym}:CA")
|
||||
} else {
|
||||
sym.clone()
|
||||
};
|
||||
(sym, code, EXCHANGES[ex_idx], CURRENCIES[ex_idx])
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut rng = SplitMix64::new(BSON_QM_ACTIONS_BENCH_SEED);
|
||||
let mut split_rows = 0usize;
|
||||
let mut dividend_rows = 0usize;
|
||||
let mut split_buf: Vec<u8> = Vec::with_capacity((rows / 20).saturating_mul(224));
|
||||
let mut dividend_buf: Vec<u8> = Vec::with_capacity(rows.saturating_mul(256));
|
||||
|
||||
for i in 0..rows {
|
||||
let is_split = (rng.next_u64() % 100) < 4;
|
||||
let sym_idx = (rng.next_u64() as usize) % symbols.len();
|
||||
let (ref symbol, ref code, exchange, currency) = symbols[sym_idx];
|
||||
let date_idx = (rng.next_u64() as usize) % date_days.len();
|
||||
let epoch_day = date_days[date_idx];
|
||||
let date_str = &date_strings[date_idx];
|
||||
let decl_idx = date_idx.saturating_sub(15);
|
||||
let decl_day = date_days[decl_idx];
|
||||
let decl_str = &date_strings[decl_idx];
|
||||
|
||||
let mut oid_bytes = [0u8; 12];
|
||||
let seq = (i as u64).to_be_bytes();
|
||||
oid_bytes[4..12].copy_from_slice(&seq);
|
||||
|
||||
let report_ms = i64::from(epoch_day) * MILLIS_PER_DAY;
|
||||
let created_ms = report_ms + 79_200_000;
|
||||
let updated_ms = created_ms + 60_000;
|
||||
|
||||
let bad_roll = rng.next_u64() % 1_000;
|
||||
let date_as_dt = (rng.next_u64() % 20) == 0;
|
||||
let decl_roll = rng.next_u64() % 1_000;
|
||||
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("_id"), ObjectId::from_bytes(oid_bytes));
|
||||
doc.append(cstr!("symbol"), symbol.as_str());
|
||||
doc.append(cstr!("exchange"), exchange);
|
||||
doc.append(cstr!("qmSearchCode"), code.as_str());
|
||||
doc.append(cstr!("reportDate"), DateTime::from_millis(report_ms));
|
||||
|
||||
if bad_roll == 0 {
|
||||
doc.append(cstr!("date"), "2023-02-29");
|
||||
} else if date_as_dt {
|
||||
doc.append(cstr!("date"), DateTime::from_millis(report_ms));
|
||||
} else {
|
||||
doc.append(cstr!("date"), date_str.as_str());
|
||||
}
|
||||
|
||||
if is_split {
|
||||
split_rows += 1;
|
||||
// ~30% declared present, ~20% Null, ~50% missing.
|
||||
if decl_roll < 300 {
|
||||
if date_as_dt {
|
||||
doc.append(
|
||||
cstr!("declared"),
|
||||
DateTime::from_millis(i64::from(decl_day) * MILLIS_PER_DAY),
|
||||
);
|
||||
} else {
|
||||
doc.append(cstr!("declared"), decl_str.as_str());
|
||||
}
|
||||
} else if decl_roll < 500 {
|
||||
doc.append(cstr!("declared"), RawBsonRef::Null);
|
||||
}
|
||||
|
||||
if bad_roll == 1 {
|
||||
doc.append(cstr!("splitratio"), "2.0");
|
||||
} else if bad_roll == 2 {
|
||||
doc.append(cstr!("splitratio"), 0.0_f64);
|
||||
} else if bad_roll != 3 && bad_roll != 4 {
|
||||
if (rng.next_u64() % 1_000) < 15 {
|
||||
match i % 3 {
|
||||
0 => doc.append(cstr!("splitratio"), 1.0_f64),
|
||||
1 => doc.append(cstr!("splitratio"), 1_i32),
|
||||
_ => doc.append(cstr!("splitratio"), 1_i64),
|
||||
}
|
||||
} else {
|
||||
let ratio = SAMPLE_RATIOS[(rng.next_u64() as usize) % SAMPLE_RATIOS.len()];
|
||||
if i % 5 == 0 && ratio >= 1.0 {
|
||||
doc.append(cstr!("splitratio"), ratio as i32);
|
||||
} else if i % 7 == 0 && ratio >= 1.0 {
|
||||
doc.append(cstr!("splitratio"), ratio as i64);
|
||||
} else {
|
||||
doc.append(cstr!("splitratio"), ratio);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
doc.append(cstr!("created_at"), DateTime::from_millis(created_ms));
|
||||
doc.append(cstr!("updated_at"), DateTime::from_millis(updated_ms));
|
||||
split_buf.extend_from_slice(doc.as_bytes());
|
||||
} else {
|
||||
dividend_rows += 1;
|
||||
// ~82% declared present, ~9% Null, ~9% missing.
|
||||
if decl_roll < 820 {
|
||||
if date_as_dt {
|
||||
doc.append(
|
||||
cstr!("declared"),
|
||||
DateTime::from_millis(i64::from(decl_day) * MILLIS_PER_DAY),
|
||||
);
|
||||
} else {
|
||||
doc.append(cstr!("declared"), decl_str.as_str());
|
||||
}
|
||||
} else if decl_roll < 910 {
|
||||
doc.append(cstr!("declared"), RawBsonRef::Null);
|
||||
}
|
||||
|
||||
let cents = (rng.next_u64() % 400) as i64;
|
||||
if bad_roll == 1 {
|
||||
doc.append(cstr!("amount"), "0.25");
|
||||
} else if bad_roll == 2 {
|
||||
doc.append(cstr!("amount"), -0.25_f64);
|
||||
} else if bad_roll != 3 {
|
||||
match i % 10 {
|
||||
0 => doc.append(cstr!("amount"), (cents / 100) as i32),
|
||||
1 => doc.append(cstr!("amount"), cents / 100),
|
||||
_ => doc.append(cstr!("amount"), cents as f64 / 100.0),
|
||||
}
|
||||
}
|
||||
|
||||
if bad_roll != 4 {
|
||||
doc.append(cstr!("currency"), currency);
|
||||
}
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
doc.append(cstr!("created_at"), DateTime::from_millis(created_ms));
|
||||
doc.append(cstr!("updated_at"), DateTime::from_millis(updated_ms));
|
||||
dividend_buf.extend_from_slice(doc.as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
let bytes = split_buf.len() + dividend_buf.len();
|
||||
let mut hash = 0u64;
|
||||
let mut err_hash = 0u64;
|
||||
|
||||
let start = Instant::now();
|
||||
let split_stats = decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| {
|
||||
hash = mix_bytes(hash, s.qm_search_code.as_bytes());
|
||||
hash = mix_u64(hash, s.ex_date as u64);
|
||||
hash = mix_u64(hash, s.ratio.to_bits());
|
||||
hash = mix_u64(hash, s.declared_date.unwrap_or(i32::MIN) as u64);
|
||||
},
|
||||
|offset, _err| {
|
||||
err_hash = mix_u64(err_hash, offset as u64 ^ 0x5171_DEAD_BEEF_0001u64);
|
||||
},
|
||||
);
|
||||
let dividend_stats = decode_qm_dividend_buffer(
|
||||
÷nd_buf,
|
||||
|d| {
|
||||
hash = mix_bytes(hash, d.qm_search_code.as_bytes());
|
||||
hash = mix_u64(hash, d.ex_date as u64);
|
||||
hash = mix_u64(hash, d.cash.to_bits());
|
||||
hash = mix_bytes(hash, d.currency.as_bytes());
|
||||
hash = mix_u64(hash, d.declared_date.unwrap_or(i32::MIN) as u64);
|
||||
},
|
||||
|offset, _err| {
|
||||
err_hash = mix_u64(err_hash, offset as u64 ^ 0xD171_DEAD_BEEF_0002u64);
|
||||
},
|
||||
);
|
||||
let elapsed_secs = start.elapsed().as_secs_f64();
|
||||
|
||||
assert_eq!(
|
||||
split_stats.decoded + split_stats.rejected_total(),
|
||||
split_stats.docs_in,
|
||||
"qmSplits decode stats must reconcile"
|
||||
);
|
||||
assert_eq!(
|
||||
dividend_stats.decoded + dividend_stats.rejected_total(),
|
||||
dividend_stats.docs_in,
|
||||
"qmDividends decode stats must reconcile"
|
||||
);
|
||||
assert_eq!(
|
||||
split_stats.docs_in + dividend_stats.docs_in,
|
||||
rows,
|
||||
"total decoded+rejected docs must equal input rows"
|
||||
);
|
||||
|
||||
let elapsed_ms = elapsed_secs * 1_000.0;
|
||||
let (docs_per_sec, ns_per_doc) = compute_rates(rows, elapsed_secs);
|
||||
let mb_per_sec = if elapsed_secs > 0.0 && elapsed_secs.is_finite() {
|
||||
(bytes as f64 / (1024.0 * 1024.0)) / elapsed_secs
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let checksum = black_box(hash ^ err_hash);
|
||||
|
||||
BsonQmActionsBenchReport {
|
||||
rows,
|
||||
split_rows,
|
||||
dividend_rows,
|
||||
bytes,
|
||||
elapsed_ms,
|
||||
docs_per_sec,
|
||||
mb_per_sec,
|
||||
ns_per_doc,
|
||||
checksum,
|
||||
split_stats,
|
||||
dividend_stats,
|
||||
}
|
||||
}
|
||||
|
||||
pub const DEFAULT_CURATE_BARS_BENCH_ROWS: usize = 2_000_000;
|
||||
pub const EOD_PRICES_FULL_ROW_COUNT: f64 = 846_000_000.0;
|
||||
const CURATE_BARS_BENCH_SEED: u64 = 0x570C_4B07_C04A_BA45;
|
||||
|
|
@ -6553,6 +6830,52 @@ mod tests {
|
|||
assert_eq!(report.stats, BsonEodDecodeStats::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bson_qm_actions_benchmark_small_run_is_deterministic() {
|
||||
let a = run_bson_qm_actions_benchmark(20_000);
|
||||
let b = run_bson_qm_actions_benchmark(20_000);
|
||||
|
||||
assert_eq!(a.rows, 20_000);
|
||||
assert_eq!(a.split_rows + a.dividend_rows, 20_000);
|
||||
assert!(a.split_rows > 0 && a.dividend_rows > 0);
|
||||
assert_eq!(a.bytes, b.bytes);
|
||||
assert!(a.bytes > 0);
|
||||
assert_eq!(a.checksum, b.checksum);
|
||||
assert_eq!(a.split_stats, b.split_stats);
|
||||
assert_eq!(a.dividend_stats, b.dividend_stats);
|
||||
assert_eq!(a.split_stats.docs_in, a.split_rows);
|
||||
assert_eq!(a.dividend_stats.docs_in, a.dividend_rows);
|
||||
assert_eq!(
|
||||
a.split_stats.decoded + a.split_stats.rejected_total(),
|
||||
a.split_stats.docs_in
|
||||
);
|
||||
assert_eq!(
|
||||
a.dividend_stats.decoded + a.dividend_stats.rejected_total(),
|
||||
a.dividend_stats.docs_in
|
||||
);
|
||||
assert!(a.split_stats.split_noop_ratio_one > 0);
|
||||
assert!(a.dividend_stats.rejected_total() > 0);
|
||||
assert!(a.docs_per_sec.is_finite() && a.docs_per_sec >= 0.0);
|
||||
assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0);
|
||||
assert!(a.ns_per_doc.is_finite() && a.ns_per_doc >= 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bson_qm_actions_benchmark_zero_rows_handles_cleanly() {
|
||||
let report = run_bson_qm_actions_benchmark(0);
|
||||
assert_eq!(report.rows, 0);
|
||||
assert_eq!(report.split_rows, 0);
|
||||
assert_eq!(report.dividend_rows, 0);
|
||||
assert_eq!(report.bytes, 0);
|
||||
assert_eq!(report.elapsed_ms, 0.0);
|
||||
assert_eq!(report.docs_per_sec, 0.0);
|
||||
assert_eq!(report.mb_per_sec, 0.0);
|
||||
assert_eq!(report.ns_per_doc, 0.0);
|
||||
assert_eq!(report.checksum, 0);
|
||||
assert_eq!(report.split_stats, BsonQmActionDecodeStats::default());
|
||||
assert_eq!(report.dividend_stats, BsonQmActionDecodeStats::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_benchmark_small_run_is_deterministic_and_cleans_up() {
|
||||
let (a, dir_a) = run_curate_bars_benchmark_tracked(20_000).unwrap();
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ use bson::spec::ElementType;
|
|||
use crate::bars::EodDailyBar;
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
const MILLIS_PER_DAY: i64 = 86_400_000;
|
||||
pub(crate) const MILLIS_PER_DAY: i64 = 86_400_000;
|
||||
const MIN_BSON_DOC_LEN: i32 = 5;
|
||||
|
||||
/// Borrowed zero-copy view of a single decoded `eodPrices` BSON document.
|
||||
|
|
@ -250,22 +250,20 @@ fn parse_ascii_digits_u32(bytes: &[u8]) -> Option<u32> {
|
|||
}
|
||||
|
||||
#[inline]
|
||||
fn parse_ymd_strict(s: &str) -> Result<i32, BsonEodPriceError> {
|
||||
pub(crate) fn parse_ymd_strict_days(s: &str) -> Option<i32> {
|
||||
let bytes = s.as_bytes();
|
||||
if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
return None;
|
||||
}
|
||||
let Some(year_u32) = parse_ascii_digits_u32(&bytes[0..4]) else {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
};
|
||||
let Some(month) = parse_ascii_digits_u32(&bytes[5..7]) else {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
};
|
||||
let Some(day) = parse_ascii_digits_u32(&bytes[8..10]) else {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
};
|
||||
ymd_to_epoch_days(year_u32 as i32, month, day)
|
||||
.map_err(|_| BsonEodPriceError::MalformedDate { field: "date" })
|
||||
let year_u32 = parse_ascii_digits_u32(&bytes[0..4])?;
|
||||
let month = parse_ascii_digits_u32(&bytes[5..7])?;
|
||||
let day = parse_ascii_digits_u32(&bytes[8..10])?;
|
||||
ymd_to_epoch_days(year_u32 as i32, month, day).ok()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn parse_ymd_strict(s: &str) -> Result<i32, BsonEodPriceError> {
|
||||
parse_ymd_strict_days(s).ok_or(BsonEodPriceError::MalformedDate { field: "date" })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
|
@ -438,11 +436,7 @@ pub fn decode_eod_price_doc<'a>(
|
|||
decode_eod_price_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed
|
||||
/// [`RawEodDailyBar`].
|
||||
pub fn decode_eod_price_bytes<'a>(
|
||||
bytes: &'a [u8],
|
||||
) -> Result<RawEodDailyBar<'a>, BsonEodPriceError> {
|
||||
pub(crate) fn parse_single_raw_doc(bytes: &[u8]) -> Result<&RawDocument, BsonEodPriceError> {
|
||||
if bytes.len() < 4 {
|
||||
return Err(BsonEodPriceError::TruncatedDocument {
|
||||
offset: 0,
|
||||
|
|
@ -471,10 +465,18 @@ pub fn decode_eod_price_bytes<'a>(
|
|||
declared_len,
|
||||
});
|
||||
}
|
||||
let doc = RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson {
|
||||
RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson {
|
||||
offset: 0,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed
|
||||
/// [`RawEodDailyBar`].
|
||||
pub fn decode_eod_price_bytes<'a>(
|
||||
bytes: &'a [u8],
|
||||
) -> Result<RawEodDailyBar<'a>, BsonEodPriceError> {
|
||||
let doc = parse_single_raw_doc(bytes)?;
|
||||
decode_eod_price_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
|
|
|
|||
792
tools/curate-etl/src/bson_qm_actions.rs
Normal file
792
tools/curate-etl/src/bson_qm_actions.rs
Normal file
|
|
@ -0,0 +1,792 @@
|
|||
//! Zero-copy raw BSON decoders for MongoDB `qmSplits` and `qmDividends` documents (`M1.2w`).
|
||||
//!
|
||||
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into
|
||||
//! borrowed [`RawQmSplit`] and [`RawQmDividend`] views without allocating a `String` or
|
||||
//! `bson::Document` per row. Callers convert borrowed views into [`SplitEvent`], [`DividendEvent`],
|
||||
//! [`SplitActionEvent`], or [`DividendActionEvent`], optionally resolving `("qm", qmSearchCode, ex_date)`
|
||||
//! through a caller-supplied key mapper (such as [`crate::provider_mapping::ProviderMappingTable::resolve`]).
|
||||
//!
|
||||
//! # Empirical Field Contract & Cited Sources
|
||||
//!
|
||||
//! - `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:92-124`: writes
|
||||
//! `qmSearchCode`, `symbol`, `exchange`, `reportDate: new Date(x.date)` plus the spread
|
||||
//! QuoteMedia API payload into `qmDividends` and `qmSplits`.
|
||||
//! - `design/DATA-CONTRACTS.md` §1 (line 25): documents `date`, `declared`, `splitratio`
|
||||
//! (`258` rows have `splitratio == 1`), and `usdFxRate` (bogus `usdFxRate: 1` on CAD dividend
|
||||
//! rows; contract rule: ignore `usdFxRate`).
|
||||
//! - **Unverified field names:** the raw MongoDB dividend cash and currency field names are not
|
||||
//! proven by any in-repo schema or fixture (`events.action.ts` spreads `...dividend` untyped).
|
||||
//! They are isolated in [`FIELD_DIVIDEND_CASH`] (`"amount"`) and [`FIELD_DIVIDEND_CURRENCY`]
|
||||
//! (`"currency"`) and explicitly listed under "Unverified field names" in `tools/curate-etl/README.md`.
|
||||
//!
|
||||
//! Accepted BSON field representations:
|
||||
//! - `qmSearchCode`, `currency`: BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only
|
||||
//! is rejected).
|
||||
//! - `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via
|
||||
//! [`crate::split::ymd_to_epoch_days`]) or BSON `DateTime` (UTC epoch day via
|
||||
//! `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check).
|
||||
//! - `declared` (optional): absent, BSON `Null`, or empty/whitespace `String` maps to `None`;
|
||||
//! otherwise strict `YYYY-MM-DD` `String` or BSON `DateTime` maps to `Some(i32)`.
|
||||
//! - `splitratio`: BSON `Double`, `Int32`, or `Int64`; must be finite and `> 0.0`. `ratio == 1.0`
|
||||
//! no-ops are **decoded, not dropped** (downstream builders drop them) and counted in
|
||||
//! [`BsonQmActionDecodeStats::split_noop_ratio_one`].
|
||||
//! - `amount` (dividend cash): BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0`
|
||||
//! (`-0.0` is normalized to `+0.0`).
|
||||
//! - `usdFxRate` and all unknown extra fields (`_id`, `symbol`, `exchange`, `reportDate`,
|
||||
//! `created_at`, `updated_at`, nested objects/arrays, etc.) are skipped without calling
|
||||
//! `elem.value()`.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
|
||||
use bson::raw::{RawBsonRef, RawDocument, RawElement};
|
||||
use bson::spec::ElementType;
|
||||
|
||||
use crate::adj::DividendEvent;
|
||||
use crate::bson_eod_prices::{
|
||||
iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError,
|
||||
MILLIS_PER_DAY,
|
||||
};
|
||||
use crate::corporate_actions::{DividendActionEvent, SplitActionEvent};
|
||||
use crate::split::SplitEvent;
|
||||
|
||||
/// MongoDB field name for the QuoteMedia security key (`events.action.ts:98,118`).
|
||||
pub const FIELD_QM_SEARCH_CODE: &str = "qmSearchCode";
|
||||
/// MongoDB field name for the ex-split / ex-dividend date (`events.action.ts:99,119`, `DATA-CONTRACTS.md:25`).
|
||||
pub const FIELD_DATE: &str = "date";
|
||||
/// MongoDB field name for the optional declaration date (`DATA-CONTRACTS.md:25`).
|
||||
pub const FIELD_DECLARED: &str = "declared";
|
||||
/// MongoDB field name for the split ratio (`DATA-CONTRACTS.md:25`).
|
||||
pub const FIELD_SPLIT_RATIO: &str = "splitratio";
|
||||
/// MongoDB field name for the bogus FX field explicitly ignored per contract (`DATA-CONTRACTS.md:25`).
|
||||
pub const FIELD_USD_FX_RATE: &str = "usdFxRate";
|
||||
/// MongoDB field name for dividend cash amount (**unverified in repo**; QuoteMedia convention).
|
||||
pub const FIELD_DIVIDEND_CASH: &str = "amount";
|
||||
/// MongoDB field name for dividend currency code (**unverified in repo**; QuoteMedia convention).
|
||||
pub const FIELD_DIVIDEND_CURRENCY: &str = "currency";
|
||||
|
||||
/// Borrowed zero-copy view of a single decoded `qmSplits` BSON document.
|
||||
///
|
||||
/// Borrows `qm_search_code` directly from the underlying `&RawDocument` byte slice.
|
||||
/// `ratio == 1.0` no-op rows are preserved here so downstream builders (`SplitTable`,
|
||||
/// `build_adj_factors`, `build_corporate_actions`) apply their own filtering and accounting.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RawQmSplit<'a> {
|
||||
pub qm_search_code: &'a str,
|
||||
/// Ex-split date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub ex_date: i32,
|
||||
/// `new_shares / old_shares` (finite and `> 0.0`).
|
||||
pub ratio: f64,
|
||||
/// Optional declaration date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub declared_date: Option<i32>,
|
||||
}
|
||||
|
||||
impl<'a> RawQmSplit<'a> {
|
||||
/// Converts this borrowed split into a [`SplitEvent`] for [`crate::split::SplitTable`] or
|
||||
/// [`crate::adj::build_adj_factors`].
|
||||
#[inline]
|
||||
pub fn to_split_event(self) -> SplitEvent {
|
||||
SplitEvent {
|
||||
ex_date: self.ex_date,
|
||||
ratio: self.ratio,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this borrowed split into a [`SplitActionEvent`] for
|
||||
/// [`crate::corporate_actions::build_corporate_actions`].
|
||||
#[inline]
|
||||
pub fn to_split_action_event(self) -> SplitActionEvent {
|
||||
SplitActionEvent {
|
||||
ex_date: self.ex_date,
|
||||
ratio: self.ratio,
|
||||
declared_date: self.declared_date,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves `(qm_search_code, ex_date)` via a caller-supplied key mapper
|
||||
/// (for example `|code, date| mapping.resolve("qm", code, date)`).
|
||||
#[inline]
|
||||
pub fn try_map_key<K, F>(self, map_key: F) -> Option<K>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
map_key(self.qm_search_code, self.ex_date)
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key and pairs it with [`SplitEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_split_event<K, F>(self, map_key: F) -> Option<(K, SplitEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_split_event()))
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key and pairs it with [`SplitActionEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_split_action_event<K, F>(self, map_key: F) -> Option<(K, SplitActionEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_split_action_event()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrowed zero-copy view of a single decoded `qmDividends` BSON document.
|
||||
///
|
||||
/// Borrows `qm_search_code` and `currency` directly from the underlying `&RawDocument` byte slice.
|
||||
/// Deliberately omits `usdFxRate` per `design/DATA-CONTRACTS.md` §1.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RawQmDividend<'a> {
|
||||
pub qm_search_code: &'a str,
|
||||
/// Ex-dividend date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub ex_date: i32,
|
||||
/// Cash dividend amount per share (finite and `>= 0.0`, with `-0.0` normalized to `+0.0`).
|
||||
pub cash: f64,
|
||||
/// Local dividend currency code (e.g. `"USD"`, `"CAD"`).
|
||||
pub currency: &'a str,
|
||||
/// Optional declaration date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub declared_date: Option<i32>,
|
||||
}
|
||||
|
||||
impl<'a> RawQmDividend<'a> {
|
||||
/// Converts this borrowed dividend into a [`DividendEvent`] for
|
||||
/// [`crate::adj::build_adj_factors`], attaching caller-supplied `prev_close` context.
|
||||
#[inline]
|
||||
pub fn to_dividend_event(
|
||||
self,
|
||||
prev_close: Option<f64>,
|
||||
prev_close_currency: Option<String>,
|
||||
) -> DividendEvent {
|
||||
DividendEvent {
|
||||
ex_date: self.ex_date,
|
||||
cash: self.cash,
|
||||
currency: self.currency.to_owned(),
|
||||
prev_close,
|
||||
prev_close_currency,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this borrowed dividend into a [`DividendActionEvent`] for
|
||||
/// [`crate::corporate_actions::build_corporate_actions`].
|
||||
#[inline]
|
||||
pub fn to_dividend_action_event(self) -> DividendActionEvent {
|
||||
DividendActionEvent {
|
||||
ex_date: self.ex_date,
|
||||
cash: self.cash,
|
||||
currency: self.currency.to_owned(),
|
||||
declared_date: self.declared_date,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves `(qm_search_code, ex_date)` via a caller-supplied key mapper
|
||||
/// (for example `|code, date| mapping.resolve("qm", code, date)`).
|
||||
#[inline]
|
||||
pub fn try_map_key<K, F>(self, map_key: F) -> Option<K>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
map_key(self.qm_search_code, self.ex_date)
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key before allocating `currency` and pairs it with [`DividendEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_dividend_event<K, F>(
|
||||
self,
|
||||
prev_close: Option<f64>,
|
||||
prev_close_currency: Option<String>,
|
||||
map_key: F,
|
||||
) -> Option<(K, DividendEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_dividend_event(prev_close, prev_close_currency)))
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key before allocating `currency` and pairs it with
|
||||
/// [`DividendActionEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_dividend_action_event<K, F>(
|
||||
self,
|
||||
map_key: F,
|
||||
) -> Option<(K, DividendActionEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_dividend_action_event()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed errors returned while decoding raw `qmSplits` or `qmDividends` BSON documents or
|
||||
/// length-prefixed buffers.
|
||||
///
|
||||
/// Every field-level error names the offending BSON field in both its structure and `Display`
|
||||
/// output; no input path panics.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum BsonQmActionError {
|
||||
/// A required field was absent from the document.
|
||||
MissingField { field: &'static str },
|
||||
/// A required string field was empty or contained only whitespace.
|
||||
EmptyField { field: &'static str },
|
||||
/// A decoded field had an unexpected BSON element type.
|
||||
WrongType {
|
||||
field: &'static str,
|
||||
actual: ElementType,
|
||||
},
|
||||
/// A date field was not a valid strict `YYYY-MM-DD` Gregorian date or BSON `DateTime`
|
||||
/// overflowed `i32` epoch days.
|
||||
MalformedDate { field: &'static str },
|
||||
/// A numeric field was non-finite (`NaN`, `±inf`) or violated its domain bound (`> 0` for
|
||||
/// `splitratio`, `>= 0` for dividend cash).
|
||||
InvalidNumber { field: &'static str, value: f64 },
|
||||
/// 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 BSON framing or element bytes were malformed.
|
||||
CorruptBson { offset: usize, detail: String },
|
||||
}
|
||||
|
||||
impl fmt::Display for BsonQmActionError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MissingField { field } => {
|
||||
write!(f, "qm action BSON missing required field '{field}'")
|
||||
}
|
||||
Self::EmptyField { field } => {
|
||||
write!(f, "qm action BSON field '{field}' must not be empty or blank")
|
||||
}
|
||||
Self::WrongType { field, actual } => {
|
||||
write!(
|
||||
f,
|
||||
"qm action BSON field '{field}' has unexpected BSON type {actual:?}"
|
||||
)
|
||||
}
|
||||
Self::MalformedDate { field } => {
|
||||
write!(
|
||||
f,
|
||||
"qm action BSON field '{field}' is not a valid YYYY-MM-DD date or in-range DateTime"
|
||||
)
|
||||
}
|
||||
Self::InvalidNumber { field, value } => {
|
||||
write!(
|
||||
f,
|
||||
"qm action BSON field '{field}' has invalid numeric value {value}"
|
||||
)
|
||||
}
|
||||
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 BsonQmActionError {}
|
||||
|
||||
#[inline]
|
||||
fn map_framing_error(err: BsonEodPriceError) -> BsonQmActionError {
|
||||
match err {
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonQmActionError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonQmActionError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptBson { offset, detail } => {
|
||||
BsonQmActionError::CorruptBson { offset, detail }
|
||||
}
|
||||
BsonEodPriceError::MissingField { field } => BsonQmActionError::MissingField { field },
|
||||
BsonEodPriceError::EmptyField { field } => BsonQmActionError::EmptyField { field },
|
||||
BsonEodPriceError::WrongType { field, actual } => {
|
||||
BsonQmActionError::WrongType { field, actual }
|
||||
}
|
||||
BsonEodPriceError::MalformedDate { field } => BsonQmActionError::MalformedDate { field },
|
||||
BsonEodPriceError::InvalidNumber { field, value } => {
|
||||
BsonQmActionError::InvalidNumber { field, value }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-batch decode and rejection accounting for [`decode_qm_split_buffer`] and
|
||||
/// [`decode_qm_dividend_buffer`].
|
||||
///
|
||||
/// Conservation invariant: `decoded + rejected_total() == docs_in`.
|
||||
/// `split_noop_ratio_one` counts decoded `qmSplits` documents with `ratio == 1.0` (a subset of
|
||||
/// `decoded`, never added to `rejected_total()`).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct BsonQmActionDecodeStats {
|
||||
pub docs_in: usize,
|
||||
pub decoded: usize,
|
||||
/// Decoded `qmSplits` rows with `splitratio == 1.0` (subset of `decoded`).
|
||||
pub split_noop_ratio_one: usize,
|
||||
pub rejected_missing_field: usize,
|
||||
pub rejected_empty_field: usize,
|
||||
pub rejected_wrong_type: usize,
|
||||
pub rejected_malformed_date: usize,
|
||||
pub rejected_invalid_number: usize,
|
||||
pub rejected_corrupt_document: usize,
|
||||
}
|
||||
|
||||
impl BsonQmActionDecodeStats {
|
||||
/// Total number of rejected documents across all error categories.
|
||||
#[inline]
|
||||
pub fn rejected_total(&self) -> usize {
|
||||
self.rejected_missing_field
|
||||
+ self.rejected_empty_field
|
||||
+ self.rejected_wrong_type
|
||||
+ self.rejected_malformed_date
|
||||
+ self.rejected_invalid_number
|
||||
+ self.rejected_corrupt_document
|
||||
}
|
||||
|
||||
/// Increments the rejection counter corresponding to `err`.
|
||||
#[inline]
|
||||
pub fn record_error(&mut self, err: &BsonQmActionError) {
|
||||
match err {
|
||||
BsonQmActionError::MissingField { .. } => self.rejected_missing_field += 1,
|
||||
BsonQmActionError::EmptyField { .. } => self.rejected_empty_field += 1,
|
||||
BsonQmActionError::WrongType { .. } => self.rejected_wrong_type += 1,
|
||||
BsonQmActionError::MalformedDate { .. } => self.rejected_malformed_date += 1,
|
||||
BsonQmActionError::InvalidNumber { .. } => self.rejected_invalid_number += 1,
|
||||
BsonQmActionError::TruncatedDocument { .. }
|
||||
| BsonQmActionError::CorruptDocumentLength { .. }
|
||||
| BsonQmActionError::CorruptBson { .. } => self.rejected_corrupt_document += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_element_value<'a>(
|
||||
field: &'static str,
|
||||
elem: RawElement<'a>,
|
||||
offset: usize,
|
||||
) -> Result<RawBsonRef<'a>, BsonQmActionError> {
|
||||
elem.value().map_err(|err| BsonQmActionError::CorruptBson {
|
||||
offset,
|
||||
detail: format!("field '{field}': {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_non_empty_str<'a>(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'a>,
|
||||
) -> Result<&'a str, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
return Err(BsonQmActionError::EmptyField { field });
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_required_date(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<i32, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::String(s) => {
|
||||
parse_ymd_strict_days(s).ok_or(BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
RawBsonRef::DateTime(dt) => {
|
||||
let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY);
|
||||
i32::try_from(days).map_err(|_| BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_optional_date(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<Option<i32>, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::Null => Ok(None),
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
parse_ymd_strict_days(s)
|
||||
.map(Some)
|
||||
.ok_or(BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
RawBsonRef::DateTime(dt) => {
|
||||
let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY);
|
||||
i32::try_from(days)
|
||||
.map(Some)
|
||||
.map_err(|_| BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_positive_number(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<f64, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => {
|
||||
if !v.is_finite() || v <= 0.0 {
|
||||
return Err(BsonQmActionError::InvalidNumber { field, value: v });
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
RawBsonRef::Int32(v) => {
|
||||
if v <= 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: f64::from(v),
|
||||
});
|
||||
}
|
||||
Ok(f64::from(v))
|
||||
}
|
||||
RawBsonRef::Int64(v) => {
|
||||
if v <= 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: v as f64,
|
||||
});
|
||||
}
|
||||
Ok(v as f64)
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_non_negative_number(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<f64, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => {
|
||||
if !v.is_finite() || v < 0.0 {
|
||||
return Err(BsonQmActionError::InvalidNumber { field, value: v });
|
||||
}
|
||||
if v == 0.0 {
|
||||
Ok(0.0)
|
||||
} else {
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
RawBsonRef::Int32(v) => {
|
||||
if v < 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: f64::from(v),
|
||||
});
|
||||
}
|
||||
Ok(f64::from(v))
|
||||
}
|
||||
RawBsonRef::Int64(v) => {
|
||||
if v < 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: v as f64,
|
||||
});
|
||||
}
|
||||
Ok(v as f64)
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_qm_split_doc_at<'a>(
|
||||
doc: &'a RawDocument,
|
||||
offset: usize,
|
||||
) -> Result<RawQmSplit<'a>, BsonQmActionError> {
|
||||
let mut qm_search_code: Option<&'a str> = None;
|
||||
let mut ex_date: Option<i32> = None;
|
||||
let mut ratio: Option<f64> = None;
|
||||
let mut declared_date: Option<i32> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonQmActionError::CorruptBson {
|
||||
offset,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let key = elem.key().as_str();
|
||||
|
||||
if key == FIELD_QM_SEARCH_CODE {
|
||||
let val = decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)?;
|
||||
qm_search_code = Some(decode_non_empty_str(FIELD_QM_SEARCH_CODE, val)?);
|
||||
} else if key == FIELD_DATE {
|
||||
let val = decode_element_value(FIELD_DATE, elem, offset)?;
|
||||
ex_date = Some(decode_required_date(FIELD_DATE, val)?);
|
||||
} else if key == FIELD_SPLIT_RATIO {
|
||||
let val = decode_element_value(FIELD_SPLIT_RATIO, elem, offset)?;
|
||||
ratio = Some(decode_positive_number(FIELD_SPLIT_RATIO, val)?);
|
||||
} else if key == FIELD_DECLARED {
|
||||
let val = decode_element_value(FIELD_DECLARED, elem, offset)?;
|
||||
declared_date = decode_optional_date(FIELD_DECLARED, val)?;
|
||||
}
|
||||
// `FIELD_USD_FX_RATE` and all unknown extra fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
let Some(qm_search_code) = qm_search_code else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
});
|
||||
};
|
||||
let Some(ex_date) = ex_date else {
|
||||
return Err(BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
};
|
||||
let Some(ratio) = ratio else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
});
|
||||
};
|
||||
|
||||
Ok(RawQmSplit {
|
||||
qm_search_code,
|
||||
ex_date,
|
||||
ratio,
|
||||
declared_date,
|
||||
})
|
||||
}
|
||||
|
||||
fn decode_qm_dividend_doc_at<'a>(
|
||||
doc: &'a RawDocument,
|
||||
offset: usize,
|
||||
) -> Result<RawQmDividend<'a>, BsonQmActionError> {
|
||||
let mut qm_search_code: Option<&'a str> = None;
|
||||
let mut ex_date: Option<i32> = None;
|
||||
let mut cash: Option<f64> = None;
|
||||
let mut currency: Option<&'a str> = None;
|
||||
let mut declared_date: Option<i32> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonQmActionError::CorruptBson {
|
||||
offset,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let key = elem.key().as_str();
|
||||
|
||||
if key == FIELD_QM_SEARCH_CODE {
|
||||
let val = decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)?;
|
||||
qm_search_code = Some(decode_non_empty_str(FIELD_QM_SEARCH_CODE, val)?);
|
||||
} else if key == FIELD_DATE {
|
||||
let val = decode_element_value(FIELD_DATE, elem, offset)?;
|
||||
ex_date = Some(decode_required_date(FIELD_DATE, val)?);
|
||||
} else if key == FIELD_DIVIDEND_CASH {
|
||||
let val = decode_element_value(FIELD_DIVIDEND_CASH, elem, offset)?;
|
||||
cash = Some(decode_non_negative_number(FIELD_DIVIDEND_CASH, val)?);
|
||||
} else if key == FIELD_DIVIDEND_CURRENCY {
|
||||
let val = decode_element_value(FIELD_DIVIDEND_CURRENCY, elem, offset)?;
|
||||
currency = Some(decode_non_empty_str(FIELD_DIVIDEND_CURRENCY, val)?);
|
||||
} else if key == FIELD_DECLARED {
|
||||
let val = decode_element_value(FIELD_DECLARED, elem, offset)?;
|
||||
declared_date = decode_optional_date(FIELD_DECLARED, val)?;
|
||||
}
|
||||
// `FIELD_USD_FX_RATE` and all unknown extra fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
let Some(qm_search_code) = qm_search_code else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
});
|
||||
};
|
||||
let Some(ex_date) = ex_date else {
|
||||
return Err(BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
};
|
||||
let Some(cash) = cash else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CASH,
|
||||
});
|
||||
};
|
||||
let Some(currency) = currency else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CURRENCY,
|
||||
});
|
||||
};
|
||||
|
||||
Ok(RawQmDividend {
|
||||
qm_search_code,
|
||||
ex_date,
|
||||
cash,
|
||||
currency,
|
||||
declared_date,
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing a `qmSplits` MongoDB document in one forward pass
|
||||
/// without allocating a `String` or owned `bson::Document`.
|
||||
#[inline]
|
||||
pub fn decode_qm_split_doc<'a>(doc: &'a RawDocument) -> Result<RawQmSplit<'a>, BsonQmActionError> {
|
||||
decode_qm_split_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed [`RawQmSplit`].
|
||||
pub fn decode_qm_split_bytes<'a>(bytes: &'a [u8]) -> Result<RawQmSplit<'a>, BsonQmActionError> {
|
||||
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
|
||||
decode_qm_split_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing a `qmDividends` MongoDB document in one forward
|
||||
/// pass without allocating a `String` or owned `bson::Document`.
|
||||
#[inline]
|
||||
pub fn decode_qm_dividend_doc<'a>(
|
||||
doc: &'a RawDocument,
|
||||
) -> Result<RawQmDividend<'a>, BsonQmActionError> {
|
||||
decode_qm_dividend_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed
|
||||
/// [`RawQmDividend`].
|
||||
pub fn decode_qm_dividend_bytes<'a>(
|
||||
bytes: &'a [u8],
|
||||
) -> Result<RawQmDividend<'a>, BsonQmActionError> {
|
||||
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
|
||||
decode_qm_dividend_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_split_doc`], invoking
|
||||
/// `on_split` for every valid document (including `splitratio == 1.0`, counted in
|
||||
/// `stats.split_noop_ratio_one`) and `on_error(byte_offset, err)` for every rejected document
|
||||
/// without aborting the stream on per-document errors.
|
||||
///
|
||||
/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`.
|
||||
pub fn decode_qm_split_buffer<'a, F, E>(
|
||||
buf: &'a [u8],
|
||||
mut on_split: F,
|
||||
mut on_error: E,
|
||||
) -> BsonQmActionDecodeStats
|
||||
where
|
||||
F: FnMut(RawQmSplit<'a>),
|
||||
E: FnMut(usize, BsonQmActionError),
|
||||
{
|
||||
let mut stats = BsonQmActionDecodeStats::default();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
stats.docs_in += 1;
|
||||
match item {
|
||||
Ok((doc_offset, doc)) => match decode_qm_split_doc_at(doc, doc_offset) {
|
||||
Ok(split) => {
|
||||
stats.decoded += 1;
|
||||
if split.ratio == 1.0 {
|
||||
stats.split_noop_ratio_one += 1;
|
||||
}
|
||||
on_split(split);
|
||||
}
|
||||
Err(err) => {
|
||||
stats.record_error(&err);
|
||||
on_error(doc_offset, err);
|
||||
}
|
||||
},
|
||||
Err((doc_offset, err)) => {
|
||||
let mapped = map_framing_error(err);
|
||||
stats.record_error(&mapped);
|
||||
on_error(doc_offset, mapped);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_dividend_doc`], invoking
|
||||
/// `on_dividend` for every valid document and `on_error(byte_offset, err)` for every rejected
|
||||
/// document without aborting the stream on per-document errors.
|
||||
///
|
||||
/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`.
|
||||
pub fn decode_qm_dividend_buffer<'a, F, E>(
|
||||
buf: &'a [u8],
|
||||
mut on_dividend: F,
|
||||
mut on_error: E,
|
||||
) -> BsonQmActionDecodeStats
|
||||
where
|
||||
F: FnMut(RawQmDividend<'a>),
|
||||
E: FnMut(usize, BsonQmActionError),
|
||||
{
|
||||
let mut stats = BsonQmActionDecodeStats::default();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
stats.docs_in += 1;
|
||||
match item {
|
||||
Ok((doc_offset, doc)) => match decode_qm_dividend_doc_at(doc, doc_offset) {
|
||||
Ok(dividend) => {
|
||||
stats.decoded += 1;
|
||||
on_dividend(dividend);
|
||||
}
|
||||
Err(err) => {
|
||||
stats.record_error(&err);
|
||||
on_error(doc_offset, err);
|
||||
}
|
||||
},
|
||||
Err((doc_offset, err)) => {
|
||||
let mapped = map_framing_error(err);
|
||||
stats.record_error(&mapped);
|
||||
on_error(doc_offset, mapped);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bson_qm_actions_tests.rs"]
|
||||
mod tests;
|
||||
883
tools/curate-etl/src/bson_qm_actions_tests.rs
Normal file
883
tools/curate-etl/src/bson_qm_actions_tests.rs
Normal file
|
|
@ -0,0 +1,883 @@
|
|||
use bson::oid::ObjectId;
|
||||
use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf};
|
||||
use bson::spec::ElementType;
|
||||
use bson::DateTime;
|
||||
|
||||
use super::*;
|
||||
use crate::corporate_actions::{build_corporate_actions, CorporateActionKind, KnownAtSource};
|
||||
use crate::curate_adj::curate_adj_factors;
|
||||
use crate::provider_mapping::{ProviderMappingRow, ProviderMappingTable};
|
||||
use crate::split::{ymd_to_epoch_days, SplitTable};
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).unwrap()
|
||||
}
|
||||
|
||||
fn make_split_doc(code: &str, date: &str, ratio: f64, declared: Option<&str>) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("splitratio"), ratio);
|
||||
if let Some(decl) = declared {
|
||||
doc.append(cstr!("declared"), decl);
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
fn make_dividend_doc(
|
||||
code: &str,
|
||||
date: &str,
|
||||
cash: f64,
|
||||
currency: &str,
|
||||
declared: Option<&str>,
|
||||
) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("amount"), cash);
|
||||
doc.append(cstr!("currency"), currency);
|
||||
if let Some(decl) = declared {
|
||||
doc.append(cstr!("declared"), decl);
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_realistic_qm_split_and_dividend_docs_and_ignores_extra_and_usd_fx_rate() {
|
||||
let mut nested = RawDocumentBuf::new();
|
||||
nested.append(cstr!("provider"), "quotemedia");
|
||||
nested.append(cstr!("version"), 1_i32);
|
||||
|
||||
let mut tags = RawArrayBuf::new();
|
||||
tags.push("ca");
|
||||
tags.push("equity");
|
||||
|
||||
// Realistic qmSplits document with extra metadata and bogus usdFxRate.
|
||||
let mut split_doc = RawDocumentBuf::new();
|
||||
split_doc.append(
|
||||
cstr!("_id"),
|
||||
ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),
|
||||
);
|
||||
split_doc.append(cstr!("symbol"), "NVDA");
|
||||
split_doc.append(cstr!("exchange"), "NASDAQ");
|
||||
split_doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
split_doc.append(cstr!("date"), "2024-06-10");
|
||||
split_doc.append(cstr!("declared"), "2024-05-22");
|
||||
split_doc.append(cstr!("splitratio"), 10.0_f64);
|
||||
split_doc.append(cstr!("usdFxRate"), "bogus-ignored-type");
|
||||
split_doc.append(
|
||||
cstr!("reportDate"),
|
||||
DateTime::from_millis(i64::from(day(2024, 6, 10)) * MILLIS_PER_DAY),
|
||||
);
|
||||
split_doc.append(cstr!("created_at"), DateTime::from_millis(1_718_000_000_000));
|
||||
split_doc.append(cstr!("updated_at"), DateTime::from_millis(1_718_000_060_000));
|
||||
split_doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref()));
|
||||
split_doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref()));
|
||||
|
||||
let split = decode_qm_split_doc(&split_doc).unwrap();
|
||||
assert_eq!(split.qm_search_code, "NVDA");
|
||||
assert_eq!(split.ex_date, day(2024, 6, 10));
|
||||
assert_eq!(split.ratio.to_bits(), 10.0_f64.to_bits());
|
||||
assert_eq!(split.declared_date, Some(day(2024, 5, 22)));
|
||||
assert_eq!(decode_qm_split_bytes(split_doc.as_bytes()).unwrap(), split);
|
||||
|
||||
// Realistic qmDividends document with bogus usdFxRate: 1 on CAD row.
|
||||
let mut div_doc = RawDocumentBuf::new();
|
||||
div_doc.append(
|
||||
cstr!("_id"),
|
||||
ObjectId::from_bytes([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]),
|
||||
);
|
||||
div_doc.append(cstr!("symbol"), "RY");
|
||||
div_doc.append(cstr!("exchange"), "TSX");
|
||||
div_doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
div_doc.append(cstr!("date"), "2024-11-15");
|
||||
div_doc.append(cstr!("declared"), "2024-10-30");
|
||||
div_doc.append(cstr!("amount"), 1.42_f64);
|
||||
div_doc.append(cstr!("currency"), "CAD");
|
||||
div_doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
div_doc.append(
|
||||
cstr!("reportDate"),
|
||||
DateTime::from_millis(i64::from(day(2024, 11, 15)) * MILLIS_PER_DAY),
|
||||
);
|
||||
div_doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref()));
|
||||
div_doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref()));
|
||||
|
||||
let div = decode_qm_dividend_doc(&div_doc).unwrap();
|
||||
assert_eq!(div.qm_search_code, "RY:CA");
|
||||
assert_eq!(div.ex_date, day(2024, 11, 15));
|
||||
assert_eq!(div.cash.to_bits(), 1.42_f64.to_bits());
|
||||
assert_eq!(div.currency, "CAD");
|
||||
assert_eq!(div.declared_date, Some(day(2024, 10, 30)));
|
||||
assert_eq!(decode_qm_dividend_bytes(div_doc.as_bytes()).unwrap(), div);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_date_and_declared_as_string_and_datetime_including_pre_1970_and_leap_day() {
|
||||
// Pre-1970 mid-day: 1969-12-31T12:34:56.789Z must floor to epoch day -1 (not 0).
|
||||
let pre_1970_ex_ms: i64 = -MILLIS_PER_DAY + (12 * 3600 + 34 * 60 + 56) * 1000 + 789;
|
||||
let pre_1970_decl_ms: i64 = -10 * MILLIS_PER_DAY + 43_200_000;
|
||||
|
||||
let mut split_dt = RawDocumentBuf::new();
|
||||
split_dt.append(cstr!("qmSearchCode"), "IBM");
|
||||
split_dt.append(cstr!("date"), DateTime::from_millis(pre_1970_ex_ms));
|
||||
split_dt.append(cstr!("declared"), DateTime::from_millis(pre_1970_decl_ms));
|
||||
split_dt.append(cstr!("splitratio"), 2_i32);
|
||||
|
||||
let split = decode_qm_split_doc(&split_dt).unwrap();
|
||||
assert_eq!(split.ex_date, -1);
|
||||
assert_eq!(split.declared_date, Some(-10));
|
||||
assert_eq!(split.ratio, 2.0);
|
||||
|
||||
// Leap day string + DateTime declared.
|
||||
let mut div_leap = RawDocumentBuf::new();
|
||||
div_leap.append(cstr!("qmSearchCode"), "TD:CA");
|
||||
div_leap.append(cstr!("date"), "2024-02-29");
|
||||
div_leap.append(
|
||||
cstr!("declared"),
|
||||
DateTime::from_millis(i64::from(day(2024, 2, 1)) * MILLIS_PER_DAY + 36_000_000),
|
||||
);
|
||||
div_leap.append(cstr!("amount"), 1.02_f64);
|
||||
div_leap.append(cstr!("currency"), "CAD");
|
||||
|
||||
let div = decode_qm_dividend_doc(&div_leap).unwrap();
|
||||
assert_eq!(div.ex_date, day(2024, 2, 29));
|
||||
assert_eq!(div.declared_date, Some(day(2024, 2, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_double_int32_int64_numerics_and_normalizes_negative_zero_cash() {
|
||||
// Splits: Double, Int32, Int64.
|
||||
for (val, expected) in [
|
||||
(RawBsonRef::Double(0.05), 0.05_f64),
|
||||
(RawBsonRef::Int32(4), 4.0_f64),
|
||||
(RawBsonRef::Int64(10), 10.0_f64),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "TEST");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), val);
|
||||
let decoded = decode_qm_split_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.ratio.to_bits(), expected.to_bits());
|
||||
}
|
||||
|
||||
// Dividends: Double, Int32, Int64, 0, and -0.0 -> +0.0.
|
||||
for (val, expected) in [
|
||||
(RawBsonRef::Double(0.25), 0.25_f64),
|
||||
(RawBsonRef::Double(-0.0), 0.0_f64),
|
||||
(RawBsonRef::Double(0.0), 0.0_f64),
|
||||
(RawBsonRef::Int32(0), 0.0_f64),
|
||||
(RawBsonRef::Int32(2), 2.0_f64),
|
||||
(RawBsonRef::Int64(0), 0.0_f64),
|
||||
(RawBsonRef::Int64(5), 5.0_f64),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "TEST");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), val);
|
||||
doc.append(cstr!("currency"), "USD");
|
||||
let decoded = decode_qm_dividend_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.cash.to_bits(), expected.to_bits());
|
||||
assert!(!decoded.cash.is_sign_negative());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_optional_declared_missing_null_empty_malformed_and_wrong_type() {
|
||||
// Missing declared -> None.
|
||||
let s_missing = make_split_doc("AAPL", "2020-08-31", 4.0, None);
|
||||
assert_eq!(decode_qm_split_doc(&s_missing).unwrap().declared_date, None);
|
||||
|
||||
// Null declared -> None.
|
||||
let mut s_null = make_split_doc("AAPL", "2020-08-31", 4.0, None);
|
||||
s_null.append(cstr!("declared"), RawBsonRef::Null);
|
||||
assert_eq!(decode_qm_split_doc(&s_null).unwrap().declared_date, None);
|
||||
|
||||
// Empty and whitespace-only declared -> None.
|
||||
for blank in ["", " ", "\t\n"] {
|
||||
let d_blank = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", Some(blank));
|
||||
assert_eq!(
|
||||
decode_qm_dividend_doc(&d_blank).unwrap().declared_date,
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
// Malformed declared -> MalformedDate naming "declared".
|
||||
let s_bad = make_split_doc("AAPL", "2020-08-31", 4.0, Some("2023-02-29"));
|
||||
let err = decode_qm_split_doc(&s_bad).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MalformedDate {
|
||||
field: FIELD_DECLARED
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DECLARED));
|
||||
|
||||
// Wrong type on declared -> WrongType naming "declared".
|
||||
let mut d_wrong = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", None);
|
||||
d_wrong.append(cstr!("declared"), 20240801_i32);
|
||||
let err = decode_qm_dividend_doc(&d_wrong).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DECLARED,
|
||||
actual: ElementType::Int32,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DECLARED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_ratio_one_is_decoded_not_dropped_and_counted_as_noop() {
|
||||
let mut buf = Vec::new();
|
||||
for val in [
|
||||
RawBsonRef::Double(1.0),
|
||||
RawBsonRef::Int32(1),
|
||||
RawBsonRef::Int64(1),
|
||||
RawBsonRef::Double(2.0),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NOOP");
|
||||
doc.append(cstr!("date"), "2024-03-15");
|
||||
doc.append(cstr!("splitratio"), val);
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
}
|
||||
|
||||
let mut decoded_ratios = Vec::new();
|
||||
let stats = decode_qm_split_buffer(
|
||||
&buf,
|
||||
|s| decoded_ratios.push(s.ratio),
|
||||
|_, err| panic!("unexpected error: {err}"),
|
||||
);
|
||||
|
||||
assert_eq!(decoded_ratios, vec![1.0, 1.0, 1.0, 2.0]);
|
||||
assert_eq!(stats.docs_in, 4);
|
||||
assert_eq!(stats.decoded, 4);
|
||||
assert_eq!(stats.split_noop_ratio_one, 3);
|
||||
assert_eq!(stats.rejected_total(), 0);
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_every_error_variant_and_names_offending_field() {
|
||||
// 1. Missing required fields on splits.
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_SPLIT_RATIO
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_SPLIT_RATIO));
|
||||
}
|
||||
|
||||
// 2. Missing required fields on dividends.
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), 0.5_f64);
|
||||
doc.append(cstr!("currency"), "USD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("amount"), 0.5_f64);
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CASH
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CASH));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), 0.5_f64);
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CURRENCY
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY));
|
||||
}
|
||||
|
||||
// 3. Empty / whitespace-only string fields.
|
||||
for blank in ["", " ", "\t\n"] {
|
||||
let s = make_split_doc(blank, "2024-06-10", 2.0, None);
|
||||
let err = decode_qm_split_doc(&s).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::EmptyField {
|
||||
field: FIELD_QM_SEARCH_CODE
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
|
||||
let d = make_dividend_doc("RY:CA", "2024-06-10", 0.5, blank, None);
|
||||
let err = decode_qm_dividend_doc(&d).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::EmptyField {
|
||||
field: FIELD_DIVIDEND_CURRENCY
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY));
|
||||
}
|
||||
|
||||
// 4. Wrong BSON types (including string-encoded numerics).
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), 123_i32);
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
actual: ElementType::Int32,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), 20240610_i32);
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DATE,
|
||||
actual: ElementType::Int32,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), "10.0");
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
actual: ElementType::String,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_SPLIT_RATIO));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), "1.42");
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DIVIDEND_CASH,
|
||||
actual: ElementType::String,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CASH));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), 1.42_f64);
|
||||
doc.append(cstr!("currency"), true);
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DIVIDEND_CURRENCY,
|
||||
actual: ElementType::Boolean,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY));
|
||||
}
|
||||
|
||||
// 5. Malformed dates (bad calendar date, bad format, and DateTime overflowing i32 days).
|
||||
for bad_date in ["2023-02-29", "2024/06/10", "2024-6-10", "not-a-date"] {
|
||||
let doc = make_split_doc("NVDA", bad_date, 2.0, None);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MalformedDate { field: FIELD_DATE });
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), DateTime::from_millis(i64::MAX));
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MalformedDate { field: FIELD_DATE });
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("declared"), DateTime::from_millis(i64::MIN));
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MalformedDate {
|
||||
field: FIELD_DECLARED
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// 6. Invalid numeric values for splitratio (<= 0 or non-finite).
|
||||
for bad_ratio in [
|
||||
RawBsonRef::Double(f64::NAN),
|
||||
RawBsonRef::Double(f64::INFINITY),
|
||||
RawBsonRef::Double(f64::NEG_INFINITY),
|
||||
RawBsonRef::Double(0.0),
|
||||
RawBsonRef::Double(-0.0),
|
||||
RawBsonRef::Double(-2.0),
|
||||
RawBsonRef::Int32(0),
|
||||
RawBsonRef::Int32(-1),
|
||||
RawBsonRef::Int64(0),
|
||||
RawBsonRef::Int64(-5),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), bad_ratio);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
BsonQmActionError::InvalidNumber {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
..
|
||||
}
|
||||
),
|
||||
"expected InvalidNumber for {bad_ratio:?}, got {err:?}"
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_SPLIT_RATIO));
|
||||
}
|
||||
|
||||
// 7. Invalid numeric values for dividend cash (< 0 or non-finite).
|
||||
for bad_cash in [
|
||||
RawBsonRef::Double(f64::NAN),
|
||||
RawBsonRef::Double(f64::INFINITY),
|
||||
RawBsonRef::Double(f64::NEG_INFINITY),
|
||||
RawBsonRef::Double(-0.01),
|
||||
RawBsonRef::Int32(-1),
|
||||
RawBsonRef::Int64(-10),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), bad_cash);
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
BsonQmActionError::InvalidNumber {
|
||||
field: FIELD_DIVIDEND_CASH,
|
||||
..
|
||||
}
|
||||
),
|
||||
"expected InvalidNumber for {bad_cash:?}, got {err:?}"
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CASH));
|
||||
}
|
||||
|
||||
// 8. Truncated and corrupt documents (zero panics).
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&[]),
|
||||
Err(BsonQmActionError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: 0,
|
||||
declared_len: None
|
||||
})
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_qm_dividend_bytes(&[1, 2, 3]),
|
||||
Err(BsonQmActionError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: 3,
|
||||
declared_len: None
|
||||
})
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&4_i32.to_le_bytes()),
|
||||
Err(BsonQmActionError::CorruptDocumentLength {
|
||||
offset: 0,
|
||||
declared_len: 4
|
||||
})
|
||||
));
|
||||
let valid_bytes = make_split_doc("NVDA", "2024-06-10", 10.0, None)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&valid_bytes[..valid_bytes.len() - 1]),
|
||||
Err(BsonQmActionError::TruncatedDocument {
|
||||
offset: 0,
|
||||
declared_len: Some(_),
|
||||
..
|
||||
})
|
||||
));
|
||||
let mut with_trailing = valid_bytes.clone();
|
||||
with_trailing.push(0);
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&with_trailing),
|
||||
Err(BsonQmActionError::CorruptDocumentLength { offset: 0, .. })
|
||||
));
|
||||
let mut bad_terminator = valid_bytes;
|
||||
*bad_terminator.last_mut().unwrap() = 0xFF;
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&bad_terminator),
|
||||
Err(BsonQmActionError::CorruptBson { offset: 0, .. })
|
||||
));
|
||||
|
||||
// Invalid UTF-8 inside a known string field (`qmSearchCode`).
|
||||
let mut invalid_utf8_doc: Vec<u8> = Vec::new();
|
||||
// Placeholder 4-byte length.
|
||||
invalid_utf8_doc.extend_from_slice(&0_i32.to_le_bytes());
|
||||
invalid_utf8_doc.push(0x02); // UTF-8 String element
|
||||
invalid_utf8_doc.extend_from_slice(b"qmSearchCode\0");
|
||||
invalid_utf8_doc.extend_from_slice(&3_i32.to_le_bytes()); // 2 bytes + NUL
|
||||
invalid_utf8_doc.extend_from_slice(&[0xFF, 0xFE, 0x00]);
|
||||
invalid_utf8_doc.push(0x00); // doc terminator
|
||||
let total_len = invalid_utf8_doc.len() as i32;
|
||||
invalid_utf8_doc[0..4].copy_from_slice(&total_len.to_le_bytes());
|
||||
let err = decode_qm_split_bytes(&invalid_utf8_doc).unwrap_err();
|
||||
assert!(matches!(err, BsonQmActionError::CorruptBson { offset: 0, .. }));
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buffer_decoders_survive_per_doc_errors_and_reconcile_stats_for_both_collections() {
|
||||
// 1. qmSplits mixed valid/invalid buffer.
|
||||
let s1 = make_split_doc("NVDA", "2024-06-10", 10.0, Some("2024-05-22"));
|
||||
let s_noop = make_split_doc("NOOP", "2024-06-11", 1.0, None);
|
||||
let mut s_missing = RawDocumentBuf::new();
|
||||
s_missing.append(cstr!("qmSearchCode"), "MISS");
|
||||
s_missing.append(cstr!("date"), "2024-06-12");
|
||||
let s_empty = make_split_doc(" ", "2024-06-13", 2.0, None);
|
||||
let mut s_wrong = RawDocumentBuf::new();
|
||||
s_wrong.append(cstr!("qmSearchCode"), "WRNG");
|
||||
s_wrong.append(cstr!("date"), "2024-06-14");
|
||||
s_wrong.append(cstr!("splitratio"), "2.0");
|
||||
let s_bad_date = make_split_doc("DATE", "2023-02-29", 2.0, None);
|
||||
let s_bad_num = make_split_doc("NUM", "2024-06-15", 0.0, None);
|
||||
let mut s_corrupt = make_split_doc("CORR", "2024-06-16", 2.0, None)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
*s_corrupt.last_mut().unwrap() = 0xAA;
|
||||
let s2 = make_split_doc("NEXM:CA", "2025-06-18", 0.05, None);
|
||||
|
||||
let mut split_buf = Vec::new();
|
||||
split_buf.extend_from_slice(s1.as_bytes());
|
||||
split_buf.extend_from_slice(s_noop.as_bytes());
|
||||
split_buf.extend_from_slice(s_missing.as_bytes());
|
||||
split_buf.extend_from_slice(s_empty.as_bytes());
|
||||
split_buf.extend_from_slice(s_wrong.as_bytes());
|
||||
split_buf.extend_from_slice(s_bad_date.as_bytes());
|
||||
split_buf.extend_from_slice(s_bad_num.as_bytes());
|
||||
split_buf.extend_from_slice(&s_corrupt);
|
||||
split_buf.extend_from_slice(s2.as_bytes());
|
||||
|
||||
let mut split_codes = Vec::new();
|
||||
let mut split_errors = Vec::new();
|
||||
let split_stats = decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| split_codes.push(s.qm_search_code.to_owned()),
|
||||
|off, err| split_errors.push((off, err)),
|
||||
);
|
||||
|
||||
assert_eq!(split_codes, vec!["NVDA", "NOOP", "NEXM:CA"]);
|
||||
assert_eq!(split_errors.len(), 6);
|
||||
assert_eq!(split_stats.docs_in, 9);
|
||||
assert_eq!(split_stats.decoded, 3);
|
||||
assert_eq!(split_stats.split_noop_ratio_one, 1);
|
||||
assert_eq!(split_stats.rejected_missing_field, 1);
|
||||
assert_eq!(split_stats.rejected_empty_field, 1);
|
||||
assert_eq!(split_stats.rejected_wrong_type, 1);
|
||||
assert_eq!(split_stats.rejected_malformed_date, 1);
|
||||
assert_eq!(split_stats.rejected_invalid_number, 1);
|
||||
assert_eq!(split_stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(
|
||||
split_stats.decoded + split_stats.rejected_total(),
|
||||
split_stats.docs_in
|
||||
);
|
||||
|
||||
// 2. qmDividends mixed valid/invalid buffer ending with a corrupt length prefix.
|
||||
let d1 = make_dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD", Some("2024-10-30"));
|
||||
let mut d_missing = RawDocumentBuf::new();
|
||||
d_missing.append(cstr!("qmSearchCode"), "MISS");
|
||||
d_missing.append(cstr!("date"), "2024-11-15");
|
||||
d_missing.append(cstr!("amount"), 0.5_f64);
|
||||
let d_empty = make_dividend_doc("RY:CA", "2024-11-15", 0.5, " ", None);
|
||||
let mut d_wrong = RawDocumentBuf::new();
|
||||
d_wrong.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
d_wrong.append(cstr!("date"), "2024-11-15");
|
||||
d_wrong.append(cstr!("amount"), "0.5");
|
||||
d_wrong.append(cstr!("currency"), "CAD");
|
||||
let d_bad_date = make_dividend_doc("RY:CA", "2024-11-15", 0.5, "CAD", Some("bad"));
|
||||
let d_bad_num = make_dividend_doc("RY:CA", "2024-11-15", -0.1, "CAD", None);
|
||||
let d2 = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", None);
|
||||
|
||||
let mut div_buf = Vec::new();
|
||||
div_buf.extend_from_slice(d1.as_bytes());
|
||||
div_buf.extend_from_slice(d_missing.as_bytes());
|
||||
div_buf.extend_from_slice(d_empty.as_bytes());
|
||||
div_buf.extend_from_slice(d_wrong.as_bytes());
|
||||
div_buf.extend_from_slice(d_bad_date.as_bytes());
|
||||
div_buf.extend_from_slice(d_bad_num.as_bytes());
|
||||
div_buf.extend_from_slice(d2.as_bytes());
|
||||
// Trailing corrupt length < 5 stops cleanly.
|
||||
div_buf.extend_from_slice(&2_i32.to_le_bytes());
|
||||
div_buf.extend_from_slice(d2.as_bytes());
|
||||
|
||||
let mut div_codes = Vec::new();
|
||||
let mut div_errors = Vec::new();
|
||||
let div_stats = decode_qm_dividend_buffer(
|
||||
&div_buf,
|
||||
|d| div_codes.push(d.qm_search_code.to_owned()),
|
||||
|off, err| div_errors.push((off, err)),
|
||||
);
|
||||
|
||||
assert_eq!(div_codes, vec!["RY:CA", "AAPL"]);
|
||||
assert_eq!(div_errors.len(), 6);
|
||||
assert_eq!(div_stats.docs_in, 8);
|
||||
assert_eq!(div_stats.decoded, 2);
|
||||
assert_eq!(div_stats.split_noop_ratio_one, 0);
|
||||
assert_eq!(div_stats.rejected_missing_field, 1);
|
||||
assert_eq!(div_stats.rejected_empty_field, 1);
|
||||
assert_eq!(div_stats.rejected_wrong_type, 1);
|
||||
assert_eq!(div_stats.rejected_malformed_date, 1);
|
||||
assert_eq!(div_stats.rejected_invalid_number, 1);
|
||||
assert_eq!(div_stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(
|
||||
div_stats.decoded + div_stats.rejected_total(),
|
||||
div_stats.docs_in
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_events_feed_split_table_curate_adj_factors_and_corporate_actions_unchanged() {
|
||||
// 1. SplitTable interoperability (NVDA 10:1 forward, NEXM:CA 1:20 reverse, 1:1 no-op).
|
||||
let mut split_buf = Vec::new();
|
||||
split_buf.extend_from_slice(
|
||||
make_split_doc("NVDA", "2024-06-10", 10.0, Some("2024-05-22")).as_bytes(),
|
||||
);
|
||||
split_buf.extend_from_slice(make_split_doc("NVDA", "2024-07-01", 1.0, None).as_bytes());
|
||||
split_buf.extend_from_slice(make_split_doc("NEXM:CA", "2025-06-18", 0.05, None).as_bytes());
|
||||
split_buf.extend_from_slice(make_split_doc("UNMAPPED", "2024-06-10", 2.0, None).as_bytes());
|
||||
|
||||
let mut div_buf = Vec::new();
|
||||
let mut ry_div = make_dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD", Some("2024-10-30"));
|
||||
ry_div.append(cstr!("usdFxRate"), 1_i32); // bogus usdFxRate must have zero effect
|
||||
div_buf.extend_from_slice(ry_div.as_bytes());
|
||||
let mut unmapped_div = make_dividend_doc("UNMAPPED", "2024-11-15", 0.50, "USD", None);
|
||||
unmapped_div.append(cstr!("usdFxRate"), 999.0_f64);
|
||||
div_buf.extend_from_slice(unmapped_div.as_bytes());
|
||||
|
||||
let mut source_splits = Vec::new();
|
||||
let split_stats = decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| source_splits.push((s.qm_search_code.to_owned(), s.to_split_event())),
|
||||
|_, err| panic!("unexpected split decode error: {err}"),
|
||||
);
|
||||
assert_eq!(split_stats.split_noop_ratio_one, 1);
|
||||
|
||||
let table = SplitTable::from_events(source_splits.iter().cloned()).unwrap();
|
||||
assert_eq!(table.cum_factor_after("NVDA", day(2024, 6, 7)), 10.0);
|
||||
assert_eq!(table.cum_factor_after("NVDA", day(2024, 6, 10)), 1.0);
|
||||
assert_eq!(table.cum_factor_after("NEXM:CA", day(2025, 6, 17)), 0.05);
|
||||
assert_eq!(table.cum_factor_after("NEXM:CA", day(2025, 6, 18)), 1.0);
|
||||
|
||||
// 2. ProviderMappingTable + curate_adj_factors interoperability.
|
||||
let mapping = ProviderMappingTable::from_rows([
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "NVDA".to_string(),
|
||||
listing_id: 101,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "NEXM:CA".to_string(),
|
||||
listing_id: 202,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "RY:CA".to_string(),
|
||||
listing_id: 303,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let mut source_divs = Vec::new();
|
||||
decode_qm_dividend_buffer(
|
||||
&div_buf,
|
||||
|d| {
|
||||
source_divs.push((
|
||||
d.qm_search_code.to_owned(),
|
||||
d.to_dividend_event(Some(142.0), Some("CAD".to_string())),
|
||||
));
|
||||
},
|
||||
|_, err| panic!("unexpected dividend decode error: {err}"),
|
||||
);
|
||||
|
||||
let curated = curate_adj_factors(&mapping, "qm", source_splits, source_divs).unwrap();
|
||||
// 1:1 NVDA split dropped by builder; UNMAPPED split & dividend dropped by mapping.
|
||||
assert_eq!(curated.rows.len(), 3);
|
||||
assert_eq!(curated.stats.builder.split_noops_dropped, 1);
|
||||
assert_eq!(curated.stats.splits_dropped_unmapped, 1);
|
||||
assert_eq!(curated.stats.dividends_dropped_unmapped, 1);
|
||||
|
||||
// Row 0: listing 101 (NVDA) 10:1 split
|
||||
assert_eq!(curated.rows[0].listing_id, 101);
|
||||
assert_eq!(curated.rows[0].ex_date, day(2024, 6, 10));
|
||||
assert_eq!(curated.rows[0].split_factor, 10.0);
|
||||
assert_eq!(curated.rows[0].cum_split_factor, 10.0);
|
||||
|
||||
// Row 1: listing 202 (NEXM:CA) 1:20 reverse split
|
||||
assert_eq!(curated.rows[1].listing_id, 202);
|
||||
assert_eq!(curated.rows[1].ex_date, day(2025, 6, 18));
|
||||
assert_eq!(curated.rows[1].split_factor, 0.05);
|
||||
|
||||
// Row 2: listing 303 (RY:CA) CAD dividend with usdFxRate ignored
|
||||
assert_eq!(curated.rows[2].listing_id, 303);
|
||||
assert_eq!(curated.rows[2].ex_date, day(2024, 11, 15));
|
||||
assert_eq!(curated.rows[2].div_cash, 1.42);
|
||||
assert_eq!(curated.rows[2].div_currency.as_deref(), Some("CAD"));
|
||||
let expected_div_factor = 142.0 / (142.0 - 1.42);
|
||||
assert!((curated.rows[2].cum_total_factor - expected_div_factor).abs() < 1e-12);
|
||||
|
||||
// 3. try_map_key / try_into_*_action_event -> build_corporate_actions.
|
||||
let mut mapped_split_actions = Vec::new();
|
||||
decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| {
|
||||
if let Some(pair) =
|
||||
s.try_into_split_action_event(|code, date| mapping.resolve("qm", code, date))
|
||||
{
|
||||
mapped_split_actions.push(pair);
|
||||
}
|
||||
},
|
||||
|_, err| panic!("unexpected error: {err}"),
|
||||
);
|
||||
|
||||
let mut mapped_div_actions = Vec::new();
|
||||
decode_qm_dividend_buffer(
|
||||
&div_buf,
|
||||
|d| {
|
||||
if let Some(pair) =
|
||||
d.try_into_dividend_action_event(|code, date| mapping.resolve("qm", code, date))
|
||||
{
|
||||
mapped_div_actions.push(pair);
|
||||
}
|
||||
},
|
||||
|_, err| panic!("unexpected error: {err}"),
|
||||
);
|
||||
|
||||
// Also verify try_into_split_event & try_into_dividend_event filter unmapped keys.
|
||||
let unmapped_split_doc = make_split_doc("UNMAPPED", "2024-06-10", 2.0, None);
|
||||
let unmapped_split = decode_qm_split_doc(&unmapped_split_doc).unwrap();
|
||||
assert_eq!(
|
||||
unmapped_split.try_into_split_event(|code, date| mapping.resolve("qm", code, date)),
|
||||
None
|
||||
);
|
||||
let mapped_div = decode_qm_dividend_doc(&ry_div).unwrap();
|
||||
let (lid, div_ev) = mapped_div
|
||||
.try_into_dividend_event(Some(142.0), Some("CAD".to_string()), |code, date| {
|
||||
mapping.resolve("qm", code, date)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(lid, 303);
|
||||
assert_eq!(div_ev.currency, "CAD");
|
||||
|
||||
let ca = build_corporate_actions(
|
||||
mapped_split_actions,
|
||||
mapped_div_actions,
|
||||
std::iter::empty(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(ca.rows.len(), 3);
|
||||
assert_eq!(ca.stats.split_noops_dropped, 1);
|
||||
|
||||
// NVDA split has declared_date -> DeclaredDate.
|
||||
assert_eq!(ca.rows[0].key, 101);
|
||||
assert_eq!(ca.rows[0].kind, CorporateActionKind::Split);
|
||||
assert_eq!(ca.rows[0].declared_date, Some(day(2024, 5, 22)));
|
||||
assert_eq!(ca.rows[0].known_at_source, KnownAtSource::DeclaredDate);
|
||||
|
||||
// NEXM split has no declared_date -> ExDateFallback.
|
||||
assert_eq!(ca.rows[1].key, 202);
|
||||
assert_eq!(ca.rows[1].kind, CorporateActionKind::Split);
|
||||
assert_eq!(ca.rows[1].declared_date, None);
|
||||
assert_eq!(ca.rows[1].known_at_source, KnownAtSource::ExDateFallback);
|
||||
|
||||
// RY:CA dividend has declared_date -> DeclaredDate.
|
||||
assert_eq!(ca.rows[2].key, 303);
|
||||
assert_eq!(ca.rows[2].kind, CorporateActionKind::Dividend);
|
||||
assert_eq!(ca.rows[2].cash_amount, Some(1.42));
|
||||
assert_eq!(ca.rows[2].currency.as_deref(), Some("CAD"));
|
||||
assert_eq!(ca.rows[2].declared_date, Some(day(2024, 10, 30)));
|
||||
assert_eq!(ca.rows[2].known_at_source, KnownAtSource::DeclaredDate);
|
||||
}
|
||||
|
|
@ -5,11 +5,11 @@
|
|||
|
||||
use crate::bench::{
|
||||
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS,
|
||||
DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_ADJ_BENCH_EVENTS, DEFAULT_CURATE_BARS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_EVENTS_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS,
|
||||
DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS,
|
||||
DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS,
|
||||
DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_CURATE_ADJ_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS,
|
||||
DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS,
|
||||
|
|
@ -35,6 +35,7 @@ pub enum CliAction {
|
|||
BenchParquetAdj(usize),
|
||||
BenchParquetCorporateActions(usize),
|
||||
BenchBsonEodPrices(usize),
|
||||
BenchBsonQmActions(usize),
|
||||
BenchCurateBars(usize),
|
||||
BenchCurateShorts(usize),
|
||||
BenchCurateEvents(usize),
|
||||
|
|
@ -65,6 +66,7 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-parquet-adj [rows] Run fixed-seed adj_factors Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_ADJ_BENCH_ROWS})\n\
|
||||
{name} bench-parquet-corporate-actions [rows] Run fixed-seed corporate_actions Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS})\n\
|
||||
{name} bench-bson-eod-prices [rows] Run fixed-seed eodPrices raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_EOD_PRICES_BENCH_ROWS})\n\
|
||||
{name} bench-bson-qm-actions [rows] Run fixed-seed qmSplits/qmDividends raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-events [rows] Run fixed-seed events curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_EVENTS_BENCH_ROWS})\n\
|
||||
|
|
@ -94,6 +96,7 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-parquet-adj [rows]\n\
|
||||
{name} bench-parquet-corporate-actions [rows]\n\
|
||||
{name} bench-bson-eod-prices [rows]\n\
|
||||
{name} bench-bson-qm-actions [rows]\n\
|
||||
{name} bench-curate-bars [rows]\n\
|
||||
{name} bench-curate-shorts [rows]\n\
|
||||
{name} bench-curate-events [rows]\n\
|
||||
|
|
@ -263,6 +266,18 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
["bench-bson-eod-prices", _, ..] => {
|
||||
Err("too many arguments for bench-bson-eod-prices".to_string())
|
||||
}
|
||||
["bench-bson-qm-actions"] => Ok(CliAction::BenchBsonQmActions(
|
||||
DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS,
|
||||
)),
|
||||
["bench-bson-qm-actions", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchBsonQmActions(n)),
|
||||
_ => Err(format!(
|
||||
"invalid row count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-bson-qm-actions", _, ..] => {
|
||||
Err("too many arguments for bench-bson-qm-actions".to_string())
|
||||
}
|
||||
["bench-curate-bars"] => Ok(CliAction::BenchCurateBars(DEFAULT_CURATE_BARS_BENCH_ROWS)),
|
||||
["bench-curate-bars", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchCurateBars(n)),
|
||||
|
|
@ -600,6 +615,24 @@ mod tests {
|
|||
assert!(parse_args(&to_args(&["bench-bson-eod-prices", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_bson_qm_actions_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-bson-qm-actions"])),
|
||||
Ok(CliAction::BenchBsonQmActions(
|
||||
DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-bson-qm-actions", "250000"])),
|
||||
Ok(CliAction::BenchBsonQmActions(250_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-bson-qm-actions", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-qm-actions", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-qm-actions", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-qm-actions", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_strings_mention_all_benchmarks() {
|
||||
let full = format_usage("curate-etl", "0.1.0");
|
||||
|
|
@ -618,6 +651,7 @@ mod tests {
|
|||
assert!(full.contains("bench-parquet-adj"));
|
||||
assert!(full.contains("bench-parquet-corporate-actions"));
|
||||
assert!(full.contains("bench-bson-eod-prices"));
|
||||
assert!(full.contains("bench-bson-qm-actions"));
|
||||
assert!(full.contains("bench-curate-bars"));
|
||||
assert!(full.contains("bench-curate-shorts"));
|
||||
assert!(full.contains("bench-curate-events"));
|
||||
|
|
@ -640,6 +674,7 @@ mod tests {
|
|||
assert!(short.contains("bench-parquet-adj"));
|
||||
assert!(short.contains("bench-parquet-corporate-actions"));
|
||||
assert!(short.contains("bench-bson-eod-prices"));
|
||||
assert!(short.contains("bench-bson-qm-actions"));
|
||||
assert!(short.contains("bench-curate-bars"));
|
||||
assert!(short.contains("bench-curate-shorts"));
|
||||
assert!(short.contains("bench-curate-events"));
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ pub mod adj;
|
|||
pub mod bars;
|
||||
pub mod bench;
|
||||
pub mod bson_eod_prices;
|
||||
pub mod bson_qm_actions;
|
||||
pub mod cli;
|
||||
pub mod corporate_actions;
|
||||
pub mod events;
|
||||
|
|
@ -32,6 +33,12 @@ pub use bson_eod_prices::{
|
|||
decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs,
|
||||
BsonEodDecodeStats, BsonEodPriceError, RawBsonDocIter, RawEodDailyBar,
|
||||
};
|
||||
pub use bson_qm_actions::{
|
||||
decode_qm_dividend_buffer, decode_qm_dividend_bytes, decode_qm_dividend_doc,
|
||||
decode_qm_split_buffer, decode_qm_split_bytes, decode_qm_split_doc, BsonQmActionDecodeStats,
|
||||
BsonQmActionError, RawQmDividend, RawQmSplit, FIELD_DATE, FIELD_DECLARED, FIELD_DIVIDEND_CASH,
|
||||
FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE, FIELD_SPLIT_RATIO, FIELD_USD_FX_RATE,
|
||||
};
|
||||
pub use corporate_actions::{
|
||||
build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionRow,
|
||||
CorporateActionsBuild, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent,
|
||||
|
|
|
|||
|
|
@ -5,12 +5,12 @@ use std::process::ExitCode;
|
|||
|
||||
use curate_etl::bench::{
|
||||
run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark,
|
||||
run_corporate_actions_benchmark, run_curate_adj_benchmark, run_curate_bars_benchmark,
|
||||
run_curate_events_benchmark, run_curate_fx_benchmark, run_curate_shorts_benchmark,
|
||||
run_events_benchmark, run_fx_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark,
|
||||
run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark,
|
||||
run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark,
|
||||
run_shorts_benchmark, run_split_benchmark,
|
||||
run_bson_qm_actions_benchmark, run_corporate_actions_benchmark, run_curate_adj_benchmark,
|
||||
run_curate_bars_benchmark, run_curate_events_benchmark, run_curate_fx_benchmark,
|
||||
run_curate_shorts_benchmark, run_events_benchmark, run_fx_benchmark, run_parquet_adj_benchmark,
|
||||
run_parquet_bars_benchmark, run_parquet_corporate_actions_benchmark,
|
||||
run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark,
|
||||
run_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark,
|
||||
};
|
||||
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
|
||||
|
||||
|
|
@ -504,6 +504,46 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchBsonQmActions(rows)) => {
|
||||
let report = run_bson_qm_actions_benchmark(rows);
|
||||
println!("curate-etl bench-bson-qm-actions");
|
||||
println!(
|
||||
" input: rows={} splits={} dividends={} bytes={}",
|
||||
report.rows, report.split_rows, report.dividend_rows, report.bytes
|
||||
);
|
||||
println!(
|
||||
" splits: decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})",
|
||||
report.split_stats.decoded,
|
||||
report.split_stats.split_noop_ratio_one,
|
||||
report.split_stats.rejected_total(),
|
||||
report.split_stats.rejected_missing_field,
|
||||
report.split_stats.rejected_empty_field,
|
||||
report.split_stats.rejected_wrong_type,
|
||||
report.split_stats.rejected_malformed_date,
|
||||
report.split_stats.rejected_invalid_number,
|
||||
report.split_stats.rejected_corrupt_document
|
||||
);
|
||||
println!(
|
||||
" dividends: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})",
|
||||
report.dividend_stats.decoded,
|
||||
report.dividend_stats.rejected_total(),
|
||||
report.dividend_stats.rejected_missing_field,
|
||||
report.dividend_stats.rejected_empty_field,
|
||||
report.dividend_stats.rejected_wrong_type,
|
||||
report.dividend_stats.rejected_malformed_date,
|
||||
report.dividend_stats.rejected_invalid_number,
|
||||
report.dividend_stats.rejected_corrupt_document
|
||||
);
|
||||
println!(
|
||||
" perf: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MB/s latency={:.2} ns/doc checksum=0x{:016x}",
|
||||
report.elapsed_ms,
|
||||
report.docs_per_sec,
|
||||
report.mb_per_sec,
|
||||
report.ns_per_doc,
|
||||
report.checksum
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateBars(rows)) => {
|
||||
let report = match run_curate_bars_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
|
|
|
|||
205
tools/curate-etl/tests/bson_qm_actions_contract.rs
Normal file
205
tools/curate-etl/tests/bson_qm_actions_contract.rs
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
//! Public-API integration contract test for `qmSplits` and `qmDividends` raw BSON decoders (`M1.2w`).
|
||||
|
||||
use bson::raw::{cstr, RawBsonRef, RawDocumentBuf};
|
||||
use bson::DateTime;
|
||||
use curate_etl::{
|
||||
build_corporate_actions, curate_adj_factors, decode_qm_dividend_buffer,
|
||||
decode_qm_dividend_bytes, decode_qm_dividend_doc, decode_qm_split_buffer,
|
||||
decode_qm_split_bytes, decode_qm_split_doc, ymd_to_epoch_days, BsonQmActionError,
|
||||
CorporateActionKind, KnownAtSource, ProviderMappingRow, ProviderMappingTable, SplitTable,
|
||||
FIELD_DATE, FIELD_DECLARED, FIELD_DIVIDEND_CASH, FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE,
|
||||
FIELD_SPLIT_RATIO, FIELD_USD_FX_RATE,
|
||||
};
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_field_constants_and_single_doc_decoders_match_contract() {
|
||||
assert_eq!(FIELD_QM_SEARCH_CODE, "qmSearchCode");
|
||||
assert_eq!(FIELD_DATE, "date");
|
||||
assert_eq!(FIELD_DECLARED, "declared");
|
||||
assert_eq!(FIELD_SPLIT_RATIO, "splitratio");
|
||||
assert_eq!(FIELD_USD_FX_RATE, "usdFxRate");
|
||||
assert_eq!(FIELD_DIVIDEND_CASH, "amount");
|
||||
assert_eq!(FIELD_DIVIDEND_CURRENCY, "currency");
|
||||
|
||||
let mut split_doc = RawDocumentBuf::new();
|
||||
split_doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
split_doc.append(cstr!("date"), "2024-06-10");
|
||||
split_doc.append(cstr!("declared"), "2024-05-22");
|
||||
split_doc.append(cstr!("splitratio"), 10_i32);
|
||||
split_doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
|
||||
let split = decode_qm_split_doc(&split_doc).unwrap();
|
||||
assert_eq!(decode_qm_split_bytes(split_doc.as_bytes()).unwrap(), split);
|
||||
assert_eq!(split.qm_search_code, "NVDA");
|
||||
assert_eq!(split.ex_date, day(2024, 6, 10));
|
||||
assert_eq!(split.ratio, 10.0);
|
||||
assert_eq!(split.declared_date, Some(day(2024, 5, 22)));
|
||||
|
||||
let mut div_doc = RawDocumentBuf::new();
|
||||
div_doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
div_doc.append(
|
||||
cstr!("date"),
|
||||
DateTime::from_millis(i64::from(day(2024, 11, 15)) * 86_400_000),
|
||||
);
|
||||
div_doc.append(cstr!("declared"), RawBsonRef::Null);
|
||||
div_doc.append(cstr!("amount"), 1.42_f64);
|
||||
div_doc.append(cstr!("currency"), "CAD");
|
||||
div_doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
|
||||
let div = decode_qm_dividend_doc(&div_doc).unwrap();
|
||||
assert_eq!(decode_qm_dividend_bytes(div_doc.as_bytes()).unwrap(), div);
|
||||
assert_eq!(div.qm_search_code, "RY:CA");
|
||||
assert_eq!(div.ex_date, day(2024, 11, 15));
|
||||
assert_eq!(div.cash, 1.42);
|
||||
assert_eq!(div.currency, "CAD");
|
||||
assert_eq!(div.declared_date, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_buffer_decoders_reconcile_and_feed_all_downstream_builders() {
|
||||
let mut split_buf = Vec::new();
|
||||
|
||||
let mut s_nvda = RawDocumentBuf::new();
|
||||
s_nvda.append(cstr!("qmSearchCode"), "NVDA");
|
||||
s_nvda.append(cstr!("date"), "2024-06-10");
|
||||
s_nvda.append(cstr!("declared"), "2024-05-22");
|
||||
s_nvda.append(cstr!("splitratio"), 10.0_f64);
|
||||
split_buf.extend_from_slice(s_nvda.as_bytes());
|
||||
|
||||
let mut s_noop = RawDocumentBuf::new();
|
||||
s_noop.append(cstr!("qmSearchCode"), "NVDA");
|
||||
s_noop.append(cstr!("date"), "2024-07-01");
|
||||
s_noop.append(cstr!("splitratio"), 1_i64);
|
||||
split_buf.extend_from_slice(s_noop.as_bytes());
|
||||
|
||||
let mut s_bad = RawDocumentBuf::new();
|
||||
s_bad.append(cstr!("qmSearchCode"), "NVDA");
|
||||
s_bad.append(cstr!("date"), "2024-07-02");
|
||||
s_bad.append(cstr!("splitratio"), -3.0_f64);
|
||||
split_buf.extend_from_slice(s_bad.as_bytes());
|
||||
|
||||
let mut div_buf = Vec::new();
|
||||
|
||||
let mut d_ry = RawDocumentBuf::new();
|
||||
d_ry.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
d_ry.append(cstr!("date"), "2024-11-15");
|
||||
d_ry.append(cstr!("declared"), "2024-10-30");
|
||||
d_ry.append(cstr!("amount"), 1.42_f64);
|
||||
d_ry.append(cstr!("currency"), "CAD");
|
||||
d_ry.append(cstr!("usdFxRate"), 1_i32);
|
||||
div_buf.extend_from_slice(d_ry.as_bytes());
|
||||
|
||||
let mut d_bad = RawDocumentBuf::new();
|
||||
d_bad.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
d_bad.append(cstr!("date"), "2023-02-29");
|
||||
d_bad.append(cstr!("amount"), 1.0_f64);
|
||||
d_bad.append(cstr!("currency"), "CAD");
|
||||
div_buf.extend_from_slice(d_bad.as_bytes());
|
||||
|
||||
let mapping = ProviderMappingTable::from_rows([
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "NVDA".to_string(),
|
||||
listing_id: 101,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "RY:CA".to_string(),
|
||||
listing_id: 303,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let mut split_events = Vec::new();
|
||||
let mut split_actions = Vec::new();
|
||||
let mut split_errs = Vec::new();
|
||||
let split_stats = decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| {
|
||||
split_events.push((s.qm_search_code.to_owned(), s.to_split_event()));
|
||||
if let Some(pair) =
|
||||
s.try_into_split_action_event(|code, date| mapping.resolve("qm", code, date))
|
||||
{
|
||||
split_actions.push(pair);
|
||||
}
|
||||
},
|
||||
|_, err| split_errs.push(err),
|
||||
);
|
||||
|
||||
assert_eq!(split_stats.docs_in, 3);
|
||||
assert_eq!(split_stats.decoded, 2);
|
||||
assert_eq!(split_stats.split_noop_ratio_one, 1);
|
||||
assert_eq!(split_stats.rejected_invalid_number, 1);
|
||||
assert_eq!(
|
||||
split_stats.decoded + split_stats.rejected_total(),
|
||||
split_stats.docs_in
|
||||
);
|
||||
assert!(matches!(
|
||||
split_errs.as_slice(),
|
||||
[BsonQmActionError::InvalidNumber {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
..
|
||||
}]
|
||||
));
|
||||
|
||||
let mut div_events = Vec::new();
|
||||
let mut div_actions = Vec::new();
|
||||
let mut div_errs = Vec::new();
|
||||
let div_stats = decode_qm_dividend_buffer(
|
||||
&div_buf,
|
||||
|d| {
|
||||
div_events.push((
|
||||
d.qm_search_code.to_owned(),
|
||||
d.to_dividend_event(Some(142.0), Some("CAD".to_string())),
|
||||
));
|
||||
if let Some(pair) =
|
||||
d.try_into_dividend_action_event(|code, date| mapping.resolve("qm", code, date))
|
||||
{
|
||||
div_actions.push(pair);
|
||||
}
|
||||
},
|
||||
|_, err| div_errs.push(err),
|
||||
);
|
||||
|
||||
assert_eq!(div_stats.docs_in, 2);
|
||||
assert_eq!(div_stats.decoded, 1);
|
||||
assert_eq!(div_stats.rejected_malformed_date, 1);
|
||||
assert_eq!(
|
||||
div_stats.decoded + div_stats.rejected_total(),
|
||||
div_stats.docs_in
|
||||
);
|
||||
assert!(matches!(
|
||||
div_errs.as_slice(),
|
||||
[BsonQmActionError::MalformedDate { field: FIELD_DATE }]
|
||||
));
|
||||
|
||||
// Feed SplitTable.
|
||||
let split_table = SplitTable::from_events(split_events.iter().cloned()).unwrap();
|
||||
assert_eq!(split_table.cum_factor_after("NVDA", day(2024, 6, 7)), 10.0);
|
||||
|
||||
// Feed curate_adj_factors.
|
||||
let adj = curate_adj_factors(&mapping, "qm", split_events, div_events).unwrap();
|
||||
assert_eq!(adj.rows.len(), 2);
|
||||
assert_eq!(adj.stats.builder.split_noops_dropped, 1);
|
||||
assert_eq!(adj.rows[0].listing_id, 101);
|
||||
assert_eq!(adj.rows[0].split_factor, 10.0);
|
||||
assert_eq!(adj.rows[1].listing_id, 303);
|
||||
assert_eq!(adj.rows[1].div_cash, 1.42);
|
||||
assert_eq!(adj.rows[1].div_currency.as_deref(), Some("CAD"));
|
||||
|
||||
// Feed build_corporate_actions.
|
||||
let ca = build_corporate_actions(split_actions, div_actions, std::iter::empty()).unwrap();
|
||||
assert_eq!(ca.rows.len(), 2);
|
||||
assert_eq!(ca.rows[0].kind, CorporateActionKind::Split);
|
||||
assert_eq!(ca.rows[0].known_at_source, KnownAtSource::DeclaredDate);
|
||||
assert_eq!(ca.rows[1].kind, CorporateActionKind::Dividend);
|
||||
assert_eq!(ca.rows[1].known_at_source, KnownAtSource::DeclaredDate);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue