T-188: M2.3p — tools/curate-etl: multi-socket ILP v2 shard-file sender (ilp_send.rs: published <prefix>.shard-<NN>.ilp files → one connection per shard via an injected connector, std TcpStream connector, fail-closed report) with tests (no new crates, no CLI/main/README/bench changes, no live QuestDB)

This commit is contained in:
Studio 2026-12-02 20:15:48 -05:00
parent 8f3f802cc0
commit 26a8b6a063
3 changed files with 1597 additions and 0 deletions

View file

@ -0,0 +1,771 @@
//! Multi-socket QuestDB ILP v2 shard-file sender (`M2.3p`).
//!
//! Streams published `<prefix>.shard-<NN>.ilp` files (produced by [`crate::run_curate_bars_1m`],
//! [`crate::run_curate_qm_bars_1m`], or [`crate::run_curate_fx_1m`]) verbatim over one dedicated
//! sink/socket per shard using `std::thread::scope`.
//!
//! # Transport & Acknowledgement Semantics
//!
//! - **No server acknowledgement over TCP:** QuestDB's TCP ILP listener sends no per-row or
//! per-batch acknowledgement. A server-side parse error or schema rejection surfaces only as a
//! dropped connection or missing rows. A successful [`send_ilp_shard_files`] return therefore
//! means **"all bytes were accepted by the local socket and write-half shutdown succeeded"**,
//! not **"all rows were committed in QuestDB"**. Verify row counts and representative values
//! separately via PGWire after loading.
//! - **Protocol Version 2 binary doubles over TCP (unverified for QuestDB `10.2.0`):** QuestDB's
//! ILP transport documentation (<https://questdb.com/docs/connect/compatibility/ilp/overview/>)
//! documents explicit client-side protocol-version-2 selection for TCP without autodetection.
//! Exact QuestDB `10.2.0` acceptance of this crate's ILP v2 binary `DOUBLE` payloads (`0x10` +
//! 8-byte LE IEEE-754) on the TCP ILP port (default `9009`) without a handshake is
//! **unverified** — confirm it in the manual `quant` load check using PGWire row counts and
//! spot-checked OHLCV/FX values before bulk ingestion.
//!
//! # Data Ownership, Discovery & Replay Semantics
//!
//! - **Completed publisher output required:** [`discover_ilp_shard_files`] consumes a completed,
//! immutable publisher output directory. Filenames alone cannot detect an in-progress
//! publication or a missing trailing shard.
//! - **Byte-for-byte streaming:** Bytes are streamed verbatim in fixed-size chunks
//! (`IlpSendOptions::buffer_bytes`) without loading whole files into RAM and without splitting,
//! re-framing, or re-encoding lines (binary `f64` fields may legitimately contain `0x0A`).
//! - **Per-key ordering & idempotent resend:** Quant data curation owns the curated shard files
//! as the durable replay baseline for OHLCV, FX values, timestamps, `known_at`, and per-key
//! ordering (`design/DATA-CONTRACTS.md` §3.B, `design/MILESTONES.md` M2). Because each shard
//! streams over a single dedicated sink in file order, per-key ordering is preserved. On any
//! shard failure, [`IlpSendError::ShardIo`] includes a partial [`IlpSendReport`] with per-shard
//! `bytes_sent` so operators can re-send the full, identical shard set against QuestDB's
//! configured `DEDUP UPSERT KEYS(ts, listing_id)` (`bars_1m`) or `DEDUP UPSERT KEYS(ts, pair)`
//! (`fx_1m`). Avoid replaying stale shard files after newer data sharing the same upsert keys
//! has been ingested.
//! - **Resource scaling:** Threads, open sockets, and read-buffer memory scale linearly with
//! shard count (`shard_count * buffer_bytes`).
use std::error::Error;
use std::fmt;
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::net::{Shutdown, SocketAddr, TcpStream, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::thread;
use std::time::Duration;
use crate::run_curate_bars_1m::is_final_shard_file_name_for_table;
/// Default per-shard streaming read buffer size (64 KiB).
pub const DEFAULT_ILP_SEND_BUFFER_BYTES: usize = 64 * 1024;
/// Default TCP connect timeout per shard socket (10 seconds).
pub const DEFAULT_ILP_TCP_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
/// Default TCP write timeout per shard socket (30 seconds).
pub const DEFAULT_ILP_TCP_WRITE_TIMEOUT: Duration = Duration::from_secs(30);
/// A discovered, validated published ILP shard file (`<prefix>.shard-<digits>.ilp`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IlpShardFile {
pub shard: usize,
pub path: PathBuf,
}
/// Streaming options for [`send_ilp_shard_files`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IlpSendOptions {
/// Fixed-size read buffer allocated per shard worker (must be `> 0`).
pub buffer_bytes: usize,
}
impl Default for IlpSendOptions {
fn default() -> Self {
Self {
buffer_bytes: DEFAULT_ILP_SEND_BUFFER_BYTES,
}
}
}
/// Socket options for [`tcp_ilp_connector`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IlpTcpOptions {
/// Connect timeout applied to each shard socket (must be `> Duration::ZERO`).
pub connect_timeout: Duration,
/// Write timeout applied to each shard socket (must be `> Duration::ZERO`).
pub write_timeout: Duration,
}
impl Default for IlpTcpOptions {
fn default() -> Self {
Self {
connect_timeout: DEFAULT_ILP_TCP_CONNECT_TIMEOUT,
write_timeout: DEFAULT_ILP_TCP_WRITE_TIMEOUT,
}
}
}
/// Per-shard delivery summary recorded in [`IlpSendReport`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IlpShardSendReport {
pub shard: usize,
pub path: PathBuf,
pub bytes_sent: u64,
}
/// Delivery summary returned by [`send_ilp_shard_files`] (and attached as a partial report on
/// [`IlpSendError::ShardIo`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IlpSendReport {
pub shards: Vec<IlpShardSendReport>,
pub total_shards: usize,
pub total_bytes_sent: u64,
}
/// Operation stage in which a per-shard I/O failure occurred.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IlpSendOp {
OpenFile,
Connect,
Read,
Write,
Flush,
}
impl fmt::Display for IlpSendOp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::OpenFile => f.write_str("open_file"),
Self::Connect => f.write_str("connect"),
Self::Read => f.write_str("read"),
Self::Write => f.write_str("write"),
Self::Flush => f.write_str("flush"),
}
}
}
/// Typed errors returned by [`discover_ilp_shard_files`], [`send_ilp_shard_files`], and
/// [`tcp_ilp_connector`].
#[derive(Debug)]
pub enum IlpSendError {
/// Shard prefix was empty or contained characters outside `[A-Za-z0-9_-]`.
InvalidPrefix { prefix: String },
/// Target directory exists but is not a directory.
InvalidDirectory { path: PathBuf, detail: String },
/// Failed to stat or read the shard directory.
ReadDir { path: PathBuf, source: io::Error },
/// No `<prefix>.shard-<digits>.ilp` files matched in `dir`.
NoShardFiles { dir: PathBuf, prefix: String },
/// A matching shard file's numeric suffix overflowed `usize`.
ShardIndexOverflow { path: PathBuf, digits: String },
/// A matching entry was not a regular file (for example, a directory or symlink).
NotRegularFile { path: PathBuf, detail: String },
/// Two matching files resolved to the same numeric shard index (e.g. `shard-0` and `shard-00`).
DuplicateShardIndex {
shard: usize,
first: PathBuf,
second: PathBuf,
},
/// Discovered shard indices did not form a contiguous `0..n` sequence.
MissingShardIndex {
expected: usize,
found: usize,
path: PathBuf,
},
/// `IlpSendOptions::buffer_bytes` was zero.
ZeroBufferBytes,
/// TCP target address was empty, malformed, or could not be resolved.
InvalidAddress { addr: String, detail: String },
/// A TCP timeout option was zero.
InvalidTimeout { field: &'static str },
/// One or more shards failed during open, connect, read, write, or flush.
///
/// `op`, `shard`, `path`, and `source` identify the lowest-index failing shard;
/// `partial_report` records `bytes_sent` for every shard after all workers finish.
ShardIo {
op: IlpSendOp,
shard: usize,
path: PathBuf,
source: io::Error,
partial_report: IlpSendReport,
},
}
impl IlpSendError {
/// Returns the partial delivery report when this error is [`IlpSendError::ShardIo`].
pub fn partial_report(&self) -> Option<&IlpSendReport> {
match self {
Self::ShardIo { partial_report, .. } => Some(partial_report),
_ => None,
}
}
}
impl fmt::Display for IlpSendError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidPrefix { prefix } => write!(
f,
"invalid ILP shard prefix {prefix:?}: must be non-empty ASCII [A-Za-z0-9_-]"
),
Self::InvalidDirectory { path, detail } => {
write!(f, "invalid ILP shard directory '{}': {detail}", path.display())
}
Self::ReadDir { path, source } => {
write!(f, "failed to read ILP shard directory '{}': {source}", path.display())
}
Self::NoShardFiles { dir, prefix } => write!(
f,
"no ILP shard files matching '{prefix}.shard-<digits>.ilp' in '{}'",
dir.display()
),
Self::ShardIndexOverflow { path, digits } => write!(
f,
"ILP shard index '{digits}' overflows usize in '{}'",
path.display()
),
Self::NotRegularFile { path, detail } => write!(
f,
"ILP shard path '{}' is not a regular file: {detail}",
path.display()
),
Self::DuplicateShardIndex {
shard,
first,
second,
} => write!(
f,
"duplicate ILP shard index {shard}: '{}' and '{}'",
first.display(),
second.display()
),
Self::MissingShardIndex {
expected,
found,
path,
} => write!(
f,
"missing ILP shard index {expected}: next shard is {found} ('{}')",
path.display()
),
Self::ZeroBufferBytes => write!(f, "ILP send buffer_bytes must be > 0"),
Self::InvalidAddress { addr, detail } => {
write!(f, "invalid ILP TCP address {addr:?}: {detail}")
}
Self::InvalidTimeout { field } => {
write!(f, "ILP TCP {field} must be > 0")
}
Self::ShardIo {
op,
shard,
path,
source,
partial_report,
} => write!(
f,
"ILP shard {shard} ('{}') failed during {op} ({source}; total_bytes_sent={})",
path.display(),
partial_report.total_bytes_sent
),
}
}
}
impl Error for IlpSendError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::ReadDir { source, .. } | Self::ShardIo { source, .. } => Some(source),
_ => None,
}
}
}
/// Validates that `prefix` is non-empty and consists solely of ASCII letters, digits, `_`, or `-`.
fn validate_prefix(prefix: &str) -> Result<(), IlpSendError> {
if prefix.is_empty()
|| !prefix
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
{
return Err(IlpSendError::InvalidPrefix {
prefix: prefix.to_string(),
});
}
Ok(())
}
/// Discovers published `<prefix>.shard-<digits>.ilp` files in a completed output directory `dir`.
///
/// Files are returned sorted by ascending numeric shard index `0..n`. Fails closed on:
/// - blank or invalid `prefix` (must match `[A-Za-z0-9_-]+`),
/// - missing or non-directory `dir`,
/// - zero matching files,
/// - any matching entry that is not a regular file (including symlinks and directories),
/// - numeric shard suffix overflowing `usize`,
/// - duplicate numeric shard indices (e.g. `shard-0` and `shard-00`), or
/// - any gap in `0..n`.
pub fn discover_ilp_shard_files(
dir: &Path,
prefix: &str,
) -> Result<Vec<IlpShardFile>, IlpSendError> {
validate_prefix(prefix)?;
let dir_meta = fs::metadata(dir).map_err(|source| IlpSendError::ReadDir {
path: dir.to_path_buf(),
source,
})?;
if !dir_meta.is_dir() {
return Err(IlpSendError::InvalidDirectory {
path: dir.to_path_buf(),
detail: "path exists and is not a directory".to_string(),
});
}
let entries = fs::read_dir(dir).map_err(|source| IlpSendError::ReadDir {
path: dir.to_path_buf(),
source,
})?;
let mut discovered: Vec<IlpShardFile> = Vec::new();
for entry in entries {
let entry = entry.map_err(|source| IlpSendError::ReadDir {
path: dir.to_path_buf(),
source,
})?;
let file_name = entry.file_name();
if !is_final_shard_file_name_for_table(prefix, &file_name) {
continue;
}
let path = entry.path();
let meta = fs::symlink_metadata(&path).map_err(|source| IlpSendError::ReadDir {
path: path.clone(),
source,
})?;
let file_type = meta.file_type();
if file_type.is_symlink() {
return Err(IlpSendError::NotRegularFile {
path,
detail: "entry is a symlink".to_string(),
});
}
if !file_type.is_file() {
let detail = if file_type.is_dir() {
"entry is a directory"
} else {
"entry is not a regular file"
};
return Err(IlpSendError::NotRegularFile {
path,
detail: detail.to_string(),
});
}
let name_str = file_name
.to_str()
.expect("is_final_shard_file_name_for_table guarantees valid UTF-8");
let digits = name_str
.strip_prefix(prefix)
.and_then(|s| s.strip_prefix(".shard-"))
.and_then(|s| s.strip_suffix(".ilp"))
.expect("is_final_shard_file_name_for_table guarantees shard filename shape");
let shard = digits
.parse::<usize>()
.map_err(|_| IlpSendError::ShardIndexOverflow {
path: path.clone(),
digits: digits.to_string(),
})?;
discovered.push(IlpShardFile { shard, path });
}
if discovered.is_empty() {
return Err(IlpSendError::NoShardFiles {
dir: dir.to_path_buf(),
prefix: prefix.to_string(),
});
}
discovered.sort_by(|a, b| a.shard.cmp(&b.shard).then_with(|| a.path.cmp(&b.path)));
for pair in discovered.windows(2) {
if pair[0].shard == pair[1].shard {
return Err(IlpSendError::DuplicateShardIndex {
shard: pair[0].shard,
first: pair[0].path.clone(),
second: pair[1].path.clone(),
});
}
}
for (expected, item) in discovered.iter().enumerate() {
if item.shard != expected {
return Err(IlpSendError::MissingShardIndex {
expected,
found: item.shard,
path: item.path.clone(),
});
}
}
Ok(discovered)
}
/// Streams each shard file in `files` verbatim to its own sink opened via `connector`, running one
/// scoped worker thread per shard.
///
/// Guarantees:
/// - Rejects `options.buffer_bytes == 0` before any file open or `connector` call.
/// - Opens each shard file before calling `connector(file.shard)`.
/// - Uses one reusable fixed-size read buffer per worker; never loads a whole file into memory and
/// never splits or re-encodes bytes.
/// - Calls `flush()` exactly once at EOF on every opened sink, including zero-length shard files.
/// - Joins every worker before returning; fails closed with [`IlpSendError::ShardIo`] carrying
/// the failing shard index, path, operation, `io::Error`, and full per-shard partial report if
/// any shard errors.
pub fn send_ilp_shard_files<W, C>(
files: &[IlpShardFile],
connector: C,
options: IlpSendOptions,
) -> Result<IlpSendReport, IlpSendError>
where
W: Write + Send,
C: Fn(usize) -> io::Result<W> + Sync,
{
if options.buffer_bytes == 0 {
return Err(IlpSendError::ZeroBufferBytes);
}
if files.is_empty() {
return Ok(IlpSendReport {
shards: Vec::new(),
total_shards: 0,
total_bytes_sent: 0,
});
}
let connector_ref = &connector;
let buffer_bytes = options.buffer_bytes;
let outcomes: Vec<ShardWorkerOutcome> = thread::scope(|scope| {
let mut handles = Vec::with_capacity(files.len());
for shard_file in files {
handles.push(scope.spawn(move || {
send_single_shard(shard_file, connector_ref, buffer_bytes)
}));
}
let mut results = Vec::with_capacity(handles.len());
let mut first_panic = None;
for handle in handles {
match handle.join() {
Ok(outcome) => results.push(outcome),
Err(payload) => {
if first_panic.is_none() {
first_panic = Some(payload);
}
}
}
}
if let Some(payload) = first_panic {
std::panic::resume_unwind(payload);
}
results
});
let mut shard_reports = Vec::with_capacity(files.len());
let mut total_bytes_sent: u64 = 0;
let mut first_failure: Option<(IlpSendOp, usize, PathBuf, io::Error)> = None;
for (shard_file, outcome) in files.iter().zip(outcomes) {
total_bytes_sent = total_bytes_sent.saturating_add(outcome.bytes_sent);
shard_reports.push(IlpShardSendReport {
shard: shard_file.shard,
path: shard_file.path.clone(),
bytes_sent: outcome.bytes_sent,
});
if first_failure.is_none() {
if let Some((op, source)) = outcome.failure {
first_failure = Some((op, shard_file.shard, shard_file.path.clone(), source));
}
}
}
let report = IlpSendReport {
total_shards: shard_reports.len(),
total_bytes_sent,
shards: shard_reports,
};
if let Some((op, shard, path, source)) = first_failure {
return Err(IlpSendError::ShardIo {
op,
shard,
path,
source,
partial_report: report,
});
}
Ok(report)
}
struct ShardWorkerOutcome {
bytes_sent: u64,
failure: Option<(IlpSendOp, io::Error)>,
}
fn send_single_shard<W, C>(
shard_file: &IlpShardFile,
connector: &C,
buffer_bytes: usize,
) -> ShardWorkerOutcome
where
W: Write,
C: Fn(usize) -> io::Result<W>,
{
let mut file = match File::open(&shard_file.path) {
Ok(file) => file,
Err(err) => {
return ShardWorkerOutcome {
bytes_sent: 0,
failure: Some((IlpSendOp::OpenFile, err)),
};
}
};
let mut sink = match connector(shard_file.shard) {
Ok(sink) => sink,
Err(err) => {
return ShardWorkerOutcome {
bytes_sent: 0,
failure: Some((IlpSendOp::Connect, err)),
};
}
};
let mut buf = vec![0u8; buffer_bytes];
let mut bytes_sent: u64 = 0;
loop {
let read_len = match file.read(&mut buf) {
Ok(0) => break,
Ok(n) => n,
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
Err(err) => {
return ShardWorkerOutcome {
bytes_sent,
failure: Some((IlpSendOp::Read, err)),
};
}
};
let mut offset = 0usize;
while offset < read_len {
match sink.write(&buf[offset..read_len]) {
Ok(0) => {
return ShardWorkerOutcome {
bytes_sent,
failure: Some((
IlpSendOp::Write,
io::Error::new(
io::ErrorKind::WriteZero,
"sink returned Ok(0) on non-empty write",
),
)),
};
}
Ok(written) => {
offset += written;
bytes_sent += written as u64;
}
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
Err(err) => {
return ShardWorkerOutcome {
bytes_sent,
failure: Some((IlpSendOp::Write, err)),
};
}
}
}
}
loop {
match sink.flush() {
Ok(()) => break,
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
Err(err) => {
return ShardWorkerOutcome {
bytes_sent,
failure: Some((IlpSendOp::Flush, err)),
};
}
}
}
ShardWorkerOutcome {
bytes_sent,
failure: None,
}
}
/// [`TcpStream`] wrapper whose [`Write::flush`] flushes the stream and performs a write-side
/// half-close (`shutdown(Shutdown::Write)`) so the peer observes clean EOF.
#[derive(Debug)]
pub struct IlpTcpSink {
stream: TcpStream,
}
impl IlpTcpSink {
/// Wraps a connected [`TcpStream`].
pub fn new(stream: TcpStream) -> Self {
Self { stream }
}
/// Borrows the underlying [`TcpStream`].
pub fn inner(&self) -> &TcpStream {
&self.stream
}
/// Unwraps and returns the underlying [`TcpStream`].
pub fn into_inner(self) -> TcpStream {
self.stream
}
}
impl Write for IlpTcpSink {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.stream.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.stream.flush()?;
self.stream.shutdown(Shutdown::Write)
}
}
/// Validates and resolves `addr` into one or more [`SocketAddr`]s without performing DNS lookups
/// on syntactically malformed inputs.
fn resolve_tcp_addr(addr: &str) -> Result<Vec<SocketAddr>, IlpSendError> {
if addr.is_empty() || addr.trim() != addr {
return Err(IlpSendError::InvalidAddress {
addr: addr.to_string(),
detail: "address must be non-empty without surrounding whitespace".to_string(),
});
}
if let Ok(sock_addr) = addr.parse::<SocketAddr>() {
return Ok(vec![sock_addr]);
}
let Some((host, port_str)) = addr.rsplit_once(':') else {
return Err(IlpSendError::InvalidAddress {
addr: addr.to_string(),
detail: "expected 'host:port'".to_string(),
});
};
if host.is_empty()
|| host
.bytes()
.any(|b| b.is_ascii_whitespace() || b.is_ascii_control())
{
return Err(IlpSendError::InvalidAddress {
addr: addr.to_string(),
detail: "host component is empty or contains invalid characters".to_string(),
});
}
if port_str.is_empty() || port_str.parse::<u16>().is_err() {
return Err(IlpSendError::InvalidAddress {
addr: addr.to_string(),
detail: "port must be a valid u16".to_string(),
});
}
let resolved: Vec<SocketAddr> = addr
.to_socket_addrs()
.map_err(|err| IlpSendError::InvalidAddress {
addr: addr.to_string(),
detail: format!("failed to resolve address: {err}"),
})?
.collect();
if resolved.is_empty() {
return Err(IlpSendError::InvalidAddress {
addr: addr.to_string(),
detail: "address resolved to zero socket addresses".to_string(),
});
}
Ok(resolved)
}
/// Builds a thread-safe TCP connector for [`send_ilp_shard_files`].
///
/// Validates `options` and resolves `addr` once before returning the connector closure so invalid
/// addresses fail closed before any connection attempt. Each shard invocation opens a fresh
/// [`TcpStream`] with `connect_timeout`, `set_nodelay(true)`, and `write_timeout`, wrapped in
/// [`IlpTcpSink`] so the sender's final `flush()` half-closes the write side (`Shutdown::Write`).
pub fn tcp_ilp_connector(
addr: &str,
options: IlpTcpOptions,
) -> Result<impl Fn(usize) -> io::Result<IlpTcpSink>, IlpSendError> {
if options.connect_timeout.is_zero() {
return Err(IlpSendError::InvalidTimeout {
field: "connect_timeout",
});
}
if options.write_timeout.is_zero() {
return Err(IlpSendError::InvalidTimeout {
field: "write_timeout",
});
}
let resolved = resolve_tcp_addr(addr)?;
let connect_timeout = options.connect_timeout;
let write_timeout = options.write_timeout;
Ok(move |_shard: usize| -> io::Result<IlpTcpSink> {
let mut last_err: Option<io::Error> = None;
for sock_addr in &resolved {
match TcpStream::connect_timeout(sock_addr, connect_timeout) {
Ok(stream) => {
stream.set_nodelay(true)?;
stream.set_write_timeout(Some(write_timeout))?;
return Ok(IlpTcpSink::new(stream));
}
Err(err) => {
last_err = Some(err);
}
}
}
Err(last_err.unwrap_or_else(|| {
io::Error::new(
io::ErrorKind::AddrNotAvailable,
"no resolved socket addresses available",
)
}))
})
}
/// Formats [`IlpSendReport`] into a deterministic machine-readable `key=value` summary in the
/// style of the crate's `format_curate_*_report` helpers.
pub fn format_ilp_send_report(report: &IlpSendReport) -> String {
let per_shard = if report.shards.is_empty() {
"none".to_string()
} else {
report
.shards
.iter()
.map(|entry| format!("{:02}={}", entry.shard, entry.bytes_sent))
.collect::<Vec<_>>()
.join(",")
};
format!(
"curate-etl ilp-send\n\
\x20 ilp_send: shards={} total_bytes_sent={} per_shard_bytes={per_shard}",
report.total_shards, report.total_bytes_sent,
)
}
#[cfg(test)]
#[path = "ilp_send_tests.rs"]
mod tests;

