rcom/tests/undo_execution.rs

1233 lines
40 KiB
Rust
Raw Permalink Normal View History

use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use rcom::actions::{
ActionResult, EntryMutationKind, EntryMutationNode, EntryMutationPlan, MutationStage,
PreparedUndoKind, TrashPolicy, TrashRecord, UndoEntry, UndoEvent, UndoJournal, UndoRecordError,
UndoResult, consume_undo_on_success, execute_entry_mutation, execute_trash, prepare_trash,
prepare_undo,
};
use rcom::domain::{Entry, EntryKind, HostAlias, Location, SourceId};
use rcom::fs::{
BackendHandle, FileOperations, FsError, LocalFileOperations, LocalFs, ReadFileSystem,
ReadPrefix,
};
use rcom::operations::{
CollisionPolicy, CommitOutcome, EntryFingerprint, ItemId, ItemOutcome, ItemPhase,
OperationKind, OperationPlanner, OperationRequest, PlanGeneration, PlanId,
SourceCleanupOutcome,
};
use rcom::test_support::{MemoryFs, MemoryTransferFs, TransferOperation};
use tempfile::TempDir;
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
fn local_backend() -> BackendHandle {
BackendHandle::new(
SourceId::Local,
Arc::new(LocalFs::new()),
Arc::new(LocalFileOperations::new()),
)
.unwrap()
}
fn epochs(fs: &MemoryTransferFs) -> BTreeMap<SourceId, u64> {
BTreeMap::from([(fs.source_id().clone(), fs.epoch())])
}
fn memory_backend(fs: &MemoryTransferFs) -> BackendHandle {
BackendHandle::new(
fs.source_id().clone(),
Arc::new(MemoryFs::new()),
Arc::new(fs.clone()),
)
.unwrap()
}
fn backends(backend: &BackendHandle) -> BTreeMap<SourceId, BackendHandle> {
BTreeMap::from([(backend.source_id().clone(), backend.clone())])
}
async fn fingerprint(backend: &BackendHandle, location: &Location) -> EntryFingerprint {
EntryFingerprint::from(&backend.transfer.metadata(location, false).await.unwrap())
}
async fn memory_create_entry(
fs: &MemoryTransferFs,
parent: Location,
name: &str,
kind: EntryMutationKind,
) -> (UndoEntry, Location) {
let plan = EntryMutationPlan::create(
PlanId::new(1),
PlanGeneration::new(1),
kind,
ItemId::new(1),
parent,
name,
epochs(fs),
)
.unwrap();
let backend = memory_backend(fs);
assert_eq!(
execute_entry_mutation(&plan, &backend, &CancellationToken::new())
.await
.outcome()
.phase(),
ItemPhase::Succeeded
);
let created = plan.destination().unwrap().clone();
let fingerprint = fingerprint(&backend, &created).await;
(
UndoEntry::Create {
plan,
created_fingerprint: fingerprint,
},
created,
)
}
async fn memory_rename_entry(
fs: &MemoryTransferFs,
source: Location,
new_name: &str,
) -> (UndoEntry, Location, Location) {
let backend = memory_backend(fs);
let original_fingerprint = fingerprint(&backend, &source).await;
let plan = EntryMutationPlan::rename(
PlanId::new(2),
PlanGeneration::new(2),
ItemId::new(2),
source.clone(),
original_fingerprint,
new_name,
epochs(fs),
)
.unwrap();
let destination = plan.destination().unwrap().clone();
assert_eq!(
execute_entry_mutation(&plan, &backend, &CancellationToken::new())
.await
.outcome()
.phase(),
ItemPhase::Succeeded
);
let renamed_fingerprint = fingerprint(&backend, &destination).await;
(
UndoEntry::Rename {
plan,
renamed_fingerprint,
},
source,
destination,
)
}
async fn make_trash_entry(
fs: &MemoryTransferFs,
originals: &[Location],
trash_root: Location,
) -> UndoEntry {
let parent = originals[0].parent().unwrap();
let mut nodes = Vec::new();
let mut records = Vec::new();
for (index, original) in originals.iter().enumerate() {
let entry = FileOperations::metadata(fs, original, false).await.unwrap();
let fingerprint = EntryFingerprint::from(&entry);
let id = ItemId::new(index as u64 + 1);
let record_id = Uuid::from_u128(index as u128 + 100);
let trashed = trash_root.join("files").join(record_id.to_string());
fs.rename(original, &trashed).await.unwrap();
nodes.push(EntryMutationNode::new(
id,
original.clone(),
original.file_name_owned().unwrap(),
Some(fingerprint.clone()),
));
records.push(
TrashRecord::new(
original.clone(),
trashed,
fingerprint,
fs.epoch(),
record_id,
)
.unwrap(),
);
}
let plan = EntryMutationPlan::new(
PlanId::new(3),
PlanGeneration::new(3),
EntryMutationKind::Trash,
parent,
Some(trash_root),
nodes,
epochs(fs),
)
.unwrap();
UndoEntry::Trash { plan, records }
}
fn actions(result: &UndoResult) -> &[ActionResult] {
result.actions().expect("entry action results")
}
fn operation_count(fs: &MemoryTransferFs, operation: TransferOperation) -> usize {
fs.operations()
.iter()
.filter(|entry| entry.operation == operation)
.count()
}
#[tokio::test]
async fn local_undo_create_removes_only_an_unchanged_file_or_empty_directory() {
let fixture = TempDir::new().unwrap();
let parent_path = fixture.path().join("work");
std::fs::create_dir(&parent_path).unwrap();
let sibling = parent_path.join("keep");
std::fs::write(&sibling, b"keep").unwrap();
let backend = local_backend();
for (name, kind) in [
("created-file", EntryMutationKind::CreateFile),
("created-dir", EntryMutationKind::CreateDirectory),
] {
let plan = EntryMutationPlan::create(
PlanId::new(10),
PlanGeneration::new(11),
kind,
ItemId::new(12),
Location::local(&parent_path),
name,
BTreeMap::new(),
)
.unwrap();
execute_entry_mutation(&plan, &backend, &CancellationToken::new()).await;
let created = plan.destination().unwrap().clone();
let entry = UndoEntry::Create {
created_fingerprint: fingerprint(&backend, &created).await,
plan,
};
let prepared = prepare_undo(
&entry,
PlanId::new(20),
PlanGeneration::new(21),
backends(&backend),
)
.await
.unwrap();
assert_eq!(prepared.id(), PlanId::new(20));
let result = prepared.execute(&CancellationToken::new()).await;
assert!(result.is_fully_successful());
assert!(!created.path().exists());
assert_eq!(std::fs::read(&sibling).unwrap(), b"keep");
}
}
#[tokio::test]
async fn changed_created_file_and_nonempty_directory_are_never_recursively_deleted() {
let file = Location::local("/work/file");
let directory = Location::local("/work/directory");
let fs = MemoryTransferFs::local()
.with_file(file.clone(), b"changed")
.with_dir(directory.clone())
.with_file(directory.join("external"), b"keep");
let file_fp = EntryFingerprint::from(&Entry::new("file", EntryKind::File).with_metadata(
Some(0),
None,
None,
));
let dir_fp = EntryFingerprint::from(
&FileOperations::metadata(&fs, &directory, false)
.await
.unwrap(),
);
for (path, kind, expected) in [
(file.clone(), EntryMutationKind::CreateFile, file_fp),
(
directory.clone(),
EntryMutationKind::CreateDirectory,
dir_fp,
),
] {
let plan = EntryMutationPlan::create(
PlanId::new(1),
PlanGeneration::new(1),
kind,
ItemId::new(1),
Location::local("/work"),
path.file_name_owned().unwrap(),
BTreeMap::new(),
)
.unwrap();
let entry = UndoEntry::Create {
plan,
created_fingerprint: expected,
};
let prepared = prepare_undo(
&entry,
PlanId::new(2),
PlanGeneration::new(2),
backends(&memory_backend(&fs)),
)
.await;
if path == file {
assert!(prepared.is_err(), "changed file reached execution");
continue;
}
let result = prepared.unwrap().execute(&CancellationToken::new()).await;
assert!(!result.is_fully_successful());
assert_eq!(actions(&result)[0].stage(), MutationStage::RemoveDir);
assert_eq!(
fs.file_contents(&directory.join("external")).unwrap(),
b"keep"
);
assert_eq!(
FileOperations::metadata(&fs, &directory, false)
.await
.unwrap()
.kind,
EntryKind::Directory
);
}
assert_eq!(operation_count(&fs, TransferOperation::RemoveFile), 0);
assert_eq!(operation_count(&fs, TransferOperation::RemoveDir), 1);
}
#[tokio::test]
async fn fake_ssh_undo_create_rename_and_multi_trash_restore_succeed() {
let host = HostAlias::new("edge");
let endpoint = SourceId::Ssh(host.clone());
let parent = Location::ssh(host.clone(), "/work");
let fs = MemoryTransferFs::new(endpoint, 7).with_dir(parent.clone());
let (create, created) = memory_create_entry(
&fs,
parent.clone(),
"created",
EntryMutationKind::CreateFile,
)
.await;
let prepared = prepare_undo(
&create,
PlanId::new(30),
PlanGeneration::new(31),
backends(&memory_backend(&fs)),
)
.await
.unwrap();
assert!(
prepared
.execute(&CancellationToken::new())
.await
.is_fully_successful()
);
assert_eq!(fs.file_contents(&created), Err(FsError::NotFound));
let original = parent.join("old");
fs.insert_file(original.clone(), b"contents");
let (rename, old, current) = memory_rename_entry(&fs, original, "new").await;
let prepared = prepare_undo(
&rename,
PlanId::new(32),
PlanGeneration::new(33),
backends(&memory_backend(&fs)),
)
.await
.unwrap();
assert!(
prepared
.execute(&CancellationToken::new())
.await
.is_fully_successful()
);
assert_eq!(fs.file_contents(&old).unwrap(), b"contents");
assert_eq!(fs.file_contents(&current), Err(FsError::NotFound));
let first = parent.join("first");
let second = parent.join("second");
fs.insert_file(first.clone(), b"first");
fs.insert_file(second.clone(), b"second");
let trash_root = Location::ssh(host, "/trash");
fs.insert_dir(trash_root.join("files"));
let trash = make_trash_entry(&fs, &[second.clone(), first.clone()], trash_root).await;
let before = operation_count(&fs, TransferOperation::Rename);
let prepared = prepare_undo(
&trash,
PlanId::new(34),
PlanGeneration::new(35),
backends(&memory_backend(&fs)),
)
.await
.unwrap();
let PreparedUndoKind::Trash { plan, restores } = prepared.kind() else {
panic!("expected trash restores")
};
assert_eq!(restores.len(), 2);
let UndoEntry::Trash { plan: original, .. } = &trash else {
unreachable!()
};
assert_eq!(plan, original);
assert!(restores[0].original() < restores[1].original());
let result = prepared.execute(&CancellationToken::new()).await;
assert!(result.is_fully_successful(), "{:?}", result.outcomes());
assert_eq!(fs.file_contents(&first).unwrap(), b"first");
assert_eq!(fs.file_contents(&second).unwrap(), b"second");
assert_eq!(operation_count(&fs, TransferOperation::Rename), before + 2);
}
#[tokio::test]
async fn local_rename_and_trash_undo_restore_typed_paths() {
let fixture = TempDir::new().unwrap();
let work = fixture.path().join("work");
let trash_files = fixture.path().join("trash/files");
std::fs::create_dir(&work).unwrap();
std::fs::create_dir_all(&trash_files).unwrap();
let backend = local_backend();
let old = Location::local(work.join("old"));
std::fs::write(old.path(), b"rename").unwrap();
let original_fp = fingerprint(&backend, &old).await;
let plan = EntryMutationPlan::rename(
PlanId::new(1),
PlanGeneration::new(1),
ItemId::new(1),
old.clone(),
original_fp,
"new",
BTreeMap::new(),
)
.unwrap();
execute_entry_mutation(&plan, &backend, &CancellationToken::new()).await;
let current = plan.destination().unwrap().clone();
let entry = UndoEntry::Rename {
plan,
renamed_fingerprint: fingerprint(&backend, &current).await,
};
let prepared = prepare_undo(
&entry,
PlanId::new(2),
PlanGeneration::new(2),
backends(&backend),
)
.await
.unwrap();
assert!(
prepared
.execute(&CancellationToken::new())
.await
.is_fully_successful()
);
assert_eq!(std::fs::read(old.path()).unwrap(), b"rename");
let original = Location::local(work.join("trashed"));
std::fs::write(original.path(), b"trash").unwrap();
let fp = fingerprint(&backend, &original).await;
let uuid = Uuid::from_u128(55);
let trashed = Location::local(trash_files.join(uuid.to_string()));
backend.transfer.rename(&original, &trashed).await.unwrap();
let record = TrashRecord::new(original.clone(), trashed, fp.clone(), 0, uuid).unwrap();
let node = EntryMutationNode::new(ItemId::new(4), original.clone(), "trashed", Some(fp));
let plan = EntryMutationPlan::new(
PlanId::new(4),
PlanGeneration::new(4),
EntryMutationKind::Trash,
Location::local(&work),
Some(Location::local(fixture.path().join("trash"))),
vec![node],
BTreeMap::new(),
)
.unwrap();
let entry = UndoEntry::Trash {
plan,
records: vec![record],
};
let prepared = prepare_undo(
&entry,
PlanId::new(5),
PlanGeneration::new(5),
backends(&backend),
)
.await
.unwrap();
assert!(
prepared
.execute(&CancellationToken::new())
.await
.is_fully_successful()
);
assert_eq!(std::fs::read(original.path()).unwrap(), b"trash");
}
#[tokio::test]
async fn rename_and_trash_conflicts_or_missing_paths_stop_before_undo_mutation() {
let parent = Location::local("/work");
let old = parent.join("old");
let fs = MemoryTransferFs::local().with_file(old.clone(), b"source");
let (rename, old, current) = memory_rename_entry(&fs, old, "new").await;
fs.insert_file(old.clone(), b"conflict");
let before = operation_count(&fs, TransferOperation::Rename);
let result = prepare_undo(
&rename,
PlanId::new(9),
PlanGeneration::new(9),
backends(&memory_backend(&fs)),
)
.await;
assert!(result.is_err());
assert_eq!(operation_count(&fs, TransferOperation::Rename), before);
assert_eq!(fs.file_contents(&old).unwrap(), b"conflict");
assert_eq!(fs.file_contents(&current).unwrap(), b"source");
fs.remove_file(&current).await.unwrap();
assert!(
prepare_undo(
&rename,
PlanId::new(9),
PlanGeneration::new(9),
backends(&memory_backend(&fs)),
)
.await
.is_err()
);
assert_eq!(operation_count(&fs, TransferOperation::Rename), before);
let first = parent.join("first");
let second = parent.join("second");
fs.insert_file(first.clone(), b"first");
fs.insert_file(second.clone(), b"second");
let trash_root = Location::local("/trash");
fs.insert_dir(trash_root.join("files"));
let trash = make_trash_entry(&fs, &[first.clone(), second.clone()], trash_root).await;
let UndoEntry::Trash { records, .. } = &trash else {
unreachable!()
};
fs.insert_file(second.clone(), b"original conflict");
let before = operation_count(&fs, TransferOperation::Rename);
assert!(
prepare_undo(
&trash,
PlanId::new(10),
PlanGeneration::new(10),
backends(&memory_backend(&fs)),
)
.await
.is_err()
);
assert_eq!(operation_count(&fs, TransferOperation::Rename), before);
assert_eq!(fs.file_contents(records[0].trashed()).unwrap(), b"first");
assert_eq!(fs.file_contents(records[1].trashed()).unwrap(), b"second");
}
#[tokio::test]
async fn stale_epoch_and_pre_cancel_do_not_start_an_undo_mutation() {
let host = HostAlias::new("edge");
let parent = Location::ssh(host.clone(), "/work");
let old = parent.join("old");
let fs = MemoryTransferFs::new(SourceId::Ssh(host), 7).with_file(old.clone(), b"source");
let (rename, _old, current) = memory_rename_entry(&fs, old, "new").await;
let before = operation_count(&fs, TransferOperation::Rename);
let _current_session = fs.reconnect(8);
assert!(
prepare_undo(
&rename,
PlanId::new(10),
PlanGeneration::new(10),
backends(&memory_backend(&fs)),
)
.await
.is_err()
);
assert_eq!(operation_count(&fs, TransferOperation::Rename), before);
assert_eq!(fs.file_contents(&current).unwrap(), b"source");
let current_session = fs.for_epoch(8);
let prepared = prepare_undo(
&rename,
PlanId::new(11),
PlanGeneration::new(11),
backends(&memory_backend(&current_session)),
)
.await
.unwrap();
let cancellation = CancellationToken::new();
cancellation.cancel();
let result = prepared.execute(&cancellation).await;
assert_eq!(actions(&result)[0].outcome().phase(), ItemPhase::Cancelled);
assert_eq!(
actions(&result)[0].outcome().commit(),
CommitOutcome::NotAttempted
);
assert_eq!(operation_count(&fs, TransferOperation::Rename), before);
assert_eq!(fs.file_contents(&current).unwrap(), b"source");
}
#[tokio::test]
async fn unknown_after_apply_is_not_retried_and_does_not_consume_the_entry() {
let parent = Location::local("/work");
let fs = MemoryTransferFs::local().with_dir(parent.clone());
let (entry, created) =
memory_create_entry(&fs, parent, "created", EntryMutationKind::CreateFile).await;
let mut journal = UndoJournal::new();
let UndoEntry::Create { plan, .. } = &entry else {
unreachable!()
};
journal
.record_create(
plan.clone(),
entry.created_fingerprint().unwrap().clone(),
&[ItemOutcome::new(
ItemId::new(1),
ItemPhase::Succeeded,
CommitOutcome::Committed,
SourceCleanupOutcome::NotRequired,
)],
)
.unwrap();
let prepared = prepare_undo(
&entry,
PlanId::new(50),
PlanGeneration::new(50),
backends(&memory_backend(&fs)),
)
.await
.unwrap();
fs.fail_after_apply(TransferOperation::RemoveFile, FsError::Timeout);
let result = prepared.execute(&CancellationToken::new()).await;
assert_eq!(
actions(&result)[0].outcome().commit(),
CommitOutcome::Unknown
);
assert_eq!(operation_count(&fs, TransferOperation::RemoveFile), 1);
assert_eq!(fs.file_contents(&created), Err(FsError::NotFound));
assert!(!consume_undo_on_success(&mut journal, &entry, &result));
assert_eq!(journal.len(), 1);
}
#[tokio::test]
async fn successful_consume_acknowledgement_is_single_shot_and_cancel_retains_entry() {
let parent = Location::local("/work");
let fs = MemoryTransferFs::local().with_dir(parent.clone());
let (entry, created) =
memory_create_entry(&fs, parent, "created", EntryMutationKind::CreateFile).await;
let mut journal = UndoJournal::new();
let UndoEntry::Create { plan, .. } = &entry else {
unreachable!()
};
journal
.record_create(
plan.clone(),
entry.created_fingerprint().unwrap().clone(),
&[ItemOutcome::new(
ItemId::new(1),
ItemPhase::Succeeded,
CommitOutcome::Committed,
SourceCleanupOutcome::NotRequired,
)],
)
.unwrap();
let prepared = prepare_undo(
&entry,
PlanId::new(60),
PlanGeneration::new(60),
backends(&memory_backend(&fs)),
)
.await
.unwrap();
let cancelled_token = CancellationToken::new();
cancelled_token.cancel();
let cancelled = prepared.execute(&cancelled_token).await;
assert!(!consume_undo_on_success(&mut journal, &entry, &cancelled));
assert_eq!(journal.len(), 1);
assert_eq!(fs.file_contents(&created).unwrap(), b"");
let result = prepared.execute(&CancellationToken::new()).await;
assert!(result.is_fully_successful());
assert!(consume_undo_on_success(&mut journal, &entry, &result));
assert!(!consume_undo_on_success(&mut journal, &entry, &result));
assert!(journal.is_empty());
assert_eq!(operation_count(&fs, TransferOperation::RemoveFile), 1);
}
#[tokio::test]
async fn rename_observer_delivers_started_then_finished() {
let old = Location::local("/work/old");
let fs = MemoryTransferFs::local().with_file(old.clone(), b"source");
let (entry, _, _) = memory_rename_entry(&fs, old, "new").await;
let prepared = prepare_undo(
&entry,
PlanId::new(70),
PlanGeneration::new(70),
backends(&memory_backend(&fs)),
)
.await
.unwrap();
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 result = prepared
.execute_observed(&CancellationToken::new(), &mut observer)
.await;
let events = events.lock().unwrap_or_else(|error| error.into_inner());
assert_eq!(events.len(), 2);
assert!(matches!(
events[0],
UndoEvent::ItemStarted(id) if id == ItemId::new(2)
));
assert!(matches!(events[1], UndoEvent::ItemFinished(_)));
drop(events);
assert!(result.is_fully_successful());
}
#[tokio::test]
async fn fixed_tree_trash_journal_is_root_scoped_and_changed_descendant_blocks_all_roots() {
let fixture = TempDir::new().unwrap();
let work = fixture.path().join("work");
let tree_path = work.join("tree");
let nested_path = tree_path.join("nested");
let leaf_path = nested_path.join("leaf.txt");
let other_path = work.join("other.txt");
std::fs::create_dir_all(&nested_path).unwrap();
std::fs::write(&leaf_path, b"confirmed leaf").unwrap();
std::fs::write(&other_path, b"other").unwrap();
let backend = local_backend();
let policy = TrashPolicy::new(
Location::local(fixture.path().join("trash")),
Some(Location::local(fixture.path())),
)
.unwrap();
let (plan, records) = prepare_trash(
PlanId::new(75),
PlanGeneration::new(75),
vec![Location::local(&other_path), Location::local(&tree_path)],
BTreeMap::new(),
&backend,
&policy,
)
.await
.unwrap();
let roots: Vec<_> = plan.nodes().iter().filter(|node| node.is_root()).collect();
assert_eq!(roots.len(), 2);
assert_eq!(plan.nodes().len(), 4);
assert_eq!(records.len(), roots.len());
let results = execute_trash(
&plan,
&records,
&backend,
&policy,
&CancellationToken::new(),
)
.await;
assert_eq!(results.len(), roots.len());
assert!(results.iter().all(|result| {
result.outcome().phase() == ItemPhase::Succeeded
&& roots.iter().any(|root| root.id() == result.outcome().id())
}));
let outcomes: Vec<_> = results.iter().map(ActionResult::outcome).collect();
let mut journal = UndoJournal::new();
journal
.record_trash(plan.clone(), records.clone(), &outcomes)
.unwrap();
assert_eq!(journal.len(), 1);
let Some(UndoEntry::Trash {
plan: recorded_plan,
records: recorded_records,
}) = journal.latest()
else {
unreachable!()
};
assert_eq!(recorded_plan.nodes().len(), 4);
assert_eq!(recorded_records.len(), 2);
let descendant = plan.nodes().iter().find(|node| !node.is_root()).unwrap();
let mut descendant_outcomes = outcomes.clone();
descendant_outcomes.push(ItemOutcome::new(
descendant.id(),
ItemPhase::Succeeded,
CommitOutcome::Committed,
SourceCleanupOutcome::NotRequired,
));
let before = journal.clone();
assert_eq!(
journal.record_trash(plan.clone(), records.clone(), &descendant_outcomes),
Err(UndoRecordError::UnexpectedOutcome(descendant.id()))
);
let mut descendant_records = records.clone();
descendant_records.push(
TrashRecord::new(
descendant.location().clone(),
policy
.root()
.join("files")
.join(Uuid::from_u128(999).to_string()),
descendant.fingerprint().unwrap().clone(),
0,
Uuid::from_u128(999),
)
.unwrap(),
);
assert_eq!(
journal.record_trash(plan.clone(), descendant_records, &outcomes),
Err(UndoRecordError::TrashRecordCountMismatch)
);
assert_eq!(journal, before);
let entry = journal.latest().cloned().unwrap();
let tree_record = records
.iter()
.find(|record| record.original() == &Location::local(&tree_path))
.unwrap();
let other_record = records
.iter()
.find(|record| record.original() == &Location::local(&other_path))
.unwrap();
std::fs::write(
tree_record.trashed().path().join("nested/leaf.txt"),
b"changed after trash",
)
.unwrap();
let prepared = prepare_undo(
&entry,
PlanId::new(76),
PlanGeneration::new(76),
backends(&backend),
)
.await;
assert!(prepared.is_err(), "changed descendant was accepted");
assert!(!tree_path.exists(), "changed root was restored");
assert!(!other_path.exists(), "another root was restored first");
assert_eq!(
std::fs::read(other_record.trashed().path()).unwrap(),
b"other"
);
assert_eq!(journal.len(), 1);
}
#[derive(Clone, Default)]
struct SharedReadFs(Arc<Mutex<MemoryFs>>);
impl SharedReadFs {
fn new(fs: MemoryFs) -> Self {
Self(Arc::new(Mutex::new(fs)))
}
fn replace(&self, fs: MemoryFs) {
*self.0.lock().unwrap_or_else(|error| error.into_inner()) = fs;
}
fn snapshot(&self) -> MemoryFs {
self.0
.lock()
.unwrap_or_else(|error| error.into_inner())
.clone()
}
}
#[async_trait]
impl ReadFileSystem for SharedReadFs {
async fn list(&self, location: &Location) -> Result<Vec<Entry>, FsError> {
self.snapshot().list(location).await
}
async fn canonicalize(&self, location: &Location) -> Result<Location, FsError> {
self.snapshot().canonicalize(location).await
}
async fn metadata(&self, location: &Location) -> Result<Entry, FsError> {
self.snapshot().metadata(location).await
}
async fn read_prefix(&self, location: &Location, limit: usize) -> Result<ReadPrefix, FsError> {
self.snapshot().read_prefix(location, limit).await
}
}
struct MoveFixture {
entry: UndoEntry,
source: MemoryTransferFs,
destination: MemoryTransferFs,
source_read: SharedReadFs,
destination_read: SharedReadFs,
original_tree: Location,
original_other: Location,
current_tree: Location,
current_other: Location,
}
async fn move_fixture(local: bool) -> MoveFixture {
move_fixture_inner(local, false).await
}
async fn dual_remote_move_fixture() -> MoveFixture {
move_fixture_inner(false, true).await
}
async fn move_fixture_inner(local: bool, separate_remote: bool) -> MoveFixture {
let (source_endpoint, destination_endpoint, source_epoch, destination_epoch) = if local {
(SourceId::Local, SourceId::Local, 0, 0)
} else if separate_remote {
(
SourceId::Ssh(HostAlias::new("source")),
SourceId::Ssh(HostAlias::new("destination")),
11,
22,
)
} else {
let endpoint = SourceId::Ssh(HostAlias::new("edge"));
(endpoint.clone(), endpoint, 11, 11)
};
let at = |endpoint: &SourceId, path: &str| Location {
source: endpoint.clone(),
path: path.into(),
};
let original_tree = at(&source_endpoint, "/work/tree");
let original_child = original_tree.join("child");
let original_other = at(&source_endpoint, "/work/other");
let original_parent = at(&source_endpoint, "/work");
let destination_root = at(&destination_endpoint, "/destination");
let current_tree = destination_root.join("tree");
let current_other = destination_root.join("other");
let source = MemoryTransferFs::new(source_endpoint.clone(), source_epoch)
.with_dir(original_tree.clone())
.with_file(original_child.clone(), b"child")
.with_file(original_other.clone(), b"other");
let destination = if source_endpoint == destination_endpoint {
source.insert_dir(destination_root.clone());
source.clone()
} else {
MemoryTransferFs::new(destination_endpoint.clone(), destination_epoch)
.with_dir(destination_root.clone())
};
let source_read = SharedReadFs::new(
MemoryFs::new()
.with_dir(original_tree.clone())
.with_file(original_child, "child")
.with_file(original_other.clone(), "other"),
);
let destination_read = SharedReadFs::new(MemoryFs::new().with_dir(destination_root.clone()));
let source_backend = BackendHandle::new(
source_endpoint.clone(),
Arc::new(source_read.clone()),
Arc::new(source.clone()),
)
.unwrap();
let destination_backend = BackendHandle::new(
destination_endpoint.clone(),
Arc::new(destination_read.clone()),
Arc::new(destination.clone()),
)
.unwrap();
let planner = OperationPlanner::new(
Arc::new(source_backend.clone()),
Arc::new(destination_backend.clone()),
);
let prepared = planner
.prepare(OperationRequest::new(
PlanId::new(80),
PlanGeneration::new(81),
OperationKind::Move,
vec![original_other.clone(), original_tree.clone()],
destination_root,
CollisionPolicy::Ask,
BTreeMap::from([
(source_endpoint, source_epoch),
(destination_endpoint, destination_epoch),
]),
))
.await
.unwrap();
if separate_remote {
// This fixture begins after a successful cross-endpoint original move. The shared double
// intentionally lacks directory staging; undo success itself is exercised with atomic
// same-endpoint SSH rename above, while this fixture tests independent endpoint epochs.
for item in prepared.items() {
match item.kind() {
EntryKind::Directory => destination.insert_dir(item.destination().clone()),
EntryKind::File => {
let contents = source.file_contents(item.source()).unwrap();
destination.insert_file(item.destination().clone(), &contents);
}
EntryKind::Symlink | EntryKind::Other => unreachable!("planner rejects these"),
}
}
for item in prepared.items().iter().rev() {
match item.kind() {
EntryKind::Directory => source.remove_dir(item.source()).await.unwrap(),
EntryKind::File => source.remove_file(item.source()).await.unwrap(),
EntryKind::Symlink | EntryKind::Other => unreachable!(),
}
}
} else {
let results = rcom::fs::execute_prepared_copy_move(
&prepared,
&source_backend,
&destination_backend,
&CancellationToken::new(),
)
.await;
assert!(
results.iter().all(|result| {
result.outcome().phase() == ItemPhase::Succeeded
&& result.outcome().commit() == CommitOutcome::Committed
&& result.outcome().source_cleanup() == SourceCleanupOutcome::Removed
}),
"original move failed: {results:?}"
);
}
let mut destination_fingerprints = BTreeMap::new();
for item in prepared.items() {
destination_fingerprints.insert(
item.id(),
fingerprint(&destination_backend, item.destination()).await,
);
}
destination_read.replace(
MemoryFs::new()
.with_dir(current_tree.clone())
.with_file(current_tree.join("child"), "child")
.with_file(current_other.clone(), "other"),
);
// The original source read model is replaced too if a later local inverse plan traverses it.
source_read.replace(MemoryFs::new().with_dir(original_parent));
MoveFixture {
entry: UndoEntry::Move {
operation: prepared,
destination_fingerprints,
},
source,
destination,
source_read,
destination_read,
original_tree,
original_other,
current_tree,
current_other,
}
}
impl MoveFixture {
fn backends(&self) -> BTreeMap<SourceId, BackendHandle> {
let source_backend = BackendHandle::new(
self.source.source_id().clone(),
Arc::new(self.source_read.clone()),
Arc::new(self.source.clone()),
)
.unwrap();
let destination_backend = BackendHandle::new(
self.destination.source_id().clone(),
Arc::new(self.destination_read.clone()),
Arc::new(self.destination.clone()),
)
.unwrap();
BTreeMap::from([
(self.source.source_id().clone(), source_backend),
(self.destination.source_id().clone(), destination_backend),
])
}
}
async fn assert_move_undo_success(local: bool) {
let fixture = move_fixture(local).await;
let prepared = prepare_undo(
&fixture.entry,
PlanId::new(90),
PlanGeneration::new(91),
fixture.backends(),
)
.await
.unwrap();
let PreparedUndoKind::Move { operation } = prepared.kind() else {
panic!("expected inverse move")
};
assert_eq!(operation.plan().kind(), OperationKind::Move);
assert_eq!(operation.plan().id(), PlanId::new(90));
assert_eq!(operation.items().len(), 3);
let result = prepared.execute(&CancellationToken::new()).await;
assert!(result.is_fully_successful(), "{:?}", result.outcomes());
assert_eq!(
fixture
.source
.file_contents(&fixture.original_tree.join("child"))
.unwrap(),
b"child"
);
assert_eq!(
fixture
.source
.file_contents(&fixture.original_other)
.unwrap(),
b"other"
);
assert_eq!(
fixture.destination.file_contents(&fixture.current_other),
Err(FsError::NotFound)
);
assert_eq!(
FileOperations::metadata(&fixture.destination, &fixture.current_tree, false,).await,
Err(FsError::NotFound)
);
}
#[tokio::test]
async fn local_and_fake_ssh_undo_move_restore_the_complete_recorded_tree() {
assert_move_undo_success(true).await;
assert_move_undo_success(false).await;
}
#[tokio::test]
async fn inverse_move_rejects_changed_descendant_new_item_and_original_conflict() {
for mode in 0..3 {
let fixture = move_fixture(false).await;
match mode {
0 => fixture
.destination
.insert_file(fixture.current_tree.join("child"), b"changed after move"),
1 => fixture
.destination
.insert_file(fixture.current_tree.join("external"), b"external"),
2 => fixture
.source
.insert_file(fixture.original_other.clone(), b"conflict"),
_ => unreachable!(),
}
if mode == 1 {
fixture.destination_read.replace(
MemoryFs::new()
.with_dir(fixture.current_tree.clone())
.with_file(fixture.current_tree.join("child"), "child")
.with_file(fixture.current_tree.join("external"), "external")
.with_file(fixture.current_other.clone(), "other"),
);
}
let before = operation_count(&fixture.source, TransferOperation::Rename)
+ operation_count(&fixture.destination, TransferOperation::Rename);
let result = prepare_undo(
&fixture.entry,
PlanId::new(92),
PlanGeneration::new(92),
fixture.backends(),
)
.await;
assert!(result.is_err(), "mode {mode} unexpectedly prepared");
let after = operation_count(&fixture.source, TransferOperation::Rename)
+ operation_count(&fixture.destination, TransferOperation::Rename);
assert_eq!(after, before, "mode {mode} attempted an inverse mutation");
}
}
#[tokio::test]
async fn inverse_move_checks_each_endpoint_epoch_and_cancel_before_mutation() {
for stale_source in [false, true] {
let fixture = dual_remote_move_fixture().await;
if stale_source {
let _ = fixture.source.reconnect(12);
} else {
let _ = fixture.destination.reconnect(23);
}
let result = prepare_undo(
&fixture.entry,
PlanId::new(93),
PlanGeneration::new(93),
fixture.backends(),
)
.await;
assert!(result.is_err(), "stale_source={stale_source}");
assert_eq!(
fixture.source.file_contents(&fixture.original_other),
Err(FsError::NotFound)
);
assert_eq!(
fixture
.destination
.file_contents(&fixture.current_other)
.unwrap(),
b"other"
);
}
let fixture = move_fixture(false).await;
let prepared = prepare_undo(
&fixture.entry,
PlanId::new(94),
PlanGeneration::new(94),
fixture.backends(),
)
.await
.unwrap();
let cancellation = CancellationToken::new();
cancellation.cancel();
let result = prepared.execute(&cancellation).await;
assert_eq!(result.outcomes().len(), 2);
assert!(
result
.outcomes()
.iter()
.all(|outcome| outcome.phase() == ItemPhase::Cancelled)
);
assert_eq!(
fixture
.destination
.file_contents(&fixture.current_other)
.unwrap(),
b"other"
);
}
#[tokio::test]
async fn move_revalidation_after_confirmation_precedes_any_mutation() {
let fixture = move_fixture(false).await;
let prepared = prepare_undo(
&fixture.entry,
PlanId::new(95),
PlanGeneration::new(95),
fixture.backends(),
)
.await
.unwrap();
fixture
.destination
.insert_file(fixture.current_other.clone(), b"changed later");
let before = operation_count(&fixture.source, TransferOperation::Rename)
+ operation_count(&fixture.destination, TransferOperation::Rename)
+ operation_count(&fixture.source, TransferOperation::Commit)
+ operation_count(&fixture.destination, TransferOperation::Commit);
let result = prepared.execute(&CancellationToken::new()).await;
assert!(!result.is_fully_successful());
assert!(result.actions().is_some());
assert!(
result
.outcomes()
.iter()
.all(|outcome| outcome.commit() == CommitOutcome::NotAttempted)
);
let after = operation_count(&fixture.source, TransferOperation::Rename)
+ operation_count(&fixture.destination, TransferOperation::Rename)
+ operation_count(&fixture.source, TransferOperation::Commit)
+ operation_count(&fixture.destination, TransferOperation::Commit);
assert_eq!(after, before);
assert_eq!(
fixture
.destination
.file_contents(&fixture.current_other)
.unwrap(),
b"changed later"
);
}