use std::sync::Arc; // The production module is included directly until the parent change exports it from actions. // These shims preserve its ordinary `crate::...` imports in this integration-test crate. mod actions { pub use rcom::actions::*; } mod domain { pub use rcom::domain::*; } mod fs { pub use rcom::fs::*; } mod operations { pub use rcom::operations::*; } #[path = "../src/actions/edit_session.rs"] mod edit_session; use async_trait::async_trait; use edit_session::{ EditUploadOutcome, EditUploadStage, EditorWorkspace, download_remote_editor, download_remote_editor_at, upload_editor_session, }; use rcom::app::SessionEpoch; use rcom::domain::{Entry, EntryKind, HostAlias, Location, SourceId}; use rcom::fs::{ BackendHandle, FileOperations, FsError, PartFile, PartWriter, ReadStream, StagingOperations, TransferCapabilities, }; use rcom::test_support::{MemoryFs, MemoryTransferFs, TransferOperation}; use tokio_util::sync::CancellationToken; const EPOCH: SessionEpoch = 17; /// Adds the part-metadata capability needed by generic streaming verification to the shared /// MemoryTransferFs double. All storage, epochs, journals, and failpoints remain in that double. #[derive(Clone)] struct EditorMemoryTransferFs { inner: MemoryTransferFs, } impl EditorMemoryTransferFs { fn new(inner: MemoryTransferFs) -> Self { Self { inner } } } #[async_trait] impl StagingOperations for EditorMemoryTransferFs {} #[async_trait] impl FileOperations for EditorMemoryTransferFs { fn source_id(&self) -> &SourceId { self.inner.source_id() } fn capabilities(&self) -> TransferCapabilities { self.inner.capabilities() } fn invalidate_session(&self, session_epoch: SessionEpoch) { self.inner.invalidate_session(session_epoch); } async fn canonicalize(&self, location: &Location) -> Result { FileOperations::canonicalize(&self.inner, location).await } async fn metadata(&self, location: &Location, follow_symlinks: bool) -> Result { 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 { 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 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 { 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 } } fn source() -> Location { Location::ssh(HostAlias::new("editor-test"), "/home/user/notes.txt") } fn backend(remote: &MemoryTransferFs, source: &Location, contents: &[u8]) -> BackendHandle { let read = MemoryFs::new().with_file(source.clone(), contents); BackendHandle::new( source.source().clone(), Arc::new(read), Arc::new(EditorMemoryTransferFs::new(remote.clone())), ) .expect("matching test backend") } async fn downloaded( contents: &[u8], ) -> (EditorWorkspace, MemoryTransferFs, Location, BackendHandle) { let source = source(); let remote = MemoryTransferFs::new(source.source().clone(), EPOCH).with_file(source.clone(), contents); let backend = backend(&remote, &source, contents); let workspace = download_remote_editor(source.clone(), &backend, EPOCH) .await .expect("download succeeds"); remote.clear_operations(); (workspace, remote, source, backend) } 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, ]; let operations = remote.operations(); assert!( operations .iter() .all(|entry| !MUTATIONS.contains(&entry.operation)), "unexpected remote mutations: {operations:?}" ); } #[tokio::test] async fn download_uses_an_explicit_owned_temporary_root() { let source = source(); let remote = MemoryTransferFs::new(source.source().clone(), EPOCH).with_file(source.clone(), b"owned"); let backend = backend(&remote, &source, b"owned"); let parent = tempfile::TempDir::new().unwrap(); let workspace = download_remote_editor_at(source, &backend, EPOCH, parent.path()) .await .unwrap(); assert!(workspace.temporary_directory().starts_with(parent.path())); assert!(workspace.temporary_path().starts_with(parent.path())); assert!(workspace.pristine_path().starts_with(parent.path())); assert_no_remote_mutations(&remote); } #[tokio::test] async fn download_is_multi_chunk_bounded_and_remote_read_only() { let contents = (0..(3 * 64 * 1024 + 7919)) .map(|index| (index % 251) as u8) .collect::>(); let source = source(); let remote = MemoryTransferFs::new(source.source().clone(), EPOCH).with_file(source.clone(), &contents); remote.set_read_chunk_size(997); let backend = backend(&remote, &source, &contents); let workspace = download_remote_editor(source.clone(), &backend, EPOCH) .await .expect("multi-chunk download"); assert_eq!(workspace.session().remote_source(), &source); assert_eq!(workspace.session().epoch(), EPOCH); assert_eq!( workspace.session().original_fingerprint().size(), Some(contents.len() as u64) ); assert!(workspace.temporary_path().is_absolute()); assert!( workspace .temporary_path() .starts_with(workspace.temporary_directory()) ); assert_eq!( tokio::fs::read(workspace.temporary_path()).await.unwrap(), contents ); assert!(!workspace.has_changed().await.unwrap()); let operations = remote.operations(); assert_eq!(operation_count(&remote, TransferOperation::Metadata), 2); assert_eq!(operation_count(&remote, TransferOperation::Read), 1); assert_no_remote_mutations(&remote); assert!(operations.iter().all(|entry| entry.epoch == EPOCH)); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let file_mode = std::fs::metadata(workspace.temporary_path()) .unwrap() .permissions() .mode() & 0o777; let directory_mode = std::fs::metadata(workspace.temporary_directory()) .unwrap() .permissions() .mode() & 0o777; assert_eq!(file_mode, 0o600); assert_eq!(directory_mode, 0o700); } } #[tokio::test] async fn unchanged_temporary_file_returns_no_upload_without_remote_calls() { let (workspace, remote, source, backend) = downloaded(b"unchanged contents\n").await; assert!(!workspace.has_changed().await.unwrap()); let result = upload_editor_session(&workspace, &backend, &CancellationToken::new()).await; assert_eq!(result.outcome(), EditUploadOutcome::NoUpload); assert_eq!(result.error(), None); assert_eq!(result.partial(), None); assert!(remote.operations().is_empty()); assert_eq!( remote.file_contents(&source).unwrap(), b"unchanged contents\n" ); } #[tokio::test] async fn metadata_only_touch_is_still_no_upload() { let (workspace, remote, _source, backend) = downloaded(b"same bytes").await; let original = std::fs::metadata(workspace.temporary_path()).unwrap(); let mut permissions = original.permissions(); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; permissions.set_mode(0o600); } std::fs::set_permissions(workspace.temporary_path(), permissions).unwrap(); let result = upload_editor_session(&workspace, &backend, &CancellationToken::new()).await; assert_eq!(result.outcome(), EditUploadOutcome::NoUpload); assert!(remote.operations().is_empty()); } #[tokio::test] async fn changed_file_streams_through_one_part_and_commits_once() { let original = vec![b'a'; 70 * 1024]; let edited = (0..(2 * 64 * 1024 + 313)) .map(|index| (index % 239) as u8) .collect::>(); let (workspace, remote, source, backend) = downloaded(&original).await; tokio::fs::write(workspace.temporary_path(), &edited) .await .unwrap(); assert!(workspace.has_changed().await.unwrap()); let result = upload_editor_session(&workspace, &backend, &CancellationToken::new()).await; assert_eq!( result.outcome(), EditUploadOutcome::Committed, "{:?}", result.error() ); assert_eq!(result.error(), None); assert_eq!(result.partial(), None); assert_eq!(remote.file_contents(&source).unwrap(), edited); assert_eq!(operation_count(&remote, TransferOperation::OpenPart), 1); assert_eq!(operation_count(&remote, TransferOperation::Commit), 1); assert_eq!(operation_count(&remote, TransferOperation::DiscardPart), 0); assert_eq!(operation_count(&remote, TransferOperation::RemoveFile), 0); assert_eq!(operation_count(&remote, TransferOperation::RemoveDir), 0); assert!(remote.part_locations().is_empty()); assert!( remote .operations() .into_iter() .filter(|entry| entry.operation == TransferOperation::Write) .all(|entry| entry.bytes.is_some_and(|bytes| bytes <= 64 * 1024)) ); } #[tokio::test] async fn same_size_and_mtime_temporary_edit_is_detected() { let (workspace, remote, source, backend) = downloaded(b"before").await; let modified = std::fs::metadata(workspace.temporary_path()) .unwrap() .modified() .unwrap(); tokio::fs::write(workspace.temporary_path(), b"AFTER!") .await .unwrap(); tokio::fs::File::open(workspace.temporary_path()) .await .unwrap() .set_modified(modified) .await .unwrap(); assert!(workspace.has_changed().await.unwrap()); let result = upload_editor_session(&workspace, &backend, &CancellationToken::new()).await; assert_eq!(result.outcome(), EditUploadOutcome::Committed); assert_eq!(remote.file_contents(&source).unwrap(), b"AFTER!"); } #[tokio::test] async fn changed_remote_with_same_size_and_mtime_is_rejected_before_part_creation() { let (workspace, remote, source, backend) = downloaded(b"remote-before").await; tokio::fs::write(workspace.temporary_path(), b"local-edit") .await .unwrap(); // MemoryTransferFs deliberately exposes no mtime. Replacing equal-length contents therefore // leaves its complete EntryFingerprint unchanged and exercises the exact-content backstop. remote.insert_file(source.clone(), b"remote-AFTER!"); assert_eq!( remote.file_contents(&source).unwrap().len(), b"remote-before".len() ); remote.clear_operations(); let result = upload_editor_session(&workspace, &backend, &CancellationToken::new()).await; assert_eq!(result.outcome(), EditUploadOutcome::Failed); assert_eq!(result.stage(), Some(EditUploadStage::RemoteRead)); assert_eq!(operation_count(&remote, TransferOperation::OpenPart), 0); assert_no_remote_mutations(&remote); assert_eq!(remote.file_contents(&source).unwrap(), b"remote-AFTER!"); assert_eq!( tokio::fs::read(workspace.temporary_path()).await.unwrap(), b"local-edit" ); } #[tokio::test] async fn stale_epoch_is_rejected_before_any_remote_write() { let (workspace, remote, source, backend) = downloaded(b"original").await; tokio::fs::write(workspace.temporary_path(), b"edited") .await .unwrap(); let _current = remote.reconnect(EPOCH + 1); remote.clear_operations(); let result = upload_editor_session(&workspace, &backend, &CancellationToken::new()).await; assert_eq!(result.outcome(), EditUploadOutcome::Failed); assert_eq!(result.stage(), Some(EditUploadStage::RemoteMetadata)); assert!( matches!(result.error(), Some(FsError::Other(message)) if message.contains("stale session epoch")) ); assert_eq!(operation_count(&remote, TransferOperation::OpenPart), 0); assert_no_remote_mutations(&remote); assert_eq!(remote.file_contents(&source).unwrap(), b"original"); } #[tokio::test] async fn pre_cancelled_upload_does_not_touch_remote() { let (workspace, remote, source, backend) = downloaded(b"original").await; tokio::fs::write(workspace.temporary_path(), b"edited") .await .unwrap(); let cancellation = CancellationToken::new(); cancellation.cancel(); let result = upload_editor_session(&workspace, &backend, &cancellation).await; assert_eq!(result.outcome(), EditUploadOutcome::Cancelled); assert_eq!(result.error(), Some(&FsError::Cancelled)); assert!(remote.operations().is_empty()); assert_eq!(remote.file_contents(&source).unwrap(), b"original"); } #[tokio::test] async fn cancellation_during_write_keeps_source_and_part_diagnostics() { let (workspace, remote, source, backend) = downloaded(&vec![b'a'; 96 * 1024]).await; tokio::fs::write(workspace.temporary_path(), vec![b'b'; 96 * 1024]) .await .unwrap(); let gate = remote.gate_next(TransferOperation::Write); let cancellation = CancellationToken::new(); let upload = { let workspace = workspace.clone(); let backend = backend.clone(); let cancellation = cancellation.clone(); tokio::spawn( async move { upload_editor_session(&workspace, &backend, &cancellation).await }, ) }; gate.wait_entered().await; cancellation.cancel(); gate.release(); let result = upload.await.unwrap(); assert_eq!(result.outcome(), EditUploadOutcome::Cancelled); assert_eq!(result.stage(), Some(EditUploadStage::Write)); assert!(result.partial().is_some()); assert_eq!(remote.part_locations().len(), 1); assert_eq!( result.partial().map(|part| part.location()), remote.part_locations().first() ); assert_eq!( remote.file_contents(&source).unwrap(), vec![b'a'; 96 * 1024] ); assert_eq!(operation_count(&remote, TransferOperation::Commit), 0); assert_eq!(operation_count(&remote, TransferOperation::DiscardPart), 0); } #[tokio::test] async fn write_after_apply_timeout_is_unknown_and_preserves_source() { let (workspace, remote, source, backend) = downloaded(b"original").await; tokio::fs::write(workspace.temporary_path(), b"edited") .await .unwrap(); remote.fail_after_apply(TransferOperation::Write, FsError::Timeout); let result = upload_editor_session(&workspace, &backend, &CancellationToken::new()).await; assert_eq!(result.outcome(), EditUploadOutcome::Unknown); assert_eq!(result.stage(), Some(EditUploadStage::Write)); assert_eq!(result.error(), Some(&FsError::Timeout)); let partial = result.partial().expect("partial diagnostics"); assert_eq!(remote.part_locations(), vec![partial.location().clone()]); assert_eq!(remote.part_contents(partial.location()).unwrap(), b"edited"); assert_eq!(remote.file_contents(&source).unwrap(), b"original"); assert_eq!(operation_count(&remote, TransferOperation::Write), 1); assert_eq!(operation_count(&remote, TransferOperation::FlushClose), 0); assert_eq!(operation_count(&remote, TransferOperation::Commit), 0); assert_eq!(operation_count(&remote, TransferOperation::DiscardPart), 0); } #[tokio::test] async fn flush_after_apply_disconnect_is_unknown_with_closed_part() { let (workspace, remote, source, backend) = downloaded(b"original").await; tokio::fs::write(workspace.temporary_path(), b"edited") .await .unwrap(); remote.disconnect_after_apply(TransferOperation::FlushClose); let result = upload_editor_session(&workspace, &backend, &CancellationToken::new()).await; assert_eq!(result.outcome(), EditUploadOutcome::Unknown); assert_eq!(result.stage(), Some(EditUploadStage::FlushClose)); assert_eq!(result.error(), Some(&FsError::Disconnected)); let partial = result.partial().expect("partial diagnostics"); assert_eq!(remote.part_locations(), vec![partial.location().clone()]); assert_eq!(remote.part_is_closed(partial.location()), Some(true)); assert_eq!(remote.part_contents(partial.location()).unwrap(), b"edited"); assert_eq!(remote.file_contents(&source).unwrap(), b"original"); assert_eq!(operation_count(&remote, TransferOperation::FlushClose), 1); assert_eq!(operation_count(&remote, TransferOperation::Commit), 0); assert_eq!(operation_count(&remote, TransferOperation::DiscardPart), 0); } #[tokio::test] async fn commit_after_apply_disconnect_is_unknown_and_never_retried() { let (workspace, remote, source, backend) = downloaded(b"original").await; tokio::fs::write(workspace.temporary_path(), b"edited") .await .unwrap(); remote.disconnect_after_apply(TransferOperation::Commit); let result = upload_editor_session(&workspace, &backend, &CancellationToken::new()).await; assert_eq!(result.outcome(), EditUploadOutcome::Unknown); assert_eq!(result.stage(), Some(EditUploadStage::Commit)); assert_eq!(result.error(), Some(&FsError::Disconnected)); let diagnostic = result .partial() .expect("commit partial identity") .location(); assert!( diagnostic .file_name() .unwrap() .to_string_lossy() .starts_with(".rcom-part-") ); // The lost response happened after rename. Diagnostics retain the old .part identity without // claiming it remains on disk, and reconciliation must not issue a second commit. assert!(remote.part_locations().is_empty()); assert_eq!(remote.file_contents(&source).unwrap(), b"edited"); assert_eq!(operation_count(&remote, TransferOperation::Commit), 1); assert_eq!(operation_count(&remote, TransferOperation::DiscardPart), 0); assert_eq!(operation_count(&remote, TransferOperation::RemoveFile), 0); assert_eq!(operation_count(&remote, TransferOperation::RemoveDir), 0); assert_eq!( tokio::fs::read(workspace.temporary_path()).await.unwrap(), b"edited" ); } #[tokio::test] async fn temporary_directory_survives_clones_and_cleans_up_on_last_drop() { let (workspace, _remote, _source, _backend) = downloaded(b"owned fixture").await; let clone = workspace.clone(); let directory = workspace.temporary_directory().to_path_buf(); let editable = workspace.temporary_path().to_path_buf(); drop(workspace); assert!(directory.exists()); assert!(editable.exists()); assert_eq!(std::fs::read(&editable).unwrap(), b"owned fixture"); drop(clone); assert!(!directory.exists()); assert!(!editable.exists()); }