View file

@ -0,0 +1,819 @@
use std::collections::{BTreeMap, HashSet};
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::Duration;
use super::*;
use crate::bars_1m::{Bar1mRow, IntradaySession, BARS_1M_SOURCE_EOD};
use crate::ilp::{shard_for_listing_id, IlpShardedWriter, IlpWriterOptions};
use crate::run_curate_bars_1m::tests::TempDirGuard;
fn write_bytes(path: &Path, bytes: &[u8]) {
fs::write(path, bytes).expect("write test shard file");
}
#[test]
fn discovers_exact_prefix_in_numeric_order() {
let dir = TempDirGuard::new("ilp-send-discover");
write_bytes(&dir.path().join("bars_1m.shard-01.ilp"), b"shard1");
write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), b"shard0");
write_bytes(&dir.path().join("bars_1m_qm.shard-00.ilp"), b"qm0");
write_bytes(&dir.path().join("fx_1m.shard-00.ilp"), b"fx0");
write_bytes(&dir.path().join("unrelated.txt"), b"ignore");
write_bytes(&dir.path().join(".bars_1m.shard-00.123.tmp"), b"staging");
let bars = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover bars_1m");
assert_eq!(
bars,
vec![
IlpShardFile {
shard: 0,
path: dir.path().join("bars_1m.shard-00.ilp"),
},
IlpShardFile {
shard: 1,
path: dir.path().join("bars_1m.shard-01.ilp"),
},
]
);
let qm = discover_ilp_shard_files(dir.path(), "bars_1m_qm").expect("discover bars_1m_qm");
assert_eq!(qm.len(), 1);
assert_eq!(qm[0].shard, 0);
assert_eq!(qm[0].path, dir.path().join("bars_1m_qm.shard-00.ilp"));
let fx = discover_ilp_shard_files(dir.path(), "fx_1m").expect("discover fx_1m");
assert_eq!(fx.len(), 1);
assert_eq!(fx[0].shard, 0);
assert_eq!(fx[0].path, dir.path().join("fx_1m.shard-00.ilp"));
// Verify numeric ordering (not lexicographic) across 0..=10.
let multi = TempDirGuard::new("ilp-send-discover-numeric");
for idx in [10usize, 2, 0, 9, 1, 8, 3, 7, 4, 6, 5] {
write_bytes(&multi.path().join(format!("bars_1m.shard-{idx}.ilp")), b"x");
}
let ordered = discover_ilp_shard_files(multi.path(), "bars_1m").expect("numeric order");
let indices: Vec<usize> = ordered.iter().map(|f| f.shard).collect();
assert_eq!(indices, (0..=10).collect::<Vec<_>>());
}
#[test]
fn rejects_invalid_shard_sets() {
// 1. Blank and invalid prefixes.
let empty_dir = TempDirGuard::new("ilp-send-empty");
for bad in ["", " ", "bars.1m", "bars/1m", "bars 1m"] {
let err = discover_ilp_shard_files(empty_dir.path(), bad).unwrap_err();
assert!(
matches!(err, IlpSendError::InvalidPrefix { .. }),
"expected InvalidPrefix for {bad:?}, got {err:?}"
);
}
// 2. Non-directory path.
let file_path = empty_dir.path().join("not_a_dir");
write_bytes(&file_path, b"x");
let err = discover_ilp_shard_files(&file_path, "bars_1m").unwrap_err();
assert!(
matches!(err, IlpSendError::InvalidDirectory { .. }),
"expected InvalidDirectory, got {err:?}"
);
// 3. No matching files.
let err = discover_ilp_shard_files(empty_dir.path(), "bars_1m").unwrap_err();
assert!(
matches!(err, IlpSendError::NoShardFiles { .. }),
"expected NoShardFiles, got {err:?}"
);
// 4. Gap in indices (00, 02).
let gap_dir = TempDirGuard::new("ilp-send-gap");
write_bytes(&gap_dir.path().join("bars_1m.shard-00.ilp"), b"a");
write_bytes(&gap_dir.path().join("bars_1m.shard-02.ilp"), b"c");
let err = discover_ilp_shard_files(gap_dir.path(), "bars_1m").unwrap_err();
assert!(
matches!(
err,
IlpSendError::MissingShardIndex {
expected: 1,
found: 2,
..
}
),
"expected MissingShardIndex(1, 2), got {err:?}"
);
// 5. Missing shard 0 (01, 02).
let no_zero_dir = TempDirGuard::new("ilp-send-no-zero");
write_bytes(&no_zero_dir.path().join("bars_1m.shard-01.ilp"), b"b");
write_bytes(&no_zero_dir.path().join("bars_1m.shard-02.ilp"), b"c");
let err = discover_ilp_shard_files(no_zero_dir.path(), "bars_1m").unwrap_err();
assert!(
matches!(
err,
IlpSendError::MissingShardIndex {
expected: 0,
found: 1,
..
}
),
"expected MissingShardIndex(0, 1), got {err:?}"
);
// 6. Duplicate numeric index (shard-0 and shard-00).
let dup_dir = TempDirGuard::new("ilp-send-dup");
write_bytes(&dup_dir.path().join("bars_1m.shard-0.ilp"), b"a");
write_bytes(&dup_dir.path().join("bars_1m.shard-00.ilp"), b"b");
let err = discover_ilp_shard_files(dup_dir.path(), "bars_1m").unwrap_err();
assert!(
matches!(err, IlpSendError::DuplicateShardIndex { shard: 0, .. }),
"expected DuplicateShardIndex(0), got {err:?}"
);
// 7. Numeric suffix overflow.
let overflow_dir = TempDirGuard::new("ilp-send-overflow");
write_bytes(
&overflow_dir
.path()
.join("bars_1m.shard-999999999999999999999999999999999999999.ilp"),
b"x",
);
let err = discover_ilp_shard_files(overflow_dir.path(), "bars_1m").unwrap_err();
assert!(
matches!(err, IlpSendError::ShardIndexOverflow { .. }),
"expected ShardIndexOverflow, got {err:?}"
);
// 8. Directory named like a shard file.
let dir_shard = TempDirGuard::new("ilp-send-dir-shard");
fs::create_dir(dir_shard.path().join("bars_1m.shard-00.ilp")).expect("create shard dir");
let err = discover_ilp_shard_files(dir_shard.path(), "bars_1m").unwrap_err();
assert!(
matches!(err, IlpSendError::NotRegularFile { .. }),
"expected NotRegularFile for directory, got {err:?}"
);
// 9. Symlink named like a shard file.
#[cfg(unix)]
{
let sym_dir = TempDirGuard::new("ilp-send-sym-shard");
let target = sym_dir.path().join("real.ilp");
write_bytes(&target, b"payload");
std::os::unix::fs::symlink(&target, sym_dir.path().join("bars_1m.shard-00.ilp"))
.expect("create symlink");
let err = discover_ilp_shard_files(sym_dir.path(), "bars_1m").unwrap_err();
assert!(
matches!(err, IlpSendError::NotRegularFile { .. }),
"expected NotRegularFile for symlink, got {err:?}"
);
}
}
struct RecordingSinkState {
bytes: Vec<u8>,
flushes: usize,
}
struct RecordingSink {
state: Arc<Mutex<RecordingSinkState>>,
}
impl Write for RecordingSink {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let mut guard = self.state.lock().expect("lock recording sink");
guard.bytes.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
let mut guard = self.state.lock().expect("lock recording sink");
guard.flushes += 1;
Ok(())
}
}
#[test]
fn streams_writer_bytes_and_flushes_every_shard() {
let dir = TempDirGuard::new("ilp-send-fidelity");
let shard_count = 3usize;
// Pick two listing_ids that hash to shards 0 and 2 so shard 1 stays zero-length.
let id_shard_0 = (1..10_000i32)
.find(|&id| shard_for_listing_id(id, shard_count) == 0)
.expect("find listing_id for shard 0");
let id_shard_2 = (1..10_000i32)
.find(|&id| shard_for_listing_id(id, shard_count) == 2)
.expect("find listing_id for shard 2");
// Construct a finite positive f64 whose IEEE-754 LE bytes include 0x0A ('\n').
let close_with_lf = f64::from_le_bytes([0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x59, 0x40]);
assert!(close_with_lf.is_finite() && close_with_lf > 0.0);
assert!(close_with_lf.to_le_bytes().contains(&0x0A));
let shard_paths: Vec<PathBuf> = (0..shard_count)
.map(|idx| dir.path().join(format!("bars_1m.shard-{idx:02}.ilp")))
.collect();
let sinks: Vec<File> = shard_paths
.iter()
.map(|p| File::create(p).expect("create shard file"))
.collect();
let mut writer =
IlpShardedWriter::new(sinks, IlpWriterOptions::default()).expect("create ILP writer");
let rows = [
(
Bar1mRow {
key: id_shard_0,
ts: 1_700_000_000_000_000,
session_date: 19_675,
open: 100.0,
high: 101.5,
low: 99.5,
close: close_with_lf,
volume: 12_345.0,
session: IntradaySession::Rth,
source: BARS_1M_SOURCE_EOD,
},
1_700_000_060_000_000i64,
),
(
Bar1mRow {
key: id_shard_0,
ts: 1_700_000_060_000_000,
session_date: 19_675,
open: close_with_lf,
high: 102.0,
low: 99.0,
close: 101.25,
volume: 6_789.0,
session: IntradaySession::Rth,
source: BARS_1M_SOURCE_EOD,
},
1_700_000_120_000_000i64,
),
(
Bar1mRow {
key: id_shard_2,
ts: 1_700_000_000_000_000,
session_date: 19_675,
open: 42.0,
high: 43.0,
low: 41.0,
close: close_with_lf,
volume: 999.0,
session: IntradaySession::Pre,
source: BARS_1M_SOURCE_EOD,
},
1_700_000_060_000_000i64,
),
];
for (row, known_at) in &rows {
writer.write_bar_1m(row, *known_at).expect("write bar_1m");
}
writer.finish().expect("finish ILP writer");
let expected_bytes: Vec<Vec<u8>> = shard_paths
.iter()
.map(|p| fs::read(p).expect("read written shard"))
.collect();
assert!(!expected_bytes[0].is_empty());
assert!(expected_bytes[1].is_empty(), "shard 1 must be zero-length");
assert!(!expected_bytes[2].is_empty());
assert!(expected_bytes[0].windows(8).any(|w| w == close_with_lf.to_le_bytes()));
let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover shards");
assert_eq!(files.len(), shard_count);
// Bounded rendezvous to verify all 3 shard workers run concurrently.
let rendezvous = Arc::new((Mutex::new(0usize), Condvar::new()));
let connect_counts = Arc::new(Mutex::new(BTreeMap::<usize, usize>::new()));
let recorded: Arc<Vec<Arc<Mutex<RecordingSinkState>>>> = Arc::new(
(0..shard_count)
.map(|_| {
Arc::new(Mutex::new(RecordingSinkState {
bytes: Vec::new(),
flushes: 0,
}))
})
.collect(),
);
let report = send_ilp_shard_files(
&files,
|shard| {
{
let mut counts = connect_counts.lock().expect("lock connect_counts");
*counts.entry(shard).or_insert(0) += 1;
}
{
let (lock, cvar) = &*rendezvous;
let mut arrived = lock.lock().expect("lock rendezvous");
*arrived += 1;
if *arrived == shard_count {
cvar.notify_all();
} else {
let (guard, timeout) = cvar
.wait_timeout_while(arrived, Duration::from_secs(2), |n| *n < shard_count)
.expect("wait rendezvous");
assert!(
!timeout.timed_out() && *guard == shard_count,
"expected all {shard_count} shard workers to overlap concurrently"
);
}
}
Ok(RecordingSink {
state: Arc::clone(&recorded[shard]),
})
},
IlpSendOptions { buffer_bytes: 7 },
)
.expect("send shards");
// Verify connector called once per shard.
let counts = connect_counts.lock().expect("lock connect_counts");
assert_eq!(counts.len(), shard_count);
for shard in 0..shard_count {
assert_eq!(counts.get(&shard), Some(&1));
}
// Verify exact byte fidelity, single flush per shard (including empty shard 1), and report.
assert_eq!(report.total_shards, shard_count);
let expected_total: u64 = expected_bytes.iter().map(|b| b.len() as u64).sum();
assert_eq!(report.total_bytes_sent, expected_total);
for shard in 0..shard_count {
let state = recorded[shard].lock().expect("lock recorded");
assert_eq!(state.bytes, expected_bytes[shard], "byte mismatch on shard {shard}");
assert_eq!(state.flushes, 1, "expected exactly one flush on shard {shard}");
assert_eq!(report.shards[shard].shard, shard);
assert_eq!(report.shards[shard].path, files[shard].path);
assert_eq!(report.shards[shard].bytes_sent, expected_bytes[shard].len() as u64);
}
let formatted = format_ilp_send_report(&report);
assert_eq!(
formatted,
format!(
"curate-etl ilp-send\n ilp_send: shards=3 total_bytes_sent={expected_total} per_shard_bytes=00={},01=0,02={}",
expected_bytes[0].len(),
expected_bytes[2].len()
)
);
}
#[test]
fn reports_connect_failure() {
let dir = TempDirGuard::new("ilp-send-connect-fail");
let p0 = dir.path().join("bars_1m.shard-00.ilp");
let p1 = dir.path().join("bars_1m.shard-01.ilp");
let p2 = dir.path().join("bars_1m.shard-02.ilp");
write_bytes(&p0, b"0123456789");
write_bytes(&p1, b"will-not-connect");
write_bytes(&p2, b"abcdef");
let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover");
let err = send_ilp_shard_files(
&files,
|shard| {
if shard == 1 {
Err(io::Error::new(
io::ErrorKind::ConnectionRefused,
"refused shard 1",
))
} else {
Ok(Vec::<u8>::new())
}
},
IlpSendOptions { buffer_bytes: 4 },
)
.unwrap_err();
match err {
IlpSendError::ShardIo {
op,
shard,
path,
source,
partial_report,
} => {
assert_eq!(op, IlpSendOp::Connect);
assert_eq!(shard, 1);
assert_eq!(path, p1);
assert_eq!(source.kind(), io::ErrorKind::ConnectionRefused);
assert_eq!(partial_report.total_shards, 3);
assert_eq!(partial_report.shards[0].bytes_sent, 10);
assert_eq!(partial_report.shards[1].bytes_sent, 0);
assert_eq!(partial_report.shards[2].bytes_sent, 6);
assert_eq!(partial_report.total_bytes_sent, 16);
}
other => panic!("expected ShardIo(Connect), got {other:?}"),
}
}
struct PartialFailWriter {
step: usize,
written: Vec<u8>,
}
impl Write for PartialFailWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.step += 1;
match self.step {
1 => {
let take = buf.len().min(5);
self.written.extend_from_slice(&buf[..take]);
Ok(take)
}
2 => Err(io::Error::new(
io::ErrorKind::Interrupted,
"transient interrupt",
)),
3 => {
let take = buf.len().min(4);
self.written.extend_from_slice(&buf[..take]);
Ok(take)
}
_ => Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"peer closed mid-write",
)),
}
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
struct WriteZeroSink;
impl Write for WriteZeroSink {
fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
Ok(0)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[test]
fn reports_partial_write_failure() {
let dir = TempDirGuard::new("ilp-send-write-fail");
let p0 = dir.path().join("bars_1m.shard-00.ilp");
let p1 = dir.path().join("bars_1m.shard-01.ilp");
let p2 = dir.path().join("bars_1m.shard-02.ilp");
write_bytes(&p0, b"shard0-payload");
write_bytes(&p1, &[b'B'; 32]);
write_bytes(&p2, b"shard2");
let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover");
let err = send_ilp_shard_files(
&files,
|shard| -> io::Result<Box<dyn Write + Send>> {
if shard == 1 {
Ok(Box::new(PartialFailWriter {
step: 0,
written: Vec::new(),
}))
} else {
Ok(Box::new(Vec::<u8>::new()))
}
},
IlpSendOptions { buffer_bytes: 16 },
)
.unwrap_err();
match err {
IlpSendError::ShardIo {
op,
shard,
path,
source,
partial_report,
} => {
assert_eq!(op, IlpSendOp::Write);
assert_eq!(shard, 1);
assert_eq!(path, p1);
assert_eq!(source.kind(), io::ErrorKind::BrokenPipe);
assert_eq!(partial_report.shards[0].bytes_sent, 14);
assert_eq!(partial_report.shards[1].bytes_sent, 9);
assert_eq!(partial_report.shards[2].bytes_sent, 6);
assert_eq!(partial_report.total_bytes_sent, 29);
}
other => panic!("expected ShardIo(Write), got {other:?}"),
}
// Also verify Ok(0) on a non-empty slice surfaces as WriteZero.
let err_zero = send_ilp_shard_files(
&files[..1],
|_shard| Ok(WriteZeroSink),
IlpSendOptions { buffer_bytes: 8 },
)
.unwrap_err();
match err_zero {
IlpSendError::ShardIo {
op,
shard,
source,
partial_report,
..
} => {
assert_eq!(op, IlpSendOp::Write);
assert_eq!(shard, 0);
assert_eq!(source.kind(), io::ErrorKind::WriteZero);
assert_eq!(partial_report.shards[0].bytes_sent, 0);
}
other => panic!("expected ShardIo(WriteZero), got {other:?}"),
}
}
struct FlushFailWriter {
written: Vec<u8>,
}
impl Write for FlushFailWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.written.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::TimedOut, "flush timed out"))
}
}
#[test]
fn reports_flush_failure() {
let dir = TempDirGuard::new("ilp-send-flush-fail");
let p0 = dir.path().join("bars_1m.shard-00.ilp");
let p1 = dir.path().join("bars_1m.shard-01.ilp");
let p2 = dir.path().join("bars_1m.shard-02.ilp");
write_bytes(&p0, b"12345");
write_bytes(&p1, b"678");
write_bytes(&p2, b"abcdefghij");
let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover");
let err = send_ilp_shard_files(
&files,
|shard| -> io::Result<Box<dyn Write + Send>> {
if shard == 2 {
Ok(Box::new(FlushFailWriter {
written: Vec::new(),
}))
} else {
Ok(Box::new(Vec::<u8>::new()))
}
},
IlpSendOptions { buffer_bytes: 4 },
)
.unwrap_err();
match err {
IlpSendError::ShardIo {
op,
shard,
path,
source,
partial_report,
} => {
assert_eq!(op, IlpSendOp::Flush);
assert_eq!(shard, 2);
assert_eq!(path, p2);
assert_eq!(source.kind(), io::ErrorKind::TimedOut);
assert_eq!(partial_report.shards[0].bytes_sent, 5);
assert_eq!(partial_report.shards[1].bytes_sent, 3);
assert_eq!(partial_report.shards[2].bytes_sent, 10);
assert_eq!(partial_report.total_bytes_sent, 18);
}
other => panic!("expected ShardIo(Flush), got {other:?}"),
}
}
#[test]
fn reports_removed_shard() {
let dir = TempDirGuard::new("ilp-send-removed");
let p0 = dir.path().join("bars_1m.shard-00.ilp");
let p1 = dir.path().join("bars_1m.shard-01.ilp");
let p2 = dir.path().join("bars_1m.shard-02.ilp");
write_bytes(&p0, b"hello");
write_bytes(&p1, b"disappearing");
write_bytes(&p2, b"world!");
let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover");
fs::remove_file(&p1).expect("remove shard 1 after discovery");
let connected_shards = Arc::new(Mutex::new(HashSet::<usize>::new()));
let err = send_ilp_shard_files(
&files,
|shard| {
connected_shards.lock().expect("lock").insert(shard);
Ok(Vec::<u8>::new())
},
IlpSendOptions { buffer_bytes: 4 },
)
.unwrap_err();
match err {
IlpSendError::ShardIo {
op,
shard,
path,
source,
partial_report,
} => {
assert_eq!(op, IlpSendOp::OpenFile);
assert_eq!(shard, 1);
assert_eq!(path, p1);
assert_eq!(source.kind(), io::ErrorKind::NotFound);
assert_eq!(partial_report.shards[0].bytes_sent, 5);
assert_eq!(partial_report.shards[1].bytes_sent, 0);
assert_eq!(partial_report.shards[2].bytes_sent, 6);
assert_eq!(partial_report.total_bytes_sent, 11);
}
other => panic!("expected ShardIo(OpenFile), got {other:?}"),
}
let connected = connected_shards.lock().expect("lock");
assert!(
!connected.contains(&1),
"connector must not be called when opening shard file fails"
);
}
#[test]
fn rejects_zero_buffer_before_connect() {
let dir = TempDirGuard::new("ilp-send-zero-buf");
write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), b"abc");
write_bytes(&dir.path().join("bars_1m.shard-01.ilp"), b"def");
let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover");
let calls = AtomicUsize::new(0);
let err = send_ilp_shard_files(
&files,
|_shard| {
calls.fetch_add(1, Ordering::SeqCst);
Ok(Vec::<u8>::new())
},
IlpSendOptions { buffer_bytes: 0 },
)
.unwrap_err();
assert!(matches!(err, IlpSendError::ZeroBufferBytes));
assert_eq!(calls.load(Ordering::SeqCst), 0);
}
#[test]
fn tcp_sends_separate_shards_and_half_closes() {
let dir = TempDirGuard::new("ilp-send-tcp");
let payload0: Vec<u8> = b"bars_1m,listing_id=1 open==\x10\x0A\x00\x00\x00\x00\x00\x59\x40 1700000000000000t\n".to_vec();
let payload1: Vec<u8> = Vec::new();
let payload2: Vec<u8> = b"bars_1m,listing_id=2 open==\x10\x01\x02\x03\x04\x05\x06\x07\x40 1700000060000000t\n".to_vec();
write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), &payload0);
write_bytes(&dir.path().join("bars_1m.shard-01.ilp"), &payload1);
write_bytes(&dir.path().join("bars_1m.shard-02.ilp"), &payload2);
let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover");
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener");
let listen_addr = listener.local_addr().expect("local addr");
let server_handle = thread::spawn(move || {
let mut reader_handles = Vec::with_capacity(3);
for _ in 0..3 {
let (mut stream, peer) = listener.accept().expect("accept shard connection");
stream
.set_read_timeout(Some(Duration::from_secs(3)))
.expect("set server read timeout");
reader_handles.push(thread::spawn(move || {
let mut buf = Vec::new();
stream
.read_to_end(&mut buf)
.expect("read shard stream to EOF via half-close");
(peer, buf)
}));
}
reader_handles
.into_iter()
.map(|h| h.join().expect("join reader thread"))
.collect::<Vec<(SocketAddr, Vec<u8>)>>()
});
let base_connector = tcp_ilp_connector(
&listen_addr.to_string(),
IlpTcpOptions {
connect_timeout: Duration::from_secs(2),
write_timeout: Duration::from_secs(2),
},
)
.expect("create tcp connector");
// Keep a cloned handle of every client socket open until AFTER the server observes EOF.
// Because drop/close only sends FIN when the last fd closes, this proves IlpTcpSink::flush()
// explicitly invoked shutdown(Shutdown::Write).
let kept_handles = Mutex::new(Vec::<TcpStream>::new());
let report = send_ilp_shard_files(
&files,
|shard| {
let sink = base_connector(shard)?;
assert!(sink.inner().nodelay().expect("query nodelay"));
kept_handles
.lock()
.expect("lock kept_handles")
.push(sink.inner().try_clone().expect("clone client TcpStream"));
Ok(sink)
},
IlpSendOptions { buffer_bytes: 13 },
)
.expect("send over loopback tcp");
// Wait for all 3 server readers to reach EOF while client socket clones are still alive.
let received = server_handle.join().expect("join server thread");
assert_eq!(kept_handles.lock().expect("lock kept_handles").len(), 3);
drop(kept_handles);
assert_eq!(received.len(), 3);
let distinct_peers: HashSet<SocketAddr> = received.iter().map(|(peer, _)| *peer).collect();
assert_eq!(
distinct_peers.len(),
3,
"expected 3 separate accepted TCP connections"
);
let mut received_payloads: Vec<Vec<u8>> = received.into_iter().map(|(_, buf)| buf).collect();
received_payloads.sort();
let mut expected_payloads = vec![payload0.clone(), payload1.clone(), payload2.clone()];
expected_payloads.sort();
assert_eq!(received_payloads, expected_payloads);
assert_eq!(report.total_shards, 3);
assert_eq!(report.shards[0].bytes_sent, payload0.len() as u64);
assert_eq!(report.shards[1].bytes_sent, 0);
assert_eq!(report.shards[2].bytes_sent, payload2.len() as u64);
assert_eq!(
report.total_bytes_sent,
(payload0.len() + payload1.len() + payload2.len()) as u64
);
}
#[test]
fn tcp_rejects_invalid_address_before_connect() {
for bad in [
"",
" ",
"127.0.0.1",
"127.0.0.1:",
"127.0.0.1:notaport",
"127.0.0.1:99999",
":9009",
"bad host:9009",
" 127.0.0.1:9009",
"127.0.0.1:9009 ",
] {
let err = match tcp_ilp_connector(bad, IlpTcpOptions::default()) {
Ok(_) => panic!("expected InvalidAddress for {bad:?}"),
Err(err) => err,
};
assert!(
matches!(err, IlpSendError::InvalidAddress { .. }),
"expected InvalidAddress for {bad:?}, got {err:?}"
);
}
let zero_connect = match tcp_ilp_connector(
"127.0.0.1:9009",
IlpTcpOptions {
connect_timeout: Duration::ZERO,
write_timeout: Duration::from_secs(1),
},
) {
Ok(_) => panic!("expected InvalidTimeout for zero connect_timeout"),
Err(err) => err,
};
assert!(matches!(
zero_connect,
IlpSendError::InvalidTimeout {
field: "connect_timeout"
}
));
let zero_write = match tcp_ilp_connector(
"127.0.0.1:9009",
IlpTcpOptions {
connect_timeout: Duration::from_secs(1),
write_timeout: Duration::ZERO,
},
) {
Ok(_) => panic!("expected InvalidTimeout for zero write_timeout"),
Err(err) => err,
};
assert!(matches!(
zero_write,
IlpSendError::InvalidTimeout {
field: "write_timeout"
}
));
}

