1807 lines
64 KiB
Rust
1807 lines
64 KiB
Rust
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, Instant};
|
|
|
|
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);
|
|
}
|
|
|
|
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");
|
|
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");
|
|
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 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");
|
|
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"
|
|
}
|
|
));
|
|
}
|
|
|
|
#[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:?}"),
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// QA (T-188) edge-case coverage.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
fn refused_loopback_addr() -> SocketAddr {
|
|
// Bind an ephemeral loopback port and immediately release it so connects are refused.
|
|
let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral loopback port");
|
|
let addr = listener.local_addr().expect("ephemeral local addr");
|
|
drop(listener);
|
|
addr
|
|
}
|
|
|
|
#[test]
|
|
fn discovery_ignores_near_miss_shard_names_and_accepts_hyphen_prefix() {
|
|
let dir = TempDirGuard::new("ilp-send-near-miss");
|
|
write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), b"real");
|
|
for near_miss in [
|
|
"bars_1m.shard-.ilp",
|
|
"bars_1m.shard-0a.ilp",
|
|
"bars_1m.shard-+1.ilp",
|
|
"bars_1m.shard--1.ilp",
|
|
"bars_1m.shard-01.ilp.tmp",
|
|
"bars_1m.shard-01.ILP",
|
|
"BARS_1M.shard-01.ilp",
|
|
"xbars_1m.shard-01.ilp",
|
|
"bars_1m.shard01.ilp",
|
|
"bars_1m_qm.shard-01.ilp",
|
|
] {
|
|
write_bytes(&dir.path().join(near_miss), b"ignored");
|
|
}
|
|
|
|
let found = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover bars_1m");
|
|
assert_eq!(
|
|
found,
|
|
vec![IlpShardFile {
|
|
shard: 0,
|
|
path: dir.path().join("bars_1m.shard-00.ilp"),
|
|
}]
|
|
);
|
|
|
|
let hyphen = TempDirGuard::new("ilp-send-hyphen-prefix");
|
|
write_bytes(&hyphen.path().join("fx-1m.shard-00.ilp"), b"fx");
|
|
let found = discover_ilp_shard_files(hyphen.path(), "fx-1m").expect("hyphen prefix");
|
|
assert_eq!(found.len(), 1);
|
|
assert_eq!(found[0].shard, 0);
|
|
|
|
let missing = dir.path().join("does-not-exist");
|
|
match discover_ilp_shard_files(&missing, "bars_1m").unwrap_err() {
|
|
IlpSendError::ReadDir { path, source } => {
|
|
assert_eq!(path, missing);
|
|
assert_eq!(source.kind(), io::ErrorKind::NotFound);
|
|
}
|
|
other => panic!("expected ReadDir(NotFound), got {other:?}"),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn streams_multi_chunk_file_with_one_byte_buffer_and_handles_empty_slice() {
|
|
let dir = TempDirGuard::new("ilp-send-one-byte");
|
|
// Deterministic pseudo-random payload covering every byte value, including 0x0A.
|
|
let mut state: u32 = 0x1234_5678;
|
|
let payload: Vec<u8> = (0..4099)
|
|
.map(|_| {
|
|
state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
|
|
(state >> 24) as u8
|
|
})
|
|
.chain(0u8..=255)
|
|
.collect();
|
|
let path = dir.path().join("fx_1m.shard-00.ilp");
|
|
write_bytes(&path, &payload);
|
|
|
|
let files = discover_ilp_shard_files(dir.path(), "fx_1m").expect("discover");
|
|
let state_cell = Arc::new(Mutex::new(RecordingSinkState {
|
|
bytes: Vec::new(),
|
|
flushes: 0,
|
|
}));
|
|
let report = send_ilp_shard_files(
|
|
&files,
|
|
|_shard| {
|
|
Ok(RecordingSink {
|
|
state: Arc::clone(&state_cell),
|
|
})
|
|
},
|
|
IlpSendOptions { buffer_bytes: 1 },
|
|
)
|
|
.expect("send one-byte buffer");
|
|
let recorded = state_cell.lock().expect("lock recorded");
|
|
assert_eq!(recorded.bytes, payload);
|
|
assert_eq!(recorded.flushes, 1);
|
|
assert_eq!(report.total_bytes_sent, payload.len() as u64);
|
|
|
|
let calls = AtomicUsize::new(0);
|
|
let empty = send_ilp_shard_files(
|
|
&[],
|
|
|_shard| {
|
|
calls.fetch_add(1, Ordering::SeqCst);
|
|
Ok(Vec::<u8>::new())
|
|
},
|
|
IlpSendOptions::default(),
|
|
)
|
|
.expect("empty slice is a no-op");
|
|
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
|
assert_eq!(empty.total_shards, 0);
|
|
assert_eq!(empty.total_bytes_sent, 0);
|
|
assert_eq!(
|
|
format_ilp_send_report(&empty),
|
|
"curate-etl ilp-send\n ilp_send: shards=0 total_bytes_sent=0 per_shard_bytes=none"
|
|
);
|
|
assert_eq!(IlpSendOptions::default().buffer_bytes, 64 * 1024);
|
|
}
|
|
|
|
#[test]
|
|
fn shard_io_error_display_and_source_name_shard_path_and_op() {
|
|
let dir = TempDirGuard::new("ilp-send-display");
|
|
let p0 = dir.path().join("bars_1m.shard-00.ilp");
|
|
let p1 = dir.path().join("bars_1m.shard-01.ilp");
|
|
write_bytes(&p0, b"abc");
|
|
write_bytes(&p1, b"defg");
|
|
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"))
|
|
} else {
|
|
Ok(Vec::<u8>::new())
|
|
}
|
|
},
|
|
IlpSendOptions { buffer_bytes: 2 },
|
|
)
|
|
.unwrap_err();
|
|
|
|
let text = err.to_string();
|
|
assert!(text.contains("ILP shard 1"), "{text}");
|
|
assert!(text.contains(&p1.display().to_string()), "{text}");
|
|
assert!(text.contains("during connect"), "{text}");
|
|
assert!(text.contains("total_bytes_sent=3"), "{text}");
|
|
|
|
let source = std::error::Error::source(&err).expect("ShardIo exposes io::Error source");
|
|
let io_source = source
|
|
.downcast_ref::<io::Error>()
|
|
.expect("source is io::Error");
|
|
assert_eq!(io_source.kind(), io::ErrorKind::ConnectionRefused);
|
|
|
|
let partial = err.partial_report().expect("ShardIo carries partial report");
|
|
assert_eq!(
|
|
format_ilp_send_report(partial),
|
|
"curate-etl ilp-send\n ilp_send: shards=2 total_bytes_sent=3 per_shard_bytes=00=3,01=0"
|
|
);
|
|
assert!(IlpSendError::ZeroBufferBytes.partial_report().is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn tcp_reports_refused_connection_as_connect_failure() {
|
|
let dir = TempDirGuard::new("ilp-send-tcp-refused");
|
|
let p0 = dir.path().join("bars_1m.shard-00.ilp");
|
|
write_bytes(&p0, b"bars_1m,listing_id=1 open=1.0 1700000000000000t\n");
|
|
let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover");
|
|
|
|
let dead = refused_loopback_addr();
|
|
let connector = tcp_ilp_connector(
|
|
&dead.to_string(),
|
|
IlpTcpOptions {
|
|
connect_timeout: Duration::from_secs(2),
|
|
write_timeout: Duration::from_secs(2),
|
|
},
|
|
)
|
|
.expect("connector creation must not connect");
|
|
|
|
match send_ilp_shard_files(&files, connector, IlpSendOptions::default()).unwrap_err() {
|
|
IlpSendError::ShardIo {
|
|
op,
|
|
shard,
|
|
path,
|
|
source,
|
|
partial_report,
|
|
} => {
|
|
assert_eq!(op, IlpSendOp::Connect);
|
|
assert_eq!(shard, 0);
|
|
assert_eq!(path, p0);
|
|
assert_eq!(source.kind(), io::ErrorKind::ConnectionRefused);
|
|
assert_eq!(partial_report.total_bytes_sent, 0);
|
|
}
|
|
other => panic!("expected ShardIo(Connect), got {other:?}"),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn tcp_connector_skips_unreachable_address_then_pins_reachable_one_for_all_shards() {
|
|
let dir = TempDirGuard::new("ilp-send-tcp-pin-first-live");
|
|
let payloads: Vec<Vec<u8>> = (0..3)
|
|
.map(|i| format!("bars_1m,listing_id={i} open=1.0 170000000000000{i}t\n").into_bytes())
|
|
.collect();
|
|
for (i, payload) in payloads.iter().enumerate() {
|
|
write_bytes(&dir.path().join(format!("bars_1m.shard-{i:02}.ilp")), payload);
|
|
}
|
|
let files = discover_ilp_shard_files(dir.path(), "bars_1m").expect("discover");
|
|
|
|
let dead = refused_loopback_addr();
|
|
let live = TcpListener::bind("127.0.0.1:0").expect("bind live endpoint");
|
|
let live_addr = live.local_addr().expect("live addr");
|
|
live.set_nonblocking(true).expect("nonblocking live");
|
|
|
|
let server = thread::spawn(move || {
|
|
let deadline = Instant::now() + Duration::from_secs(3);
|
|
let mut readers = Vec::new();
|
|
for accepted in 0..3 {
|
|
let (mut stream, _) = accept_with_deadline(&live, deadline, accepted, 3);
|
|
stream
|
|
.set_read_timeout(Some(Duration::from_secs(3)))
|
|
.expect("read timeout");
|
|
readers.push(thread::spawn(move || {
|
|
let mut buf = Vec::new();
|
|
stream.read_to_end(&mut buf).expect("read to EOF");
|
|
buf
|
|
}));
|
|
}
|
|
readers
|
|
.into_iter()
|
|
.map(|h| h.join().expect("join reader"))
|
|
.collect::<Vec<_>>()
|
|
});
|
|
|
|
let connector = tcp_ilp_connector_for_addrs(
|
|
vec![dead, live_addr],
|
|
IlpTcpOptions {
|
|
connect_timeout: Duration::from_secs(2),
|
|
write_timeout: Duration::from_secs(2),
|
|
},
|
|
)
|
|
.expect("connector");
|
|
let peers = Mutex::new(Vec::<SocketAddr>::new());
|
|
let report = send_ilp_shard_files(
|
|
&files,
|
|
|shard| {
|
|
let sink = connector(shard)?;
|
|
peers
|
|
.lock()
|
|
.expect("lock peers")
|
|
.push(sink.inner().peer_addr().expect("peer addr"));
|
|
Ok(sink)
|
|
},
|
|
IlpSendOptions { buffer_bytes: 5 },
|
|
)
|
|
.expect("send via first reachable address");
|
|
|
|
let mut received = server.join().expect("join server");
|
|
received.sort();
|
|
let mut expected = payloads.clone();
|
|
expected.sort();
|
|
assert_eq!(received, expected);
|
|
let peers = peers.into_inner().expect("peers");
|
|
assert_eq!(peers.len(), 3);
|
|
assert!(peers.iter().all(|p| *p == live_addr), "{peers:?}");
|
|
assert_eq!(
|
|
report.total_bytes_sent,
|
|
payloads.iter().map(|p| p.len() as u64).sum::<u64>()
|
|
);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// `run_send_ilp` wrapper tests (`M2.3q`).
|
|
// ---------------------------------------------------------------------------
|
|
|
|
#[test]
|
|
fn run_send_ilp_end_to_end_over_loopback() {
|
|
let dir = TempDirGuard::new("run-send-ilp-e2e");
|
|
let payload0: Vec<u8> = vec![
|
|
b'f', b'x', b'_', b'1', b'm', b',', b'p', b'a', b'i', b'r', b'=', b'U', b'S', b'D', b'C',
|
|
b'A', b'D', b' ', b'c', b'=', b'=', 0x10, 0x0A, 0xFF, 0xFE, 0x80, 0x00, 0x00, 0xF0, 0x3F,
|
|
b' ', b'1', b'7', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0',
|
|
b'0', b'0', b't', b'\n',
|
|
];
|
|
let payload1: Vec<u8> = Vec::new();
|
|
let payload2: Vec<u8> = vec![
|
|
b'f', b'x', b'_', b'1', b'm', b',', b'p', b'a', b'i', b'r', b'=', b'U', b'S', b'D', b'C',
|
|
b'A', b'D', b' ', b'c', b'=', b'=', 0x10, 0xC0, 0x81, 0x0A, 0x0A, 0x01, 0x02, 0xF5, 0x3F,
|
|
b' ', b'1', b'7', b'0', b'0', b'0', b'0', b'0', b'0', b'6', b'0', b'0', b'0', b'0', b'0',
|
|
b'0', b'0', b't', b'\n',
|
|
];
|
|
assert!(std::str::from_utf8(&payload0).is_err());
|
|
assert!(std::str::from_utf8(&payload2).is_err());
|
|
assert!(payload0.contains(&0x0A));
|
|
assert!(payload2.contains(&0x0A));
|
|
|
|
write_bytes(&dir.path().join("fx_1m.shard-00.ilp"), &payload0);
|
|
write_bytes(&dir.path().join("fx_1m.shard-01.ilp"), &payload1);
|
|
write_bytes(&dir.path().join("fx_1m.shard-02.ilp"), &payload2);
|
|
|
|
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 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");
|
|
reader_handles.push(thread::spawn(move || {
|
|
let mut buf = Vec::new();
|
|
stream
|
|
.read_to_end(&mut buf)
|
|
.expect("read shard stream to EOF");
|
|
(peer, buf)
|
|
}));
|
|
}
|
|
let received: Vec<(SocketAddr, Vec<u8>)> = reader_handles
|
|
.into_iter()
|
|
.map(|h| h.join().expect("join reader thread"))
|
|
.collect();
|
|
(listener, received)
|
|
});
|
|
|
|
let report = run_send_ilp(&SendIlpArgs {
|
|
dir: dir.path().to_path_buf(),
|
|
prefix: "fx_1m".to_string(),
|
|
addr: listen_addr.to_string(),
|
|
})
|
|
.expect("run_send_ilp should succeed over loopback");
|
|
|
|
let (listener, received) = server_handle.join().expect("join server thread");
|
|
|
|
// Verify no extra 4th connection was opened.
|
|
match listener.accept() {
|
|
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
|
Ok((_, peer)) => panic!("unexpected extra connection from {peer}"),
|
|
Err(err) => panic!("unexpected error checking accept queue: {err}"),
|
|
}
|
|
|
|
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 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);
|
|
|
|
let expected_total = (payload0.len() + payload1.len() + payload2.len()) as u64;
|
|
assert_eq!(report.total_shards, 3);
|
|
assert_eq!(report.shards[0].shard, 0);
|
|
assert_eq!(report.shards[0].bytes_sent, payload0.len() as u64);
|
|
assert_eq!(report.shards[1].shard, 1);
|
|
assert_eq!(report.shards[1].bytes_sent, 0);
|
|
assert_eq!(report.shards[2].shard, 2);
|
|
assert_eq!(report.shards[2].bytes_sent, payload2.len() as u64);
|
|
assert_eq!(report.total_bytes_sent, expected_total);
|
|
|
|
assert_eq!(
|
|
format_ilp_send_report(&report),
|
|
format!(
|
|
"curate-etl ilp-send\n ilp_send: shards=3 total_bytes_sent={expected_total} per_shard_bytes=00={},01=0,02={}",
|
|
payload0.len(),
|
|
payload2.len()
|
|
)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn run_send_ilp_fails_closed_on_discovery_and_address_errors_with_zero_connections() {
|
|
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 listener nonblocking");
|
|
|
|
let assert_zero_accepts = |label: &str| match listener.accept() {
|
|
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
|
Ok((_, peer)) => panic!("{label}: unexpectedly accepted connection from {peer}"),
|
|
Err(err) => panic!("{label}: unexpected accept error: {err}"),
|
|
};
|
|
|
|
// (a) Missing directory -> ReadDir(NotFound), zero connections.
|
|
let base = TempDirGuard::new("run-send-ilp-fail-closed");
|
|
let missing_dir = base.path().join("does-not-exist");
|
|
let err = run_send_ilp(&SendIlpArgs {
|
|
dir: missing_dir.clone(),
|
|
prefix: "fx_1m".to_string(),
|
|
addr: listen_addr.to_string(),
|
|
})
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(err, IlpSendError::ReadDir { ref source, .. } if source.kind() == io::ErrorKind::NotFound),
|
|
"expected ReadDir(NotFound), got {err:?}"
|
|
);
|
|
assert_zero_accepts("missing directory");
|
|
|
|
// (b) Empty directory -> NoShardFiles, zero connections.
|
|
let empty_dir = TempDirGuard::new("run-send-ilp-empty");
|
|
let err = run_send_ilp(&SendIlpArgs {
|
|
dir: empty_dir.path().to_path_buf(),
|
|
prefix: "fx_1m".to_string(),
|
|
addr: listen_addr.to_string(),
|
|
})
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(err, IlpSendError::NoShardFiles { .. }),
|
|
"expected NoShardFiles, got {err:?}"
|
|
);
|
|
assert_zero_accepts("empty directory");
|
|
|
|
// (c) Discovery failure paired with malformed address -> discovery error takes precedence.
|
|
let err = run_send_ilp(&SendIlpArgs {
|
|
dir: empty_dir.path().to_path_buf(),
|
|
prefix: "fx_1m".to_string(),
|
|
addr: "not-an-addr".to_string(),
|
|
})
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(err, IlpSendError::NoShardFiles { .. }),
|
|
"expected discovery error before address validation, got {err:?}"
|
|
);
|
|
assert_zero_accepts("empty directory with malformed address");
|
|
|
|
// (d) Shard gap (00 + 02) -> MissingShardIndex, zero connections.
|
|
let gap_dir = TempDirGuard::new("run-send-ilp-gap");
|
|
write_bytes(&gap_dir.path().join("fx_1m.shard-00.ilp"), b"a");
|
|
write_bytes(&gap_dir.path().join("fx_1m.shard-02.ilp"), b"c");
|
|
let err = run_send_ilp(&SendIlpArgs {
|
|
dir: gap_dir.path().to_path_buf(),
|
|
prefix: "fx_1m".to_string(),
|
|
addr: listen_addr.to_string(),
|
|
})
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(
|
|
err,
|
|
IlpSendError::MissingShardIndex {
|
|
expected: 1,
|
|
found: 2,
|
|
..
|
|
}
|
|
),
|
|
"expected MissingShardIndex(1, 2), got {err:?}"
|
|
);
|
|
assert_zero_accepts("shard gap");
|
|
|
|
// (e) Valid shards + malformed address -> InvalidAddress before any connect.
|
|
let valid_dir = TempDirGuard::new("run-send-ilp-bad-addr");
|
|
write_bytes(&valid_dir.path().join("fx_1m.shard-00.ilp"), b"ok");
|
|
for bad_addr in ["not-an-addr", "127.0.0.1", "127.0.0.1:notaport"] {
|
|
let err = run_send_ilp(&SendIlpArgs {
|
|
dir: valid_dir.path().to_path_buf(),
|
|
prefix: "fx_1m".to_string(),
|
|
addr: bad_addr.to_string(),
|
|
})
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(err, IlpSendError::InvalidAddress { .. }),
|
|
"expected InvalidAddress for {bad_addr:?}, got {err:?}"
|
|
);
|
|
}
|
|
assert_zero_accepts("malformed address");
|
|
}
|
|
|
|
#[test]
|
|
fn run_send_ilp_refused_connection_returns_connect_error_and_zero_partial_report() {
|
|
let dir = TempDirGuard::new("run-send-ilp-refused");
|
|
let p0 = dir.path().join("fx_1m.shard-00.ilp");
|
|
let p1 = dir.path().join("fx_1m.shard-01.ilp");
|
|
let p2 = dir.path().join("fx_1m.shard-02.ilp");
|
|
write_bytes(&p0, b"shard0");
|
|
write_bytes(&p1, b"");
|
|
write_bytes(&p2, b"shard2");
|
|
|
|
let dead = refused_loopback_addr();
|
|
let err = run_send_ilp(&SendIlpArgs {
|
|
dir: dir.path().to_path_buf(),
|
|
prefix: "fx_1m".to_string(),
|
|
addr: dead.to_string(),
|
|
})
|
|
.unwrap_err();
|
|
|
|
match err {
|
|
IlpSendError::ShardIo {
|
|
op,
|
|
shard,
|
|
path,
|
|
source,
|
|
partial_report,
|
|
} => {
|
|
assert_eq!(op, IlpSendOp::Connect);
|
|
assert_eq!(shard, 0);
|
|
assert_eq!(path, p0);
|
|
assert_eq!(source.kind(), io::ErrorKind::ConnectionRefused);
|
|
assert_eq!(partial_report.total_shards, 3);
|
|
assert_eq!(partial_report.total_bytes_sent, 0);
|
|
assert_eq!(partial_report.shards.len(), 3);
|
|
for (idx, entry) in partial_report.shards.iter().enumerate() {
|
|
assert_eq!(entry.shard, idx);
|
|
assert_eq!(entry.bytes_sent, 0);
|
|
}
|
|
}
|
|
other => panic!("expected ShardIo(Connect), got {other:?}"),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn run_send_ilp_mixed_folder_isolates_bars_1m_bars_1m_qm_and_fx_1m() {
|
|
let dir = TempDirGuard::new("run-send-ilp-mixed-folder");
|
|
let bars0 = b"bars_1m,listing_id=1 close=10.0 1700000000000000t\n".to_vec();
|
|
let bars1 = b"bars_1m,listing_id=2 close=20.0 1700000060000000t\n".to_vec();
|
|
let qm0 = b"bars_1m,listing_id=1,source=qm_raw close=10.5 1700000000000000t\n".to_vec();
|
|
let fx0 = b"fx_1m,pair=USDCAD close=1.38 1700000000000000t\n".to_vec();
|
|
|
|
write_bytes(&dir.path().join("bars_1m.shard-00.ilp"), &bars0);
|
|
write_bytes(&dir.path().join("bars_1m.shard-01.ilp"), &bars1);
|
|
write_bytes(&dir.path().join("bars_1m_qm.shard-00.ilp"), &qm0);
|
|
write_bytes(&dir.path().join("fx_1m.shard-00.ilp"), &fx0);
|
|
write_bytes(&dir.path().join("notes.txt"), b"unrelated");
|
|
|
|
let cases: [(&str, Vec<Vec<u8>>); 3] = [
|
|
("bars_1m", vec![bars0.clone(), bars1.clone()]),
|
|
("bars_1m_qm", vec![qm0.clone()]),
|
|
("fx_1m", vec![fx0.clone()]),
|
|
];
|
|
|
|
for (prefix, mut expected) in cases {
|
|
let count = expected.len();
|
|
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 readers = Vec::with_capacity(count);
|
|
for accepted in 0..count {
|
|
let (mut stream, _) = accept_with_deadline(&listener, deadline, accepted, count);
|
|
stream
|
|
.set_read_timeout(Some(Duration::from_secs(3)))
|
|
.expect("set server read timeout");
|
|
readers.push(thread::spawn(move || {
|
|
let mut buf = Vec::new();
|
|
stream.read_to_end(&mut buf).expect("read shard to EOF");
|
|
buf
|
|
}));
|
|
}
|
|
let received: Vec<Vec<u8>> = readers
|
|
.into_iter()
|
|
.map(|h| h.join().expect("join reader"))
|
|
.collect();
|
|
(listener, received)
|
|
});
|
|
|
|
let report = run_send_ilp(&SendIlpArgs {
|
|
dir: dir.path().to_path_buf(),
|
|
prefix: prefix.to_string(),
|
|
addr: listen_addr.to_string(),
|
|
})
|
|
.expect("run_send_ilp should send only matching prefix");
|
|
|
|
let (listener, mut received) = server_handle.join().expect("join server");
|
|
match listener.accept() {
|
|
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
|
Ok((_, peer)) => panic!("{prefix}: unexpected extra connection from {peer}"),
|
|
Err(err) => panic!("{prefix}: unexpected accept error: {err}"),
|
|
}
|
|
|
|
received.sort();
|
|
expected.sort();
|
|
assert_eq!(received, expected, "payload mismatch for prefix {prefix}");
|
|
assert_eq!(report.total_shards, count);
|
|
let expected_bytes: u64 = expected.iter().map(|b| b.len() as u64).sum();
|
|
assert_eq!(report.total_bytes_sent, expected_bytes);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn run_send_ilp_gap_precedes_malformed_addr_and_file_as_dir_rejected_with_zero_connections() {
|
|
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 listener nonblocking");
|
|
|
|
let assert_zero_accepts = |label: &str| match listener.accept() {
|
|
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
|
Ok((_, peer)) => panic!("{label}: unexpectedly accepted connection from {peer}"),
|
|
Err(err) => panic!("{label}: unexpected accept error: {err}"),
|
|
};
|
|
|
|
// Shard gap paired with malformed address -> MissingShardIndex precedes InvalidAddress.
|
|
let gap_dir = TempDirGuard::new("run-send-ilp-gap-precedence");
|
|
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 = run_send_ilp(&SendIlpArgs {
|
|
dir: gap_dir.path().to_path_buf(),
|
|
prefix: "bars_1m".to_string(),
|
|
addr: "not-an-addr".to_string(),
|
|
})
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(
|
|
err,
|
|
IlpSendError::MissingShardIndex {
|
|
expected: 1,
|
|
found: 2,
|
|
..
|
|
}
|
|
),
|
|
"expected MissingShardIndex(1, 2) before InvalidAddress, got {err:?}"
|
|
);
|
|
assert_zero_accepts("shard gap with malformed addr");
|
|
|
|
// Regular file passed as --dir -> InvalidDirectory, zero connections.
|
|
let file_dir = TempDirGuard::new("run-send-ilp-file-as-dir");
|
|
let file_path = file_dir.path().join("not_a_dir.ilp");
|
|
write_bytes(&file_path, b"not a directory");
|
|
let err = run_send_ilp(&SendIlpArgs {
|
|
dir: file_path,
|
|
prefix: "bars_1m".to_string(),
|
|
addr: listen_addr.to_string(),
|
|
})
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(err, IlpSendError::InvalidDirectory { .. }),
|
|
"expected InvalidDirectory, got {err:?}"
|
|
);
|
|
assert_zero_accepts("file passed as dir");
|
|
}
|
|
|
|
#[test]
|
|
fn run_send_ilp_streams_payloads_larger_than_default_buffer_byte_for_byte() {
|
|
// Arrange: two shards spanning several DEFAULT_ILP_SEND_BUFFER_BYTES chunks with a
|
|
// non-aligned tail, filled from a fixed-seed LCG so contents are deterministic.
|
|
let dir = TempDirGuard::new("run-send-ilp-large");
|
|
let mut state: u64 = 0x5EED_1234_ABCD_0001;
|
|
let mut next_byte = || {
|
|
state = state
|
|
.wrapping_mul(6_364_136_223_846_793_005)
|
|
.wrapping_add(1_442_695_040_888_963_407);
|
|
(state >> 56) as u8
|
|
};
|
|
let len0 = DEFAULT_ILP_SEND_BUFFER_BYTES * 3 + 17;
|
|
let len1 = DEFAULT_ILP_SEND_BUFFER_BYTES + 1;
|
|
let payload0: Vec<u8> = (0..len0).map(|_| next_byte()).collect();
|
|
let payload1: Vec<u8> = (0..len1).map(|_| next_byte()).collect();
|
|
assert_ne!(payload0[..len1], payload1[..]);
|
|
write_bytes(&dir.path().join("bars_1m_qm.shard-00.ilp"), &payload0);
|
|
write_bytes(&dir.path().join("bars_1m_qm.shard-01.ilp"), &payload1);
|
|
|
|
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 = thread::spawn(move || {
|
|
let deadline = Instant::now() + Duration::from_secs(5);
|
|
let mut readers = Vec::with_capacity(2);
|
|
for accepted in 0..2 {
|
|
let (mut stream, _) = accept_with_deadline(&listener, deadline, accepted, 2);
|
|
stream
|
|
.set_read_timeout(Some(Duration::from_secs(5)))
|
|
.expect("set server read timeout");
|
|
readers.push(thread::spawn(move || {
|
|
let mut buf = Vec::new();
|
|
stream.read_to_end(&mut buf).expect("read shard to EOF");
|
|
buf
|
|
}));
|
|
}
|
|
let received: Vec<Vec<u8>> = readers
|
|
.into_iter()
|
|
.map(|h| h.join().expect("join reader"))
|
|
.collect();
|
|
(listener, received)
|
|
});
|
|
|
|
// Act
|
|
let report = run_send_ilp(&SendIlpArgs {
|
|
dir: dir.path().to_path_buf(),
|
|
prefix: "bars_1m_qm".to_string(),
|
|
addr: listen_addr.to_string(),
|
|
})
|
|
.expect("run_send_ilp should stream multi-chunk shards");
|
|
let (listener, mut received) = server.join().expect("join server");
|
|
|
|
// Assert
|
|
match listener.accept() {
|
|
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
|
Ok((_, peer)) => panic!("unexpected extra connection from {peer}"),
|
|
Err(err) => panic!("unexpected accept error: {err}"),
|
|
}
|
|
received.sort();
|
|
let mut expected = vec![payload0.clone(), payload1.clone()];
|
|
expected.sort();
|
|
assert!(
|
|
received == expected,
|
|
"received payloads differ from shard files"
|
|
);
|
|
assert_eq!(report.total_shards, 2);
|
|
assert_eq!(report.shards[0].bytes_sent, len0 as u64);
|
|
assert_eq!(report.shards[1].bytes_sent, len1 as u64);
|
|
assert_eq!(report.total_bytes_sent, (len0 + len1) as u64);
|
|
}
|
|
|
|
#[test]
|
|
fn run_send_ilp_resolves_hostname_addr_and_delivers_every_shard() {
|
|
// Arrange: `--addr` is passed through as `host:port`, so a hostname (not only an IP
|
|
// literal) must resolve and pin the reachable loopback address for every shard.
|
|
let dir = TempDirGuard::new("run-send-ilp-hostname");
|
|
let payload0 = b"bars_1m,listing_id=7 close=1.5 1700000000000000t\n".to_vec();
|
|
let payload1 = b"bars_1m,listing_id=8 close=2.5 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);
|
|
|
|
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener");
|
|
let port = listener.local_addr().expect("local addr").port();
|
|
listener
|
|
.set_nonblocking(true)
|
|
.expect("set loopback listener nonblocking");
|
|
let server = thread::spawn(move || {
|
|
let deadline = Instant::now() + Duration::from_secs(5);
|
|
let mut readers = Vec::with_capacity(2);
|
|
for accepted in 0..2 {
|
|
let (mut stream, _) = accept_with_deadline(&listener, deadline, accepted, 2);
|
|
stream
|
|
.set_read_timeout(Some(Duration::from_secs(5)))
|
|
.expect("set server read timeout");
|
|
readers.push(thread::spawn(move || {
|
|
let mut buf = Vec::new();
|
|
stream.read_to_end(&mut buf).expect("read shard to EOF");
|
|
buf
|
|
}));
|
|
}
|
|
let received: Vec<Vec<u8>> = readers
|
|
.into_iter()
|
|
.map(|h| h.join().expect("join reader"))
|
|
.collect();
|
|
(listener, received)
|
|
});
|
|
|
|
// Act
|
|
let report = run_send_ilp(&SendIlpArgs {
|
|
dir: dir.path().to_path_buf(),
|
|
prefix: "bars_1m".to_string(),
|
|
addr: format!("localhost:{port}"),
|
|
})
|
|
.expect("run_send_ilp should resolve localhost and deliver");
|
|
let (listener, mut received) = server.join().expect("join server");
|
|
|
|
// Assert
|
|
match listener.accept() {
|
|
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
|
Ok((_, peer)) => panic!("unexpected extra connection from {peer}"),
|
|
Err(err) => panic!("unexpected accept error: {err}"),
|
|
}
|
|
received.sort();
|
|
let mut expected = vec![payload0.clone(), payload1.clone()];
|
|
expected.sort();
|
|
assert_eq!(received, expected);
|
|
assert_eq!(report.total_shards, 2);
|
|
assert_eq!(
|
|
report.total_bytes_sent,
|
|
(payload0.len() + payload1.len()) as u64
|
|
);
|
|
}
|