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

416 lines
14 KiB
Rust

use std::collections::BTreeMap;
use std::path::Path;
use std::sync::Arc;
use rcom::actions::{
EditUploadOutcome, EntryMutationKind, EntryMutationPlan, TrashPolicy, UndoJournal,
download_remote_editor_at, execute_delete, execute_entry_mutation, execute_undo,
prepare_delete, prepare_trash, prepare_undo, upload_editor_session,
};
use rcom::domain::{HostAlias, Location, SourceId};
use rcom::fs::{BackendHandle, BackendRegistry, FsError, LocalFs, execute_prepared_copy_move};
use rcom::operations::{
CollisionPolicy, CommitOutcome, EntryFingerprint, ItemPhase, OperationKind, OperationPlanner,
OperationRequest, PlanGeneration, PlanId, SourceCleanupOutcome,
};
use rcom::ssh::{ConnectionManager, OpenSshConnector};
use tempfile::TempDir;
use tokio::io::AsyncReadExt;
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
const HOST: &str = "hermesVM";
fn epochs(epoch: u64) -> BTreeMap<SourceId, u64> {
BTreeMap::from([(SourceId::Ssh(HostAlias::new(HOST)), epoch)])
}
fn inside(location: &Location, sandbox: &Path) {
assert_eq!(location.source, SourceId::Ssh(HostAlias::new(HOST)));
assert!(location.path().starts_with(sandbox), "path escaped sandbox");
}
fn assert_action_success(result: &rcom::actions::ActionResult) {
assert_eq!(result.outcome().phase(), ItemPhase::Succeeded);
assert_eq!(result.outcome().commit(), CommitOutcome::Committed);
assert!(matches!(
result.outcome().source_cleanup(),
SourceCleanupOutcome::NotRequired | SourceCleanupOutcome::Removed
));
}
async fn remote_text(backend: &BackendHandle, location: &Location) -> Vec<u8> {
let mut bytes = Vec::new();
backend
.transfer
.open_read(location)
.await
.unwrap()
.read_to_end(&mut bytes)
.await
.unwrap();
bytes
}
async fn overwrite_owned(backend: &BackendHandle, destination: &Location, contents: &[u8]) {
let source = backend.transfer.metadata(destination, false).await.unwrap();
let mut part = backend.transfer.open_part(destination).await.unwrap();
backend
.transfer
.write_part(&mut part, contents)
.await
.unwrap();
let part = backend.transfer.flush_and_close(part).await.unwrap();
backend
.transfer
.commit_part_with_metadata(part, &source)
.await
.unwrap();
}
async fn undo_latest(journal: &mut UndoJournal, backend: &BackendHandle, id: u64) {
let entry = journal.latest().cloned().unwrap();
let prepared = prepare_undo(
&entry,
PlanId::new(id),
PlanGeneration::new(id),
BTreeMap::from([(backend.source_id().clone(), backend.clone())]),
)
.await
.unwrap();
let result = execute_undo(&prepared, &CancellationToken::new()).await;
assert!(result.is_fully_successful(), "undo failed: {result:?}");
assert!(rcom::actions::consume_undo_on_success(
journal, &entry, &result
));
}
#[tokio::test]
#[ignore = "all writes are restricted to a fresh hermesVM UUID sandbox"]
async fn hermesvm_file_actions_and_editor_acceptance() {
let host = HostAlias::new(HOST);
let connections = ConnectionManager::new(
Arc::new(OpenSshConnector::default()),
BackendRegistry::new(Arc::new(LocalFs::new())),
);
let connection = connections.connect(&host).await.unwrap();
let epoch = connection.epoch;
let backend = connections
.resolve_operations(&Location::ssh(host.clone(), "/tmp"), Some(epoch))
.await
.unwrap();
let sandbox_path = std::path::PathBuf::from(format!("/tmp/rcom-acceptance-{}", Uuid::new_v4()));
let sandbox = Location::ssh(host, sandbox_path.clone());
match backend.transfer.metadata(&sandbox, false).await {
Err(FsError::NotFound) => {}
Ok(_) => panic!("refusing to reuse an existing sandbox"),
Err(error) => panic!("cannot inspect sandbox: {error}"),
}
backend.transfer.create_dir(&sandbox).await.unwrap();
let work = sandbox.join("work");
let moved = sandbox.join("moved");
backend.transfer.create_dir(&work).await.unwrap();
backend.transfer.create_dir(&moved).await.unwrap();
let policy = TrashPolicy::new(sandbox.join("trash"), Some(sandbox.clone())).unwrap();
let editor_temp = TempDir::new().unwrap();
let mut journal = UndoJournal::new();
let file = work.join("file.txt");
let create = EntryMutationPlan::create(
PlanId::new(1),
PlanGeneration::new(1),
EntryMutationKind::CreateFile,
rcom::operations::ItemId::new(1),
work.clone(),
"file.txt",
epochs(epoch),
)
.unwrap();
inside(create.destination().unwrap(), &sandbox_path);
let created = execute_entry_mutation(&create, &backend, &CancellationToken::new()).await;
assert_action_success(&created);
let created_fingerprint =
EntryFingerprint::from(&backend.transfer.metadata(&file, false).await.unwrap());
journal
.record_create(
create.clone(),
created_fingerprint.clone(),
&[created.outcome()],
)
.unwrap();
let rename = EntryMutationPlan::rename(
PlanId::new(2),
PlanGeneration::new(2),
rcom::operations::ItemId::new(1),
file.clone(),
created_fingerprint,
"renamed.txt",
epochs(epoch),
)
.unwrap();
let renamed = execute_entry_mutation(&rename, &backend, &CancellationToken::new()).await;
assert_action_success(&renamed);
let renamed_path = work.join("renamed.txt");
let renamed_fingerprint = EntryFingerprint::from(
&backend
.transfer
.metadata(&renamed_path, false)
.await
.unwrap(),
);
journal
.record_rename(rename.clone(), renamed_fingerprint, &[renamed.outcome()])
.unwrap();
undo_latest(&mut journal, &backend, 3).await;
assert_eq!(remote_text(&backend, &file).await, b"");
let (trash_plan, records) = prepare_trash(
PlanId::new(4),
PlanGeneration::new(4),
vec![file.clone()],
epochs(epoch),
&backend,
&policy,
)
.await
.unwrap();
inside(records[0].trashed(), &sandbox_path);
let trashed_results = rcom::actions::execute_trash(
&trash_plan,
&records,
&backend,
&policy,
&CancellationToken::new(),
)
.await;
assert_eq!(trashed_results.len(), 1);
assert_action_success(&trashed_results[0]);
journal
.record_trash(
trash_plan.clone(),
records.clone(),
&trashed_results
.iter()
.map(|result| result.outcome())
.collect::<Vec<_>>(),
)
.unwrap();
undo_latest(&mut journal, &backend, 5).await;
assert_eq!(remote_text(&backend, &file).await, b"");
// Trash/undo of a non-empty directory uses root-scoped records but validates the full tree.
let directory = work.join("directory");
let child = directory.join("child.txt");
backend.transfer.create_dir(&directory).await.unwrap();
backend.transfer.create_file(&child).await.unwrap();
overwrite_owned(&backend, &child, b"child").await;
let (directory_plan, directory_records) = prepare_trash(
PlanId::new(100),
PlanGeneration::new(100),
vec![directory.clone()],
epochs(epoch),
&backend,
&policy,
)
.await
.unwrap();
assert!(directory_plan.nodes().len() > 1);
assert_eq!(directory_records.len(), 1);
let directory_results = rcom::actions::execute_trash(
&directory_plan,
&directory_records,
&backend,
&policy,
&CancellationToken::new(),
)
.await;
assert_eq!(directory_results.len(), 1);
assert_action_success(&directory_results[0]);
journal
.record_trash(
directory_plan,
directory_records.clone(),
&directory_results
.iter()
.map(|result| result.outcome())
.collect::<Vec<_>>(),
)
.unwrap();
undo_latest(&mut journal, &backend, 101).await;
assert_eq!(remote_text(&backend, &child).await, b"child");
let move_request = OperationRequest::new(
PlanId::new(6),
PlanGeneration::new(6),
OperationKind::Move,
vec![file.clone()],
moved.clone(),
CollisionPolicy::Ask,
epochs(epoch),
);
let prepared_move = OperationPlanner::new(Arc::new(backend.clone()), Arc::new(backend.clone()))
.prepare(move_request)
.await
.unwrap();
for item in prepared_move.items() {
inside(item.source(), &sandbox_path);
inside(item.destination(), &sandbox_path);
}
let move_results = execute_prepared_copy_move(
&prepared_move,
&backend,
&backend,
&CancellationToken::new(),
)
.await;
assert!(move_results.iter().all(|result| {
result.outcome().phase() == ItemPhase::Succeeded
&& result.outcome().source_cleanup() == SourceCleanupOutcome::Removed
}));
let mut destination_fingerprints = BTreeMap::new();
for item in prepared_move.items() {
destination_fingerprints.insert(
item.id(),
EntryFingerprint::from(
&backend
.transfer
.metadata(item.destination(), false)
.await
.unwrap(),
),
);
}
journal
.record_move(
prepared_move.clone(),
destination_fingerprints,
&move_results
.iter()
.map(|result| result.outcome())
.collect::<Vec<_>>(),
)
.unwrap();
undo_latest(&mut journal, &backend, 7).await;
assert_eq!(remote_text(&backend, &file).await, b"");
// Create a separate file for remote editing and prove that unchanged input never uploads.
let edit_file = work.join("edit.txt");
backend.transfer.create_file(&edit_file).await.unwrap();
overwrite_owned(&backend, &edit_file, b"before").await;
let workspace =
download_remote_editor_at(edit_file.clone(), &backend, epoch, editor_temp.path())
.await
.unwrap();
inside(workspace.session().remote_source(), &sandbox_path);
assert!(
workspace
.temporary_directory()
.starts_with(editor_temp.path())
);
assert!(workspace.temporary_path().starts_with(editor_temp.path()));
assert!(workspace.pristine_path().starts_with(editor_temp.path()));
assert_eq!(
upload_editor_session(&workspace, &backend, &CancellationToken::new())
.await
.outcome(),
EditUploadOutcome::NoUpload
);
tokio::fs::write(workspace.temporary_path(), b"after")
.await
.unwrap();
assert!(workspace.has_changed().await.unwrap());
assert_eq!(
upload_editor_session(&workspace, &backend, &CancellationToken::new())
.await
.outcome(),
EditUploadOutcome::Committed
);
assert_eq!(remote_text(&backend, &edit_file).await, b"after");
// A changed remote source invalidates an older editor session before any new part is created.
let stale_workspace =
download_remote_editor_at(edit_file.clone(), &backend, epoch, editor_temp.path())
.await
.unwrap();
tokio::fs::write(stale_workspace.temporary_path(), b"stale")
.await
.unwrap();
overwrite_owned(&backend, &edit_file, b"external").await;
let stale = upload_editor_session(&stale_workspace, &backend, &CancellationToken::new()).await;
assert_eq!(stale.outcome(), EditUploadOutcome::Failed);
assert_eq!(remote_text(&backend, &edit_file).await, b"external");
drop(stale_workspace);
let empty = work.join("empty");
let create_empty = EntryMutationPlan::create(
PlanId::new(8),
PlanGeneration::new(8),
EntryMutationKind::CreateDirectory,
rcom::operations::ItemId::new(1),
work.clone(),
"empty",
epochs(epoch),
)
.unwrap();
assert_action_success(
&execute_entry_mutation(&create_empty, &backend, &CancellationToken::new()).await,
);
let delete = prepare_delete(
PlanId::new(9),
PlanGeneration::new(9),
vec![
file.clone(),
edit_file.clone(),
empty.clone(),
directory.clone(),
],
epochs(epoch),
&backend,
)
.await
.unwrap();
let deleted = execute_delete(&delete, &backend, &CancellationToken::new()).await;
assert_eq!(deleted.len(), 4);
assert!(
deleted
.iter()
.all(|result| result.outcome().phase() == ItemPhase::Succeeded)
);
// Only known, owned records and empty directories remain after the operations.
let info = policy
.root()
.join("info")
.join(format!("{}.trashinfo", records[0].id()));
inside(&info, &sandbox_path);
backend.transfer.remove_file(&info).await.unwrap();
let directory_info = policy
.root()
.join("info")
.join(format!("{}.trashinfo", directory_records[0].id()));
inside(&directory_info, &sandbox_path);
backend.transfer.remove_file(&directory_info).await.unwrap();
backend
.transfer
.remove_dir(&policy.root().join("info"))
.await
.unwrap();
backend
.transfer
.remove_dir(&policy.root().join("files"))
.await
.unwrap();
backend.transfer.remove_dir(policy.root()).await.unwrap();
backend.transfer.remove_dir(&moved).await.unwrap();
backend.transfer.remove_dir(&work).await.unwrap();
backend.transfer.remove_dir(&sandbox).await.unwrap();
assert_eq!(
backend
.transfer
.metadata(&sandbox, false)
.await
.unwrap_err(),
FsError::NotFound
);
}