rcom/tests/editor_runtime.rs

673 lines
23 KiB
Rust
Raw Permalink Normal View History

use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use async_trait::async_trait;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use rcom::actions::{EditorCommand, EditorOutcome, ExternalEditor};
use rcom::app::{Command, EditorPhase, Overlay};
use rcom::domain::{Entry, EntryKind, HostAlias, Location, SourceId};
use rcom::fs::{
BackendRegistry, FileOperations, FsError, LocalFs, PartFile, PartWriter, ReadFileSystem,
ReadStream, StagingOperations, TransferCapabilities,
};
use rcom::operations::TaskStatus;
use rcom::session::Application;
use rcom::ssh::{ConnectionManager, DiscoveryResult, SshConnector};
use rcom::test_support::{FaultInjectEditor, MemoryFs, MemoryTransferFs, TransferOperation};
use tempfile::TempDir;
use tokio::sync::mpsc;
const EPOCH: u64 = 1;
struct RefusedConnector;
#[async_trait]
impl SshConnector for RefusedConnector {
async fn connect(&self, _host: &HostAlias) -> Result<Arc<dyn ReadFileSystem>, FsError> {
panic!("local editor tests must not use SSH")
}
}
#[derive(Clone, Debug)]
struct WritingEditor {
edits: Arc<Mutex<VecDeque<Vec<u8>>>>,
invocations: Arc<Mutex<Vec<PathBuf>>>,
outcome: EditorOutcome,
}
impl WritingEditor {
fn new<const N: usize>(edits: [&[u8]; N]) -> Self {
Self {
edits: Arc::new(Mutex::new(edits.into_iter().map(<[u8]>::to_vec).collect())),
invocations: Arc::new(Mutex::new(Vec::new())),
outcome: EditorOutcome::Success,
}
}
fn nonzero<const N: usize>(edits: [&[u8]; N], code: i32) -> Self {
Self {
outcome: EditorOutcome::NonZero(Some(code)),
..Self::new(edits)
}
}
fn invocations(&self) -> Vec<PathBuf> {
self.invocations
.lock()
.unwrap_or_else(|error| error.into_inner())
.clone()
}
}
#[async_trait]
impl ExternalEditor for WritingEditor {
async fn edit(&self, _command: &EditorCommand, path: &Path) -> Result<EditorOutcome, FsError> {
self.invocations
.lock()
.unwrap_or_else(|error| error.into_inner())
.push(path.to_path_buf());
let edit = self
.edits
.lock()
.unwrap_or_else(|error| error.into_inner())
.pop_front()
.unwrap_or_default();
tokio::fs::write(path, edit).await.map_err(FsError::from)?;
Ok(self.outcome)
}
}
fn command() -> EditorCommand {
EditorCommand::parse("deterministic-editor --flag").unwrap()
}
async fn settle(application: &mut Application, results: &mut mpsc::Receiver<Command>) {
loop {
match tokio::time::timeout(Duration::from_millis(75), results.recv()).await {
Ok(Some(command)) => application.dispatch(command),
Ok(None) => panic!("runtime result channel closed"),
Err(_) => return,
}
}
}
fn local_application(
path: &Path,
editor: Arc<dyn ExternalEditor>,
) -> (Application, mpsc::Receiver<Command>) {
let connections = ConnectionManager::new(
Arc::new(RefusedConnector),
BackendRegistry::new(Arc::new(LocalFs::new())),
);
Application::new_with_editor_command(
Location::local(path),
connections,
DiscoveryResult::default(),
command(),
editor,
)
}
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
async fn invoke_editor(application: &mut Application, results: &mut mpsc::Receiver<Command>) {
application.handle_key(key(KeyCode::Char('e')), 20);
settle(application, results).await;
application.run_pending_editor().await;
}
#[tokio::test]
async fn local_success_uses_typed_path_refreshes_and_preserves_workspace_state() {
let fixture = TempDir::new().unwrap();
let file = fixture.path().join("note.txt");
std::fs::write(&file, b"before").unwrap();
std::fs::write(fixture.path().join("other.txt"), b"other").unwrap();
let editor = Arc::new(WritingEditor::new([b"after"]));
let (mut application, mut results) = local_application(fixture.path(), editor.clone());
application.start();
settle(&mut application, &mut results).await;
let generation = application.state().active_pane().listing_generation;
let selection = application.state().active_pane().selection;
invoke_editor(&mut application, &mut results).await;
settle(&mut application, &mut results).await;
assert_eq!(std::fs::read(&file).unwrap(), b"after");
assert_eq!(editor.invocations(), vec![file.clone()]);
assert_eq!(application.state().active_pane().selection, selection);
assert!(
application.state().active_pane().listing_generation > generation,
"successful local editing refreshes its owning pane"
);
assert_eq!(application.state().overlay, Overlay::None);
}
#[tokio::test]
async fn local_nonzero_does_not_rollback_or_delete_bytes_written_by_editor() {
let fixture = TempDir::new().unwrap();
let file = fixture.path().join("note.txt");
std::fs::write(&file, b"before").unwrap();
let editor = Arc::new(WritingEditor::nonzero([b"written-before-failure"], 23));
let (mut application, mut results) = local_application(fixture.path(), editor);
application.start();
settle(&mut application, &mut results).await;
let generation = application.state().active_pane().listing_generation;
invoke_editor(&mut application, &mut results).await;
settle(&mut application, &mut results).await;
assert!(file.is_file());
assert_eq!(std::fs::read(file).unwrap(), b"written-before-failure");
assert_eq!(
application.state().active_pane().listing_generation,
generation
);
assert_eq!(application.state().overlay, Overlay::Edit);
}
#[tokio::test]
async fn local_nonzero_and_spawn_error_do_not_delete_rollback_or_refresh() {
for result in [
Ok(EditorOutcome::NonZero(Some(9))),
Err(FsError::Other("injected spawn failure".into())),
] {
let fixture = TempDir::new().unwrap();
let file = fixture.path().join("note.txt");
std::fs::write(&file, b"original").unwrap();
let editor = Arc::new(FaultInjectEditor::new());
match result {
Ok(EditorOutcome::NonZero(code)) => editor.queue_nonzero(code),
Err(error) => editor.queue_spawn_error(error),
_ => unreachable!(),
}
let (mut application, mut results) = local_application(fixture.path(), editor.clone());
application.start();
settle(&mut application, &mut results).await;
let generation = application.state().active_pane().listing_generation;
let panes = application.state().panes.clone();
invoke_editor(&mut application, &mut results).await;
settle(&mut application, &mut results).await;
assert_eq!(std::fs::read(&file).unwrap(), b"original");
assert_eq!(editor.invocations().len(), 1);
assert_eq!(
application.state().active_pane().listing_generation,
generation
);
assert_eq!(application.state().panes[1], panes[1]);
assert_eq!(application.state().overlay, Overlay::Edit);
assert!(application.state().deferred_action.is_some());
assert!(application.state().task_manager.is_empty());
}
}
#[tokio::test]
async fn editor_spawn_error_preserves_existing_tasks_panes_and_selection() {
let fixture = TempDir::new().unwrap();
std::fs::write(fixture.path().join("note.txt"), b"original").unwrap();
let editor = Arc::new(FaultInjectEditor::new());
editor.queue_spawn_error(FsError::Other("spawn failed".into()));
let (mut application, mut results) = local_application(fixture.path(), editor);
application.start();
settle(&mut application, &mut results).await;
application.dispatch(Command::CreateFile);
application.dispatch(Command::EntryInput('x'));
application.dispatch(Command::SubmitEntry);
application.dispatch(Command::ConfirmEntryAction);
settle(&mut application, &mut results).await;
application.dispatch(Command::SelectFirst);
settle(&mut application, &mut results).await;
let panes = application.state().panes.clone();
let tasks = application.state().task_manager.clone();
let active = application.state().active;
invoke_editor(&mut application, &mut results).await;
settle(&mut application, &mut results).await;
assert_eq!(application.state().panes, panes);
assert_eq!(application.state().task_manager, tasks);
assert_eq!(application.state().active, active);
}
#[tokio::test]
async fn stale_hovered_source_never_reaches_editor_process() {
let fixture = TempDir::new().unwrap();
let file = fixture.path().join("first.txt");
std::fs::write(&file, b"first").unwrap();
std::fs::write(fixture.path().join("second.txt"), b"second").unwrap();
let editor = Arc::new(FaultInjectEditor::new());
let (mut application, mut results) = local_application(fixture.path(), editor.clone());
application.start();
settle(&mut application, &mut results).await;
application.handle_key(key(KeyCode::Char('e')), 20);
application.dispatch(Command::MoveSelection(1));
settle(&mut application, &mut results).await;
application.run_pending_editor().await;
assert!(editor.invocations().is_empty());
assert_eq!(std::fs::read(file).unwrap(), b"first");
assert_eq!(application.state().overlay, Overlay::Edit);
assert!(application.state().editor.is_none());
}
#[derive(Clone)]
struct EditorTransfer {
inner: MemoryTransferFs,
}
#[async_trait]
impl StagingOperations for EditorTransfer {}
#[async_trait]
impl FileOperations for EditorTransfer {
fn source_id(&self) -> &SourceId {
self.inner.source_id()
}
fn capabilities(&self) -> TransferCapabilities {
self.inner.capabilities()
}
fn invalidate_session(&self, session_epoch: u64) {
self.inner.invalidate_session(session_epoch);
}
async fn canonicalize(&self, location: &Location) -> Result<Location, FsError> {
ReadFileSystem::canonicalize(&self.inner, location).await
}
async fn metadata(&self, location: &Location, follow_symlinks: bool) -> Result<Entry, FsError> {
match FileOperations::metadata(&self.inner, location, follow_symlinks).await {
Err(FsError::NotFound) => match self.inner.part_contents(location) {
Ok(contents) => Ok(Entry::new(
location.file_name_owned().unwrap_or_default(),
EntryKind::File,
)
.with_metadata(Some(contents.len() as u64), None, None)),
Err(_) => Err(FsError::NotFound),
},
result => result,
}
}
async fn open_read(&self, location: &Location) -> Result<ReadStream, FsError> {
self.inner.open_read(location).await
}
async fn open_part(&self, destination: &Location) -> Result<PartWriter, FsError> {
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<PartFile, FsError> {
self.inner.flush_and_close(part).await
}
async fn commit_part(&self, part: PartFile) -> Result<(), FsError> {
self.inner.commit_part(part).await
}
async fn commit_part_with_metadata(
&self,
part: PartFile,
source: &Entry,
) -> Result<(), FsError> {
self.inner.commit_part_with_metadata(part, source).await
}
fn take_capability_warnings(&self) -> Vec<String> {
self.inner.take_capability_warnings()
}
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.rename(from, to).await
}
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 RemoteConnector {
read: Arc<MemoryFs>,
transfer: Arc<EditorTransfer>,
}
#[async_trait]
impl SshConnector for RemoteConnector {
async fn connect(&self, _host: &HostAlias) -> Result<Arc<dyn ReadFileSystem>, FsError> {
Ok(self.read.clone())
}
async fn connect_with_operations(
&self,
_host: &HostAlias,
_session_epoch: u64,
) -> Result<(Arc<dyn ReadFileSystem>, Option<Arc<dyn FileOperations>>), FsError> {
Ok((self.read.clone(), Some(self.transfer.clone())))
}
}
struct RemoteFixture {
application: Application,
results: mpsc::Receiver<Command>,
remote: MemoryTransferFs,
source: Location,
host: HostAlias,
}
async fn remote_fixture(editor: Arc<dyn ExternalEditor>) -> RemoteFixture {
let host = HostAlias::new("editor-runtime");
let source = Location::ssh(host.clone(), "/home/user/note.txt");
let remote = MemoryTransferFs::new(source.source.clone(), EPOCH)
.with_file(source.clone(), b"remote-before");
let read = Arc::new(MemoryFs::new().with_file(source.clone(), b"remote-before"));
let transfer = Arc::new(EditorTransfer {
inner: remote.clone(),
});
let connector = Arc::new(RemoteConnector {
read: read.clone(),
transfer,
});
let connections =
ConnectionManager::new(connector, BackendRegistry::new(Arc::new(LocalFs::new())));
let (mut application, mut results) = Application::new_with_editor_command(
Location::ssh(host.clone(), "/home/user"),
connections,
DiscoveryResult::default(),
command(),
editor,
);
application.dispatch(Command::ConnectSsh(host.clone()));
settle(&mut application, &mut results).await;
application.dispatch(Command::GoHome(Location::ssh(host.clone(), "/home/user")));
settle(&mut application, &mut results).await;
assert_eq!(application.state().active_pane().entries.len(), 1);
RemoteFixture {
application,
results,
remote,
source,
host,
}
}
fn operation_count(remote: &MemoryTransferFs, operation: TransferOperation) -> usize {
remote
.operations()
.into_iter()
.filter(|entry| entry.operation == operation)
.count()
}
fn assert_no_remote_mutations(remote: &MemoryTransferFs) {
const MUTATIONS: [TransferOperation; 8] = [
TransferOperation::OpenPart,
TransferOperation::Write,
TransferOperation::FlushClose,
TransferOperation::Commit,
TransferOperation::DiscardPart,
TransferOperation::Rename,
TransferOperation::RemoveFile,
TransferOperation::RemoveDir,
];
assert!(
remote
.operations()
.iter()
.all(|entry| !MUTATIONS.contains(&entry.operation)),
"unexpected remote mutations: {:?}",
remote.operations()
);
}
#[tokio::test]
async fn ssh_unchanged_skips_upload_cleans_owned_workspace_and_never_queues() {
let editor = Arc::new(FaultInjectEditor::new());
let mut fixture = remote_fixture(editor.clone()).await;
invoke_editor(&mut fixture.application, &mut fixture.results).await;
settle(&mut fixture.application, &mut fixture.results).await;
assert_eq!(fixture.application.state().overlay, Overlay::None);
assert!(fixture.application.state().task_manager.is_empty());
assert_no_remote_mutations(&fixture.remote);
let invocations = editor.invocations();
assert_eq!(invocations.len(), 1);
assert!(
!invocations[0].path.exists(),
"owned temporary file was cleaned"
);
}
#[tokio::test]
async fn ssh_changed_double_confirmation_uploads_once_and_cleans_workspace() {
let editor = Arc::new(WritingEditor::new([b"remote-after"]));
let mut fixture = remote_fixture(editor.clone()).await;
fixture.application.handle_key(key(KeyCode::Char('e')), 20);
settle(&mut fixture.application, &mut fixture.results).await;
assert_no_remote_mutations(&fixture.remote);
fixture.application.run_pending_editor().await;
assert_eq!(fixture.application.state().overlay, Overlay::Edit);
assert_eq!(
fixture.application.state().editor.as_ref().unwrap().phase,
EditorPhase::ConfirmUpload
);
assert_no_remote_mutations(&fixture.remote);
fixture.application.handle_key(key(KeyCode::Enter), 20);
fixture.application.handle_key(key(KeyCode::Enter), 20);
settle(&mut fixture.application, &mut fixture.results).await;
assert_eq!(fixture.application.state().task_manager.len(), 1);
let task = fixture
.application
.state()
.task_manager
.tasks()
.next()
.unwrap();
assert_eq!(
task.status(),
TaskStatus::Succeeded,
"diagnostics: {:?}; outcomes: {:?}",
fixture.application.state().diagnostics_for(task.id()),
task.outcomes().collect::<Vec<_>>()
);
assert_eq!(
fixture.remote.file_contents(&fixture.source).unwrap(),
b"remote-after"
);
assert_eq!(
operation_count(&fixture.remote, TransferOperation::OpenPart),
1
);
assert_eq!(
operation_count(&fixture.remote, TransferOperation::Commit),
1
);
let paths = editor.invocations();
assert!(!paths[0].exists(), "terminal upload released its workspace");
}
#[tokio::test]
async fn ssh_cancel_and_stale_epoch_do_not_write_or_queue() {
for stale in [false, true] {
let editor = Arc::new(WritingEditor::new([b"discard-me"]));
let mut fixture = remote_fixture(editor.clone()).await;
invoke_editor(&mut fixture.application, &mut fixture.results).await;
assert_eq!(fixture.application.state().overlay, Overlay::Edit);
if stale {
fixture.application.dispatch(Command::SynchronizeSshEpoch {
host: fixture.host.clone(),
session_epoch: EPOCH + 1,
});
}
fixture
.application
.handle_key(key(if stale { KeyCode::Enter } else { KeyCode::Esc }), 20);
settle(&mut fixture.application, &mut fixture.results).await;
assert!(fixture.application.state().task_manager.is_empty());
assert_no_remote_mutations(&fixture.remote);
assert_eq!(
fixture.remote.file_contents(&fixture.source).unwrap(),
b"remote-before"
);
let paths = editor.invocations();
assert!(!paths[0].exists());
}
}
#[tokio::test]
async fn ssh_upload_fault_has_item_outcome_part_diagnostic_and_no_retry() {
let editor = Arc::new(WritingEditor::new([b"must-not-commit"]));
let mut fixture = remote_fixture(editor.clone()).await;
invoke_editor(&mut fixture.application, &mut fixture.results).await;
fixture.remote.fail_next(
TransferOperation::Write,
FsError::Other("injected write".into()),
);
fixture.application.handle_key(key(KeyCode::Enter), 20);
settle(&mut fixture.application, &mut fixture.results).await;
let task = fixture
.application
.state()
.task_manager
.tasks()
.next()
.unwrap();
assert_eq!(task.status(), TaskStatus::Failed);
let diagnostics = fixture.application.state().diagnostics_for(task.id());
assert!(
diagnostics
.iter()
.any(|diagnostic| diagnostic.partial.is_some())
);
assert_eq!(
operation_count(&fixture.remote, TransferOperation::Write),
1
);
assert_eq!(
operation_count(&fixture.remote, TransferOperation::Commit),
0
);
assert_eq!(
fixture.remote.file_contents(&fixture.source).unwrap(),
b"remote-before"
);
}
#[tokio::test]
async fn queued_edit_upload_dispatches_once_after_active_terminal_event() {
let editor = Arc::new(WritingEditor::new([b"first-edit", b"second-edit"]));
let mut fixture = remote_fixture(editor.clone()).await;
invoke_editor(&mut fixture.application, &mut fixture.results).await;
let gate = fixture.remote.gate_next(TransferOperation::Write);
fixture.application.handle_key(key(KeyCode::Enter), 20);
gate.wait_entered().await;
invoke_editor(&mut fixture.application, &mut fixture.results).await;
fixture.application.handle_key(key(KeyCode::Enter), 20);
fixture.application.handle_key(key(KeyCode::Enter), 20);
assert_eq!(fixture.application.state().task_manager.len(), 2);
assert_eq!(fixture.application.state().task_manager.queued_len(), 1);
assert_eq!(
operation_count(&fixture.remote, TransferOperation::OpenPart),
1
);
gate.release();
settle(&mut fixture.application, &mut fixture.results).await;
let statuses = fixture
.application
.state()
.task_manager
.tasks()
.map(|task| task.status())
.collect::<Vec<_>>();
assert_eq!(statuses, vec![TaskStatus::Succeeded, TaskStatus::Failed]);
assert_eq!(
operation_count(&fixture.remote, TransferOperation::OpenPart),
1
);
assert_eq!(
operation_count(&fixture.remote, TransferOperation::Commit),
1
);
assert!(
fixture
.application
.state()
.task_manager
.tasks()
.all(|task| task.status().is_terminal())
);
}
#[tokio::test]
async fn running_upload_cancellation_is_acknowledged_without_commit_or_retry() {
let editor = Arc::new(WritingEditor::new([b"cancelled-edit"]));
let mut fixture = remote_fixture(editor.clone()).await;
invoke_editor(&mut fixture.application, &mut fixture.results).await;
let gate = fixture.remote.gate_next(TransferOperation::Write);
fixture.application.handle_key(key(KeyCode::Enter), 20);
gate.wait_entered().await;
fixture.application.dispatch(Command::OpenTasks);
fixture.application.dispatch(Command::CancelSelectedTask);
gate.release();
settle(&mut fixture.application, &mut fixture.results).await;
let task = fixture
.application
.state()
.task_manager
.tasks()
.next()
.unwrap();
assert_eq!(task.status(), TaskStatus::Cancelled);
assert_eq!(
operation_count(&fixture.remote, TransferOperation::Write),
1
);
assert_eq!(
operation_count(&fixture.remote, TransferOperation::Commit),
0
);
assert_eq!(
fixture.remote.file_contents(&fixture.source).unwrap(),
b"remote-before"
);
assert!(
fixture
.application
.state()
.diagnostics_for(task.id())
.iter()
.any(|diagnostic| diagnostic.partial.is_some())
);
}