#[path = "common/bucket.rs"]
mod common;
use common::{BUFFER_SIZE, Fault, TestBucket};
use more_asserts::{assert_gt, assert_lt};
use storage_transfer_lib::{Error, ReadConfig, TransferConfig, TransferLimits, TransferProgress};
#[tokio::test]
async fn reads_ahead_of_a_slow_writer_with_bounded_buffers() {
let config = TransferConfig {
limits: TransferLimits::new(1, 3).unwrap(),
chunk_size: 5 * 1024 * 1024,
read: ReadConfig {
concurrency: 2,
prefetch: 2,
},
..TransferConfig::default()
};
let bucket = TestBucket::new(&[10 * BUFFER_SIZE + 13], Fault::SlowWrite)
.with_chunk_size(config.chunk_size);
let mut engine = bucket.engine_with_config(config);
let progress = engine.subscribe();
tokio::time::timeout(std::time::Duration::from_secs(10), async {
let run = engine.run();
tokio::pin!(run);
tokio::select! {
result = &mut run => panic!("finished before the blocked write: {result:?}"),
_ = bucket.write_started.notified() => {}
}
for _ in 0..20 {
tokio::task::yield_now().await;
}
let snapshot = *progress.borrow();
assert_gt!(snapshot.read_bytes, 0);
assert_lt!(snapshot.read_bytes, (10 * BUFFER_SIZE + 13) as u64);
assert_eq!(snapshot.copied_bytes, 0);
bucket.assert_bounded_read_ahead(config.read.concurrency + config.read.prefetch + 2);
bucket.resume_write.notify_one();
run.await.unwrap();
})
.await
.expect("read-ahead or writer deadlocked");
bucket.assert_completed(3);
}
#[tokio::test]
async fn concurrent_reads_preserve_order_and_share_the_http_limit() {
for (concurrency, prefetch) in [(4, 0), (2, 3)] {
let bucket = TestBucket::new(&[4 * BUFFER_SIZE + 13], Fault::ConcurrentRead);
let mut engine = bucket.engine_with_config(TransferConfig {
limits: TransferLimits::new(1, 2).unwrap(),
read: ReadConfig {
concurrency,
prefetch,
},
..TransferConfig::default()
});
let summary = tokio::time::timeout(std::time::Duration::from_secs(10), engine.run())
.await
.expect("concurrent reads deadlocked")
.unwrap();
assert_eq!(summary.copied_objects, 1);
bucket.assert_completed(2);
}
}
#[tokio::test]
async fn read_ahead_with_one_http_permit_does_not_deadlock() {
let bucket = TestBucket::new(&[4 * BUFFER_SIZE + 13], Fault::None);
tokio::time::timeout(
std::time::Duration::from_secs(10),
bucket.copy_with_config(
0,
TransferConfig {
limits: TransferLimits::new(1, 1).unwrap(),
read: ReadConfig {
concurrency: 4,
prefetch: 2,
},
..TransferConfig::default()
},
),
)
.await
.expect("read-ahead deadlocked with writes")
.unwrap();
bucket.assert_completed(1);
}
#[tokio::test]
async fn rejects_invalid_read_options() {
let bucket = TestBucket::new(&[17], Fault::None);
assert!(matches!(
bucket
.copy_with_config(
0,
TransferConfig {
read: ReadConfig {
concurrency: 0,
..ReadConfig::default()
},
..TransferConfig::default()
}
)
.await,
Err(Error::InvalidLimit {
field: "read.concurrency",
..
})
));
assert!(matches!(
bucket
.copy_with_config(
0,
TransferConfig {
read: ReadConfig {
concurrency: 2,
prefetch: usize::MAX
},
..TransferConfig::default()
}
)
.await,
Err(Error::InvalidConfig("read.prefetch"))
));
}
#[tokio::test]
async fn copies_objects_in_bounded_ranges_with_one_http_permit() {
for chunk_size in [5 * 1024 * 1024, BUFFER_SIZE] {
for size in [0, 17, chunk_size, chunk_size + 13, 3 * chunk_size + 7] {
let bucket = TestBucket::new(&[size], Fault::None).with_chunk_size(chunk_size);
bucket.copy(0).await.unwrap();
bucket.assert_completed(1);
}
}
}
#[tokio::test]
async fn existing_destination_is_not_overwritten() {
for size in [17, 2 * BUFFER_SIZE + 13] {
let bucket = TestBucket::new(&[size], Fault::ExistingDestination);
assert!(
matches!(bucket.copy(0).await, Err(Error::Storage(error)) if error.kind() == opendal::ErrorKind::ConditionNotMatch)
);
bucket.assert_destination_unchanged();
}
}
#[tokio::test]
async fn transfers_bucket_with_shared_http_limit() {
let sizes = [0, 17, 2048, BUFFER_SIZE + 13].repeat(2);
for sizes in [&[][..], sizes.as_slice()] {
for (queue_size, http_limit) in [(1, 1), (2, 3)] {
let bucket = TestBucket::new(sizes, Fault::None);
let mut engine = bucket.engine(TransferLimits::new(queue_size, http_limit).unwrap());
let progress = engine.subscribe();
let summary = engine.run().await.unwrap();
assert_eq!(
summary,
TransferProgress {
listed_objects: sizes.len() as u64,
read_bytes: sizes.iter().sum::<usize>() as u64,
copied_objects: sizes.len() as u64,
copied_bytes: sizes.iter().sum::<usize>() as u64,
}
);
assert_eq!(*progress.borrow(), summary);
bucket.assert_completed(http_limit);
}
}
}
#[tokio::test]
async fn propagates_listing_worker_and_panic_failures_after_stopping_tasks() {
for fault in [Fault::Listing, Fault::Copy, Fault::Panic] {
let bucket = TestBucket::new(&[0, 17, BUFFER_SIZE + 13], fault);
let mut engine = bucket.engine(TransferLimits::new(1, 2).unwrap());
let error = engine.run().await.unwrap_err();
match fault {
Fault::Panic => assert!(matches!(error, Error::Task(error) if error.is_panic())),
Fault::Listing | Fault::Copy => assert!(
matches!(error, Error::Storage(error) if error.kind() == opendal::ErrorKind::PermissionDenied)
),
_ => unreachable!(),
}
bucket.assert_stopped();
}
}
#[tokio::test(start_paused = true)]
async fn retries_both_operators() {
for size in [17, BUFFER_SIZE + 13] {
let bucket = TestBucket::new(&[size], Fault::Throttled);
let mut engine = bucket.engine(TransferLimits::new(1, 1).unwrap());
let summary = engine.run().await.unwrap();
assert_eq!(summary.copied_objects, 1);
assert_eq!(summary.read_bytes, size as u64);
bucket.assert_completed(1);
bucket.assert_failures(1, 1, 0);
}
}
#[tokio::test(start_paused = true)]
async fn write_failure_attempts_cleanup_and_preserves_first_error() {
for fault in [Fault::AbortDenied, Fault::AbortHang] {
let bucket = TestBucket::new(&[BUFFER_SIZE + 13, 17, 17, 17], fault);
let mut engine = bucket.engine(TransferLimits::new(1, 1).unwrap());
let error = engine.run().await.unwrap_err();
assert!(
matches!(error, Error::Storage(error) if error.kind() == opendal::ErrorKind::PermissionDenied)
);
bucket.assert_failures(
0,
0,
if matches!(fault, Fault::AbortHang) {
3
} else {
1
},
);
bucket.assert_stopped();
}
}
#[tokio::test(start_paused = true)]
async fn reports_completed_and_incomplete_objects() {
for (fault, expected, read_bytes) in [
(Fault::None, "copied", 17),
(Fault::UnavailableDestination, "failed", 17),
(Fault::TimeoutRead, "failed", 0),
] {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("report.jsonl");
let bucket = TestBucket::new(&[17], fault);
let mut engine = bucket.engine(TransferLimits::new(1, 1).unwrap());
let result = engine.run_with_report(&path).await;
match fault {
Fault::None => assert_eq!(result.unwrap().copied_objects, 1),
Fault::UnavailableDestination => {
assert!(matches!(result, Err(Error::Storage(_))));
bucket.assert_failures(0, 3, 0);
}
Fault::TimeoutRead => {
assert!(matches!(result, Err(Error::Storage(_))));
bucket.assert_failures(3, 0, 0);
}
_ => unreachable!(),
}
let report = tokio::fs::read_to_string(&path).await.unwrap();
let records: Vec<serde_json::Value> = report
.lines()
.map(|line| serde_json::from_str(line).unwrap())
.collect();
assert_eq!(records.len(), 2);
assert_eq!(records[0]["path"], "objects/0");
assert_eq!(records[0]["status"], expected);
assert_eq!(records[1]["type"], "finished");
assert_eq!(records[1]["progress"]["read_bytes"], read_bytes);
assert_eq!(
records[1]["progress"]["copied_objects"],
u64::from(expected == "copied")
);
assert!(matches!(
engine.run_with_report(&path).await,
Err(Error::Report(_))
));
assert_eq!(tokio::fs::read_to_string(path).await.unwrap(), report);
}
}
#[tokio::test]
async fn copies_relative_paths_between_directory_roots_and_reports_full_keys() {
for (source, destination) in [
("", "brightdata/"),
("raw/", ""),
("input/raw", "datasets/brightdata"),
] {
let bucket = TestBucket::new(&[0, 17, BUFFER_SIZE + 13], Fault::None)
.with_prefixes(source, destination);
let mut engine = bucket.engine(TransferLimits::new(1, 1).unwrap());
let directory = tempfile::tempdir().unwrap();
let report = directory.path().join("report.jsonl");
let summary = tokio::time::timeout(
std::time::Duration::from_secs(30),
engine.run_with_report(&report),
)
.await
.expect("directory copy deadlocked")
.unwrap();
assert_eq!(summary.copied_objects, 3);
bucket.assert_completed(1);
let source = opendal::raw::normalize_root(source)
.trim_start_matches('/')
.to_owned();
let destination = opendal::raw::normalize_root(destination)
.trim_start_matches('/')
.to_owned();
let records: Vec<serde_json::Value> = tokio::fs::read_to_string(report)
.await
.unwrap()
.lines()
.map(|line| serde_json::from_str(line).unwrap())
.collect();
for record in &records[..3] {
let path = record["path"].as_str().unwrap();
assert_eq!(record["source_path"], format!("{source}{path}"));
assert_eq!(record["destination_path"], format!("{destination}{path}"));
}
}
}
#[tokio::test]
async fn prefixed_collisions_leave_destination_unchanged() {
let bucket = TestBucket::new(&[BUFFER_SIZE + 13], Fault::ExistingDestination)
.with_prefixes("raw/", "brightdata/");
assert!(bucket.copy(0).await.is_err());
bucket.assert_destination_unchanged();
}
#[tokio::test]
async fn rejects_invalid_chunk_sizes_and_excess_parts_before_io() {
use opendal::MetadataBuilder;
use storage_transfer_lib::{ObjectTask, TransferEngine, copy_object};
let (source, destination) = TestBucket::new(&[1], Fault::Panic).operators();
let mut task = ObjectTask {
path: "objects/0".into(),
metadata: MetadataBuilder::file(1).build(),
};
let too_large = destination
.info()
.capability()
.write_multi_max_size
.unwrap()
.checked_add(1);
for chunk_size in [Some(0), Some(1), too_large].into_iter().flatten() {
let config = TransferConfig {
chunk_size,
..TransferConfig::default()
};
let construction = TransferEngine::new(source.clone(), destination.clone(), config)
.err()
.unwrap();
let copy = copy_object(&source, &destination, &task, &config)
.await
.unwrap_err();
for error in [construction, copy] {
if chunk_size == 0 {
assert!(matches!(error, Error::InvalidConfig("chunk_size")));
} else {
assert!(matches!(error, Error::Unsupported(_)));
}
}
}
let overflow = TransferConfig {
chunk_size: usize::MAX / 2 + 1,
read: ReadConfig {
concurrency: 2,
prefetch: 0,
},
..TransferConfig::default()
};
assert!(matches!(
copy_object(&source, &destination, &task, &overflow).await,
Err(Error::InvalidConfig("read.prefetch"))
));
let config = TransferConfig {
chunk_size: 5 * 1024 * 1024,
..TransferConfig::default()
};
task.metadata = MetadataBuilder::file(config.chunk_size as u64 * 10_000 + 1).build();
assert!(matches!(
copy_object(&source, &destination, &task, &config).await,
Err(Error::Unsupported(_))
));
}