871 lines
30 KiB
Rust
871 lines
30 KiB
Rust
//! 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::sync::Mutex;
|
|
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 {
|
|
SpawnWorker,
|
|
OpenFile,
|
|
Connect,
|
|
Read,
|
|
Write,
|
|
Flush,
|
|
}
|
|
|
|
impl fmt::Display for IlpSendOp {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match *self {
|
|
Self::SpawnWorker => f.write_str("spawn_worker"),
|
|
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| {
|
|
enum WorkerSlot<'scope> {
|
|
Running(thread::ScopedJoinHandle<'scope, ShardWorkerOutcome>),
|
|
SpawnFailed(io::Error),
|
|
}
|
|
|
|
let mut slots = Vec::with_capacity(files.len());
|
|
for shard_file in files {
|
|
let spawned = thread::Builder::new()
|
|
.name(format!("ilp-send-shard-{}", shard_file.shard))
|
|
.spawn_scoped(scope, move || {
|
|
send_single_shard(shard_file, connector_ref, buffer_bytes)
|
|
});
|
|
match spawned {
|
|
Ok(handle) => slots.push(WorkerSlot::Running(handle)),
|
|
Err(err) => slots.push(WorkerSlot::SpawnFailed(err)),
|
|
}
|
|
}
|
|
|
|
let mut results = Vec::with_capacity(slots.len());
|
|
let mut first_panic = None;
|
|
for slot in slots {
|
|
match slot {
|
|
WorkerSlot::Running(handle) => match handle.join() {
|
|
Ok(outcome) => results.push(outcome),
|
|
Err(payload) => {
|
|
if first_panic.is_none() {
|
|
first_panic = Some(payload);
|
|
}
|
|
}
|
|
},
|
|
WorkerSlot::SpawnFailed(err) => results.push(ShardWorkerOutcome {
|
|
bytes_sent: 0,
|
|
failure: Some((IlpSendOp::SpawnWorker, err)),
|
|
}),
|
|
}
|
|
}
|
|
if let Some(payload) = first_panic {
|
|
std::panic::resume_unwind(payload);
|
|
}
|
|
results
|
|
});
|
|
|
|
let mut ordered: Vec<(&IlpShardFile, ShardWorkerOutcome)> =
|
|
files.iter().zip(outcomes).collect();
|
|
ordered.sort_by(|(a, _), (b, _)| a.shard.cmp(&b.shard).then_with(|| a.path.cmp(&b.path)));
|
|
|
|
let mut shard_reports = Vec::with_capacity(ordered.len());
|
|
let mut total_bytes_sent: u64 = 0;
|
|
let mut first_failure: Option<(IlpSendOp, usize, PathBuf, io::Error)> = None;
|
|
|
|
for (shard_file, outcome) in ordered {
|
|
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)
|
|
}
|
|
|
|
fn connect_tcp_sink(
|
|
sock_addr: &SocketAddr,
|
|
connect_timeout: Duration,
|
|
write_timeout: Duration,
|
|
) -> io::Result<IlpTcpSink> {
|
|
let stream = TcpStream::connect_timeout(sock_addr, connect_timeout)?;
|
|
stream.set_nodelay(true)?;
|
|
stream.set_write_timeout(Some(write_timeout))?;
|
|
Ok(IlpTcpSink::new(stream))
|
|
}
|
|
|
|
fn tcp_ilp_connector_for_addrs(
|
|
resolved: Vec<SocketAddr>,
|
|
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 connect_timeout = options.connect_timeout;
|
|
let write_timeout = options.write_timeout;
|
|
// Pin one resolved endpoint for the lifetime of this connector so shards can never silently
|
|
// split a single load across two different QuestDB instances if a hostname resolves to
|
|
// multiple addresses.
|
|
let pinned_addr: Mutex<Option<SocketAddr>> = Mutex::new(None);
|
|
|
|
Ok(move |_shard: usize| -> io::Result<IlpTcpSink> {
|
|
let already_pinned = {
|
|
let guard = pinned_addr
|
|
.lock()
|
|
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
*guard
|
|
};
|
|
|
|
if let Some(sock_addr) = already_pinned {
|
|
return connect_tcp_sink(&sock_addr, connect_timeout, write_timeout);
|
|
}
|
|
|
|
let mut guard = pinned_addr
|
|
.lock()
|
|
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
if let Some(sock_addr) = *guard {
|
|
drop(guard);
|
|
return connect_tcp_sink(&sock_addr, connect_timeout, write_timeout);
|
|
}
|
|
|
|
let mut last_err: Option<io::Error> = None;
|
|
for sock_addr in &resolved {
|
|
match TcpStream::connect_timeout(sock_addr, connect_timeout) {
|
|
Ok(stream) => {
|
|
*guard = Some(*sock_addr);
|
|
drop(guard);
|
|
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",
|
|
)
|
|
}))
|
|
})
|
|
}
|
|
|
|
/// 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. Pins a single resolved [`SocketAddr`] for
|
|
/// all shards so a load can never split across multiple backend instances. 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)?;
|
|
tcp_ilp_connector_for_addrs(resolved, options)
|
|
}
|
|
|
|
/// Arguments for the `send-ilp` CLI subcommand and [`run_send_ilp`].
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct SendIlpArgs {
|
|
pub dir: PathBuf,
|
|
pub prefix: String,
|
|
pub addr: String,
|
|
}
|
|
|
|
/// Discovers published `<prefix>.shard-<digits>.ilp` files in `args.dir`, validates and resolves
|
|
/// `args.addr` via [`tcp_ilp_connector`] with [`IlpTcpOptions::default()`], and streams all shards
|
|
/// via [`send_ilp_shard_files`] with [`IlpSendOptions::default()`].
|
|
///
|
|
/// Discovery runs before address resolution or any socket connection so a bad directory or
|
|
/// incomplete shard set never opens a socket.
|
|
pub fn run_send_ilp(args: &SendIlpArgs) -> Result<IlpSendReport, IlpSendError> {
|
|
let files = discover_ilp_shard_files(&args.dir, &args.prefix)?;
|
|
let connector = tcp_ilp_connector(&args.addr, IlpTcpOptions::default())?;
|
|
send_ilp_shard_files(&files, connector, IlpSendOptions::default())
|
|
}
|
|
|
|
/// 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;
|