rcom/tests/delete_execution.rs

398 lines
14 KiB
Rust
Raw Permalink Normal View History

use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::Path;
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use rcom::actions::{
DeleteEvent, MutationStage, execute_delete, execute_delete_observed, prepare_delete,
};
use rcom::domain::{Entry, EntryKind, Location, SourceId};
use rcom::fs::{BackendHandle, FsError, LocalFileOperations, LocalFs, ReadFileSystem, ReadPrefix};
use rcom::operations::{
CommitOutcome, ItemPhase, PlanGeneration, PlanId, SourceCleanupOutcome, TaskResult,
};
use rcom::test_support::{MemoryFs, MemoryTransferFs, TransferOperation};
use tempfile::TempDir;
use tokio_util::sync::CancellationToken;
fn backend() -> BackendHandle {
BackendHandle::new(
SourceId::Local,
Arc::new(LocalFs::new()),
Arc::new(LocalFileOperations::new()),
)
.unwrap()
}
async fn prepare(
sources: Vec<Location>,
backend: &BackendHandle,
) -> rcom::actions::EntryMutationPlan {
prepare_delete(
PlanId::new(31),
PlanGeneration::new(7),
sources,
BTreeMap::new(),
backend,
)
.await
.unwrap()
}
#[tokio::test]
async fn delete_executes_the_confirmed_tree_in_stable_post_order() {
let fixture = TempDir::new().unwrap();
let root = fixture.path().join("tree");
std::fs::create_dir(&root).unwrap();
std::fs::create_dir(root.join("sub")).unwrap();
std::fs::create_dir(root.join("empty")).unwrap();
std::fs::write(root.join("sub/nested.txt"), b"nested").unwrap();
std::fs::write(root.join("top.txt"), b"top").unwrap();
let backend = backend();
let plan = prepare(vec![Location::local(&root)], &backend).await;
assert!(root.join("sub/nested.txt").exists());
let relative: Vec<_> = plan
.nodes()
.iter()
.map(|node| node.relative_path().to_path_buf())
.collect();
assert_eq!(
relative,
[
Path::new("tree/empty"),
Path::new("tree/sub/nested.txt"),
Path::new("tree/sub"),
Path::new("tree/top.txt"),
Path::new("tree"),
]
);
assert!(plan.nodes().iter().all(|node| node.fingerprint().is_some()));
assert_eq!(plan.source(), &Location::local(fixture.path()));
assert!(plan.destination().is_none());
let results = execute_delete(&plan, &backend, &CancellationToken::new()).await;
assert_eq!(results.len(), 1);
let result = &results[0];
assert_eq!(result.outcome().id(), plan.nodes().last().unwrap().id());
assert_eq!(result.outcome().phase(), ItemPhase::Succeeded);
assert_eq!(result.outcome().commit(), CommitOutcome::Committed);
assert_eq!(
result.outcome().source_cleanup(),
SourceCleanupOutcome::NotRequired
);
assert!(!root.exists());
assert!(fixture.path().exists());
}
#[tokio::test]
async fn delete_plan_and_results_cover_every_selected_root_not_only_the_first() {
let fixture = TempDir::new().unwrap();
let first = fixture.path().join("a");
let second = fixture.path().join("b");
let keep = fixture.path().join("keep");
std::fs::write(&first, b"a").unwrap();
std::fs::write(&second, b"b").unwrap();
std::fs::write(&keep, b"keep").unwrap();
let backend = backend();
let plan = prepare(
vec![Location::local(&second), Location::local(&first)],
&backend,
)
.await;
assert_eq!(plan.nodes().len(), 2);
assert_eq!(plan.nodes()[0].relative_path(), Path::new("a"));
assert_eq!(plan.nodes()[1].relative_path(), Path::new("b"));
assert!(first.exists() && second.exists());
let results = execute_delete(&plan, &backend, &CancellationToken::new()).await;
assert_eq!(results.len(), 2);
assert_eq!(results[0].outcome().id(), plan.nodes()[0].id());
assert_eq!(results[1].outcome().id(), plan.nodes()[1].id());
assert!(
results
.iter()
.all(|result| result.outcome().phase() == ItemPhase::Succeeded)
);
assert!(!first.exists());
assert!(!second.exists());
assert_eq!(std::fs::read(keep).unwrap(), b"keep");
}
struct UnsafeListingFs(OsString);
#[async_trait]
impl ReadFileSystem for UnsafeListingFs {
async fn list(&self, _location: &Location) -> Result<Vec<Entry>, FsError> {
Ok(vec![Entry::new(self.0.clone(), EntryKind::File)])
}
async fn canonicalize(&self, _location: &Location) -> Result<Location, FsError> {
Err(FsError::Unsupported("not used by delete planning".into()))
}
async fn metadata(&self, _location: &Location) -> Result<Entry, FsError> {
Err(FsError::Unsupported("not used by delete planning".into()))
}
async fn read_prefix(
&self,
_location: &Location,
_limit: usize,
) -> Result<ReadPrefix, FsError> {
Err(FsError::Unsupported("not used by delete planning".into()))
}
}
#[tokio::test]
async fn delete_planning_rejects_every_unsafe_child_name_before_accessing_it() {
let fixture = TempDir::new().unwrap();
let root = fixture.path().join("tree");
std::fs::create_dir(&root).unwrap();
for name in ["", "/absolute", ".", "..", "one/two"] {
let backend = BackendHandle::new(
SourceId::Local,
Arc::new(UnsafeListingFs(OsString::from(name))),
Arc::new(LocalFileOperations::new()),
)
.unwrap();
let result = prepare_delete(
PlanId::new(31),
PlanGeneration::new(7),
vec![Location::local(&root)],
BTreeMap::new(),
&backend,
)
.await;
assert!(result.is_err(), "unsafe child name {name:?} was accepted");
assert!(root.is_dir());
}
}
#[cfg(unix)]
#[tokio::test]
async fn delete_removes_a_symlink_without_following_it_to_the_target() {
let fixture = TempDir::new().unwrap();
let target = fixture.path().join("target");
let link = fixture.path().join("link");
std::fs::create_dir(&target).unwrap();
std::fs::write(target.join("keep"), b"keep").unwrap();
std::os::unix::fs::symlink(&target, &link).unwrap();
let backend = backend();
let plan = prepare(vec![Location::local(&link)], &backend).await;
assert_eq!(plan.nodes().len(), 1);
assert_eq!(
plan.nodes()[0].fingerprint().unwrap().kind(),
EntryKind::Symlink
);
let results = execute_delete(&plan, &backend, &CancellationToken::new()).await;
assert_eq!(results[0].outcome().phase(), ItemPhase::Succeeded);
assert!(std::fs::symlink_metadata(&link).is_err());
assert_eq!(std::fs::read(target.join("keep")).unwrap(), b"keep");
}
#[cfg(unix)]
#[tokio::test]
async fn delete_removes_a_special_file_without_opening_it() {
let fixture = TempDir::new().unwrap();
let socket = fixture.path().join("socket");
let _listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
let backend = backend();
let plan = prepare(vec![Location::local(&socket)], &backend).await;
assert_eq!(plan.nodes().len(), 1);
assert_eq!(
plan.nodes()[0].fingerprint().unwrap().kind(),
EntryKind::Other
);
let results = execute_delete(&plan, &backend, &CancellationToken::new()).await;
assert_eq!(results[0].outcome().phase(), ItemPhase::Succeeded);
assert!(!socket.exists());
}
#[tokio::test]
async fn delete_refuses_a_node_whose_fingerprint_changed_after_confirmation() {
let fixture = TempDir::new().unwrap();
let file = fixture.path().join("file");
std::fs::write(&file, b"confirmed").unwrap();
let backend = backend();
let plan = prepare(vec![Location::local(&file)], &backend).await;
std::fs::write(&file, b"changed after confirmation").unwrap();
let results = execute_delete(&plan, &backend, &CancellationToken::new()).await;
assert_eq!(results.len(), 1);
assert_eq!(results[0].outcome().phase(), ItemPhase::Failed);
assert_eq!(results[0].outcome().commit(), CommitOutcome::NotAttempted);
assert_eq!(
results[0].outcome().source_cleanup(),
SourceCleanupOutcome::NotRequired
);
assert_eq!(std::fs::read(&file).unwrap(), b"changed after confirmation");
}
#[tokio::test]
async fn delete_reports_partial_cleanup_when_an_external_file_keeps_the_root_nonempty() {
let fixture = TempDir::new().unwrap();
let root = fixture.path().join("tree");
let confirmed = root.join("confirmed");
let external = root.join("external");
std::fs::create_dir(&root).unwrap();
std::fs::write(&confirmed, b"confirmed").unwrap();
let backend = backend();
let plan = prepare(vec![Location::local(&root)], &backend).await;
std::fs::write(&external, b"external").unwrap();
let results = execute_delete(&plan, &backend, &CancellationToken::new()).await;
assert_eq!(results.len(), 1);
assert_eq!(results[0].outcome().phase(), ItemPhase::Failed);
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
assert_eq!(results[0].stage(), MutationStage::RemoveDir);
assert_eq!(
TaskResult::from_outcomes(&[results[0].outcome()]),
TaskResult::Partial
);
assert_eq!(
results[0].outcome().source_cleanup(),
SourceCleanupOutcome::NotRequired
);
assert!(!confirmed.exists());
assert_eq!(std::fs::read(external).unwrap(), b"external");
assert!(root.is_dir());
}
#[tokio::test]
async fn delete_cancellation_prevents_every_new_mutation_and_returns_each_root() {
let fixture = TempDir::new().unwrap();
let first = fixture.path().join("a");
let second = fixture.path().join("b");
std::fs::write(&first, b"a").unwrap();
std::fs::write(&second, b"b").unwrap();
let backend = backend();
let plan = prepare(
vec![Location::local(&first), Location::local(&second)],
&backend,
)
.await;
let cancellation = CancellationToken::new();
cancellation.cancel();
let results = execute_delete(&plan, &backend, &cancellation).await;
assert_eq!(results.len(), 2);
assert!(
results
.iter()
.all(|result| result.outcome().phase() == ItemPhase::Cancelled)
);
assert!(
results
.iter()
.all(|result| result.outcome().commit() == CommitOutcome::NotAttempted)
);
assert_eq!(std::fs::read(first).unwrap(), b"a");
assert_eq!(std::fs::read(second).unwrap(), b"b");
}
#[tokio::test]
async fn delete_observed_starts_before_metadata_and_finishes_a_cancelled_root_in_order() {
let location = Location::local("/file");
let read = MemoryFs::new().with_file(location.clone(), b"contents");
let transfer = MemoryTransferFs::local().with_file(location.clone(), b"contents");
let backend =
BackendHandle::new(SourceId::Local, Arc::new(read), Arc::new(transfer.clone())).unwrap();
let plan = prepare(vec![location.clone()], &backend).await;
let root_id = plan.nodes()[0].id();
transfer.clear_operations();
let gate = transfer.gate_next(TransferOperation::Metadata);
let cancellation = CancellationToken::new();
let events = Arc::new(Mutex::new(Vec::new()));
let mut observer = {
let events = events.clone();
move |event| {
events
.lock()
.unwrap_or_else(|error| error.into_inner())
.push(event);
}
};
let execution = execute_delete_observed(&plan, &backend, &cancellation, &mut observer);
let controller = async {
gate.wait_entered().await;
// The metadata gate proves that Started was delivered before the root's first recheck.
assert_eq!(
*events.lock().unwrap_or_else(|error| error.into_inner()),
[DeleteEvent::ItemStarted(root_id)]
);
cancellation.cancel();
gate.release();
};
let (results, ()) = tokio::join!(execution, controller);
assert_eq!(results[0].outcome().phase(), ItemPhase::Cancelled);
assert_eq!(results[0].error(), Some(&FsError::Cancelled));
assert_eq!(
*events.lock().unwrap_or_else(|error| error.into_inner()),
[
DeleteEvent::ItemStarted(root_id),
DeleteEvent::ItemFinished(results[0].clone()),
]
);
assert_eq!(transfer.file_contents(&location).unwrap(), b"contents");
assert!(
transfer
.operations()
.iter()
.all(|entry| entry.operation != TransferOperation::RemoveFile)
);
}
#[tokio::test]
async fn delete_timeout_or_disconnect_after_mutation_is_unknown_and_never_retried() {
for error in [FsError::Timeout, FsError::Disconnected] {
let location = Location::local("/file");
let read = MemoryFs::new().with_file(location.clone(), b"contents");
let transfer = MemoryTransferFs::local().with_file(location.clone(), b"contents");
let backend =
BackendHandle::new(SourceId::Local, Arc::new(read), Arc::new(transfer.clone()))
.unwrap();
let plan = prepare(vec![location.clone()], &backend).await;
transfer.clear_operations();
transfer.fail_after_apply(TransferOperation::RemoveFile, error.clone());
let results = execute_delete(&plan, &backend, &CancellationToken::new()).await;
assert_eq!(results.len(), 1);
assert_eq!(results[0].outcome().phase(), ItemPhase::Failed);
assert_eq!(results[0].outcome().commit(), CommitOutcome::Unknown);
assert_eq!(results[0].stage(), MutationStage::RemoveFile);
assert_eq!(results[0].error(), Some(&error));
assert_eq!(transfer.file_contents(&location), Err(FsError::NotFound));
assert_eq!(
transfer
.operations()
.iter()
.filter(|entry| entry.operation == TransferOperation::RemoveFile)
.count(),
1
);
}
}