use std::collections::BTreeMap; use std::sync::Arc; use proptest::prelude::*; use rcom::actions::{ EntryMutationKind, EntryMutationNode, EntryMutationPlan, TrashRecord, UndoEntry, UndoJournal, UndoRecordError, }; use rcom::domain::{Entry, EntryKind, HostAlias, Location, SourceId}; use rcom::fs::BackendHandle; use rcom::operations::{ CollisionPolicy, CommitOutcome, EntryFingerprint, ItemId, ItemOutcome, ItemPhase, OperationKind, OperationPlanner, OperationRequest, PlanGeneration, PlanId, PreparedOperation, SourceCleanupOutcome, }; use rcom::test_support::{MemoryFs, MemoryTransferFs}; use uuid::Uuid; fn fingerprint(kind: EntryKind) -> EntryFingerprint { EntryFingerprint::from(&Entry::new("snapshot", kind).with_metadata(Some(17), None, Some(0o600))) } fn succeeded(id: ItemId) -> ItemOutcome { ItemOutcome::new( id, ItemPhase::Succeeded, CommitOutcome::Committed, SourceCleanupOutcome::NotRequired, ) } fn create_plan(id: u64, kind: EntryMutationKind) -> EntryMutationPlan { EntryMutationPlan::create( PlanId::new(id), PlanGeneration::new(id), kind, ItemId::new(id), Location::local("/work"), format!("created-{id}"), BTreeMap::from([(SourceId::Local, id + 10_000)]), ) .expect("the generated create plan is valid") } fn rename_plan(id: u64) -> EntryMutationPlan { EntryMutationPlan::rename( PlanId::new(id), PlanGeneration::new(id), ItemId::new(id), Location::local(format!("/work/old-{id}")), fingerprint(EntryKind::File), format!("new-{id}"), BTreeMap::from([(SourceId::Local, id + 20_000)]), ) .expect("the generated rename plan is valid") } fn trash_plan(id: u64, count: usize) -> EntryMutationPlan { let source = Location::local("/work"); let nodes = (0..count) .map(|index| { let name = format!("item-{index}"); EntryMutationNode::new( ItemId::new(index as u64 + 1), source.join(&name), name, Some(fingerprint(EntryKind::File)), ) }) .collect(); EntryMutationPlan::new( PlanId::new(id), PlanGeneration::new(id), EntryMutationKind::Trash, source, Some(Location::local("/trash")), nodes, BTreeMap::from([(SourceId::Local, 77)]), ) .expect("the generated trash plan is valid") } fn trash_records(plan: &EntryMutationPlan) -> Vec { plan.nodes() .iter() .map(|node| { TrashRecord::new( node.location().clone(), Location::local(format!("/trash/files/{}", node.id().get())), node.fingerprint() .expect("trash nodes have fingerprints") .clone(), 77, Uuid::from_u128(u128::from(node.id().get())), ) .expect("same-endpoint trash records are valid") }) .collect() } async fn prepared_operation(id: u64, kind: OperationKind) -> PreparedOperation { let source_endpoint = SourceId::Ssh(HostAlias::new("source")); let destination_endpoint = SourceId::Ssh(HostAlias::new("destination")); let tree = Location::ssh(HostAlias::new("source"), "/work/tree"); let child = Location::ssh(HostAlias::new("source"), "/work/tree/child"); let other = Location::ssh(HostAlias::new("source"), "/work/other"); let destination_root = Location::ssh(HostAlias::new("destination"), "/destination"); let source_read = Arc::new( MemoryFs::new() .with_dir(tree.clone()) .with_file(child.clone(), "child") .with_file(other.clone(), "other"), ); let source_transfer = Arc::new( MemoryTransferFs::new(source_endpoint.clone(), 11) .with_dir(tree) .with_file(child, "child") .with_file(other, "other"), ); let destination_read = Arc::new(MemoryFs::new().with_dir(destination_root.clone())); let destination_transfer = Arc::new( MemoryTransferFs::new(destination_endpoint.clone(), 22).with_dir(destination_root.clone()), ); let source_handle = BackendHandle::new(source_endpoint.clone(), source_read, source_transfer) .expect("source adapters have the same endpoint"); let destination_handle = BackendHandle::new( destination_endpoint.clone(), destination_read, destination_transfer, ) .expect("destination adapters have the same endpoint"); OperationPlanner::new(Arc::new(source_handle), Arc::new(destination_handle)) .prepare(OperationRequest::new( PlanId::new(id), PlanGeneration::new(id + 1), kind, vec![ Location::ssh(HostAlias::new("source"), "/work/tree"), Location::ssh(HostAlias::new("source"), "/work/other"), ], Location::ssh(HostAlias::new("destination"), "/destination"), CollisionPolicy::Ask, BTreeMap::from([(source_endpoint, 11), (destination_endpoint, 22)]), )) .await .expect("the in-memory prepared operation is valid") } fn root_outcomes(operation: &PreparedOperation) -> Vec { operation .plan() .sources() .iter() .map(|source| succeeded(source.id())) .collect() } fn moved_fingerprints(operation: &PreparedOperation) -> BTreeMap { operation .items() .iter() .map(|item| (item.id(), item.fingerprint().clone())) .collect() } #[tokio::test] async fn entries_capture_complete_immutable_snapshots_fingerprints_and_epochs() { let mut journal = UndoJournal::new(); let create = create_plan(1, EntryMutationKind::CreateFile); let create_epochs = create.endpoint_epochs().clone(); let created_fingerprint = fingerprint(EntryKind::File); journal .record_create( create.clone(), created_fingerprint.clone(), &[succeeded(ItemId::new(1))], ) .unwrap(); let rename = rename_plan(2); let renamed_fingerprint = fingerprint(EntryKind::File); journal .record_rename( rename.clone(), renamed_fingerprint.clone(), &[succeeded(ItemId::new(2))], ) .unwrap(); let movement = prepared_operation(3, OperationKind::Move).await; let destination_fingerprints = moved_fingerprints(&movement); journal .record_move( movement.clone(), destination_fingerprints.clone(), &root_outcomes(&movement), ) .unwrap(); let trash = trash_plan(4, 2); let records = trash_records(&trash); journal .record_trash( trash.clone(), records.clone(), &[succeeded(ItemId::new(2)), succeeded(ItemId::new(1))], ) .unwrap(); let entry = journal.latest().unwrap(); assert_eq!(entry.mutation_plan(), Some(&trash)); assert_eq!(entry.trash_records(), Some(records.as_slice())); assert_eq!(entry.endpoint_epochs(), trash.endpoint_epochs()); let entry = journal.take_last().unwrap(); assert!(matches!(entry, UndoEntry::Trash { .. })); let entry = journal.latest().unwrap(); assert_eq!(entry.prepared_operation(), Some(&movement)); assert_eq!(entry.operation_plan(), Some(movement.plan())); assert_eq!( entry.destination_fingerprints(), Some(&destination_fingerprints) ); assert_eq!(entry.endpoint_epochs(), movement.plan().endpoint_epochs()); assert_eq!(entry.plan_id(), PlanId::new(3)); assert_eq!(entry.generation(), PlanGeneration::new(4)); journal.take_last().unwrap(); let entry = journal.latest().unwrap(); assert_eq!(entry.mutation_plan(), Some(&rename)); assert_eq!(entry.renamed_fingerprint(), Some(&renamed_fingerprint)); journal.take_last().unwrap(); let entry = journal.latest().unwrap(); assert_eq!(entry.mutation_plan(), Some(&create)); assert_eq!(entry.created_fingerprint(), Some(&created_fingerprint)); assert_eq!(entry.endpoint_epochs(), &create_epochs); assert!(journal.warnings().is_empty()); } #[tokio::test] async fn copy_permanent_delete_and_partial_results_leave_the_journal_unchanged() { let mut journal = UndoJournal::new(); journal .record_create( create_plan(90, EntryMutationKind::CreateFile), fingerprint(EntryKind::File), &[succeeded(ItemId::new(90))], ) .unwrap(); let before = journal.clone(); let copy = prepared_operation(91, OperationKind::Copy).await; assert_eq!( journal.record_move( copy.clone(), moved_fingerprints(©), &root_outcomes(©), ), Err(UndoRecordError::CopyNotUndoable) ); assert_eq!(journal, before); let movement = prepared_operation(92, OperationKind::Move).await; let mut partial_move = root_outcomes(&movement); partial_move[1] = ItemOutcome::new( partial_move[1].id(), ItemPhase::Succeeded, CommitOutcome::Committed, SourceCleanupOutcome::Failed, ); assert_eq!( journal.record_move( movement.clone(), moved_fingerprints(&movement), &partial_move, ), Err(UndoRecordError::UnsuccessfulOutcome(partial_move[1].id())) ); assert_eq!(journal, before); let trash = trash_plan(93, 2); let partial_trash = [ succeeded(ItemId::new(1)), ItemOutcome::new( ItemId::new(2), ItemPhase::Failed, CommitOutcome::Unknown, SourceCleanupOutcome::NotAttempted, ), ]; assert_eq!( journal.record_trash(trash.clone(), trash_records(&trash), &partial_trash), Err(UndoRecordError::UnsuccessfulOutcome(ItemId::new(2))) ); assert_eq!(journal, before); let cancelled_rename = [ItemOutcome::new( ItemId::new(94), ItemPhase::Cancelled, CommitOutcome::NotAttempted, SourceCleanupOutcome::NotAttempted, )]; assert_eq!( journal.record_rename( rename_plan(94), fingerprint(EntryKind::File), &cancelled_rename, ), Err(UndoRecordError::UnsuccessfulOutcome(ItemId::new(94))) ); assert_eq!(journal, before); let delete = EntryMutationPlan::new( PlanId::new(95), PlanGeneration::new(95), EntryMutationKind::Delete, Location::local("/work"), None, vec![EntryMutationNode::new( ItemId::new(95), Location::local("/work/permanent"), "permanent", Some(fingerprint(EntryKind::File)), )], BTreeMap::new(), ) .unwrap(); assert_eq!( journal.record_create(delete, fingerprint(EntryKind::File), &[]), Err(UndoRecordError::UnsupportedMutation( EntryMutationKind::Delete )) ); assert_eq!(journal, before); // There is deliberately no record_copy, record_delete, or record_edit API. } #[tokio::test] async fn outcome_and_trash_record_order_do_not_change_entries() { let mut forward = UndoJournal::new(); let mut reversed = UndoJournal::new(); let trash = trash_plan(120, 8); let records = trash_records(&trash); let mut reversed_records = records.clone(); reversed_records.reverse(); let outcomes: Vec<_> = (1..=8).map(|id| succeeded(ItemId::new(id))).collect(); let mut reversed_outcomes = outcomes.clone(); reversed_outcomes.reverse(); forward .record_trash(trash.clone(), records, &outcomes) .unwrap(); reversed .record_trash(trash, reversed_records, &reversed_outcomes) .unwrap(); assert_eq!(forward.latest(), reversed.latest()); let first = prepared_operation(121, OperationKind::Move).await; let second = prepared_operation(121, OperationKind::Move).await; let outcomes = root_outcomes(&first); let mut reversed_outcomes = outcomes.clone(); reversed_outcomes.reverse(); forward .record_move(first.clone(), moved_fingerprints(&first), &outcomes) .unwrap(); reversed .record_move( second.clone(), moved_fingerprints(&second), &reversed_outcomes, ) .unwrap(); assert_eq!(forward.latest(), reversed.latest()); } fn outcome_strategy(id: u64) -> impl Strategy { (0..4_usize, 0..4_usize, 0..5_usize).prop_map(move |(phase, commit, cleanup)| { let phases = [ ItemPhase::Succeeded, ItemPhase::Skipped, ItemPhase::Failed, ItemPhase::Cancelled, ]; let commits = [ CommitOutcome::NotAttempted, CommitOutcome::NotCommitted, CommitOutcome::Committed, CommitOutcome::Unknown, ]; let cleanups = [ SourceCleanupOutcome::NotRequired, SourceCleanupOutcome::NotAttempted, SourceCleanupOutcome::Removed, SourceCleanupOutcome::Partial, SourceCleanupOutcome::Failed, ]; ItemOutcome::new( ItemId::new(id), phases[phase], commits[commit], cleanups[cleanup], ) }) } fn is_full_success(outcome: ItemOutcome) -> bool { outcome.phase() == ItemPhase::Succeeded && outcome.commit() == CommitOutcome::Committed && matches!( outcome.source_cleanup(), SourceCleanupOutcome::NotRequired | SourceCleanupOutcome::Removed ) } proptest! { #[test] fn journal_is_lifo_and_evicts_only_the_oldest_with_warnings( ids in prop::collection::vec(0_u64..1_000, 0..300), ) { let mut journal = UndoJournal::default(); for id in &ids { journal.record_create( create_plan(*id, EntryMutationKind::CreateFile), fingerprint(EntryKind::File), &[succeeded(ItemId::new(*id))], ).expect("every generated outcome is fully successful"); } let retained_from = ids.len().saturating_sub(UndoJournal::CAPACITY); prop_assert_eq!(journal.len(), ids.len().min(UndoJournal::CAPACITY)); prop_assert_eq!(journal.is_empty(), ids.is_empty()); prop_assert_eq!(journal.warnings().len(), retained_from); for (index, warning) in journal.warnings().iter().enumerate() { let evicted = format!("oldest plan {}", ids[index]); prop_assert!(warning.contains(evicted.as_str())); } for id in ids[retained_from..].iter().rev() { prop_assert_eq!(journal.take_last().map(|entry| entry.plan_id()), Some(PlanId::new(*id))); } prop_assert!(journal.take_last().is_none()); prop_assert!(journal.is_empty()); } #[test] fn only_fully_successful_outcomes_are_recorded(outcome in outcome_strategy(7)) { let mut journal = UndoJournal::new(); journal.record_create( create_plan(6, EntryMutationKind::CreateFile), fingerprint(EntryKind::File), &[succeeded(ItemId::new(6))], ).unwrap(); let before = journal.clone(); let result = journal.record_create( create_plan(7, EntryMutationKind::CreateFile), fingerprint(EntryKind::File), &[outcome], ); if is_full_success(outcome) { prop_assert!(result.is_ok()); prop_assert_eq!(journal.len(), 2); prop_assert_eq!(journal.latest().map(UndoEntry::plan_id), Some(PlanId::new(7))); } else { prop_assert_eq!(result, Err(UndoRecordError::UnsuccessfulOutcome(ItemId::new(7)))); prop_assert_eq!(&journal, &before); } } #[test] fn trash_outcome_and_record_order_are_independent( count in 1_usize..16, reverse in any::(), rotation in any::(), ) { let plan = trash_plan(200, count); let records = trash_records(&plan); let outcomes: Vec<_> = plan.nodes().iter().map(|node| succeeded(node.id())).collect(); let mut reordered_records = records.clone(); let mut reordered_outcomes = outcomes.clone(); if reverse { reordered_records.reverse(); reordered_outcomes.reverse(); } let rotation = rotation % count; reordered_records.rotate_left(rotation); reordered_outcomes.rotate_left(rotation); let mut canonical = UndoJournal::new(); let mut reordered = UndoJournal::new(); canonical.record_trash(plan.clone(), records, &outcomes).unwrap(); reordered.record_trash(plan, reordered_records, &reordered_outcomes).unwrap(); prop_assert_eq!(canonical.latest(), reordered.latest()); } #[test] fn restart_default_is_empty_after_any_history( ids in prop::collection::vec(0_u64..1_000, 0..300), ) { let mut current = UndoJournal::new(); for id in ids { current.record_create( create_plan(id, EntryMutationKind::CreateFile), fingerprint(EntryKind::File), &[succeeded(ItemId::new(id))], ).unwrap(); } let mut restarted = UndoJournal::default(); prop_assert_eq!(restarted.len(), 0); prop_assert!(restarted.is_empty()); prop_assert!(restarted.latest().is_none()); prop_assert!(restarted.take_last().is_none()); prop_assert!(restarted.warnings().is_empty()); } }