rcom/tests/runtime_destructive_actions.rs
2026-12-05 23:30:06 +03:00

209 lines
7.4 KiB
Rust

use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use rcom::app::{AppState, Command, Overlay, PaneId};
use rcom::domain::{Entry, EntryKind, HostAlias, Location, SourceId};
use rcom::fs::{BackendRegistry, FileOperations, FsError, LocalFs, ReadFileSystem};
use rcom::operations::{OperationEventKind, TaskStatus};
use rcom::runtime::EffectRunner;
use rcom::ssh::{ConnectionManager, SshConnector};
use rcom::test_support::{MemoryFs, MemoryTransferFs, TransferOperation};
use tempfile::TempDir;
use tokio::sync::mpsc;
struct NoNetwork;
#[async_trait]
impl SshConnector for NoNetwork {
async fn connect(&self, _host: &HostAlias) -> Result<Arc<dyn ReadFileSystem>, FsError> {
panic!("local delete must not access SSH")
}
}
#[derive(Clone, Default)]
struct Remote {
transfer: Arc<std::sync::Mutex<Option<Arc<MemoryTransferFs>>>>,
}
#[async_trait]
impl SshConnector for Remote {
async fn connect(&self, host: &HostAlias) -> Result<Arc<dyn ReadFileSystem>, FsError> {
let root = Location::ssh(host.clone(), "/remote");
let file = root.join("file.txt");
Ok(Arc::new(
MemoryFs::new().with_dir(root).with_file(file, b"remote"),
))
}
async fn connect_with_operations(
&self,
host: &HostAlias,
epoch: u64,
) -> Result<(Arc<dyn ReadFileSystem>, Option<Arc<dyn FileOperations>>), FsError> {
let read = self.connect(host).await?;
let root = Location::ssh(host.clone(), "/remote");
let transfer = Arc::new(
MemoryTransferFs::new(SourceId::Ssh(host.clone()), epoch)
.with_dir(root.clone())
.with_file(root.join("file.txt"), b"remote"),
);
*self.transfer.lock().unwrap() = Some(transfer.clone());
Ok((read, Some(transfer)))
}
}
fn dispatch(app: &mut AppState, runner: &mut EffectRunner, command: Command) {
for effect in app.reduce(command) {
runner.execute(effect);
}
}
async fn next(results: &mut mpsc::Receiver<Command>) -> Command {
tokio::time::timeout(Duration::from_secs(5), results.recv())
.await
.expect("destructive action timed out")
.expect("runtime channel closed")
}
async fn finish(
app: &mut AppState,
runner: &mut EffectRunner,
results: &mut mpsc::Receiver<Command>,
) {
loop {
let command = next(results).await;
let terminal = matches!(
&command,
Command::OperationEvent(event)
if matches!(event.kind, OperationEventKind::Completed | OperationEventKind::CancellationAcknowledged)
);
dispatch(app, runner, command);
if terminal {
return;
}
}
}
#[tokio::test]
async fn permanent_delete_executes_the_confirmed_local_tree_once() {
let fixture = TempDir::new().unwrap();
let tree = fixture.path().join("tree");
std::fs::create_dir(&tree).unwrap();
std::fs::write(tree.join("nested.txt"), b"nested").unwrap();
let entry = LocalFs::new()
.metadata(&Location::local(&tree))
.await
.unwrap();
let connections = ConnectionManager::new(
Arc::new(NoNetwork),
BackendRegistry::new(Arc::new(LocalFs::new())),
);
let (mut runner, mut results) = EffectRunner::new(connections);
let mut app = AppState::new(Location::local(fixture.path()));
app.active_pane_mut().entries = vec![entry];
app.active_pane_mut().selection.set(Some(0), 1);
dispatch(&mut app, &mut runner, Command::PermanentDelete);
let Command::EntryActionPrepared(result) = next(&mut results).await else {
panic!("expected delete preparation");
};
assert!(result.result.is_ok());
dispatch(&mut app, &mut runner, Command::EntryActionPrepared(result));
assert_eq!(app.overlay, Overlay::ConfirmEntryAction);
assert!(tree.exists());
dispatch(&mut app, &mut runner, Command::ConfirmEntryAction);
dispatch(&mut app, &mut runner, Command::ConfirmEntryAction);
finish(&mut app, &mut runner, &mut results).await;
assert!(!tree.exists());
assert_eq!(app.task_manager.len(), 1);
assert_eq!(
app.task_manager.tasks().next().unwrap().status(),
TaskStatus::Succeeded
);
}
#[tokio::test]
async fn gated_remote_trash_cancellation_preserves_source_without_retry() {
let host = HostAlias::new("edge");
let connector = Remote::default();
let connections = ConnectionManager::new(
Arc::new(connector.clone()),
BackendRegistry::new(Arc::new(LocalFs::new())),
);
let connection = connections.connect(&host).await.unwrap();
let remote_root = Location::ssh(host.clone(), "/remote");
let source = remote_root.join("file.txt");
let transfer = connector.transfer.lock().unwrap().clone().unwrap();
let (mut runner, mut results) = EffectRunner::new(connections);
let mut app = AppState::new(remote_root.clone());
app.pane_mut(PaneId::Left).session_epoch = Some(connection.epoch);
app.pane_mut(PaneId::Left).entries =
vec![Entry::new("file.txt", EntryKind::File).with_metadata(Some(6), None, None)];
app.pane_mut(PaneId::Left).selection.set(Some(0), 1);
dispatch(&mut app, &mut runner, Command::Trash);
let Command::EntryActionPrepared(result) = next(&mut results).await else {
panic!("expected trash preparation");
};
let prepared = result.result.as_ref().unwrap();
let trashed = prepared.trash_records[0].trashed().clone();
dispatch(&mut app, &mut runner, Command::EntryActionPrepared(result));
let gate = transfer.gate_next(TransferOperation::Metadata);
dispatch(&mut app, &mut runner, Command::ConfirmEntryAction);
loop {
let command = next(&mut results).await;
let started = matches!(
&command,
Command::OperationEvent(event)
if matches!(event.kind, OperationEventKind::ItemStarted(_))
);
dispatch(&mut app, &mut runner, command);
if started {
break;
}
}
let mut waiting = Box::pin(gate.wait_entered());
loop {
tokio::select! {
_ = &mut waiting => break,
command = next(&mut results) => {
let terminal = matches!(
&command,
Command::OperationEvent(event)
if matches!(event.kind, OperationEventKind::Completed | OperationEventKind::CancellationAcknowledged)
);
dispatch(&mut app, &mut runner, command);
if terminal {
panic!(
"trash ended before rename gate: operations={:?}, tasks={:?}",
transfer.operations(),
app.task_manager.tasks().collect::<Vec<_>>()
);
}
}
}
}
dispatch(&mut app, &mut runner, Command::OpenTasks);
dispatch(&mut app, &mut runner, Command::CancelSelectedTask);
gate.release();
finish(&mut app, &mut runner, &mut results).await;
assert_eq!(transfer.file_contents(&source).unwrap(), b"remote");
assert_eq!(transfer.file_contents(&trashed), Err(FsError::NotFound));
assert_eq!(
app.task_manager.tasks().next().unwrap().status(),
TaskStatus::Cancelled
);
assert_eq!(
transfer
.operations()
.iter()
.filter(|entry| entry.operation == TransferOperation::Rename)
.count(),
0
);
}