View file

@ -22,6 +22,7 @@ pub mod events;
pub mod fundamentals;
pub mod fx;
pub mod ilp;
pub mod ilp_send;
pub mod macro_series;
pub mod mongo_safety;
pub mod mongo_stream;
@ -156,6 +157,12 @@ pub use ilp::{
DEFAULT_ILP_MAX_BATCH_BYTES, DEFAULT_ILP_MAX_BATCH_ROWS, FNV1A_64_OFFSET_BASIS,
FNV1A_64_PRIME, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M,
};
pub use ilp_send::{
discover_ilp_shard_files, format_ilp_send_report, send_ilp_shard_files, tcp_ilp_connector,
IlpSendError, IlpSendOp, IlpSendOptions, IlpSendReport, IlpShardFile, IlpShardSendReport,
IlpTcpOptions, IlpTcpSink, DEFAULT_ILP_SEND_BUFFER_BYTES, DEFAULT_ILP_TCP_CONNECT_TIMEOUT,
DEFAULT_ILP_TCP_WRITE_TIMEOUT,
};
pub use macro_series::{
build_macro_rows, MacroBuild, MacroBuildStats, MacroError, MacroLagClass, MacroObservation,
MacroRow, GDP65_LAG_DAYS, GDP90_LAG_DAYS, MACRO_KNOWN_AT_SOURCE, MONTHLY_RELEASE_LAG_DAYS,