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

574 lines
19 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Pure, socket-free QuestDB ILP v2 line encoder and sharded batch writer for
//! `bars_1m` and `fx_1m`.
//!
//! # Wire format (QuestDB ILP Protocol Version 2)
//!
//! Verified against the official `questdb-rs` client source in
//! `questdb/c-questdb-client` (`main` branch, `questdb-rs`):
//! - Binary `DOUBLE` type tag (`DOUBLE_TYPE = 16` / `0x10`):
//! `questdb-rs/src/ingress.rs` lines 157–159.
//! - Tag/field separators and binary `f64` field encoding (`<name>==\x10<8 LE IEEE-754 bytes>`):
//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 569–713.
//! - ILP escaping for `SYMBOL` values (space, `,`, `=`, `\n`, `\r`, and `\` prefixed with `\`):
//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 36–84.
//! - Timestamp column microsecond suffix (`<name>=<epoch_micros>t`):
//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 1026–1047.
//! - Designated timestamp microsecond suffix (` <epoch_micros>t\n`, non-negative):
//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 1087–1116.
//!
//! # Table contracts
//!
//! Column names and types match `M2_INTRADAY_SCHEMAS` in `libs/data/questdb/src/schema.ts`
//! and `design/DATA-CONTRACTS.md` §3.B:
//! - `bars_1m`: symbols `listing_id`, `session`, `source`; binary doubles `open`, `high`, `low`,
//! `close`, `volume` (`vwap` is omitted / NULL); timestamp column `known_at`; designated
//! timestamp `ts` (UTC microseconds).
//! - `fx_1m`: symbols `pair`, `source`; binary doubles `open`, `high`, `low`, `close`;
//! designated timestamp `ts` (UTC microseconds).
//!
//! # Deterministic sharding
//!
//! [`IlpShardedWriter`] routes rows deterministically using 64-bit FNV-1a modulo shard count
//! (`fnv1a_64(key_bytes) % shard_count`):
//! - `bars_1m` hashes `listing_id` as its 4-byte little-endian representation
//! (`listing_id.to_le_bytes()`).
//! - `fx_1m` hashes `pair` as its raw UTF-8 bytes (`pair.as_bytes()`).
//!
//! All rows for a given key always land on the same shard in their exact input order, preserving
//! the per-key ordering required by `DEDUP UPSERT KEYS(ts, listing_id)` / `KEYS(ts, pair)`.
use std::error::Error;
use std::fmt;
use std::io::{self, Write};
use crate::bars_1m::Bar1mRow;
/// QuestDB ILP v2 binary `DOUBLE` type byte (`16` / `0x10`).
pub const ILP_V2_DOUBLE_TYPE: u8 = 0x10;
/// Canonical QuestDB table name for 1-minute equity bars.
pub const TABLE_BARS_1M: &str = "bars_1m";
/// Canonical QuestDB table name for 1-minute FX bars.
pub const TABLE_FX_1M: &str = "fx_1m";
/// 64-bit FNV-1a offset basis used for deterministic shard routing.
pub const FNV1A_64_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
/// 64-bit FNV-1a prime used for deterministic shard routing.
pub const FNV1A_64_PRIME: u64 = 0x0000_0100_0000_01b3;
/// Default maximum buffered bytes per shard before flushing a batch (1 MiB).
pub const DEFAULT_ILP_MAX_BATCH_BYTES: usize = 1_048_576;
/// Default maximum buffered rows per shard before flushing a batch.
pub const DEFAULT_ILP_MAX_BATCH_ROWS: usize = 10_000;
/// A single `fx_1m` 1-minute FX bar input for QuestDB ILP v2 encoding.
///
/// Matches `M2_INTRADAY_SCHEMAS.fx_1m` in `libs/data/questdb/src/schema.ts`:
/// `pair` (SYMBOL), `open`/`high`/`low`/`close` (DOUBLE), `source` (SYMBOL), `ts` (TIMESTAMP).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Fx1mRow<'a> {
pub pair: &'a str,
/// Bar start timestamp in UTC microseconds since the Unix epoch (must be `>= 0`).
pub ts: i64,
pub open: f64,
pub high: f64,
pub low: f64,
pub close: f64,
pub source: &'a str,
}
/// Typed validation errors returned by [`encode_bar_1m`] and [`encode_fx_1m`].
///
/// Encoding is atomic: when an error is returned, the caller's destination buffer is left
/// completely unmodified.
#[derive(Debug, Clone, PartialEq)]
pub enum IlpEncodeError {
/// A `DOUBLE` field was non-finite (`NaN`, `+inf`, or `-inf`).
NonFiniteDouble { field: &'static str, value: f64 },
/// The designated timestamp `ts` was negative (QuestDB ILP requires `ts >= 0`).
NegativeTimestamp { field: &'static str, value: i64 },
/// A required `SYMBOL` column value was empty.
EmptySymbol { field: &'static str },
}
impl fmt::Display for IlpEncodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::NonFiniteDouble { field, value } => {
write!(f, "non-finite ILP double field '{field}': {value}")
}
Self::NegativeTimestamp { field, value } => {
write!(
f,
"negative ILP designated timestamp '{field}': {value} (must be >= 0)"
)
}
Self::EmptySymbol { field } => {
write!(f, "empty ILP symbol field '{field}'")
}
}
}
}
impl Error for IlpEncodeError {}
/// Batching limits for [`IlpShardedWriter`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IlpWriterOptions {
/// Maximum buffered bytes per shard before flushing (must be `>= 1`).
pub max_batch_bytes: usize,
/// Maximum buffered rows per shard before flushing (must be `>= 1`).
pub max_batch_rows: usize,
}
impl Default for IlpWriterOptions {
fn default() -> Self {
Self {
max_batch_bytes: DEFAULT_ILP_MAX_BATCH_BYTES,
max_batch_rows: DEFAULT_ILP_MAX_BATCH_ROWS,
}
}
}
/// Summary statistics returned by [`IlpShardedWriter::finish`].
///
/// Conservation invariants:
/// - `per_shard_rows.iter().sum::<usize>() == rows`
/// - `bytes` equals the exact sum of bytes written across all successful shard `write_all` calls.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IlpWriteStats {
pub rows: usize,
pub bytes: usize,
pub flushes: usize,
pub per_shard_rows: Vec<usize>,
}
/// Typed errors returned by [`IlpShardedWriter`].
#[derive(Debug)]
pub enum IlpWriterError {
/// No sinks were provided to [`IlpShardedWriter::new`].
EmptySinks,
/// [`IlpWriterOptions::max_batch_bytes`] was `0`.
ZeroMaxBatchBytes,
/// [`IlpWriterOptions::max_batch_rows`] was `0`.
ZeroMaxBatchRows,
/// Row encoding failed before mutating any shard buffer.
Encode(IlpEncodeError),
/// A sink `write_all` or `flush` call failed on `shard`.
Io { shard: usize, source: io::Error },
/// A previous I/O failure on `failed_shard` poisoned the writer; no further writes are allowed.
Poisoned { failed_shard: usize },
}
impl fmt::Display for IlpWriterError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EmptySinks => write!(f, "ILP sharded writer requires at least one sink"),
Self::ZeroMaxBatchBytes => {
write!(f, "ILP writer max_batch_bytes must be >= 1")
}
Self::ZeroMaxBatchRows => {
write!(f, "ILP writer max_batch_rows must be >= 1")
}
Self::Encode(err) => write!(f, "ILP encode error: {err}"),
Self::Io { shard, source } => {
write!(f, "ILP writer I/O error on shard {shard}: {source}")
}
Self::Poisoned { failed_shard } => write!(
f,
"ILP writer is poisoned after prior I/O error on shard {failed_shard}"
),
}
}
}
impl Error for IlpWriterError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Encode(err) => Some(err),
Self::Io { source, .. } => Some(source),
Self::EmptySinks
| Self::ZeroMaxBatchBytes
| Self::ZeroMaxBatchRows
| Self::Poisoned { .. } => None,
}
}
}
impl From<IlpEncodeError> for IlpWriterError {
fn from(err: IlpEncodeError) -> Self {
Self::Encode(err)
}
}
/// Computes the 64-bit FNV-1a hash of `bytes`.
#[inline]
pub fn fnv1a_64(bytes: &[u8]) -> u64 {
let mut hash = FNV1A_64_OFFSET_BASIS;
for &b in bytes {
hash ^= u64::from(b);
hash = hash.wrapping_mul(FNV1A_64_PRIME);
}
hash
}
/// Deterministic shard index for an equity `listing_id` (`i32` hashed as 4 little-endian bytes).
#[inline]
pub fn shard_for_listing_id(listing_id: i32, shard_count: usize) -> usize {
debug_assert!(shard_count > 0);
(fnv1a_64(&listing_id.to_le_bytes()) % (shard_count as u64)) as usize
}
/// Deterministic shard index for an FX `pair` (hashed as raw UTF-8 bytes).
#[inline]
pub fn shard_for_fx_pair(pair: &str, shard_count: usize) -> usize {
debug_assert!(shard_count > 0);
(fnv1a_64(pair.as_bytes()) % (shard_count as u64)) as usize
}
#[inline]
fn validate_finite(field: &'static str, value: f64) -> Result<(), IlpEncodeError> {
if value.is_finite() {
Ok(())
} else {
Err(IlpEncodeError::NonFiniteDouble { field, value })
}
}
#[inline]
fn validate_non_negative_ts(field: &'static str, value: i64) -> Result<(), IlpEncodeError> {
if value >= 0 {
Ok(())
} else {
Err(IlpEncodeError::NegativeTimestamp { field, value })
}
}
/// Escapes an ILP tag/symbol value by prefixing space, `,`, `=`, `\n`, `\r`, and `\` with `\`.
#[inline]
fn write_escaped_symbol(buf: &mut Vec<u8>, value: &str) {
let bytes = value.as_bytes();
let mut last = 0usize;
for (i, &b) in bytes.iter().enumerate() {
if matches!(b, b' ' | b',' | b'=' | b'\n' | b'\r' | b'\\') {
if last < i {
buf.extend_from_slice(&bytes[last..i]);
}
buf.push(b'\\');
buf.push(b);
last = i + 1;
}
}
if last < bytes.len() {
buf.extend_from_slice(&bytes[last..]);
}
}
#[inline]
fn write_i64_decimal(buf: &mut Vec<u8>, value: i64) {
let mut tmp = [0u8; 20];
let negative = value < 0;
let mut mag = value.unsigned_abs();
let mut pos = tmp.len();
if mag == 0 {
pos -= 1;
tmp[pos] = b'0';
} else {
while mag > 0 {
pos -= 1;
tmp[pos] = b'0' + (mag % 10) as u8;
mag /= 10;
}
}
if negative {
pos -= 1;
tmp[pos] = b'-';
}
buf.extend_from_slice(&tmp[pos..]);
}
#[inline]
fn write_binary_f64(buf: &mut Vec<u8>, name: &str, value: f64) {
buf.extend_from_slice(name.as_bytes());
buf.extend_from_slice(&[b'=', b'=', ILP_V2_DOUBLE_TYPE]);
buf.extend_from_slice(&value.to_le_bytes());
}
/// Encodes one curated `bars_1m` row in QuestDB ILP v2 format into `buf`.
///
/// Emits:
/// - Table `bars_1m`
/// - Symbols `listing_id` (decimal `row.key`), `session` (`PRE`/`RTH`/`POST`), `source`
/// - Binary `f64` columns `open`, `high`, `low`, `close`, `volume` (`vwap` omitted / NULL)
/// - Timestamp column `known_at=<known_at_micros>t`
/// - Designated timestamp ` <row.ts>t\n`
///
/// Validates all doubles, `source`, and non-negative `row.ts` before appending any bytes so
/// `buf` is left untouched on error.
pub fn encode_bar_1m(
buf: &mut Vec<u8>,
row: &Bar1mRow<i32>,
known_at_micros: i64,
) -> Result<(), IlpEncodeError> {
if row.source.is_empty() {
return Err(IlpEncodeError::EmptySymbol { field: "source" });
}
validate_finite("open", row.open)?;
validate_finite("high", row.high)?;
validate_finite("low", row.low)?;
validate_finite("close", row.close)?;
validate_finite("volume", row.volume)?;
validate_non_negative_ts("ts", row.ts)?;
buf.extend_from_slice(TABLE_BARS_1M.as_bytes());
buf.extend_from_slice(b",listing_id=");
write_i64_decimal(buf, i64::from(row.key));
buf.extend_from_slice(b",session=");
buf.extend_from_slice(row.session.as_str().as_bytes());
buf.extend_from_slice(b",source=");
write_escaped_symbol(buf, row.source);
buf.push(b' ');
write_binary_f64(buf, "open", row.open);
buf.push(b',');
write_binary_f64(buf, "high", row.high);
buf.push(b',');
write_binary_f64(buf, "low", row.low);
buf.push(b',');
write_binary_f64(buf, "close", row.close);
buf.push(b',');
write_binary_f64(buf, "volume", row.volume);
buf.extend_from_slice(b",known_at=");
write_i64_decimal(buf, known_at_micros);
buf.extend_from_slice(b"t ");
write_i64_decimal(buf, row.ts);
buf.extend_from_slice(b"t\n");
Ok(())
}
/// Encodes one `fx_1m` row in QuestDB ILP v2 format into `buf`.
///
/// Emits:
/// - Table `fx_1m`
/// - Symbols `pair`, `source`
/// - Binary `f64` columns `open`, `high`, `low`, `close`
/// - Designated timestamp ` <row.ts>t\n`
///
/// Validates `pair`, `source`, all doubles, and non-negative `row.ts` before appending any bytes
/// so `buf` is left untouched on error.
pub fn encode_fx_1m(buf: &mut Vec<u8>, row: &Fx1mRow<'_>) -> Result<(), IlpEncodeError> {
if row.pair.is_empty() {
return Err(IlpEncodeError::EmptySymbol { field: "pair" });
}
if row.source.is_empty() {
return Err(IlpEncodeError::EmptySymbol { field: "source" });
}
validate_finite("open", row.open)?;
validate_finite("high", row.high)?;
validate_finite("low", row.low)?;
validate_finite("close", row.close)?;
validate_non_negative_ts("ts", row.ts)?;
buf.extend_from_slice(TABLE_FX_1M.as_bytes());
buf.extend_from_slice(b",pair=");
write_escaped_symbol(buf, row.pair);
buf.extend_from_slice(b",source=");
write_escaped_symbol(buf, row.source);
buf.push(b' ');
write_binary_f64(buf, "open", row.open);
buf.push(b',');
write_binary_f64(buf, "high", row.high);
buf.push(b',');
write_binary_f64(buf, "low", row.low);
buf.push(b',');
write_binary_f64(buf, "close", row.close);
buf.push(b' ');
write_i64_decimal(buf, row.ts);
buf.extend_from_slice(b"t\n");
Ok(())
}
struct ShardState<W> {
sink: W,
buf: Vec<u8>,
pending_rows: usize,
written_rows: usize,
}
/// Deterministic, sink-agnostic sharded QuestDB ILP v2 batch writer.
///
/// Buffers complete ILP lines per shard and flushes whole-line batches to injected [`Write`]
/// sinks when either `max_batch_rows` or `max_batch_bytes` is reached, or on [`Self::finish`].
pub struct IlpShardedWriter<W: Write + Send> {
shards: Vec<ShardState<W>>,
options: IlpWriterOptions,
scratch: Vec<u8>,
rows_written: usize,
bytes_written: usize,
flushes: usize,
poisoned_shard: Option<usize>,
}
impl<W: Write + Send> IlpShardedWriter<W> {
/// Creates a new sharded writer over `sinks` with the given batching `options`.
///
/// Returns an error if `sinks` is empty or either batch limit is zero.
pub fn new(sinks: Vec<W>, options: IlpWriterOptions) -> Result<Self, IlpWriterError> {
if sinks.is_empty() {
return Err(IlpWriterError::EmptySinks);
}
if options.max_batch_bytes == 0 {
return Err(IlpWriterError::ZeroMaxBatchBytes);
}
if options.max_batch_rows == 0 {
return Err(IlpWriterError::ZeroMaxBatchRows);
}
let initial_buf_cap = options.max_batch_bytes.min(DEFAULT_ILP_MAX_BATCH_BYTES);
let shards = sinks
.into_iter()
.map(|sink| ShardState {
sink,
buf: Vec::with_capacity(initial_buf_cap),
pending_rows: 0,
written_rows: 0,
})
.collect();
Ok(Self {
shards,
options,
scratch: Vec::with_capacity(256),
rows_written: 0,
bytes_written: 0,
flushes: 0,
poisoned_shard: None,
})
}
/// Returns the number of configured shards.
#[inline]
pub fn shard_count(&self) -> usize {
self.shards.len()
}
/// Returns `(flushed_rows, pending_rows)` across all shards.
#[inline]
pub(crate) fn row_counts(&self) -> (usize, usize) {
let pending = self.shards.iter().map(|s| s.pending_rows).sum();
(self.rows_written, pending)
}
/// Encodes and buffers one `bars_1m` row on the shard determined by `row.key`.
pub fn write_bar_1m(
&mut self,
row: &Bar1mRow<i32>,
known_at_micros: i64,
) -> Result<(), IlpWriterError> {
if let Some(failed_shard) = self.poisoned_shard {
return Err(IlpWriterError::Poisoned { failed_shard });
}
self.scratch.clear();
encode_bar_1m(&mut self.scratch, row, known_at_micros)?;
let shard_idx = shard_for_listing_id(row.key, self.shards.len());
self.enqueue_scratch_row(shard_idx)
}
/// Encodes and buffers one `fx_1m` row on the shard determined by `row.pair`.
pub fn write_fx_1m(&mut self, row: &Fx1mRow<'_>) -> Result<(), IlpWriterError> {
if let Some(failed_shard) = self.poisoned_shard {
return Err(IlpWriterError::Poisoned { failed_shard });
}
self.scratch.clear();
encode_fx_1m(&mut self.scratch, row)?;
let shard_idx = shard_for_fx_pair(row.pair, self.shards.len());
self.enqueue_scratch_row(shard_idx)
}
/// Flushes all remaining buffered batches and underlying sinks, returning write statistics.
pub fn finish(mut self) -> Result<IlpWriteStats, IlpWriterError> {
if let Some(failed_shard) = self.poisoned_shard {
return Err(IlpWriterError::Poisoned { failed_shard });
}
for shard_idx in 0..self.shards.len() {
if !self.shards[shard_idx].buf.is_empty() {
self.flush_shard(shard_idx)?;
}
if let Err(source) = self.shards[shard_idx].sink.flush() {
self.poisoned_shard = Some(shard_idx);
return Err(IlpWriterError::Io {
shard: shard_idx,
source,
});
}
}
let per_shard_rows = self.shards.iter().map(|s| s.written_rows).collect();
Ok(IlpWriteStats {
rows: self.rows_written,
bytes: self.bytes_written,
flushes: self.flushes,
per_shard_rows,
})
}
fn enqueue_scratch_row(&mut self, shard_idx: usize) -> Result<(), IlpWriterError> {
let row_len = self.scratch.len();
let needs_preflush = {
let shard = &self.shards[shard_idx];
!shard.buf.is_empty()
&& shard.buf.len().saturating_add(row_len) > self.options.max_batch_bytes
};
if needs_preflush {
self.flush_shard(shard_idx)?;
}
let needs_postflush = {
let shard = &mut self.shards[shard_idx];
shard.buf.extend_from_slice(&self.scratch);
shard.pending_rows += 1;
shard.pending_rows >= self.options.max_batch_rows
|| shard.buf.len() >= self.options.max_batch_bytes
};
if needs_postflush {
self.flush_shard(shard_idx)?;
}
Ok(())
}
fn flush_shard(&mut self, shard_idx: usize) -> Result<(), IlpWriterError> {
let shard = &mut self.shards[shard_idx];
if shard.buf.is_empty() {
return Ok(());
}
if let Err(source) = shard.sink.write_all(&shard.buf) {
self.poisoned_shard = Some(shard_idx);
return Err(IlpWriterError::Io {
shard: shard_idx,
source,
});
}
let bytes = shard.buf.len();
let rows = shard.pending_rows;
shard.buf.clear();
shard.pending_rows = 0;
shard.written_rows += rows;
self.rows_written += rows;
self.bytes_written += bytes;
self.flushes += 1;
Ok(())
}
}
#[cfg(test)]
#[path = "ilp_tests.rs"]
mod tests;