use std::collections::BTreeMap; use std::sync::Arc; use rcom::actions::{ ActionResult, EntryMutationKind, EntryMutationPlan, MutationStage, execute_entry_mutation, }; use rcom::domain::{EntryKind, HostAlias, Location, SourceId}; use rcom::fs::{BackendHandle, FileOperations, FsError}; use rcom::operations::{ CommitOutcome, EntryFingerprint, ItemId, ItemPhase, PlanGeneration, PlanId, SourceCleanupOutcome, }; use rcom::test_support::{MemoryFs, MemoryTransferFs, TransferJournalEntry, TransferOperation}; use tokio_util::sync::CancellationToken; fn backend(fs: &MemoryTransferFs) -> BackendHandle { BackendHandle::new( fs.source_id().clone(), Arc::new(MemoryFs::new()), Arc::new(fs.clone()), ) .expect("matching in-memory endpoint") } fn create_plan(kind: EntryMutationKind, parent: Location, name: &str) -> EntryMutationPlan { EntryMutationPlan::create( PlanId::new(1), PlanGeneration::new(1), kind, ItemId::new(11), parent, name, BTreeMap::new(), ) .expect("valid create plan") } fn rename_plan_with_fingerprint( source: Location, fingerprint: EntryFingerprint, new_name: &str, endpoint_epochs: BTreeMap, ) -> EntryMutationPlan { EntryMutationPlan::rename( PlanId::new(2), PlanGeneration::new(1), ItemId::new(12), source, fingerprint, new_name, endpoint_epochs, ) .expect("valid rename plan") } async fn rename_plan(fs: &MemoryTransferFs, source: Location, new_name: &str) -> EntryMutationPlan { let fingerprint = EntryFingerprint::from( &fs.metadata(&source, false) .await .expect("source fixture metadata"), ); rename_plan_with_fingerprint(source, fingerprint, new_name, BTreeMap::new()) } fn operation_count(operations: &[TransferJournalEntry], operation: TransferOperation) -> usize { operations .iter() .filter(|entry| entry.operation == operation) .count() } fn assert_committed(result: &ActionResult, id: ItemId) { assert_eq!(result.outcome().id(), id); assert_eq!(result.outcome().phase(), ItemPhase::Succeeded); assert_eq!(result.outcome().commit(), CommitOutcome::Committed); assert_eq!( result.outcome().source_cleanup(), SourceCleanupOutcome::NotRequired ); assert_eq!(result.error(), None); } fn assert_not_attempted(result: &ActionResult, stage: MutationStage) { assert_eq!(result.outcome().phase(), ItemPhase::Failed); assert_eq!(result.outcome().commit(), CommitOutcome::NotAttempted); assert_eq!( result.outcome().source_cleanup(), SourceCleanupOutcome::NotRequired ); assert_eq!(result.stage(), stage); assert!(result.error().is_some()); } #[tokio::test] async fn create_file_commits_one_empty_file_without_source_cleanup() { let parent = Location::local("/work"); let destination = parent.join("new.txt"); let fs = MemoryTransferFs::local().with_dir(parent.clone()); let backend = backend(&fs); let plan = create_plan(EntryMutationKind::CreateFile, parent, "new.txt"); let result = execute_entry_mutation(&plan, &backend, &CancellationToken::new()).await; assert_committed(&result, ItemId::new(11)); assert_eq!(result.stage(), MutationStage::CreateFile); assert_eq!(fs.file_contents(&destination).unwrap(), b""); let operations = fs.operations(); assert_eq!( operation_count(&operations, TransferOperation::CreateFile), 1 ); assert_eq!( operation_count(&operations, TransferOperation::RemoveFile), 0 ); assert_eq!( operation_count(&operations, TransferOperation::RemoveDir), 0 ); } #[tokio::test] async fn create_directory_commits_one_real_directory() { let parent = Location::local("/work"); let destination = parent.join("new-dir"); let fs = MemoryTransferFs::local().with_dir(parent.clone()); let backend = backend(&fs); let plan = create_plan(EntryMutationKind::CreateDirectory, parent, "new-dir"); let result = execute_entry_mutation(&plan, &backend, &CancellationToken::new()).await; assert_committed(&result, ItemId::new(11)); assert_eq!(result.stage(), MutationStage::CreateDirectory); assert_eq!( fs.metadata(&destination, false).await.unwrap().kind, EntryKind::Directory ); let operations = fs.operations(); assert_eq!( operation_count(&operations, TransferOperation::CreateDir), 1 ); assert_eq!( operation_count(&operations, TransferOperation::CreateFile), 0 ); } #[tokio::test] async fn rename_preserves_file_contents_and_directory_tree() { let file_source = Location::local("/work/old.txt"); let file_destination = Location::local("/work/new.txt"); let directory_source = Location::local("/work/old-dir"); let directory_destination = Location::local("/work/new-dir"); let fs = MemoryTransferFs::local() .with_file(file_source.clone(), b"confirmed contents") .with_dir(directory_source.clone()) .with_file(directory_source.join("child.txt"), b"child"); let backend = backend(&fs); let file_plan = rename_plan(&fs, file_source.clone(), "new.txt").await; let file_result = execute_entry_mutation(&file_plan, &backend, &CancellationToken::new()).await; assert_committed(&file_result, ItemId::new(12)); assert_eq!(file_result.stage(), MutationStage::Rename); assert_eq!(fs.file_contents(&file_source), Err(FsError::NotFound)); assert_eq!( fs.file_contents(&file_destination).unwrap(), b"confirmed contents" ); let directory_plan = rename_plan(&fs, directory_source.clone(), "new-dir").await; let directory_result = execute_entry_mutation(&directory_plan, &backend, &CancellationToken::new()).await; assert_committed(&directory_result, ItemId::new(12)); assert_eq!( fs.metadata(&directory_source, false).await, Err(FsError::NotFound) ); assert_eq!( fs.file_contents(&directory_destination.join("child.txt")) .unwrap(), b"child" ); assert_eq!( operation_count(&fs.operations(), TransferOperation::Rename), 2 ); assert_eq!( operation_count(&fs.operations(), TransferOperation::RemoveFile), 0 ); assert_eq!( operation_count(&fs.operations(), TransferOperation::RemoveDir), 0 ); } #[tokio::test] async fn create_and_rename_collisions_stop_before_mutation_and_preserve_both_entries() { let parent = Location::local("/work"); let existing = parent.join("taken"); let source = parent.join("source"); let fs = MemoryTransferFs::local() .with_file(existing.clone(), b"destination") .with_file(source.clone(), b"source"); let backend = backend(&fs); let create = create_plan(EntryMutationKind::CreateFile, parent.clone(), "taken"); let create_result = execute_entry_mutation(&create, &backend, &CancellationToken::new()).await; assert_not_attempted(&create_result, MutationStage::Destination); assert_eq!(fs.file_contents(&existing).unwrap(), b"destination"); assert_eq!( operation_count(&fs.operations(), TransferOperation::CreateFile), 0 ); let rename = rename_plan(&fs, source.clone(), "taken").await; let rename_result = execute_entry_mutation(&rename, &backend, &CancellationToken::new()).await; assert_not_attempted(&rename_result, MutationStage::Destination); assert_eq!(fs.file_contents(&source).unwrap(), b"source"); assert_eq!(fs.file_contents(&existing).unwrap(), b"destination"); assert_eq!( operation_count(&fs.operations(), TransferOperation::Rename), 0 ); } #[tokio::test] async fn changed_rename_source_is_rejected_without_mutation() { let source = Location::local("/work/source"); let destination = Location::local("/work/destination"); let fs = MemoryTransferFs::local().with_file(source.clone(), b"confirmed"); let backend = backend(&fs); let plan = rename_plan(&fs, source.clone(), "destination").await; fs.insert_file(source.clone(), b"changed after confirmation"); let result = execute_entry_mutation(&plan, &backend, &CancellationToken::new()).await; assert_not_attempted(&result, MutationStage::SourceFingerprint); assert_eq!( fs.file_contents(&source).unwrap(), b"changed after confirmation" ); assert_eq!(fs.file_contents(&destination), Err(FsError::NotFound)); assert_eq!( operation_count(&fs.operations(), TransferOperation::Rename), 0 ); } #[tokio::test] async fn cancellation_before_execution_does_not_even_recheck_destination() { let parent = Location::local("/work"); let fs = MemoryTransferFs::local().with_dir(parent.clone()); let backend = backend(&fs); let plan = create_plan(EntryMutationKind::CreateFile, parent, "new"); let cancellation = CancellationToken::new(); cancellation.cancel(); let result = execute_entry_mutation(&plan, &backend, &cancellation).await; assert_eq!(result.outcome().phase(), ItemPhase::Cancelled); assert_eq!(result.outcome().commit(), CommitOutcome::NotAttempted); assert_eq!(result.error(), Some(&FsError::Cancelled)); assert!(fs.operations().is_empty()); } #[tokio::test] async fn cancellation_during_source_recheck_prevents_rename() { let source = Location::local("/work/source"); let destination = Location::local("/work/destination"); let fs = MemoryTransferFs::local().with_file(source.clone(), b"source"); let backend = Arc::new(backend(&fs)); let plan = Arc::new(rename_plan(&fs, source.clone(), "destination").await); let cancellation = CancellationToken::new(); let gate = fs.gate_next(TransferOperation::Metadata); let task = { let backend = backend.clone(); let plan = plan.clone(); let cancellation = cancellation.clone(); tokio::spawn(async move { execute_entry_mutation(&plan, &backend, &cancellation).await }) }; gate.wait_entered().await; cancellation.cancel(); gate.release(); let result = task.await.unwrap(); assert_eq!(result.outcome().phase(), ItemPhase::Cancelled); assert_eq!(result.outcome().commit(), CommitOutcome::NotAttempted); assert_eq!(result.stage(), MutationStage::Rename); assert_eq!(result.error(), Some(&FsError::Cancelled)); assert_eq!(fs.file_contents(&source).unwrap(), b"source"); assert_eq!(fs.file_contents(&destination), Err(FsError::NotFound)); assert_eq!( operation_count(&fs.operations(), TransferOperation::Rename), 0 ); } #[tokio::test] async fn create_after_apply_timeout_is_unknown_and_never_retried() { let parent = Location::local("/work"); let destination = parent.join("new"); let fs = MemoryTransferFs::local().with_dir(parent.clone()); let backend = backend(&fs); let plan = create_plan(EntryMutationKind::CreateFile, parent, "new"); fs.fail_after_apply(TransferOperation::CreateFile, FsError::Timeout); let result = execute_entry_mutation(&plan, &backend, &CancellationToken::new()).await; assert_eq!(result.outcome().phase(), ItemPhase::Failed); assert_eq!(result.outcome().commit(), CommitOutcome::Unknown); assert_eq!(result.stage(), MutationStage::CreateFile); assert_eq!(result.error(), Some(&FsError::Timeout)); assert_eq!(fs.file_contents(&destination).unwrap(), b""); assert_eq!( operation_count(&fs.operations(), TransferOperation::CreateFile), 1 ); } #[tokio::test] async fn rename_after_apply_disconnect_reconciles_exact_fingerprint_without_retry() { let source = Location::local("/work/source"); let destination = Location::local("/work/destination"); let fs = MemoryTransferFs::local().with_file(source.clone(), b"source"); let backend = backend(&fs); let plan = rename_plan(&fs, source.clone(), "destination").await; fs.disconnect_after_apply(TransferOperation::Rename); let result = execute_entry_mutation(&plan, &backend, &CancellationToken::new()).await; assert_committed(&result, ItemId::new(12)); assert_eq!(result.stage(), MutationStage::Reconcile); assert_eq!(fs.file_contents(&source), Err(FsError::NotFound)); assert_eq!(fs.file_contents(&destination).unwrap(), b"source"); assert_eq!( operation_count(&fs.operations(), TransferOperation::Rename), 1 ); } #[tokio::test] async fn rename_after_apply_error_stays_unknown_when_reconcile_cannot_prove_commit() { let source = Location::local("/work/source"); let destination = Location::local("/work/destination"); let fs = MemoryTransferFs::local().with_file(source.clone(), b"source"); let backend = backend(&fs); let plan = rename_plan(&fs, source.clone(), "destination").await; fs.disconnect_after_apply(TransferOperation::Rename); fs.pass_next(TransferOperation::Metadata); fs.pass_next(TransferOperation::Metadata); fs.fail_next(TransferOperation::Metadata, FsError::Disconnected); let result = execute_entry_mutation(&plan, &backend, &CancellationToken::new()).await; assert_eq!(result.outcome().phase(), ItemPhase::Failed); assert_eq!(result.outcome().commit(), CommitOutcome::Unknown); assert_eq!(result.stage(), MutationStage::Rename); assert_eq!(result.error(), Some(&FsError::Disconnected)); assert_eq!( operation_count(&fs.operations(), TransferOperation::Rename), 1 ); assert_eq!(fs.file_contents(&source), Err(FsError::NotFound)); assert_eq!(fs.file_contents(&destination).unwrap(), b"source"); } #[tokio::test] async fn rename_error_with_source_still_present_is_unknown_and_not_retried() { let source = Location::local("/work/source"); let destination = Location::local("/work/destination"); let fs = MemoryTransferFs::local().with_file(source.clone(), b"source"); let backend = backend(&fs); let plan = rename_plan(&fs, source.clone(), "destination").await; fs.fail_next(TransferOperation::Rename, FsError::PermissionDenied); let result = execute_entry_mutation(&plan, &backend, &CancellationToken::new()).await; assert_eq!(result.outcome().commit(), CommitOutcome::Unknown); assert_eq!(result.error(), Some(&FsError::PermissionDenied)); assert_eq!( operation_count(&fs.operations(), TransferOperation::Rename), 1 ); assert_eq!(fs.file_contents(&source).unwrap(), b"source"); assert_eq!(fs.file_contents(&destination), Err(FsError::NotFound)); } #[tokio::test] async fn endpoint_mismatch_is_rejected_before_any_backend_call() { let host = HostAlias::new("edge"); let remote_parent = Location::ssh(host, "/work"); let local_fs = MemoryTransferFs::local(); let backend = backend(&local_fs); let plan = create_plan(EntryMutationKind::CreateFile, remote_parent, "new"); let result = execute_entry_mutation(&plan, &backend, &CancellationToken::new()).await; assert_not_attempted(&result, MutationStage::Validation); assert!(local_fs.operations().is_empty()); } #[tokio::test] async fn stale_session_epoch_is_rejected_before_rename() { let host = HostAlias::new("edge"); let endpoint = SourceId::Ssh(host.clone()); let source = Location::ssh(host, "/work/source"); let fs = MemoryTransferFs::new(endpoint.clone(), 7).with_file(source.clone(), b"source"); let backend = backend(&fs); let fingerprint = EntryFingerprint::from(&fs.metadata(&source, false).await.unwrap()); let plan = rename_plan_with_fingerprint( source.clone(), fingerprint, "destination", BTreeMap::from([(endpoint, 7)]), ); let _current = fs.reconnect(8); fs.clear_operations(); let result = execute_entry_mutation(&plan, &backend, &CancellationToken::new()).await; assert_not_attempted(&result, MutationStage::SourceFingerprint); assert_eq!(fs.file_contents(&source).unwrap(), b"source"); assert_eq!( operation_count(&fs.operations(), TransferOperation::Rename), 0 ); }