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

553 lines
20 KiB
Rust

use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use rcom::app::{AppState, CollisionChoice, Command, Overlay, PaneId, PaneMode};
use rcom::domain::{Entry, EntryKind, HostAlias, Location, SourceId};
use rcom::fs::{BackendRegistry, FileOperations, FsError, LocalFs, ReadFileSystem};
use rcom::operations::{CommitOutcome, OperationEventKind, TaskResult, TaskStatus};
use rcom::runtime::EffectRunner;
use rcom::ssh::{ConnectionManager, SshConnector};
use rcom::test_support::{MemoryTransferFs, TransferOperation};
use tempfile::TempDir;
use tokio::sync::mpsc;
struct NoNetwork;
#[derive(Clone, Default)]
struct GatedRemote {
transfer: Arc<std::sync::Mutex<Option<Arc<MemoryTransferFs>>>>,
}
impl GatedRemote {
fn backends(
&self,
host: &HostAlias,
epoch: u64,
) -> (Arc<dyn ReadFileSystem>, Arc<MemoryTransferFs>) {
let root = Location::ssh(host.clone(), "/remote");
let transfer =
Arc::new(MemoryTransferFs::new(SourceId::Ssh(host.clone()), epoch).with_dir(root));
let read: Arc<dyn ReadFileSystem> = transfer.clone();
*self.transfer.lock().unwrap() = Some(transfer.clone());
(read, transfer)
}
}
#[async_trait]
impl SshConnector for GatedRemote {
async fn connect(&self, host: &HostAlias) -> Result<Arc<dyn ReadFileSystem>, FsError> {
Ok(self.backends(host, 1).0)
}
async fn connect_with_operations(
&self,
host: &HostAlias,
session_epoch: u64,
) -> Result<(Arc<dyn ReadFileSystem>, Option<Arc<dyn FileOperations>>), FsError> {
let (read, transfer) = self.backends(host, session_epoch);
Ok((read, Some(transfer)))
}
}
#[async_trait]
impl SshConnector for NoNetwork {
async fn connect(&self, _host: &HostAlias) -> Result<Arc<dyn ReadFileSystem>, FsError> {
panic!("local runtime operations must not access SSH")
}
}
fn execute(app: &mut AppState, runner: &mut EffectRunner, command: Command) {
for effect in app.reduce(command) {
runner.execute(effect);
}
}
async fn next_command(receiver: &mut mpsc::Receiver<Command>) -> Command {
tokio::time::timeout(Duration::from_secs(5), receiver.recv())
.await
.expect("runtime command timeout")
.expect("runtime result channel closed")
}
async fn finish_plan(
app: &mut AppState,
runner: &mut EffectRunner,
receiver: &mut mpsc::Receiver<Command>,
) {
execute(app, runner, Command::Copy);
let command = next_command(receiver).await;
let Command::PlanFinished(result) = command else {
panic!("expected planner result, got {command:?}");
};
assert!(
result.result.is_ok(),
"planning failed: {:?}",
result.result
);
assert!(app.reduce(Command::PlanFinished(result)).is_empty());
assert_eq!(app.overlay, Overlay::ConfirmOperation);
}
async fn settle_listings(
app: &mut AppState,
runner: &mut EffectRunner,
receiver: &mut mpsc::Receiver<Command>,
) {
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
loop {
match tokio::time::timeout(Duration::from_millis(50), receiver.recv()).await {
Ok(Some(command)) => {
for effect in app.reduce(command) {
runner.execute(effect);
}
}
Ok(None) => panic!("runtime channel closed"),
Err(_) if app.panes.iter().any(|pane| pane.loading) => {
assert!(
tokio::time::Instant::now() < deadline,
"listing did not settle: {:?}",
app.panes
);
}
Err(_) => return,
}
}
}
async fn finish_execution(
app: &mut AppState,
runner: &mut EffectRunner,
receiver: &mut mpsc::Receiver<Command>,
) {
loop {
let command = next_command(receiver).await;
let terminal = matches!(
&command,
Command::OperationEvent(event)
if matches!(event.kind, OperationEventKind::Completed | OperationEventKind::CancellationAcknowledged)
);
for effect in app.reduce(command) {
runner.execute(effect);
}
if terminal {
return;
}
}
}
#[tokio::test]
async fn selection_confirmation_copy_and_move_flow_through_real_local_runtime() {
let fixture = TempDir::new().unwrap();
let source = fixture.path().join("source");
let copy_destination = fixture.path().join("copy");
let move_destination = fixture.path().join("move");
std::fs::create_dir(&source).unwrap();
std::fs::create_dir(&copy_destination).unwrap();
std::fs::create_dir(&move_destination).unwrap();
std::fs::write(source.join("a.txt"), vec![b'a'; 70 * 1024]).unwrap();
std::fs::write(source.join("b.txt"), b"second").unwrap();
let registry = BackendRegistry::new(Arc::new(LocalFs::new()));
let connections = ConnectionManager::new(Arc::new(NoNetwork), registry);
let (mut runner, mut results) = EffectRunner::new(connections);
let mut app = AppState::new(Location::local(&source));
app.mode = PaneMode::Dual;
app.pane_mut(PaneId::Right).location = Location::local(&copy_destination);
app.pane_mut(PaneId::Left).entries = vec![
Entry::new("a.txt", EntryKind::File),
Entry::new("b.txt", EntryKind::File),
];
app.pane_mut(PaneId::Left).selection.set(Some(0), 2);
execute(&mut app, &mut runner, Command::SelectAll);
// F5 starts read-only planning only. No destination or part file exists before confirmation.
finish_plan(&mut app, &mut runner, &mut results).await;
assert_eq!(std::fs::read_dir(&copy_destination).unwrap().count(), 0);
execute(&mut app, &mut runner, Command::ConfirmOperation);
execute(&mut app, &mut runner, Command::ConfirmOperation);
finish_execution(&mut app, &mut runner, &mut results).await;
assert_eq!(
std::fs::read(copy_destination.join("a.txt")).unwrap(),
vec![b'a'; 70 * 1024]
);
assert_eq!(
std::fs::read(copy_destination.join("b.txt")).unwrap(),
b"second"
);
assert!(source.join("a.txt").exists());
assert!(source.join("b.txt").exists());
settle_listings(&mut app, &mut runner, &mut results).await;
let destination_names: Vec<_> = app
.pane(PaneId::Right)
.entries
.iter()
.map(|entry| entry.name.clone())
.collect();
assert_eq!(destination_names, ["a.txt", "b.txt"]);
assert_eq!(app.active, PaneId::Left);
assert_eq!(
app.task_manager.tasks().next().unwrap().status(),
TaskStatus::Succeeded
);
assert_eq!(
app.task_manager.len(),
1,
"double confirmation cannot start twice"
);
app.pane_mut(PaneId::Right).location = Location::local(&move_destination);
for effect in app.reduce(Command::Move) {
runner.execute(effect);
}
let Command::PlanFinished(result) = next_command(&mut results).await else {
panic!("expected move planner result");
};
app.reduce(Command::PlanFinished(result));
execute(&mut app, &mut runner, Command::ConfirmOperation);
finish_execution(&mut app, &mut runner, &mut results).await;
assert!(!source.join("a.txt").exists());
assert!(!source.join("b.txt").exists());
assert_eq!(
std::fs::read(move_destination.join("a.txt")).unwrap(),
vec![b'a'; 70 * 1024]
);
assert_eq!(
std::fs::read(move_destination.join("b.txt")).unwrap(),
b"second"
);
settle_listings(&mut app, &mut runner, &mut results).await;
assert!(app.pane(PaneId::Left).entries.is_empty());
assert_eq!(app.pane(PaneId::Right).entries.len(), 2);
assert_eq!(app.task_manager.len(), 2);
assert!(
app.task_manager
.tasks()
.all(|task| task.status() == TaskStatus::Succeeded)
);
assert!(fixture.path().read_dir().unwrap().all(|entry| {
let path = entry.unwrap().path();
!path
.file_name()
.unwrap()
.to_string_lossy()
.starts_with(".rcom-part-")
}));
}
#[tokio::test]
async fn gated_remote_write_cancels_without_commit_or_source_delete() {
let fixture = TempDir::new().unwrap();
let source = fixture.path().join("source");
let source_file = source.join("file.txt");
std::fs::create_dir(&source).unwrap();
std::fs::write(&source_file, b"local contents").unwrap();
let host = HostAlias::new("edge");
let connector = GatedRemote::default();
let registry = BackendRegistry::new(Arc::new(LocalFs::new()));
let connections = ConnectionManager::new(Arc::new(connector.clone()), registry);
let connection = connections.connect(&host).await.unwrap();
let remote = connection.home.join("remote");
let remote_file = remote.join("file.txt");
let transfer = connector.transfer.lock().unwrap().clone().unwrap();
let gate = transfer.gate_next(TransferOperation::Write);
let (mut runner, mut results) = EffectRunner::new(connections);
let mut app = AppState::new(Location::local(&source));
app.mode = PaneMode::Dual;
app.pane_mut(PaneId::Left).entries = vec![Entry::new("file.txt", EntryKind::File)];
app.pane_mut(PaneId::Left).selection.set(Some(0), 1);
app.pane_mut(PaneId::Right).location = remote;
app.pane_mut(PaneId::Right).session_epoch = Some(connection.epoch);
for effect in app.reduce(Command::Copy) {
runner.execute(effect);
}
let Command::PlanFinished(result) = next_command(&mut results).await else {
panic!("expected remote planner result");
};
assert!(
result.result.is_ok(),
"planning failed: {:?}",
result.result
);
app.reduce(Command::PlanFinished(result));
execute(&mut app, &mut runner, Command::ConfirmOperation);
loop {
let command = next_command(&mut results).await;
let started = matches!(
&command,
Command::OperationEvent(event)
if matches!(event.kind, OperationEventKind::ItemStarted(_))
);
for effect in app.reduce(command) {
runner.execute(effect);
}
if started {
break;
}
}
tokio::time::timeout(Duration::from_secs(5), gate.wait_entered())
.await
.unwrap_or_else(|_| {
panic!(
"write gate was not reached; operations={:?}, tasks={:?}",
transfer.operations(),
app.task_manager.tasks().collect::<Vec<_>>()
)
});
execute(&mut app, &mut runner, Command::OpenTasks);
execute(&mut app, &mut runner, Command::CancelSelectedTask);
gate.release();
finish_execution(&mut app, &mut runner, &mut results).await;
let task = app.task_manager.tasks().next().unwrap();
assert_eq!(task.status(), TaskStatus::Cancelled);
assert_eq!(std::fs::read(&source_file).unwrap(), b"local contents");
assert!(matches!(
transfer.file_contents(&remote_file),
Err(FsError::NotFound)
));
assert!(!transfer.operations().iter().any(|entry| {
matches!(
entry.operation,
TransferOperation::Commit
| TransferOperation::RemoveFile
| TransferOperation::RemoveDir
)
}));
assert_eq!(transfer.part_locations().len(), 1);
assert!(
app.diagnostics_for(task.id())
.iter()
.any(|diagnostic| diagnostic.partial.is_some())
);
}
#[tokio::test]
async fn cancel_after_commit_keeps_cancel_visible_and_refreshes_the_actual_destination() {
let fixture = TempDir::new().unwrap();
let source = fixture.path().join("source");
std::fs::create_dir(&source).unwrap();
std::fs::write(source.join("a.txt"), b"first").unwrap();
std::fs::write(source.join("b.txt"), b"second").unwrap();
let host = HostAlias::new("edge");
let connector = GatedRemote::default();
let connections = ConnectionManager::new(
Arc::new(connector.clone()),
BackendRegistry::new(Arc::new(LocalFs::new())),
);
let connection = connections.connect(&host).await.unwrap();
let remote = connection.home.join("remote");
let transfer = connector.transfer.lock().unwrap().clone().unwrap();
transfer.pass_next(TransferOperation::Write);
let second_write = transfer.gate_next(TransferOperation::Write);
let (mut runner, mut results) = EffectRunner::new(connections);
let mut app = AppState::new(remote.clone());
app.active_pane_mut().session_epoch = Some(connection.epoch);
execute(&mut app, &mut runner, Command::Refresh);
settle_listings(&mut app, &mut runner, &mut results).await;
execute(&mut app, &mut runner, Command::TogglePaneMode);
settle_listings(&mut app, &mut runner, &mut results).await;
execute(
&mut app,
&mut runner,
Command::GoHome(Location::local(&source)),
);
settle_listings(&mut app, &mut runner, &mut results).await;
assert_eq!(app.pane(PaneId::Right).location, remote);
assert_eq!(app.pane(PaneId::Left).entries.len(), 2);
execute(&mut app, &mut runner, Command::SelectAll);
finish_plan(&mut app, &mut runner, &mut results).await;
execute(&mut app, &mut runner, Command::ConfirmOperation);
loop {
let command = tokio::time::timeout(Duration::from_secs(1), results.recv())
.await
.unwrap_or_else(|_| {
panic!(
"no commit event; operations={:?}, tasks={:?}",
transfer.operations(),
app.task_manager.tasks().collect::<Vec<_>>()
)
})
.unwrap();
let committed = matches!(
&command,
Command::OperationEvent(event)
if matches!(&event.kind, OperationEventKind::ItemFinished(outcome)
if outcome.commit() == CommitOutcome::Committed)
);
for effect in app.reduce(command) {
runner.execute(effect);
}
if committed {
break;
}
}
execute(&mut app, &mut runner, Command::OpenTasks);
execute(&mut app, &mut runner, Command::CancelSelectedTask);
second_write.release();
finish_execution(&mut app, &mut runner, &mut results).await;
let task = app.task_manager.tasks().next().unwrap();
assert_eq!(task.status(), TaskStatus::Cancelled);
assert_eq!(task.result(), Some(TaskResult::Cancelled));
assert_eq!(
transfer.file_contents(&remote.join("a.txt")).unwrap(),
b"first"
);
assert!(matches!(
transfer.file_contents(&remote.join("b.txt")),
Err(FsError::NotFound)
));
assert!(source.join("a.txt").exists());
assert!(source.join("b.txt").exists());
settle_listings(&mut app, &mut runner, &mut results).await;
let visible: Vec<_> = app
.pane(PaneId::Right)
.entries
.iter()
.map(|entry| entry.name.clone())
.collect();
assert_eq!(visible, ["a.txt"]);
assert_eq!(app.active, PaneId::Left);
}
#[tokio::test]
async fn collision_choices_are_replanned_and_applied_per_item() {
let fixture = TempDir::new().unwrap();
let source = fixture.path().join("source");
let destination = fixture.path().join("destination");
std::fs::create_dir(&source).unwrap();
std::fs::create_dir(&destination).unwrap();
std::fs::write(source.join("a.txt"), b"new a").unwrap();
std::fs::write(source.join("b.txt"), b"new b").unwrap();
std::fs::write(destination.join("a.txt"), b"old a").unwrap();
std::fs::write(destination.join("b.txt"), b"old b").unwrap();
let registry = BackendRegistry::new(Arc::new(LocalFs::new()));
let connections = ConnectionManager::new(Arc::new(NoNetwork), registry);
let (mut runner, mut results) = EffectRunner::new(connections);
let mut app = AppState::new(Location::local(&source));
app.mode = PaneMode::Dual;
app.pane_mut(PaneId::Right).location = Location::local(&destination);
app.pane_mut(PaneId::Left).entries = vec![
Entry::new("a.txt", EntryKind::File),
Entry::new("b.txt", EntryKind::File),
];
app.pane_mut(PaneId::Left).selection.set(Some(0), 2);
execute(&mut app, &mut runner, Command::SelectAll);
execute(&mut app, &mut runner, Command::Copy);
let Command::PlanFinished(first) = next_command(&mut results).await else {
panic!("expected first collision plan");
};
let first_output = first.result.as_ref().unwrap();
assert_eq!(first_output.collisions.len(), 1);
assert_eq!(first_output.collisions[0].source.path, source.join("a.txt"));
app.reduce(Command::PlanFinished(first));
assert_eq!(app.overlay, Overlay::Collision);
execute(
&mut app,
&mut runner,
Command::ResolveCollision {
choice: CollisionChoice::Overwrite,
apply_to_all: false,
},
);
let Command::PlanFinished(second) = next_command(&mut results).await else {
panic!("expected second collision plan");
};
let second_output = second.result.as_ref().unwrap();
assert_eq!(second_output.collisions.len(), 1);
assert_eq!(
second_output.collisions[0].source.path,
source.join("b.txt")
);
app.reduce(Command::PlanFinished(second));
execute(
&mut app,
&mut runner,
Command::ResolveCollision {
choice: CollisionChoice::Skip,
apply_to_all: false,
},
);
let Command::PlanFinished(final_plan) = next_command(&mut results).await else {
panic!("expected resolved plan");
};
assert!(final_plan.result.as_ref().unwrap().collisions.is_empty());
app.reduce(Command::PlanFinished(final_plan));
assert_eq!(app.overlay, Overlay::ConfirmOperation);
execute(&mut app, &mut runner, Command::ConfirmOperation);
finish_execution(&mut app, &mut runner, &mut results).await;
assert_eq!(std::fs::read(destination.join("a.txt")).unwrap(), b"new a");
assert_eq!(std::fs::read(destination.join("b.txt")).unwrap(), b"old b");
assert_eq!(std::fs::read(source.join("a.txt")).unwrap(), b"new a");
assert_eq!(std::fs::read(source.join("b.txt")).unwrap(), b"new b");
let task = app.task_manager.tasks().next().unwrap();
assert_ne!(task.status(), TaskStatus::Succeeded);
assert_eq!(task.plan().collision_policies().len(), 2);
}
#[tokio::test]
async fn source_disappearing_after_confirmation_stops_before_any_item_commits() {
let fixture = TempDir::new().unwrap();
let source = fixture.path().join("source");
let destination = fixture.path().join("destination");
std::fs::create_dir(&source).unwrap();
std::fs::create_dir(&destination).unwrap();
std::fs::write(source.join("a.txt"), b"first").unwrap();
std::fs::write(source.join("b.txt"), b"second").unwrap();
let registry = BackendRegistry::new(Arc::new(LocalFs::new()));
let connections = ConnectionManager::new(Arc::new(NoNetwork), registry);
let (mut runner, mut results) = EffectRunner::new(connections);
let mut app = AppState::new(Location::local(&source));
app.mode = PaneMode::Dual;
app.pane_mut(PaneId::Right).location = Location::local(&destination);
app.pane_mut(PaneId::Left).entries = vec![
Entry::new("a.txt", EntryKind::File),
Entry::new("b.txt", EntryKind::File),
];
app.pane_mut(PaneId::Left).selection.set(Some(0), 2);
execute(&mut app, &mut runner, Command::SelectAll);
execute(&mut app, &mut runner, Command::Copy);
let Command::PlanFinished(result) = next_command(&mut results).await else {
panic!("expected planner result");
};
app.reduce(Command::PlanFinished(result));
// Hold the confirmed write effect while the second source disappears externally.
let effects = app.reduce(Command::ConfirmOperation);
std::fs::remove_file(source.join("b.txt")).unwrap();
for effect in effects {
runner.execute(effect);
}
finish_execution(&mut app, &mut runner, &mut results).await;
assert_eq!(std::fs::read_dir(&destination).unwrap().count(), 0);
assert_eq!(std::fs::read(source.join("a.txt")).unwrap(), b"first");
let task = app.task_manager.tasks().next().unwrap();
assert_eq!(task.status(), TaskStatus::Failed);
assert!(
task.outcomes()
.all(|outcome| { outcome.commit() == rcom::operations::CommitOutcome::NotAttempted })
);
assert!(
app.diagnostics_for(task.id())
.iter()
.any(|diagnostic| diagnostic.message.contains("stale"))
);
}