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:
parent
26a8b6a063
commit
bdf634ebb2
2 changed files with 329 additions and 27 deletions
|
|
@ -46,6 +46,7 @@ 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;
|
||||
|
||||
|
|
@ -120,6 +121,7 @@ pub struct IlpSendReport {
|
|||
/// Operation stage in which a per-shard I/O failure occurred.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum IlpSendOp {
|
||||
SpawnWorker,
|
||||
OpenFile,
|
||||
Connect,
|
||||
Read,
|
||||
|
|
@ -130,6 +132,7 @@ pub enum IlpSendOp {
|
|||
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"),
|
||||
|
|
@ -444,23 +447,40 @@ where
|
|||
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)
|
||||
}));
|
||||
enum WorkerSlot<'scope> {
|
||||
Running(thread::ScopedJoinHandle<'scope, ShardWorkerOutcome>),
|
||||
SpawnFailed(io::Error),
|
||||
}
|
||||
|
||||
let mut results = Vec::with_capacity(handles.len());
|
||||
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 handle in handles {
|
||||
match handle.join() {
|
||||
Ok(outcome) => results.push(outcome),
|
||||
Err(payload) => {
|
||||
if first_panic.is_none() {
|
||||
first_panic = Some(payload);
|
||||
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 {
|
||||
|
|
@ -469,11 +489,15 @@ where
|
|||
results
|
||||
});
|
||||
|
||||
let mut shard_reports = Vec::with_capacity(files.len());
|
||||
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 files.iter().zip(outcomes) {
|
||||
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,
|
||||
|
|
@ -697,14 +721,19 @@ fn resolve_tcp_addr(addr: &str) -> Result<Vec<SocketAddr>, IlpSendError> {
|
|||
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,
|
||||
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() {
|
||||
|
|
@ -718,15 +747,39 @@ pub fn tcp_ilp_connector(
|
|||
});
|
||||
}
|
||||
|
||||
let resolved = resolve_tcp_addr(addr)?;
|
||||
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));
|
||||
|
|
@ -745,6 +798,33 @@ pub fn tcp_ilp_connector(
|
|||
})
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ 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 std::time::{Duration, Instant};
|
||||
|
||||
use super::*;
|
||||
use crate::bars_1m::{Bar1mRow, IntradaySession, BARS_1M_SOURCE_EOD};
|
||||
|
|
@ -666,6 +666,35 @@ fn rejects_zero_buffer_before_connect() {
|
|||
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
fn accept_with_deadline(
|
||||
listener: &TcpListener,
|
||||
deadline: Instant,
|
||||
accepted_so_far: usize,
|
||||
expected_total: usize,
|
||||
) -> (TcpStream, SocketAddr) {
|
||||
loop {
|
||||
match listener.accept() {
|
||||
Ok((stream, peer)) => {
|
||||
stream
|
||||
.set_nonblocking(false)
|
||||
.expect("set accepted stream blocking");
|
||||
return (stream, peer);
|
||||
}
|
||||
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {
|
||||
if Instant::now() >= deadline {
|
||||
panic!(
|
||||
"timed out waiting for shard TCP connection: received {accepted_so_far} of {expected_total} connections"
|
||||
);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
Err(err) => panic!(
|
||||
"accept failed after receiving {accepted_so_far} of {expected_total} connections: {err}"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tcp_sends_separate_shards_and_half_closes() {
|
||||
let dir = TempDirGuard::new("ilp-send-tcp");
|
||||
|
|
@ -680,11 +709,15 @@ fn tcp_sends_separate_shards_and_half_closes() {
|
|||
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");
|
||||
listener
|
||||
.set_nonblocking(true)
|
||||
.expect("set loopback listener nonblocking");
|
||||
|
||||
let server_handle = thread::spawn(move || {
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
let mut reader_handles = Vec::with_capacity(3);
|
||||
for _ in 0..3 {
|
||||
let (mut stream, peer) = listener.accept().expect("accept shard connection");
|
||||
for accepted in 0..3 {
|
||||
let (mut stream, peer) = accept_with_deadline(&listener, deadline, accepted, 3);
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.expect("set server read timeout");
|
||||
|
|
@ -817,3 +850,192 @@ fn tcp_rejects_invalid_address_before_connect() {
|
|||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tcp_pins_single_endpoint_and_does_not_fail_over_mid_send() {
|
||||
let dir = TempDirGuard::new("ilp-send-tcp-pin");
|
||||
let p0 = dir.path().join("bars_1m.shard-00.ilp");
|
||||
let p1 = dir.path().join("bars_1m.shard-01.ilp");
|
||||
let payload0 = b"bars_1m,listing_id=1 open=1.0 1700000000000000t\n";
|
||||
let payload1 = b"bars_1m,listing_id=2 open=2.0 1700000060000000t\n";
|
||||
write_bytes(&p0, payload0);
|
||||
write_bytes(&p1, payload1);
|
||||
|
||||
let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover");
|
||||
|
||||
let listener_a = TcpListener::bind("127.0.0.1:0").expect("bind endpoint A");
|
||||
let addr_a = listener_a.local_addr().expect("addr A");
|
||||
listener_a
|
||||
.set_nonblocking(true)
|
||||
.expect("set listener A nonblocking");
|
||||
|
||||
let listener_b = TcpListener::bind("127.0.0.1:0").expect("bind endpoint B");
|
||||
let addr_b = listener_b.local_addr().expect("addr B");
|
||||
listener_b
|
||||
.set_nonblocking(true)
|
||||
.expect("set listener B nonblocking");
|
||||
|
||||
let a_closed = Arc::new((Mutex::new(false), Condvar::new()));
|
||||
let a_closed_server = Arc::clone(&a_closed);
|
||||
|
||||
// Server A accepts shard 0, closes its listener (simulating restart/refusal for shard 1),
|
||||
// signals shard 1 to attempt connect, and finishes reading shard 0 to EOF.
|
||||
let server_a = thread::spawn(move || {
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
let (mut stream, _) = accept_with_deadline(&listener_a, deadline, 0, 1);
|
||||
drop(listener_a);
|
||||
{
|
||||
let (lock, cvar) = &*a_closed_server;
|
||||
let mut closed = lock.lock().expect("lock a_closed");
|
||||
*closed = true;
|
||||
cvar.notify_all();
|
||||
}
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.expect("set read timeout");
|
||||
let mut buf = Vec::new();
|
||||
stream.read_to_end(&mut buf).expect("read shard 0 to EOF");
|
||||
buf
|
||||
});
|
||||
|
||||
let base_connector = tcp_ilp_connector_for_addrs(
|
||||
vec![addr_a, addr_b],
|
||||
IlpTcpOptions {
|
||||
connect_timeout: Duration::from_secs(2),
|
||||
write_timeout: Duration::from_secs(2),
|
||||
},
|
||||
)
|
||||
.expect("create multi-addr tcp connector");
|
||||
|
||||
let err = send_ilp_shard_files(
|
||||
&files,
|
||||
|shard| {
|
||||
if shard == 1 {
|
||||
let (lock, cvar) = &*a_closed;
|
||||
let closed = lock.lock().expect("lock a_closed");
|
||||
let (guard, timeout) = cvar
|
||||
.wait_timeout_while(closed, Duration::from_secs(3), |c| !*c)
|
||||
.expect("wait for listener A to close");
|
||||
assert!(
|
||||
!timeout.timed_out() && *guard,
|
||||
"timed out waiting for endpoint A listener to close"
|
||||
);
|
||||
}
|
||||
base_connector(shard)
|
||||
},
|
||||
IlpSendOptions { buffer_bytes: 16 },
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
let received_a = server_a.join().expect("join server A");
|
||||
assert_eq!(received_a, payload0);
|
||||
|
||||
// Endpoint B must never have received a connection attempt.
|
||||
match listener_b.accept() {
|
||||
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
||||
Ok((_, peer)) => panic!("shard 1 unexpectedly failed over to endpoint B from {peer}"),
|
||||
Err(err) => panic!("unexpected error checking endpoint B: {err}"),
|
||||
}
|
||||
|
||||
match err {
|
||||
IlpSendError::ShardIo {
|
||||
op,
|
||||
shard,
|
||||
path,
|
||||
partial_report,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(op, IlpSendOp::Connect);
|
||||
assert_eq!(shard, 1);
|
||||
assert_eq!(path, p1);
|
||||
assert_eq!(partial_report.total_shards, 2);
|
||||
assert_eq!(partial_report.shards[0].shard, 0);
|
||||
assert_eq!(partial_report.shards[0].bytes_sent, payload0.len() as u64);
|
||||
assert_eq!(partial_report.shards[1].shard, 1);
|
||||
assert_eq!(partial_report.shards[1].bytes_sent, 0);
|
||||
assert_eq!(partial_report.total_bytes_sent, payload0.len() as u64);
|
||||
}
|
||||
other => panic!("expected ShardIo(Connect) on shard 1, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orders_report_and_lowest_failure_for_unsorted_input() {
|
||||
let dir = TempDirGuard::new("ilp-send-unsorted");
|
||||
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"aaaa");
|
||||
write_bytes(&p1, b"bb");
|
||||
write_bytes(&p2, b"cccccc");
|
||||
|
||||
let unsorted = vec![
|
||||
IlpShardFile {
|
||||
shard: 2,
|
||||
path: p2.clone(),
|
||||
},
|
||||
IlpShardFile {
|
||||
shard: 0,
|
||||
path: p0.clone(),
|
||||
},
|
||||
IlpShardFile {
|
||||
shard: 1,
|
||||
path: p1.clone(),
|
||||
},
|
||||
];
|
||||
|
||||
let ok_report = send_ilp_shard_files(
|
||||
&unsorted,
|
||||
|_shard| Ok(Vec::<u8>::new()),
|
||||
IlpSendOptions { buffer_bytes: 4 },
|
||||
)
|
||||
.expect("send unsorted slice");
|
||||
assert_eq!(
|
||||
ok_report
|
||||
.shards
|
||||
.iter()
|
||||
.map(|s| (s.shard, s.bytes_sent))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![(0, 4), (1, 2), (2, 6)]
|
||||
);
|
||||
|
||||
let err = send_ilp_shard_files(
|
||||
&unsorted,
|
||||
|shard| {
|
||||
if shard == 1 || shard == 2 {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::ConnectionRefused,
|
||||
format!("refused shard {shard}"),
|
||||
))
|
||||
} else {
|
||||
Ok(Vec::<u8>::new())
|
||||
}
|
||||
},
|
||||
IlpSendOptions { buffer_bytes: 4 },
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
match err {
|
||||
IlpSendError::ShardIo {
|
||||
op,
|
||||
shard,
|
||||
path,
|
||||
partial_report,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(op, IlpSendOp::Connect);
|
||||
assert_eq!(shard, 1, "must report lowest-index failing shard");
|
||||
assert_eq!(path, p1);
|
||||
assert_eq!(
|
||||
partial_report
|
||||
.shards
|
||||
.iter()
|
||||
.map(|s| (s.shard, s.bytes_sent))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![(0, 4), (1, 0), (2, 0)]
|
||||
);
|
||||
assert_eq!(partial_report.total_bytes_sent, 4);
|
||||
}
|
||||
other => panic!("expected ShardIo(Connect) on shard 1, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue