use std::collections::BTreeMap; use std::sync::Arc; use std::time::Duration; use async_trait::async_trait; use rcom::app::{AppState, Command, Overlay}; use rcom::domain::{Entry, EntryKind, HostAlias, Location, SourceId}; use rcom::fs::{ BackendRegistry, FileOperations, FsError, LocalFs, PartFile, PartWriter, ReadFileSystem, ReadStream, StagingDirectory, StagingOperations, TransferCapabilities, }; use rcom::operations::{CommitOutcome, ItemId, OperationEvent, OperationEventKind, TaskStatus}; use rcom::runtime::EffectRunner; use rcom::ssh::{ConnectionManager, SshConnector}; use rcom::test_support::{MemoryTransferFs, TransferOperation}; use tempfile::TempDir; use tokio::sync::mpsc; /// Applies the first rename and then makes only its two reconciliation reads inconclusive. struct AmbiguousRenameFs { inner: Arc, reconciliation_failures: std::sync::Mutex, } impl AmbiguousRenameFs { fn new(inner: Arc) -> Self { Self { inner, reconciliation_failures: std::sync::Mutex::new(0), } } } #[async_trait] impl StagingOperations for AmbiguousRenameFs { async fn create_dir(&self, location: &Location) -> Result<(), FsError> { self.inner.create_dir(location).await } async fn create_staging_dir( &self, destination: &Location, ) -> Result { self.inner.create_staging_dir(destination).await } } #[async_trait] impl FileOperations for AmbiguousRenameFs { fn source_id(&self) -> &SourceId { self.inner.source_id() } fn capabilities(&self) -> TransferCapabilities { self.inner.capabilities() } async fn canonicalize(&self, location: &Location) -> Result { FileOperations::canonicalize(&*self.inner, location).await } async fn metadata(&self, location: &Location, follow: bool) -> Result { let fail = { let mut failures = self.reconciliation_failures.lock().unwrap(); if *failures > 0 { *failures -= 1; true } else { false } }; if fail { return Err(FsError::Timeout); } FileOperations::metadata(&*self.inner, location, follow).await } async fn open_read(&self, location: &Location) -> Result { self.inner.open_read(location).await } async fn open_part(&self, destination: &Location) -> Result { self.inner.open_part(destination).await } async fn write_part(&self, part: &mut PartWriter, chunk: &[u8]) -> Result<(), FsError> { self.inner.write_part(part, chunk).await } async fn flush_and_close(&self, part: PartWriter) -> Result { self.inner.flush_and_close(part).await } async fn commit_part(&self, part: PartFile) -> Result<(), FsError> { self.inner.commit_part(part).await } async fn discard_part(&self, part: PartFile) -> Result<(), FsError> { self.inner.discard_part(part).await } async fn create_file(&self, location: &Location) -> Result<(), FsError> { self.inner.create_file(location).await } async fn rename(&self, from: &Location, to: &Location) -> Result<(), FsError> { self.inner .fail_after_apply(TransferOperation::Rename, FsError::Timeout); let result = self.inner.rename(from, to).await; if result == Err(FsError::Timeout) { *self.reconciliation_failures.lock().unwrap() = 2; } result } async fn remove_file(&self, location: &Location) -> Result<(), FsError> { self.inner.remove_file(location).await } async fn remove_dir(&self, location: &Location) -> Result<(), FsError> { self.inner.remove_dir(location).await } } struct FakeSsh { read: Arc, operations: Arc, } #[async_trait] impl SshConnector for FakeSsh { async fn connect(&self, _host: &HostAlias) -> Result, FsError> { Ok(self.read.clone()) } async fn connect_with_operations( &self, _host: &HostAlias, _session_epoch: u64, ) -> Result<(Arc, Option>), FsError> { Ok((self.read.clone(), Some(self.operations.clone()))) } } struct Harness { // Keeps the only real filesystem location alive; all mutations remain in MemoryTransferFs. _fixture: TempDir, app: AppState, runner: EffectRunner, results: mpsc::Receiver, fs: Arc, first: Location, second: Location, created: Location, } impl Harness { async fn new() -> Self { Self::with_ambiguous_rename(false).await } async fn ambiguous_trash() -> Self { Self::with_ambiguous_rename(true).await } async fn with_ambiguous_rename(ambiguous_rename: bool) -> Self { let fixture = TempDir::new().unwrap(); let host = HostAlias::new("failure-queue"); let root = Location::ssh(host.clone(), fixture.path().join("work")); let first = root.join("a.txt"); let second = root.join("b.txt"); let created = root.join("queued.txt"); let fs = Arc::new( MemoryTransferFs::new(SourceId::Ssh(host.clone()), 1) .with_dir(root.clone()) .with_file(first.clone(), b"first") .with_file(second.clone(), b"second"), ); let operations: Arc = if ambiguous_rename { Arc::new(AmbiguousRenameFs::new(fs.clone())) } else { fs.clone() }; let connections = ConnectionManager::new( Arc::new(FakeSsh { read: fs.clone(), operations, }), BackendRegistry::new(Arc::new(LocalFs::new())), ); let connection = connections.connect(&host).await.unwrap(); let (runner, results) = EffectRunner::new(connections); let mut app = AppState::new(root); app.active_pane_mut().session_epoch = Some(connection.epoch); app.active_pane_mut().entries = vec![ Entry::new("a.txt", EntryKind::File).with_metadata(Some(5), None, None), Entry::new("b.txt", EntryKind::File).with_metadata(Some(6), None, None), ]; Self { _fixture: fixture, app, runner, results, fs, first, second, created, } } fn dispatch(&mut self, command: Command) { for effect in self.app.reduce(command) { self.runner.execute(effect); } } async fn next(&mut self) -> Command { tokio::time::timeout(Duration::from_secs(5), self.results.recv()) .await .unwrap_or_else(|_| { panic!( "runtime queue stalled: {:?}", self.app.task_manager.tasks().collect::>() ) }) .expect("runtime result channel closed") } async fn prepare(&mut self, action: Command) -> Vec { self.dispatch(Command::SelectAll); self.dispatch(action); let Command::EntryActionPrepared(result) = self.next().await else { panic!("expected entry-action preparation"); }; let prepared = result.result.as_ref().unwrap(); let root_ids = prepared.plan.nodes().iter().map(|node| node.id()).collect(); self.dispatch(Command::EntryActionPrepared(result)); assert_eq!(self.app.overlay, Overlay::ConfirmEntryAction); root_ids } fn confirm_and_queue_create(&mut self) { self.dispatch(Command::ConfirmEntryAction); assert_eq!(self.app.task_manager.len(), 1); self.dispatch(Command::CreateFile); for character in "queued.txt".chars() { self.dispatch(Command::EntryInput(character)); } self.dispatch(Command::SubmitEntry); self.dispatch(Command::ConfirmEntryAction); assert_eq!(self.app.task_manager.len(), 2); assert_eq!( self.app.task_manager.tasks().last().unwrap().status(), TaskStatus::Queued ); } async fn finish_both(&mut self) -> Vec { let operations: Vec<_> = self .app .task_manager .tasks() .map(|task| task.operation_id()) .collect(); let mut events = Vec::new(); let mut completed = BTreeMap::new(); while completed.len() < 2 { let command = self.next().await; if let Command::OperationEvent(event) = &command { if matches!(event.kind, OperationEventKind::Completed) { *completed.entry(event.operation_id).or_insert(0_usize) += 1; } events.push(event.clone()); } self.dispatch(command); } assert_eq!(completed.len(), 2); assert!(operations.iter().all(|operation| { completed.get(operation) == Some(&1) && events.iter().any(|event| { event.operation_id == *operation && matches!(event.kind, OperationEventKind::Completed) }) })); events } } async fn assert_failure_releases_queue( mut harness: Harness, action: Command, inject: impl FnOnce(&MemoryTransferFs), expected_first_commit: CommitOutcome, ) -> Harness { let root_ids = harness.prepare(action).await; assert_eq!(root_ids.len(), 2); inject(&harness.fs); harness.confirm_and_queue_create(); let operations: Vec<_> = harness .app .task_manager .tasks() .map(|task| task.operation_id()) .collect(); let events = harness.finish_both().await; for (operation, expected_items) in operations.iter().zip([root_ids, vec![ItemId::new(1)]]) { let started: Vec<_> = events .iter() .filter_map(|event| match event.kind { OperationEventKind::ItemStarted(item) if event.operation_id == *operation => { Some(item) } _ => None, }) .collect(); assert_eq!(started, expected_items, "each root must start exactly once"); assert_eq!( events .iter() .filter(|event| event.operation_id == *operation && matches!(event.kind, OperationEventKind::ItemFinished(_))) .count(), expected_items.len() ); } assert!( !events .iter() .any(|event| matches!(event.kind, OperationEventKind::ItemCommitted(_))), "entry actions must not acquire synthetic commit events" ); let outcomes: Vec<_> = events .iter() .filter_map(|event| match event.kind { OperationEventKind::ItemFinished(outcome) if event.operation_id == operations[0] => { Some(outcome) } _ => None, }) .collect(); assert_eq!(outcomes[0].commit(), expected_first_commit); assert_eq!(outcomes[1].commit(), CommitOutcome::NotAttempted); let tasks: Vec<_> = harness.app.task_manager.tasks().collect(); assert_eq!(tasks[0].status(), TaskStatus::Failed); assert_eq!(tasks[1].status(), TaskStatus::Succeeded); assert_eq!(harness.app.task_manager.active_task(), None); assert_eq!(harness.app.task_manager.queued_len(), 0); assert_eq!(harness.fs.file_contents(&harness.created).unwrap(), b""); assert_eq!( harness .fs .operations() .iter() .filter(|entry| entry.operation == TransferOperation::CreateFile) .count(), 1, "the queued create must execute exactly once" ); harness } #[tokio::test] async fn delete_after_apply_timeout_completes_and_runs_the_queued_create() { let harness = assert_failure_releases_queue( Harness::new().await, Command::PermanentDelete, |fs| fs.fail_after_apply(TransferOperation::RemoveFile, FsError::Timeout), CommitOutcome::Unknown, ) .await; assert_eq!( harness.fs.file_contents(&harness.first), Err(FsError::NotFound) ); assert_eq!( harness.fs.file_contents(&harness.second).unwrap(), b"second" ); assert_eq!( harness .fs .operations() .iter() .filter(|entry| entry.operation == TransferOperation::RemoveFile) .count(), 1 ); } #[tokio::test] async fn trash_shared_setup_failure_completes_and_runs_the_queued_create() { let harness = assert_failure_releases_queue( Harness::new().await, Command::Trash, |fs| fs.fail_next(TransferOperation::CreateDir, FsError::PermissionDenied), CommitOutcome::NotAttempted, ) .await; assert_eq!(harness.fs.file_contents(&harness.first).unwrap(), b"first"); assert_eq!( harness.fs.file_contents(&harness.second).unwrap(), b"second" ); assert_eq!( harness .fs .operations() .iter() .filter(|entry| entry.operation == TransferOperation::Rename) .count(), 0 ); } #[tokio::test] async fn trash_ambiguous_first_root_completes_and_runs_the_queued_create() { let harness = assert_failure_releases_queue( Harness::ambiguous_trash().await, Command::Trash, |_| {}, CommitOutcome::Unknown, ) .await; assert_eq!( harness.fs.file_contents(&harness.first), Err(FsError::NotFound) ); assert_eq!( harness.fs.file_contents(&harness.second).unwrap(), b"second" ); assert_eq!( harness .fs .operations() .iter() .filter(|entry| entry.operation == TransferOperation::Rename) .count(), 1 ); }