1580 lines
52 KiB
Rust
1580 lines
52 KiB
Rust
use std::collections::BTreeMap;
|
|
use std::fs;
|
|
use std::io;
|
|
use std::path::{Path, PathBuf};
|
|
use std::pin::Pin;
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
use std::sync::{Arc, Mutex};
|
|
use std::task::{Context, Poll};
|
|
use std::time::{Duration, SystemTime};
|
|
|
|
use async_trait::async_trait;
|
|
use rcom::domain::{Entry, EntryKind, Location};
|
|
use rcom::fs::{
|
|
BackendHandle, FileOperations, FsError, LocalFileOperations, LocalFs, PartFile, PartWriter,
|
|
ReadFileSystem, ReadPrefix, ReadStream, StagingDirectory, StagingOperations,
|
|
TRANSFER_CHUNK_SIZE, TransferCapabilities, TransferEvent, TransferItemResult, TransferStage,
|
|
execute_copy_move, execute_copy_move_observed, execute_prepared_copy_move,
|
|
};
|
|
use rcom::operations::{
|
|
CollisionPolicy, CommitOutcome, ItemId, ItemPhase, OperationKind, OperationPlan,
|
|
OperationPlanner, OperationRequest, PlanGeneration, PlanId, PreparedOperation,
|
|
SourceCleanupOutcome, SourceItem, TaskResult,
|
|
};
|
|
use tempfile::TempDir;
|
|
use tokio::io::{AsyncRead, AsyncWriteExt, ReadBuf};
|
|
use tokio_util::sync::CancellationToken;
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
|
|
enum Fault {
|
|
OpenPart,
|
|
Read,
|
|
Write,
|
|
Flush,
|
|
Close,
|
|
Size,
|
|
Commit,
|
|
CommitAfterApply,
|
|
Rename,
|
|
RenameAfterApply,
|
|
RemoveFile,
|
|
RemoveDir,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct FaultState {
|
|
failures: Vec<(Fault, FsError)>,
|
|
cross_device_renames: usize,
|
|
cancel_on_write: Option<CancellationToken>,
|
|
cancel_on_commit: Option<CancellationToken>,
|
|
create_on_write: Option<PathBuf>,
|
|
change_after_commit: Option<PathBuf>,
|
|
create_after_rename: Option<PathBuf>,
|
|
open_part_calls: usize,
|
|
write_calls: usize,
|
|
flush_calls: usize,
|
|
commit_calls: usize,
|
|
rename_calls: usize,
|
|
remove_calls: usize,
|
|
}
|
|
|
|
#[derive(Clone, Default)]
|
|
struct FaultOperations {
|
|
inner: LocalFileOperations,
|
|
state: Arc<Mutex<FaultState>>,
|
|
}
|
|
|
|
impl FaultOperations {
|
|
fn new() -> Self {
|
|
Self::default()
|
|
}
|
|
|
|
fn fail(&self, fault: Fault, error: FsError) {
|
|
self.lock().failures.push((fault, error));
|
|
}
|
|
|
|
fn take(&self, fault: Fault) -> Option<FsError> {
|
|
let mut state = self.lock();
|
|
let index = state.failures.iter().position(|(kind, _)| *kind == fault)?;
|
|
Some(state.failures.remove(index).1)
|
|
}
|
|
|
|
fn lock(&self) -> std::sync::MutexGuard<'_, FaultState> {
|
|
self.state.lock().unwrap_or_else(|error| error.into_inner())
|
|
}
|
|
|
|
fn cross_device_once(&self) {
|
|
self.lock().cross_device_renames = 1;
|
|
}
|
|
|
|
fn cancel_on_write(&self, token: CancellationToken) {
|
|
self.lock().cancel_on_write = Some(token);
|
|
}
|
|
|
|
fn cancel_on_commit(&self, token: CancellationToken) {
|
|
self.lock().cancel_on_commit = Some(token);
|
|
}
|
|
|
|
fn create_on_write(&self, path: PathBuf) {
|
|
self.lock().create_on_write = Some(path);
|
|
}
|
|
|
|
fn change_after_commit(&self, path: PathBuf) {
|
|
self.lock().change_after_commit = Some(path);
|
|
}
|
|
|
|
fn create_after_rename(&self, path: PathBuf) {
|
|
self.lock().create_after_rename = Some(path);
|
|
}
|
|
|
|
fn calls(&self) -> (usize, usize, usize, usize, usize, usize) {
|
|
let state = self.lock();
|
|
(
|
|
state.open_part_calls,
|
|
state.write_calls,
|
|
state.flush_calls,
|
|
state.commit_calls,
|
|
state.rename_calls,
|
|
state.remove_calls,
|
|
)
|
|
}
|
|
}
|
|
|
|
struct FaultReader {
|
|
inner: ReadStream,
|
|
error: Option<FsError>,
|
|
}
|
|
|
|
impl AsyncRead for FaultReader {
|
|
fn poll_read(
|
|
mut self: Pin<&mut Self>,
|
|
context: &mut Context<'_>,
|
|
buffer: &mut ReadBuf<'_>,
|
|
) -> Poll<io::Result<()>> {
|
|
if self.error.take().is_some() {
|
|
return Poll::Ready(Err(io::Error::other("injected read failure")));
|
|
}
|
|
Pin::new(&mut self.inner).poll_read(context, buffer)
|
|
}
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct MaliciousSecondListing {
|
|
local: LocalFs,
|
|
calls: AtomicUsize,
|
|
}
|
|
|
|
#[async_trait]
|
|
impl ReadFileSystem for MaliciousSecondListing {
|
|
async fn list(&self, location: &Location) -> Result<Vec<Entry>, FsError> {
|
|
if self.calls.fetch_add(1, Ordering::AcqRel) == 0 {
|
|
self.local.list(location).await
|
|
} else {
|
|
Ok(vec![Entry::new("../escape", EntryKind::File)])
|
|
}
|
|
}
|
|
|
|
async fn canonicalize(&self, location: &Location) -> Result<Location, FsError> {
|
|
self.local.canonicalize(location).await
|
|
}
|
|
|
|
async fn metadata(&self, location: &Location) -> Result<Entry, FsError> {
|
|
self.local.metadata(location).await
|
|
}
|
|
|
|
async fn read_prefix(&self, location: &Location, limit: usize) -> Result<ReadPrefix, FsError> {
|
|
self.local.read_prefix(location, limit).await
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
impl FileOperations for FaultOperations {
|
|
fn source_id(&self) -> &rcom::domain::SourceId {
|
|
self.inner.source_id()
|
|
}
|
|
|
|
fn capabilities(&self) -> TransferCapabilities {
|
|
self.inner.capabilities()
|
|
}
|
|
|
|
async fn canonicalize(&self, location: &Location) -> Result<Location, FsError> {
|
|
self.inner.canonicalize(location).await
|
|
}
|
|
|
|
async fn metadata(&self, location: &Location, follow_symlinks: bool) -> Result<Entry, FsError> {
|
|
let mut entry = self.inner.metadata(location, follow_symlinks).await?;
|
|
let is_part = location
|
|
.file_name()
|
|
.and_then(|name| name.to_str())
|
|
.is_some_and(|name| name.starts_with(".rcom-part-"));
|
|
if is_part && self.take(Fault::Size).is_some() {
|
|
entry.size = entry.size.map(|size| size.saturating_add(1));
|
|
}
|
|
Ok(entry)
|
|
}
|
|
|
|
async fn open_read(&self, location: &Location) -> Result<ReadStream, FsError> {
|
|
let stream = self.inner.open_read(location).await?;
|
|
if self.take(Fault::Read).is_some() {
|
|
Ok(ReadStream::new(
|
|
location.clone(),
|
|
FaultReader {
|
|
inner: stream,
|
|
error: Some(FsError::Other("injected read".into())),
|
|
},
|
|
))
|
|
} else {
|
|
Ok(stream)
|
|
}
|
|
}
|
|
|
|
async fn open_part(&self, destination: &Location) -> Result<PartWriter, FsError> {
|
|
self.lock().open_part_calls += 1;
|
|
if let Some(error) = self.take(Fault::OpenPart) {
|
|
return Err(error);
|
|
}
|
|
self.inner.open_part(destination).await
|
|
}
|
|
|
|
async fn write_part(&self, part: &mut PartWriter, chunk: &[u8]) -> Result<(), FsError> {
|
|
self.lock().write_calls += 1;
|
|
if let Some(error) = self.take(Fault::Write) {
|
|
return Err(error);
|
|
}
|
|
self.inner.write_part(part, chunk).await?;
|
|
let create = self.lock().create_on_write.take();
|
|
if let Some(path) = create {
|
|
fs::write(path, b"existing destination").unwrap();
|
|
}
|
|
let token = self.lock().cancel_on_write.take();
|
|
if let Some(token) = token {
|
|
token.cancel();
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
async fn flush_and_close(&self, part: PartWriter) -> Result<PartFile, FsError> {
|
|
self.lock().flush_calls += 1;
|
|
if let Some(error) = self.take(Fault::Flush) {
|
|
return Err(error);
|
|
}
|
|
if let Some(error) = self.take(Fault::Close) {
|
|
let mut part = part;
|
|
part.flush().await.unwrap();
|
|
part.shutdown().await.unwrap();
|
|
return Err(error);
|
|
}
|
|
self.inner.flush_and_close(part).await
|
|
}
|
|
|
|
async fn commit_part(&self, part: PartFile) -> Result<(), FsError> {
|
|
self.lock().commit_calls += 1;
|
|
if let Some(error) = self.take(Fault::Commit) {
|
|
return Err(error);
|
|
}
|
|
let after_apply = self.take(Fault::CommitAfterApply);
|
|
self.inner.commit_part(part).await?;
|
|
let change = self.lock().change_after_commit.take();
|
|
if let Some(path) = change {
|
|
fs::write(path, b"changed source with another size").unwrap();
|
|
}
|
|
let token = self.lock().cancel_on_commit.take();
|
|
if let Some(token) = token {
|
|
token.cancel();
|
|
}
|
|
if let Some(error) = after_apply {
|
|
return Err(error);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
async fn discard_part(&self, part: PartFile) -> Result<(), FsError> {
|
|
self.inner.discard_part(part).await
|
|
}
|
|
|
|
async fn rename(&self, from: &Location, to: &Location) -> Result<(), FsError> {
|
|
self.lock().rename_calls += 1;
|
|
let cross_device = {
|
|
let mut state = self.lock();
|
|
if state.cross_device_renames == 0 {
|
|
false
|
|
} else {
|
|
state.cross_device_renames -= 1;
|
|
true
|
|
}
|
|
};
|
|
if cross_device {
|
|
return Err(FsError::Unsupported("cross-device rename".into()));
|
|
}
|
|
if let Some(error) = self.take(Fault::Rename) {
|
|
return Err(error);
|
|
}
|
|
let after_apply = self.take(Fault::RenameAfterApply);
|
|
self.inner.rename(from, to).await?;
|
|
let create = self.lock().create_after_rename.take();
|
|
if let Some(path) = create {
|
|
fs::write(path, b"external addition").unwrap();
|
|
}
|
|
if let Some(error) = after_apply {
|
|
return Err(error);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
async fn remove_file(&self, location: &Location) -> Result<(), FsError> {
|
|
self.lock().remove_calls += 1;
|
|
if let Some(error) = self.take(Fault::RemoveFile) {
|
|
return Err(error);
|
|
}
|
|
self.inner.remove_file(location).await
|
|
}
|
|
|
|
async fn remove_dir(&self, location: &Location) -> Result<(), FsError> {
|
|
self.lock().remove_calls += 1;
|
|
if let Some(error) = self.take(Fault::RemoveDir) {
|
|
return Err(error);
|
|
}
|
|
self.inner.remove_dir(location).await
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
impl StagingOperations for FaultOperations {
|
|
async fn create_dir(&self, location: &Location) -> Result<(), FsError> {
|
|
self.inner.create_dir(location).await
|
|
}
|
|
|
|
async fn create_staging_dir(
|
|
&self,
|
|
destination: &Location,
|
|
) -> Result<StagingDirectory, FsError> {
|
|
self.inner.create_staging_dir(destination).await
|
|
}
|
|
}
|
|
|
|
fn handle(operations: &Arc<FaultOperations>) -> BackendHandle {
|
|
BackendHandle::new(
|
|
rcom::domain::SourceId::Local,
|
|
Arc::new(LocalFs::new()),
|
|
operations.clone(),
|
|
)
|
|
.unwrap()
|
|
}
|
|
|
|
fn handle_with_read(
|
|
operations: &Arc<FaultOperations>,
|
|
read: Arc<dyn ReadFileSystem>,
|
|
) -> BackendHandle {
|
|
BackendHandle::new(rcom::domain::SourceId::Local, read, operations.clone()).unwrap()
|
|
}
|
|
|
|
async fn prepare_with_handles(
|
|
source: &BackendHandle,
|
|
destination: &BackendHandle,
|
|
kind: OperationKind,
|
|
sources: Vec<Location>,
|
|
destination_directory: &Path,
|
|
policy: CollisionPolicy,
|
|
) -> PreparedOperation {
|
|
OperationPlanner::new(Arc::new(source.clone()), Arc::new(destination.clone()))
|
|
.prepare(OperationRequest::new(
|
|
PlanId::new(101),
|
|
PlanGeneration::new(1),
|
|
kind,
|
|
sources,
|
|
Location::local(destination_directory),
|
|
policy,
|
|
BTreeMap::new(),
|
|
))
|
|
.await
|
|
.unwrap()
|
|
}
|
|
|
|
async fn prepare_local(
|
|
source: &Arc<FaultOperations>,
|
|
destination: &Arc<FaultOperations>,
|
|
kind: OperationKind,
|
|
sources: Vec<PathBuf>,
|
|
destination_directory: &Path,
|
|
policy: CollisionPolicy,
|
|
) -> PreparedOperation {
|
|
let source_handle = handle(source);
|
|
let destination_handle = handle(destination);
|
|
prepare_with_handles(
|
|
&source_handle,
|
|
&destination_handle,
|
|
kind,
|
|
sources.into_iter().map(Location::local).collect(),
|
|
destination_directory,
|
|
policy,
|
|
)
|
|
.await
|
|
}
|
|
|
|
fn plan(kind: OperationKind, sources: Vec<PathBuf>, destination: &Path) -> OperationPlan {
|
|
plan_with_policy(kind, sources, destination, CollisionPolicy::Skip)
|
|
}
|
|
|
|
fn plan_with_policy(
|
|
kind: OperationKind,
|
|
sources: Vec<PathBuf>,
|
|
destination: &Path,
|
|
policy: CollisionPolicy,
|
|
) -> OperationPlan {
|
|
OperationPlan::new(
|
|
PlanId::new(1),
|
|
PlanGeneration::new(1),
|
|
kind,
|
|
sources
|
|
.into_iter()
|
|
.enumerate()
|
|
.map(|(index, source)| {
|
|
SourceItem::new(ItemId::new(index as u64 + 1), Location::local(source))
|
|
})
|
|
.collect(),
|
|
Location::local(destination),
|
|
policy,
|
|
None,
|
|
None,
|
|
BTreeMap::new(),
|
|
)
|
|
.unwrap()
|
|
}
|
|
|
|
async fn execute(
|
|
plan: &OperationPlan,
|
|
source: &Arc<FaultOperations>,
|
|
destination: &Arc<FaultOperations>,
|
|
cancellation: &CancellationToken,
|
|
) -> Vec<TransferItemResult> {
|
|
execute_copy_move(plan, &handle(source), &handle(destination), cancellation).await
|
|
}
|
|
|
|
fn part_paths(path: &Path) -> Vec<PathBuf> {
|
|
let Ok(entries) = fs::read_dir(path) else {
|
|
return Vec::new();
|
|
};
|
|
entries
|
|
.map(Result::unwrap)
|
|
.map(|entry| entry.path())
|
|
.filter(|path| {
|
|
path.file_name()
|
|
.and_then(|name| name.to_str())
|
|
.is_some_and(|name| name.starts_with(".rcom-part-"))
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn local_parts_are_unique_streamed_and_owned_by_their_adapter() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let source = fixture.path().join("source");
|
|
let destination = fixture.path().join("destination");
|
|
fs::write(&source, b"abcdef").unwrap();
|
|
let operations = LocalFileOperations::new();
|
|
|
|
let mut stream = operations
|
|
.open_read(&Location::local(&source))
|
|
.await
|
|
.unwrap();
|
|
let mut bytes = Vec::new();
|
|
tokio::io::AsyncReadExt::read_to_end(&mut stream, &mut bytes)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(bytes, b"abcdef");
|
|
|
|
let first = operations
|
|
.open_part(&Location::local(&destination))
|
|
.await
|
|
.unwrap();
|
|
let second = operations
|
|
.open_part(&Location::local(&destination))
|
|
.await
|
|
.unwrap();
|
|
assert_ne!(first.part().location(), second.part().location());
|
|
assert_eq!(
|
|
first.part().location().path().parent(),
|
|
Some(fixture.path()),
|
|
"part is a sibling of the final destination, not its child"
|
|
);
|
|
assert!(
|
|
first
|
|
.part()
|
|
.location()
|
|
.file_name()
|
|
.unwrap()
|
|
.to_string_lossy()
|
|
.starts_with(".rcom-part-")
|
|
);
|
|
|
|
let foreign = LocalFileOperations::new();
|
|
let foreign_part = first.part().clone();
|
|
assert_eq!(
|
|
foreign.discard_part(foreign_part).await,
|
|
Err(FsError::PermissionDenied)
|
|
);
|
|
assert!(first.part().location().path().exists());
|
|
operations
|
|
.discard_part(second.part().clone())
|
|
.await
|
|
.unwrap();
|
|
assert!(!second.part().location().path().exists());
|
|
drop(first);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn copy_streams_multiple_chunks_and_leaves_no_part_after_commit() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let sources = fixture.path().join("sources");
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&sources).unwrap();
|
|
fs::create_dir(&destinations).unwrap();
|
|
let source = sources.join("large.bin");
|
|
let expected: Vec<u8> = (0..(TRANSFER_CHUNK_SIZE * 2 + 137))
|
|
.map(|index| (index % 251) as u8)
|
|
.collect();
|
|
fs::write(&source, &expected).unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
|
|
let operation = plan(OperationKind::Copy, vec![source.clone()], &destinations);
|
|
let cancellation = CancellationToken::new();
|
|
let mut events = Vec::new();
|
|
let mut observer = |event| events.push(event);
|
|
let results = execute_copy_move_observed(
|
|
&operation,
|
|
&handle(&source_ops),
|
|
&handle(&destination_ops),
|
|
&cancellation,
|
|
&mut observer,
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results.len(), 1);
|
|
assert_eq!(results[0].outcome().phase(), ItemPhase::Succeeded);
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
|
|
assert!(matches!(
|
|
events.first(),
|
|
Some(TransferEvent::ItemStarted(_))
|
|
));
|
|
let deltas: Vec<u64> = events
|
|
.iter()
|
|
.filter_map(|event| match event {
|
|
TransferEvent::Bytes { delta, .. } => Some(*delta),
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
assert_eq!(
|
|
deltas,
|
|
vec![TRANSFER_CHUNK_SIZE as u64, TRANSFER_CHUNK_SIZE as u64, 137]
|
|
);
|
|
assert!(matches!(
|
|
events.get(events.len() - 2),
|
|
Some(TransferEvent::ItemCommitted(_))
|
|
));
|
|
assert!(matches!(
|
|
events.last(),
|
|
Some(TransferEvent::ItemFinished(result)) if result.outcome().phase() == ItemPhase::Succeeded
|
|
));
|
|
assert_eq!(fs::read(destinations.join("large.bin")).unwrap(), expected);
|
|
assert_eq!(fs::read(source).unwrap(), expected);
|
|
assert!(part_paths(&destinations).is_empty());
|
|
assert_eq!(destination_ops.calls().1, 3, "two full chunks and a tail");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn local_commit_preserves_mtime_and_unix_permissions() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let source = fixture.path().join("source.txt");
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
fs::write(&source, b"contents").unwrap();
|
|
let modified = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
|
|
std::fs::File::open(&source)
|
|
.unwrap()
|
|
.set_modified(modified)
|
|
.unwrap();
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::PermissionsExt;
|
|
fs::set_permissions(&source, fs::Permissions::from_mode(0o640)).unwrap();
|
|
}
|
|
let operations = Arc::new(LocalFileOperations::new());
|
|
let handle = BackendHandle::new(
|
|
rcom::domain::SourceId::Local,
|
|
Arc::new(LocalFs::new()),
|
|
operations.clone(),
|
|
)
|
|
.unwrap();
|
|
|
|
let results = execute_copy_move(
|
|
&plan(OperationKind::Copy, vec![source], &destinations),
|
|
&handle,
|
|
&handle,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
|
|
let destination = destinations.join("source.txt");
|
|
assert_eq!(
|
|
fs::metadata(&destination).unwrap().modified().unwrap(),
|
|
modified
|
|
);
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::PermissionsExt;
|
|
assert_eq!(
|
|
fs::metadata(destination).unwrap().permissions().mode() & 0o7777,
|
|
0o640
|
|
);
|
|
}
|
|
assert!(operations.take_capability_warnings().is_empty());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn directory_is_built_in_a_sibling_staging_root_and_committed_once() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let source = fixture.path().join("tree");
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
fs::create_dir_all(source.join("nested/empty")).unwrap();
|
|
fs::write(source.join("nested/data"), b"nested contents").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
|
|
let results = execute(
|
|
&plan(OperationKind::Copy, vec![source.clone()], &destinations),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().phase(), ItemPhase::Succeeded);
|
|
assert_eq!(
|
|
fs::read(destinations.join("tree/nested/data")).unwrap(),
|
|
b"nested contents"
|
|
);
|
|
assert!(destinations.join("tree/nested/empty").is_dir());
|
|
assert!(part_paths(&destinations).is_empty());
|
|
assert_eq!(
|
|
destination_ops.calls().4,
|
|
1,
|
|
"only the staging root is renamed"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn same_endpoint_move_uses_safe_rename_without_a_part() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let source = fixture.path().join("source");
|
|
fs::write(&source, b"move").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
|
|
let results = execute(
|
|
&plan(OperationKind::Move, vec![source.clone()], &destinations),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().phase(), ItemPhase::Succeeded);
|
|
assert_eq!(
|
|
results[0].outcome().source_cleanup(),
|
|
SourceCleanupOutcome::Removed
|
|
);
|
|
assert!(!source.exists());
|
|
assert_eq!(fs::read(destinations.join("source")).unwrap(), b"move");
|
|
assert_eq!(source_ops.calls().4, 1);
|
|
assert_eq!(destination_ops.calls().0, 0);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn cross_device_move_falls_back_to_copy_then_post_order_delete() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let source = fixture.path().join("tree");
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
fs::create_dir_all(source.join("nested")).unwrap();
|
|
fs::write(source.join("nested/file"), b"contents").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
source_ops.cross_device_once();
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
|
|
let results = execute(
|
|
&plan(OperationKind::Move, vec![source.clone()], &destinations),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().phase(), ItemPhase::Succeeded);
|
|
assert_eq!(
|
|
results[0].outcome().source_cleanup(),
|
|
SourceCleanupOutcome::Removed
|
|
);
|
|
assert!(!source.exists());
|
|
assert_eq!(
|
|
fs::read(destinations.join("tree/nested/file")).unwrap(),
|
|
b"contents"
|
|
);
|
|
assert_eq!(source_ops.calls().5, 3, "file, nested directory, then root");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn collision_skip_and_recheck_preserve_existing_destination_and_source() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let source = fixture.path().join("source");
|
|
let final_destination = destinations.join("source");
|
|
fs::write(&source, b"new source").unwrap();
|
|
fs::write(&final_destination, b"old destination").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
|
|
let skipped = execute(
|
|
&plan(OperationKind::Move, vec![source.clone()], &destinations),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
assert_eq!(skipped[0].outcome().phase(), ItemPhase::Skipped);
|
|
assert_eq!(fs::read(&final_destination).unwrap(), b"old destination");
|
|
assert_eq!(fs::read(&source).unwrap(), b"new source");
|
|
assert_eq!(destination_ops.calls().0, 0);
|
|
|
|
fs::remove_file(&final_destination).unwrap();
|
|
destination_ops.create_on_write(final_destination.clone());
|
|
let late = execute(
|
|
&plan(OperationKind::Copy, vec![source.clone()], &destinations),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
assert_eq!(late[0].outcome().phase(), ItemPhase::Skipped);
|
|
assert_eq!(late[0].outcome().commit(), CommitOutcome::NotCommitted);
|
|
assert_eq!(late[0].stage(), Some(TransferStage::Collision));
|
|
assert!(late[0].partial().is_some());
|
|
assert_eq!(
|
|
fs::read(final_destination).unwrap(),
|
|
b"existing destination"
|
|
);
|
|
assert_eq!(fs::read(source).unwrap(), b"new source");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn per_item_collision_policies_drive_skip_and_overwrite() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let skipped = fixture.path().join("skipped");
|
|
let overwritten = fixture.path().join("overwritten");
|
|
fs::write(&skipped, b"new skipped").unwrap();
|
|
fs::write(&overwritten, b"new overwritten").unwrap();
|
|
fs::write(destinations.join("skipped"), b"old skipped").unwrap();
|
|
fs::write(destinations.join("overwritten"), b"old overwritten").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
let operation = plan_with_policy(
|
|
OperationKind::Copy,
|
|
vec![skipped, overwritten],
|
|
&destinations,
|
|
CollisionPolicy::Ask,
|
|
)
|
|
.with_collision_policies(BTreeMap::from([
|
|
(ItemId::new(1), CollisionPolicy::Skip),
|
|
(ItemId::new(2), CollisionPolicy::Overwrite),
|
|
]));
|
|
|
|
let results = execute(
|
|
&operation,
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().phase(), ItemPhase::Skipped);
|
|
assert_eq!(results[1].outcome().phase(), ItemPhase::Succeeded);
|
|
assert_eq!(
|
|
fs::read(destinations.join("skipped")).unwrap(),
|
|
b"old skipped"
|
|
);
|
|
assert_eq!(
|
|
fs::read(destinations.join("overwritten")).unwrap(),
|
|
b"new overwritten"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn confirmed_file_overwrite_commits_but_directory_merge_is_rejected() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let source = fixture.path().join("source");
|
|
fs::write(&source, b"new").unwrap();
|
|
fs::write(destinations.join("source"), b"old").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
|
|
let overwritten = execute(
|
|
&plan_with_policy(
|
|
OperationKind::Copy,
|
|
vec![source.clone()],
|
|
&destinations,
|
|
CollisionPolicy::Overwrite,
|
|
),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
assert_eq!(overwritten[0].outcome().phase(), ItemPhase::Succeeded);
|
|
assert_eq!(fs::read(destinations.join("source")).unwrap(), b"new");
|
|
|
|
let directory = fixture.path().join("directory");
|
|
fs::create_dir(&directory).unwrap();
|
|
fs::create_dir(destinations.join("directory")).unwrap();
|
|
let rejected = execute(
|
|
&plan_with_policy(
|
|
OperationKind::Copy,
|
|
vec![directory],
|
|
&destinations,
|
|
CollisionPolicy::Overwrite,
|
|
),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
assert_eq!(rejected[0].outcome().phase(), ItemPhase::Failed);
|
|
assert_eq!(rejected[0].outcome().commit(), CommitOutcome::NotAttempted);
|
|
assert_eq!(rejected[0].stage(), Some(TransferStage::Collision));
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn overwrite_after_apply_disconnect_is_unknown_and_never_deletes_source() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let source = fixture.path().join("source");
|
|
let final_destination = destinations.join("source");
|
|
fs::write(&source, b"new").unwrap();
|
|
fs::write(&final_destination, b"old").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
destination_ops.fail(Fault::CommitAfterApply, FsError::Disconnected);
|
|
|
|
let operation = plan_with_policy(
|
|
OperationKind::Move,
|
|
vec![source.clone()],
|
|
&destinations,
|
|
CollisionPolicy::Overwrite,
|
|
);
|
|
let cancellation = CancellationToken::new();
|
|
let mut events = Vec::new();
|
|
let mut observer = |event| events.push(event);
|
|
let results = execute_copy_move_observed(
|
|
&operation,
|
|
&handle(&source_ops),
|
|
&handle(&destination_ops),
|
|
&cancellation,
|
|
&mut observer,
|
|
)
|
|
.await;
|
|
|
|
assert!(
|
|
!events
|
|
.iter()
|
|
.any(|event| matches!(event, TransferEvent::ItemCommitted(_)))
|
|
);
|
|
assert_eq!(results[0].outcome().phase(), ItemPhase::Failed);
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Unknown);
|
|
assert_eq!(
|
|
results[0].outcome().source_cleanup(),
|
|
SourceCleanupOutcome::NotAttempted
|
|
);
|
|
assert_eq!(source_ops.calls().5, 0);
|
|
assert_eq!(fs::read(&source).unwrap(), b"new");
|
|
assert_eq!(fs::read(&final_destination).unwrap(), b"new");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn failures_are_not_retried_and_preserve_source_and_destination() {
|
|
for (fault, stage, has_part) in [
|
|
(Fault::Read, TransferStage::Read, true),
|
|
(Fault::OpenPart, TransferStage::OpenPart, false),
|
|
(Fault::Write, TransferStage::Write, true),
|
|
(Fault::Flush, TransferStage::FlushClose, true),
|
|
(Fault::Close, TransferStage::FlushClose, true),
|
|
(Fault::Size, TransferStage::SizeVerify, true),
|
|
(Fault::Commit, TransferStage::CommitRename, true),
|
|
] {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let source = fixture.path().join("source");
|
|
fs::write(&source, vec![b'x'; TRANSFER_CHUNK_SIZE + 1]).unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
source_ops.cross_device_once();
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
let failing = if fault == Fault::Read {
|
|
&source_ops
|
|
} else {
|
|
&destination_ops
|
|
};
|
|
failing.fail(fault, FsError::Other(format!("injected {fault:?}")));
|
|
|
|
let results = execute(
|
|
&plan(OperationKind::Move, vec![source.clone()], &destinations),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().phase(), ItemPhase::Failed, "{fault:?}");
|
|
assert_eq!(results[0].stage(), Some(stage), "{fault:?}");
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::NotCommitted);
|
|
assert_eq!(results[0].partial().is_some(), has_part, "{fault:?}");
|
|
assert_eq!(
|
|
fs::read(&source).unwrap(),
|
|
vec![b'x'; TRANSFER_CHUNK_SIZE + 1]
|
|
);
|
|
assert!(!destinations.join("source").exists(), "{fault:?}");
|
|
assert_eq!(
|
|
destination_ops.calls().3,
|
|
usize::from(fault == Fault::Commit)
|
|
);
|
|
if has_part {
|
|
let part = results[0].partial().unwrap();
|
|
assert!(part.location().path().exists());
|
|
assert!(part.location().path().starts_with(&destinations));
|
|
}
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn timeout_during_write_is_unknown_and_mutation_is_not_retried() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let source = fixture.path().join("source");
|
|
fs::write(&source, b"contents").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
destination_ops.fail(Fault::Write, FsError::Timeout);
|
|
|
|
let results = execute(
|
|
&plan(OperationKind::Copy, vec![source.clone()], &destinations),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Unknown);
|
|
assert_eq!(destination_ops.calls().1, 1);
|
|
assert_eq!(
|
|
TaskResult::from_outcomes(&[results[0].outcome()]),
|
|
TaskResult::Failed
|
|
);
|
|
assert!(source.exists());
|
|
assert!(results[0].partial().unwrap().location().path().exists());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn after_apply_commit_and_rename_are_reconciled_without_retry() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let copy_source = fixture.path().join("copy-source");
|
|
fs::write(©_source, b"copied").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
destination_ops.fail(Fault::CommitAfterApply, FsError::Timeout);
|
|
|
|
let copied = execute(
|
|
&plan(
|
|
OperationKind::Copy,
|
|
vec![copy_source.clone()],
|
|
&destinations,
|
|
),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
assert_eq!(copied[0].outcome().commit(), CommitOutcome::Committed);
|
|
assert!(copied[0].partial().is_none());
|
|
assert_eq!(destination_ops.calls().3, 1);
|
|
assert!(copy_source.exists());
|
|
assert_eq!(
|
|
fs::read(destinations.join("copy-source")).unwrap(),
|
|
b"copied"
|
|
);
|
|
|
|
let move_source = fixture.path().join("move-source");
|
|
fs::write(&move_source, b"moved").unwrap();
|
|
source_ops.fail(Fault::RenameAfterApply, FsError::Timeout);
|
|
let moved = execute(
|
|
&plan(
|
|
OperationKind::Move,
|
|
vec![move_source.clone()],
|
|
&destinations,
|
|
),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
assert_eq!(moved[0].outcome().commit(), CommitOutcome::Committed);
|
|
assert_eq!(
|
|
moved[0].outcome().source_cleanup(),
|
|
SourceCleanupOutcome::Removed
|
|
);
|
|
assert!(!move_source.exists());
|
|
assert_eq!(
|
|
fs::read(destinations.join("move-source")).unwrap(),
|
|
b"moved"
|
|
);
|
|
assert_eq!(source_ops.calls().4, 1);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn delete_failure_after_commit_is_partial_and_keeps_destination() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let source = fixture.path().join("source");
|
|
fs::write(&source, b"source").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
source_ops.cross_device_once();
|
|
source_ops.fail(Fault::RemoveFile, FsError::PermissionDenied);
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
|
|
let results = execute(
|
|
&plan(OperationKind::Move, vec![source.clone()], &destinations),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().phase(), ItemPhase::Failed);
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
|
|
assert_eq!(
|
|
results[0].outcome().source_cleanup(),
|
|
SourceCleanupOutcome::Failed
|
|
);
|
|
assert_eq!(results[0].stage(), Some(TransferStage::SourceDelete));
|
|
assert!(source.exists());
|
|
assert_eq!(fs::read(destinations.join("source")).unwrap(), b"source");
|
|
assert_eq!(source_ops.calls().5, 1, "failed delete is not retried");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn changed_source_is_preserved_and_reported_after_commit() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let source = fixture.path().join("source");
|
|
fs::write(&source, b"before").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
source_ops.cross_device_once();
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
destination_ops.change_after_commit(source.clone());
|
|
|
|
let results = execute(
|
|
&plan(OperationKind::Move, vec![source.clone()], &destinations),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert!(results[0].source_changed());
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
|
|
assert_eq!(
|
|
results[0].outcome().source_cleanup(),
|
|
SourceCleanupOutcome::NotAttempted
|
|
);
|
|
assert_eq!(results[0].stage(), Some(TransferStage::SourceFingerprint));
|
|
assert_eq!(
|
|
fs::read(source).unwrap(),
|
|
b"changed source with another size"
|
|
);
|
|
assert_eq!(fs::read(destinations.join("source")).unwrap(), b"before");
|
|
assert_eq!(source_ops.calls().5, 0);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn external_file_added_after_tree_commit_prevents_blind_source_cleanup() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let source = fixture.path().join("tree");
|
|
fs::create_dir(&source).unwrap();
|
|
fs::write(source.join("planned"), b"planned").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
source_ops.cross_device_once();
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
destination_ops.create_after_rename(source.join("external"));
|
|
|
|
let results = execute(
|
|
&plan(OperationKind::Move, vec![source.clone()], &destinations),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert!(results[0].source_changed());
|
|
assert_eq!(source_ops.calls().5, 0);
|
|
assert_eq!(fs::read(source.join("planned")).unwrap(), b"planned");
|
|
assert_eq!(
|
|
fs::read(source.join("external")).unwrap(),
|
|
b"external addition"
|
|
);
|
|
assert_eq!(
|
|
fs::read(destinations.join("tree/planned")).unwrap(),
|
|
b"planned"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn nested_failure_leaves_staging_for_diagnostics_without_final_commit() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let source = fixture.path().join("tree");
|
|
fs::create_dir(&source).unwrap();
|
|
fs::write(source.join("file"), b"contents").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
source_ops.cross_device_once();
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
destination_ops.fail(Fault::Write, FsError::Other("write failed".into()));
|
|
|
|
let results = execute(
|
|
&plan(OperationKind::Move, vec![source.clone()], &destinations),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::NotCommitted);
|
|
assert!(results[0].partial().is_some());
|
|
assert!(results[0].staging().is_some());
|
|
assert_eq!(results[0].residual_locations().len(), 2);
|
|
assert!(results[0].staging().unwrap().location().path().is_dir());
|
|
assert!(!destinations.join("tree").exists());
|
|
assert_eq!(fs::read(source.join("file")).unwrap(), b"contents");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn cancellation_between_chunks_leaves_part_and_blocks_commit_and_source_delete() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let first = fixture.path().join("first");
|
|
let second = fixture.path().join("second");
|
|
fs::write(&first, vec![b'a'; TRANSFER_CHUNK_SIZE * 2]).unwrap();
|
|
fs::write(&second, b"second").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
source_ops.cross_device_once();
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
let cancellation = CancellationToken::new();
|
|
destination_ops.cancel_on_write(cancellation.clone());
|
|
|
|
let results = execute(
|
|
&plan(
|
|
OperationKind::Move,
|
|
vec![first.clone(), second.clone()],
|
|
&destinations,
|
|
),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&cancellation,
|
|
)
|
|
.await;
|
|
|
|
assert!(cancellation.is_cancelled());
|
|
assert_eq!(results[0].outcome().phase(), ItemPhase::Cancelled);
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::NotCommitted);
|
|
assert!(results[0].partial().unwrap().location().path().exists());
|
|
assert_eq!(results[1].outcome().phase(), ItemPhase::Cancelled);
|
|
assert_eq!(results[1].outcome().commit(), CommitOutcome::NotAttempted);
|
|
assert_eq!(
|
|
destination_ops.calls().0,
|
|
1,
|
|
"no part is created for later items"
|
|
);
|
|
assert_eq!(
|
|
destination_ops.calls().3,
|
|
0,
|
|
"no commit follows cancellation"
|
|
);
|
|
assert_eq!(
|
|
source_ops.calls().5,
|
|
0,
|
|
"no source delete follows cancellation"
|
|
);
|
|
assert!(first.exists());
|
|
assert!(second.exists());
|
|
assert!(!destinations.join("first").exists());
|
|
assert!(!destinations.join("second").exists());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn cancellation_after_commit_preserves_source_and_starts_no_new_item() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let first = fixture.path().join("first");
|
|
let second = fixture.path().join("second");
|
|
fs::write(&first, b"first").unwrap();
|
|
fs::write(&second, b"second").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
source_ops.cross_device_once();
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
let cancellation = CancellationToken::new();
|
|
destination_ops.cancel_on_commit(cancellation.clone());
|
|
|
|
let results = execute(
|
|
&plan(
|
|
OperationKind::Move,
|
|
vec![first.clone(), second.clone()],
|
|
&destinations,
|
|
),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&cancellation,
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().phase(), ItemPhase::Cancelled);
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
|
|
assert_eq!(
|
|
results[0].outcome().source_cleanup(),
|
|
SourceCleanupOutcome::NotAttempted
|
|
);
|
|
assert_eq!(results[1].outcome().phase(), ItemPhase::Cancelled);
|
|
assert_eq!(destination_ops.calls().0, 1);
|
|
assert_eq!(destination_ops.calls().3, 1);
|
|
assert_eq!(source_ops.calls().5, 0);
|
|
assert!(first.exists());
|
|
assert!(second.exists());
|
|
assert!(destinations.join("first").exists());
|
|
assert!(!destinations.join("second").exists());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn cancellation_before_execution_creates_no_mutations() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let source = fixture.path().join("source");
|
|
fs::write(&source, b"source").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
let cancellation = CancellationToken::new();
|
|
cancellation.cancel();
|
|
|
|
let results = execute(
|
|
&plan(OperationKind::Move, vec![source.clone()], fixture.path()),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&cancellation,
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().phase(), ItemPhase::Cancelled);
|
|
assert_eq!(destination_ops.calls().0, 0);
|
|
assert_eq!(source_ops.calls().4, 0);
|
|
assert_eq!(source_ops.calls().5, 0);
|
|
assert!(source.exists());
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[tokio::test]
|
|
async fn symlinks_and_special_files_are_rejected_without_staging() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let target = fixture.path().join("target");
|
|
fs::write(&target, b"target").unwrap();
|
|
let link = fixture.path().join("link");
|
|
std::os::unix::fs::symlink(&target, &link).unwrap();
|
|
let socket = fixture.path().join("socket");
|
|
let _listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
|
|
let results = execute(
|
|
&plan(OperationKind::Copy, vec![link, socket], &destinations),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
for result in results {
|
|
assert_eq!(result.outcome().phase(), ItemPhase::Failed);
|
|
assert_eq!(result.outcome().commit(), CommitOutcome::NotAttempted);
|
|
assert!(matches!(result.error(), Some(FsError::Unsupported(_))));
|
|
}
|
|
assert_eq!(destination_ops.calls().0, 0);
|
|
assert_eq!(destination_ops.calls().4, 0);
|
|
assert!(part_paths(&destinations).is_empty());
|
|
assert_eq!(fs::read(target).unwrap(), b"target");
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[tokio::test]
|
|
async fn symlink_inside_tree_is_not_traversed() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let outside = fixture.path().join("outside");
|
|
fs::create_dir(&outside).unwrap();
|
|
fs::write(outside.join("secret"), b"secret").unwrap();
|
|
let source = fixture.path().join("tree");
|
|
fs::create_dir(&source).unwrap();
|
|
std::os::unix::fs::symlink(&outside, source.join("link")).unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
|
|
let results = execute(
|
|
&plan(OperationKind::Copy, vec![source], &destinations),
|
|
&source_ops,
|
|
&destination_ops,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().phase(), ItemPhase::Failed);
|
|
assert!(results[0].staging().is_none());
|
|
assert!(!destinations.join("tree").exists());
|
|
assert!(part_paths(&destinations).is_empty());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn prepared_tree_never_uses_a_malicious_second_listing_and_legacy_rejects_it() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let source = fixture.path().join("tree");
|
|
let prepared_destinations = fixture.path().join("prepared-destinations");
|
|
let legacy_destinations = fixture.path().join("legacy-destinations");
|
|
fs::create_dir(&source).unwrap();
|
|
fs::create_dir(&prepared_destinations).unwrap();
|
|
fs::create_dir(&legacy_destinations).unwrap();
|
|
fs::write(source.join("safe"), b"safe").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let prepared_destination_ops = Arc::new(FaultOperations::new());
|
|
let read = Arc::new(MaliciousSecondListing::default());
|
|
let source_handle = handle_with_read(&source_ops, read.clone());
|
|
let prepared_destination_handle = handle(&prepared_destination_ops);
|
|
let prepared = prepare_with_handles(
|
|
&source_handle,
|
|
&prepared_destination_handle,
|
|
OperationKind::Copy,
|
|
vec![Location::local(source.clone())],
|
|
&prepared_destinations,
|
|
CollisionPolicy::Ask,
|
|
)
|
|
.await;
|
|
assert_eq!(read.calls.load(Ordering::Acquire), 1);
|
|
|
|
let prepared_results = execute_prepared_copy_move(
|
|
&prepared,
|
|
&source_handle,
|
|
&prepared_destination_handle,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(prepared_results[0].outcome().phase(), ItemPhase::Succeeded);
|
|
assert_eq!(read.calls.load(Ordering::Acquire), 1);
|
|
assert_eq!(
|
|
fs::read(prepared_destinations.join("tree/safe")).unwrap(),
|
|
b"safe"
|
|
);
|
|
|
|
let legacy_destination_ops = Arc::new(FaultOperations::new());
|
|
let legacy_results = execute_copy_move(
|
|
&plan(
|
|
OperationKind::Copy,
|
|
vec![source.clone()],
|
|
&legacy_destinations,
|
|
),
|
|
&source_handle,
|
|
&handle(&legacy_destination_ops),
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(read.calls.load(Ordering::Acquire), 2);
|
|
assert_eq!(legacy_results[0].outcome().phase(), ItemPhase::Failed);
|
|
assert_eq!(
|
|
legacy_results[0].outcome().commit(),
|
|
CommitOutcome::NotAttempted
|
|
);
|
|
assert_eq!(legacy_destination_ops.calls().0, 0);
|
|
assert_eq!(legacy_destination_ops.calls().3, 0);
|
|
assert_eq!(source_ops.calls().5, 0);
|
|
assert!(!fixture.path().join("escape").exists());
|
|
assert_eq!(fs::read(source.join("safe")).unwrap(), b"safe");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn prepared_overwrite_recheck_rejects_changed_destination_and_preserves_source() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let source = fixture.path().join("source");
|
|
let final_destination = destinations.join("source");
|
|
fs::write(&source, b"new").unwrap();
|
|
fs::write(&final_destination, b"old").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
let prepared = prepare_local(
|
|
&source_ops,
|
|
&destination_ops,
|
|
OperationKind::Move,
|
|
vec![source.clone()],
|
|
&destinations,
|
|
CollisionPolicy::Overwrite,
|
|
)
|
|
.await;
|
|
destination_ops.create_on_write(final_destination.clone());
|
|
|
|
let results = execute_prepared_copy_move(
|
|
&prepared,
|
|
&handle(&source_ops),
|
|
&handle(&destination_ops),
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().phase(), ItemPhase::Failed);
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::NotCommitted);
|
|
assert_eq!(results[0].stage(), Some(TransferStage::Collision));
|
|
assert!(results[0].partial().is_some());
|
|
assert_eq!(destination_ops.calls().3, 0);
|
|
assert_eq!(source_ops.calls().5, 0);
|
|
assert_eq!(fs::read(&source).unwrap(), b"new");
|
|
assert_eq!(
|
|
fs::read(&final_destination).unwrap(),
|
|
b"existing destination"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn prepared_source_same_size_content_and_mtime_change_fails_before_mutation() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let source = fixture.path().join("source");
|
|
fs::write(&source, b"aa").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
let prepared = prepare_local(
|
|
&source_ops,
|
|
&destination_ops,
|
|
OperationKind::Move,
|
|
vec![source.clone()],
|
|
&destinations,
|
|
CollisionPolicy::Ask,
|
|
)
|
|
.await;
|
|
|
|
fs::write(&source, b"bb").unwrap();
|
|
let file = fs::OpenOptions::new().write(true).open(&source).unwrap();
|
|
file.set_times(fs::FileTimes::new().set_modified(SystemTime::now() + Duration::from_secs(20)))
|
|
.unwrap();
|
|
|
|
let results = execute_prepared_copy_move(
|
|
&prepared,
|
|
&handle(&source_ops),
|
|
&handle(&destination_ops),
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().phase(), ItemPhase::Failed);
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::NotAttempted);
|
|
assert_eq!(results[0].stage(), Some(TransferStage::SourceFingerprint));
|
|
assert_eq!(source_ops.calls().4, 0);
|
|
assert_eq!(source_ops.calls().5, 0);
|
|
assert_eq!(destination_ops.calls().0, 0);
|
|
assert_eq!(fs::read(&source).unwrap(), b"bb");
|
|
assert!(!destinations.join("source").exists());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn confirmed_unchanged_prepared_copy_and_move_succeed() {
|
|
for kind in [OperationKind::Copy, OperationKind::Move] {
|
|
let fixture = TempDir::new().unwrap();
|
|
let source = fixture.path().join("tree");
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
fs::create_dir_all(source.join("nested")).unwrap();
|
|
fs::write(source.join("nested/file"), b"confirmed").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
let prepared = prepare_local(
|
|
&source_ops,
|
|
&destination_ops,
|
|
kind,
|
|
vec![source.clone()],
|
|
&destinations,
|
|
CollisionPolicy::Ask,
|
|
)
|
|
.await;
|
|
|
|
let results = execute_prepared_copy_move(
|
|
&prepared,
|
|
&handle(&source_ops),
|
|
&handle(&destination_ops),
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results.len(), 1);
|
|
assert_eq!(results[0].outcome().phase(), ItemPhase::Succeeded);
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
|
|
assert_eq!(
|
|
fs::read(destinations.join("tree/nested/file")).unwrap(),
|
|
b"confirmed"
|
|
);
|
|
assert_eq!(source.exists(), kind == OperationKind::Copy);
|
|
assert!(part_paths(&destinations).is_empty());
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn prepared_create_recheck_rejects_a_destination_that_appeared() {
|
|
let fixture = TempDir::new().unwrap();
|
|
let destinations = fixture.path().join("destinations");
|
|
fs::create_dir(&destinations).unwrap();
|
|
let source = fixture.path().join("source");
|
|
let final_destination = destinations.join("source");
|
|
fs::write(&source, b"source").unwrap();
|
|
let source_ops = Arc::new(FaultOperations::new());
|
|
let destination_ops = Arc::new(FaultOperations::new());
|
|
let prepared = prepare_local(
|
|
&source_ops,
|
|
&destination_ops,
|
|
OperationKind::Copy,
|
|
vec![source.clone()],
|
|
&destinations,
|
|
CollisionPolicy::Ask,
|
|
)
|
|
.await;
|
|
destination_ops.create_on_write(final_destination.clone());
|
|
|
|
let results = execute_prepared_copy_move(
|
|
&prepared,
|
|
&handle(&source_ops),
|
|
&handle(&destination_ops),
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::NotCommitted);
|
|
assert_eq!(results[0].stage(), Some(TransferStage::Collision));
|
|
assert_eq!(destination_ops.calls().3, 0);
|
|
assert_eq!(source_ops.calls().5, 0);
|
|
assert_eq!(fs::read(&source).unwrap(), b"source");
|
|
assert_eq!(
|
|
fs::read(&final_destination).unwrap(),
|
|
b"existing destination"
|
|
);
|
|
}
|