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

1103 lines
37 KiB
Rust

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use rcom::actions::{
ActionResult, EntryMutationKind, MutationStage, TrashEvent, TrashPolicy, TrashRecord,
execute_trash, execute_trash_observed, prepare_trash,
};
use rcom::domain::{Entry, EntryKind, HostAlias, Location, SourceId};
use rcom::fs::{
BackendHandle, FileOperations, FsError, LocalFileOperations, LocalFs, PartFile, PartWriter,
ReadFileSystem, ReadStream, StagingDirectory, StagingOperations, TransferCapabilities,
};
use rcom::operations::{CommitOutcome, ItemPhase, PlanGeneration, PlanId, SourceCleanupOutcome};
use rcom::test_support::{FsOperation, MemoryTransferFs, RecordingFs, TransferOperation};
use tempfile::TempDir;
use tokio_util::sync::CancellationToken;
const ROOT: &str = "/sandbox/trash";
const SANDBOX: &str = "/sandbox";
/// The shared double records part contents separately and does not expose them through metadata.
/// Generic copy/move correctly performs a size check, so this adapter supplies that one missing
/// read while leaving all mutations, failpoints, epochs, and journals in the shared double.
#[derive(Clone)]
struct PartMetadataFs(MemoryTransferFs);
#[async_trait]
impl StagingOperations for PartMetadataFs {
async fn create_dir(&self, location: &Location) -> Result<(), FsError> {
self.0.create_dir(location).await
}
async fn create_staging_dir(
&self,
destination: &Location,
) -> Result<StagingDirectory, FsError> {
self.0.create_staging_dir(destination).await
}
}
#[async_trait]
impl FileOperations for PartMetadataFs {
fn source_id(&self) -> &SourceId {
self.0.source_id()
}
fn capabilities(&self) -> TransferCapabilities {
self.0.capabilities()
}
async fn canonicalize(&self, location: &Location) -> Result<Location, FsError> {
FileOperations::canonicalize(&self.0, location).await
}
async fn metadata(&self, location: &Location, follow: bool) -> Result<Entry, FsError> {
match FileOperations::metadata(&self.0, location, follow).await {
Err(FsError::NotFound) => {
let contents = self.0.part_contents(location)?;
Ok(Entry::new(
location.file_name_owned().unwrap_or_default(),
EntryKind::File,
)
.with_metadata(Some(contents.len() as u64), None, None))
}
result => result,
}
}
async fn open_read(&self, location: &Location) -> Result<ReadStream, FsError> {
self.0.open_read(location).await
}
async fn open_part(&self, destination: &Location) -> Result<PartWriter, FsError> {
self.0.open_part(destination).await
}
async fn write_part(&self, part: &mut PartWriter, chunk: &[u8]) -> Result<(), FsError> {
self.0.write_part(part, chunk).await
}
async fn flush_and_close(&self, part: PartWriter) -> Result<PartFile, FsError> {
self.0.flush_and_close(part).await
}
async fn commit_part(&self, part: PartFile) -> Result<(), FsError> {
self.0.commit_part(part).await
}
async fn discard_part(&self, part: PartFile) -> Result<(), FsError> {
self.0.discard_part(part).await
}
async fn create_file(&self, location: &Location) -> Result<(), FsError> {
self.0.create_file(location).await
}
async fn rename(&self, from: &Location, to: &Location) -> Result<(), FsError> {
self.0.rename(from, to).await
}
async fn remove_file(&self, location: &Location) -> Result<(), FsError> {
self.0.remove_file(location).await
}
async fn remove_dir(&self, location: &Location) -> Result<(), FsError> {
self.0.remove_dir(location).await
}
}
fn memory_backend(fs: &MemoryTransferFs) -> BackendHandle {
memory_backend_with_read(fs, Arc::new(fs.clone()))
}
fn memory_backend_with_read(fs: &MemoryTransferFs, read: Arc<dyn ReadFileSystem>) -> BackendHandle {
BackendHandle::new(
fs.source_id().clone(),
read,
Arc::new(PartMetadataFs(fs.clone())),
)
.unwrap()
}
fn local_backend() -> BackendHandle {
BackendHandle::new(
SourceId::Local,
Arc::new(LocalFs::new()),
Arc::new(LocalFileOperations::new()),
)
.unwrap()
}
/// Fails the initial trash rename and the prepared executor's rename, then permits staging commits.
#[derive(Clone)]
struct CrossDeviceLocalFs {
inner: LocalFileOperations,
remaining_failures: Arc<Mutex<usize>>,
}
impl CrossDeviceLocalFs {
fn new(failures: usize) -> Self {
Self {
inner: LocalFileOperations::new(),
remaining_failures: Arc::new(Mutex::new(failures)),
}
}
fn remaining_failures(&self) -> usize {
*self
.remaining_failures
.lock()
.unwrap_or_else(|error| error.into_inner())
}
}
#[async_trait]
impl StagingOperations for CrossDeviceLocalFs {
async fn create_dir(&self, location: &Location) -> Result<(), FsError> {
self.inner.create_dir(location).await
}
async fn create_staging_dir(
&self,
destination: &Location,
) -> Result<StagingDirectory, FsError> {
self.inner.create_staging_dir(destination).await
}
}
#[async_trait]
impl FileOperations for CrossDeviceLocalFs {
fn source_id(&self) -> &SourceId {
self.inner.source_id()
}
fn capabilities(&self) -> TransferCapabilities {
self.inner.capabilities()
}
async fn canonicalize(&self, location: &Location) -> Result<Location, FsError> {
self.inner.canonicalize(location).await
}
async fn metadata(&self, location: &Location, follow: bool) -> Result<Entry, FsError> {
self.inner.metadata(location, follow).await
}
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 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> {
let should_fail = {
let mut remaining = self
.remaining_failures
.lock()
.unwrap_or_else(|error| error.into_inner());
if *remaining > 0 {
*remaining -= 1;
true
} else {
false
}
};
if should_fail {
return Err(FsError::Unsupported("cross-device rename".into()));
}
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 policy(root: Location, sandbox: Option<Location>) -> TrashPolicy {
TrashPolicy::new(root, sandbox).unwrap()
}
async fn prepare_memory(
fs: &MemoryTransferFs,
sources: Vec<Location>,
) -> (
rcom::actions::EntryMutationPlan,
Vec<TrashRecord>,
TrashPolicy,
) {
let endpoint = fs.source_id().clone();
let root = Location {
source: endpoint.clone(),
path: ROOT.into(),
};
let sandbox = Location {
source: endpoint.clone(),
path: SANDBOX.into(),
};
let policy = policy(root, Some(sandbox));
let backend = memory_backend(fs);
let (plan, records) = prepare_trash(
PlanId::new(71),
PlanGeneration::new(9),
sources,
BTreeMap::from([(endpoint, fs.epoch())]),
&backend,
&policy,
)
.await
.unwrap();
(plan, records, policy)
}
fn info_location(record: &TrashRecord, root: &Location) -> Location {
root.join("info").join(format!("{}.trashinfo", record.id()))
}
fn operation_count(fs: &MemoryTransferFs, operation: TransferOperation) -> usize {
fs.operations()
.iter()
.filter(|entry| entry.operation == operation)
.count()
}
fn assert_not_moved(result: &ActionResult, stage: MutationStage) {
assert_eq!(result.outcome().phase(), ItemPhase::Failed);
assert_eq!(result.outcome().commit(), CommitOutcome::NotAttempted);
assert_eq!(result.stage(), stage);
assert!(result.error().is_some());
}
#[tokio::test]
async fn trash_success_writes_percent_encoded_restore_info_before_one_safe_rename() {
let fixture = TempDir::new().unwrap();
let work = fixture.path().join("work");
std::fs::create_dir(&work).unwrap();
let source_path = work.join("a b%#т.txt");
std::fs::write(&source_path, b"contents").unwrap();
let source = Location::local(&source_path);
let root = Location::local(fixture.path().join("trash"));
let sandbox = Location::local(fixture.path());
let policy = policy(root.clone(), Some(sandbox));
let backend = local_backend();
let (plan, records) = prepare_trash(
PlanId::new(1),
PlanGeneration::new(1),
vec![source.clone()],
BTreeMap::new(),
&backend,
&policy,
)
.await
.unwrap();
assert_eq!(plan.kind(), EntryMutationKind::Trash);
assert_eq!(records.len(), 1);
assert_eq!(records[0].original(), &source);
assert_eq!(
records[0].fingerprint(),
plan.nodes()[0].fingerprint().unwrap()
);
assert!(source_path.exists());
assert!(!root.path().exists());
let results = execute_trash(
&plan,
&records,
&backend,
&policy,
&CancellationToken::new(),
)
.await;
assert_eq!(results.len(), 1);
assert_eq!(results[0].outcome().phase(), ItemPhase::Succeeded);
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
assert_eq!(
results[0].outcome().source_cleanup(),
SourceCleanupOutcome::NotRequired
);
assert_eq!(results[0].stage(), MutationStage::TrashMove);
assert!(!source_path.exists());
assert_eq!(
std::fs::read(records[0].trashed().path()).unwrap(),
b"contents"
);
let info = std::fs::read_to_string(info_location(&records[0], &root).path()).unwrap();
assert!(info.starts_with("[Trash Info]\nPath="));
let encoded_path = info
.lines()
.find_map(|line| line.strip_prefix("Path="))
.unwrap();
assert!(encoded_path.ends_with("/a%20b%25%23%D1%82.txt"));
assert!(!encoded_path.contains(' '));
let deletion_date = info
.lines()
.find_map(|line| line.strip_prefix("DeletionDate="))
.unwrap();
assert_eq!(deletion_date.len(), "2026-12-05T12:34:56".len());
assert_eq!(
std::fs::read_dir(root.join("info").path()).unwrap().count(),
1
);
}
#[tokio::test]
async fn trash_multi_uses_unique_uuids_and_prepare_is_read_only_for_local_and_ssh() {
for host in [None, Some(HostAlias::new("edge"))] {
let endpoint = host.clone().map_or(SourceId::Local, SourceId::Ssh);
let first = Location {
source: endpoint.clone(),
path: "/sandbox/work/b.txt".into(),
};
let second = Location {
source: endpoint.clone(),
path: "/sandbox/work/a.txt".into(),
};
let fs = MemoryTransferFs::new(endpoint, 17)
.with_file(first.clone(), b"first")
.with_file(second.clone(), b"second");
let (plan, records, policy) =
prepare_memory(&fs, vec![first.clone(), second.clone()]).await;
assert_eq!(plan.nodes()[0].location(), &second);
assert_eq!(plan.nodes()[1].location(), &first);
assert_eq!(records.len(), 2);
assert_eq!(
records
.iter()
.map(TrashRecord::id)
.collect::<BTreeSet<_>>()
.len(),
2
);
assert!(records.iter().all(|record| record.epoch() == 17));
assert!(
fs.operations()
.iter()
.all(|entry| entry.operation == TransferOperation::Metadata)
);
fs.clear_operations();
let results = execute_trash(
&plan,
&records,
&memory_backend(&fs),
&policy,
&CancellationToken::new(),
)
.await;
assert_eq!(results.len(), 2);
assert!(results.iter().all(|result| {
result.outcome().phase() == ItemPhase::Succeeded
&& result.outcome().commit() == CommitOutcome::Committed
}));
assert_eq!(fs.file_contents(&first), Err(FsError::NotFound));
assert_eq!(fs.file_contents(&second), Err(FsError::NotFound));
assert_eq!(fs.file_contents(records[0].trashed()).unwrap(), b"second");
assert_eq!(fs.file_contents(records[1].trashed()).unwrap(), b"first");
assert_eq!(operation_count(&fs, TransferOperation::Rename), 2);
assert_eq!(operation_count(&fs, TransferOperation::RemoveFile), 0);
assert_eq!(operation_count(&fs, TransferOperation::RemoveDir), 0);
}
}
#[cfg(unix)]
#[tokio::test]
async fn trash_planning_rejects_a_symlink_without_touching_target_or_root() {
let fixture = TempDir::new().unwrap();
let target = fixture.path().join("target");
let link = fixture.path().join("link");
std::fs::write(&target, b"keep").unwrap();
std::os::unix::fs::symlink(&target, &link).unwrap();
let root = Location::local(fixture.path().join("trash"));
let policy = policy(root.clone(), Some(Location::local(fixture.path())));
let result = prepare_trash(
PlanId::new(1),
PlanGeneration::new(1),
vec![Location::local(&link)],
BTreeMap::new(),
&local_backend(),
&policy,
)
.await;
assert!(matches!(result, Err(FsError::Unsupported(_))));
assert_eq!(std::fs::read(target).unwrap(), b"keep");
assert!(std::fs::symlink_metadata(link).is_ok());
assert!(!root.path().exists());
}
#[tokio::test]
async fn trash_existing_file_or_info_collision_preserves_source_and_existing_bytes() {
for collision_is_info in [false, true] {
let source = Location::local("/sandbox/work/source");
let fs = MemoryTransferFs::local().with_file(source.clone(), b"source");
let (plan, records, policy) = prepare_memory(&fs, vec![source.clone()]).await;
let collision = if collision_is_info {
info_location(&records[0], policy.root())
} else {
records[0].trashed().clone()
};
fs.insert_file(collision.clone(), b"do not overwrite");
fs.clear_operations();
let results = execute_trash(
&plan,
&records,
&memory_backend(&fs),
&policy,
&CancellationToken::new(),
)
.await;
assert_not_moved(&results[0], MutationStage::Destination);
assert_eq!(fs.file_contents(&source).unwrap(), b"source");
assert_eq!(fs.file_contents(&collision).unwrap(), b"do not overwrite");
assert_eq!(operation_count(&fs, TransferOperation::OpenPart), 0);
assert_eq!(operation_count(&fs, TransferOperation::Rename), 0);
assert_eq!(operation_count(&fs, TransferOperation::RemoveFile), 0);
}
}
#[tokio::test]
async fn trash_info_write_failure_preserves_source_and_diagnoses_owned_part() {
let source = Location::local("/sandbox/work/source");
let fs = MemoryTransferFs::local().with_file(source.clone(), b"source");
let (plan, records, policy) = prepare_memory(&fs, vec![source.clone()]).await;
fs.clear_operations();
fs.fail_next(TransferOperation::Write, FsError::PermissionDenied);
let results = execute_trash(
&plan,
&records,
&memory_backend(&fs),
&policy,
&CancellationToken::new(),
)
.await;
assert_not_moved(&results[0], MutationStage::TrashInfo);
assert_eq!(fs.file_contents(&source).unwrap(), b"source");
assert_eq!(
fs.file_contents(&info_location(&records[0], policy.root())),
Err(FsError::NotFound)
);
let parts = fs.part_locations();
assert_eq!(parts.len(), 1);
let diagnostic = results[0].error().unwrap().to_string();
assert!(diagnostic.contains(parts[0].path().to_string_lossy().as_ref()));
assert!(fs.part_is_closed(&parts[0]) == Some(false));
assert_eq!(operation_count(&fs, TransferOperation::DiscardPart), 0);
assert_eq!(operation_count(&fs, TransferOperation::Rename), 0);
assert_eq!(operation_count(&fs, TransferOperation::RemoveFile), 0);
}
#[tokio::test]
async fn trash_rename_failure_preserves_source_and_never_falls_back_to_delete() {
let source = Location::local("/sandbox/work/source");
let fs = MemoryTransferFs::local().with_file(source.clone(), b"source");
let (plan, records, policy) = prepare_memory(&fs, vec![source.clone()]).await;
fs.clear_operations();
fs.fail_next(TransferOperation::Rename, FsError::PermissionDenied);
let results = execute_trash(
&plan,
&records,
&memory_backend(&fs),
&policy,
&CancellationToken::new(),
)
.await;
assert_eq!(results[0].outcome().phase(), ItemPhase::Failed);
assert_eq!(results[0].outcome().commit(), CommitOutcome::NotCommitted);
assert_eq!(results[0].stage(), MutationStage::TrashMove);
assert_eq!(fs.file_contents(&source).unwrap(), b"source");
assert_eq!(
fs.file_contents(records[0].trashed()),
Err(FsError::NotFound)
);
assert!(
!fs.file_contents(&info_location(&records[0], policy.root()))
.unwrap()
.is_empty()
);
assert_eq!(operation_count(&fs, TransferOperation::Rename), 1);
assert_eq!(operation_count(&fs, TransferOperation::Read), 0);
assert_eq!(operation_count(&fs, TransferOperation::RemoveFile), 0);
assert_eq!(operation_count(&fs, TransferOperation::RemoveDir), 0);
}
#[tokio::test]
async fn trash_cross_device_uses_confirmed_prepared_move_and_cleans_source_once() {
let source = Location::local("/sandbox/work/source");
let fs = MemoryTransferFs::local().with_file(source.clone(), b"source contents");
let (plan, records, policy) = prepare_memory(&fs, vec![source.clone()]).await;
fs.clear_operations();
for _ in 0..2 {
fs.fail_next(
TransferOperation::Rename,
FsError::Unsupported("cross-device rename".into()),
);
}
let results = execute_trash(
&plan,
&records,
&memory_backend(&fs),
&policy,
&CancellationToken::new(),
)
.await;
assert_eq!(
results[0].outcome().phase(),
ItemPhase::Succeeded,
"{:?}",
results[0]
);
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
assert_eq!(results[0].stage(), MutationStage::TrashMove);
assert_eq!(fs.file_contents(&source), Err(FsError::NotFound));
assert_eq!(
fs.file_contents(records[0].trashed()).unwrap(),
b"source contents"
);
assert_eq!(operation_count(&fs, TransferOperation::Rename), 3);
assert_eq!(operation_count(&fs, TransferOperation::Read), 1);
assert_eq!(operation_count(&fs, TransferOperation::Commit), 2);
assert_eq!(operation_count(&fs, TransferOperation::RemoveFile), 1);
assert_eq!(operation_count(&fs, TransferOperation::RemoveDir), 1);
}
#[tokio::test]
async fn trash_cross_device_directory_uses_the_fixed_tree_without_execution_listing() {
let fixture = TempDir::new().unwrap();
let source_path = fixture.path().join("work/root");
let nested_path = source_path.join("nested");
let first_path = source_path.join("a.txt");
let second_path = nested_path.join("b.txt");
std::fs::create_dir_all(&nested_path).unwrap();
std::fs::write(&first_path, b"first").unwrap();
std::fs::write(&second_path, b"second").unwrap();
let source = Location::local(&source_path);
let nested = Location::local(&nested_path);
let reader = Arc::new(RecordingFs::new(Arc::new(LocalFs::new())));
let transfer = CrossDeviceLocalFs::new(2);
let backend = BackendHandle::new(SourceId::Local, reader.clone(), Arc::new(transfer)).unwrap();
let policy = policy(
Location::local(fixture.path().join("trash")),
Some(Location::local(fixture.path())),
);
let (plan, records) = prepare_trash(
PlanId::new(72),
PlanGeneration::new(10),
vec![source],
BTreeMap::new(),
&backend,
&policy,
)
.await
.unwrap();
assert_eq!(
plan.nodes()
.iter()
.map(|node| node.relative_path().to_path_buf())
.collect::<Vec<_>>(),
[
PathBuf::from("root"),
PathBuf::from("root/a.txt"),
PathBuf::from("root/nested"),
PathBuf::from("root/nested/b.txt"),
]
);
assert_eq!(
plan.nodes()
.iter()
.map(|node| node.id().get())
.collect::<Vec<_>>(),
[1, 2, 3, 4]
);
assert!(plan.nodes().iter().all(|node| node.fingerprint().is_some()));
assert_eq!(records.len(), 1);
assert!(
reader
.operations()
.iter()
.any(|entry| { entry.operation == FsOperation::List && entry.location == nested })
);
reader.clear();
let results = execute_trash(
&plan,
&records,
&backend,
&policy,
&CancellationToken::new(),
)
.await;
assert_eq!(results.len(), 1);
assert_eq!(results[0].outcome().id(), plan.nodes()[0].id());
assert_eq!(
results[0].outcome().phase(),
ItemPhase::Succeeded,
"{:?}",
results[0]
);
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
assert!(!source_path.exists());
assert_eq!(
std::fs::read(records[0].trashed().path().join("a.txt")).unwrap(),
b"first"
);
assert_eq!(
std::fs::read(records[0].trashed().path().join("nested/b.txt")).unwrap(),
b"second"
);
assert!(
reader
.operations()
.iter()
.all(|entry| entry.operation != FsOperation::List),
"execution must not rediscover the confirmed tree"
);
}
#[tokio::test]
async fn trash_cross_device_rejects_a_replaced_descendant_without_copy_or_delete() {
let source = Location::local("/sandbox/work/root");
let confirmed = Location::local("/sandbox/work/root/nested/confirmed.txt");
let fs = MemoryTransferFs::local()
.with_dir(source.clone())
.with_file(confirmed.clone(), b"confirmed");
let reader = Arc::new(RecordingFs::new(Arc::new(fs.clone())));
let backend = memory_backend_with_read(&fs, reader.clone());
let policy = policy(Location::local(ROOT), Some(Location::local(SANDBOX)));
let (plan, records) = prepare_trash(
PlanId::new(73),
PlanGeneration::new(11),
vec![source.clone()],
BTreeMap::new(),
&backend,
&policy,
)
.await
.unwrap();
assert_eq!(plan.nodes().len(), 3);
reader.clear();
fs.clear_operations();
// This is the unconfirmed content that a second OperationPlanner listing would otherwise add
// to the execution plan after confirmation.
fs.insert_file(confirmed.clone(), b"malicious replacement");
for _ in 0..2 {
fs.fail_next(
TransferOperation::Rename,
FsError::Unsupported("cross-device rename".into()),
);
}
let results = execute_trash(
&plan,
&records,
&backend,
&policy,
&CancellationToken::new(),
)
.await;
assert_eq!(results.len(), 1);
assert_not_moved(&results[0], MutationStage::TrashMove);
assert_eq!(
fs.file_contents(&confirmed).unwrap(),
b"malicious replacement"
);
assert_eq!(
fs.file_contents(records[0].trashed()),
Err(FsError::NotFound)
);
assert_eq!(operation_count(&fs, TransferOperation::Read), 0);
assert_eq!(operation_count(&fs, TransferOperation::Rename), 1);
assert_eq!(operation_count(&fs, TransferOperation::RemoveFile), 0);
assert_eq!(operation_count(&fs, TransferOperation::RemoveDir), 0);
assert!(
reader
.operations()
.iter()
.all(|entry| entry.operation != FsOperation::List)
);
}
#[tokio::test]
async fn trash_cross_device_rejects_an_external_descendant_before_commit_or_delete() {
let fixture = TempDir::new().unwrap();
let source_path = fixture.path().join("work/root");
let nested_path = source_path.join("nested");
let confirmed_path = nested_path.join("confirmed.txt");
std::fs::create_dir_all(&nested_path).unwrap();
std::fs::write(&confirmed_path, b"confirmed").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&nested_path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let source = Location::local(&source_path);
let nested = Location::local(&nested_path);
let root = Location::local(fixture.path().join("trash"));
let policy = policy(root, Some(Location::local(fixture.path())));
let reader = Arc::new(RecordingFs::new(Arc::new(LocalFs::new())));
let transfer = CrossDeviceLocalFs::new(2);
let backend =
BackendHandle::new(SourceId::Local, reader.clone(), Arc::new(transfer.clone())).unwrap();
let (plan, records) = prepare_trash(
PlanId::new(74),
PlanGeneration::new(12),
vec![source],
BTreeMap::new(),
&backend,
&policy,
)
.await
.unwrap();
let confirmed_nested = plan
.nodes()
.iter()
.find(|node| node.location() == &nested)
.unwrap()
.fingerprint()
.unwrap()
.clone();
reader.clear();
let external_path = nested_path.join("external.txt");
std::fs::write(&external_path, b"external").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&nested_path, std::fs::Permissions::from_mode(0o700)).unwrap();
}
let current_nested = rcom::operations::EntryFingerprint::from(
&backend.transfer.metadata(&nested, false).await.unwrap(),
);
assert_ne!(current_nested, confirmed_nested);
let results = execute_trash(
&plan,
&records,
&backend,
&policy,
&CancellationToken::new(),
)
.await;
assert_eq!(results.len(), 1);
assert_not_moved(&results[0], MutationStage::TrashMove);
assert_eq!(std::fs::read(&confirmed_path).unwrap(), b"confirmed");
assert_eq!(std::fs::read(&external_path).unwrap(), b"external");
assert!(!records[0].trashed().path().exists());
assert_eq!(
transfer.remaining_failures(),
1,
"the prepared executor must reject the tree before its own rename or copy"
);
assert!(
reader
.operations()
.iter()
.all(|entry| entry.operation != FsOperation::List),
"a second listing must not admit the external file"
);
}
#[tokio::test]
async fn trash_cross_device_write_failure_preserves_source_and_residuals() {
let source = Location::local("/sandbox/work/source");
let fs = MemoryTransferFs::local().with_file(source.clone(), b"source contents");
let (plan, records, policy) = prepare_memory(&fs, vec![source.clone()]).await;
fs.clear_operations();
for _ in 0..2 {
fs.fail_next(
TransferOperation::Rename,
FsError::Unsupported("cross-device rename".into()),
);
}
// The first write is the .trashinfo payload; the second is the copied source payload.
fs.pass_next(TransferOperation::Write);
fs.fail_next(TransferOperation::Write, FsError::PermissionDenied);
let results = execute_trash(
&plan,
&records,
&memory_backend(&fs),
&policy,
&CancellationToken::new(),
)
.await;
assert_eq!(results[0].outcome().phase(), ItemPhase::Failed);
assert_eq!(results[0].outcome().commit(), CommitOutcome::NotCommitted);
assert_eq!(results[0].stage(), MutationStage::TrashMove);
assert_eq!(fs.file_contents(&source).unwrap(), b"source contents");
assert_eq!(
fs.file_contents(records[0].trashed()),
Err(FsError::NotFound)
);
assert_eq!(operation_count(&fs, TransferOperation::RemoveFile), 0);
assert_eq!(operation_count(&fs, TransferOperation::RemoveDir), 0);
assert_eq!(fs.part_locations().len(), 1);
assert_eq!(operation_count(&fs, TransferOperation::DiscardPart), 0);
}
#[tokio::test]
async fn trash_cross_device_cleanup_failure_reports_commit_separately() {
let source = Location::local("/sandbox/work/source");
let fs = MemoryTransferFs::local().with_file(source.clone(), b"source contents");
let (plan, records, policy) = prepare_memory(&fs, vec![source.clone()]).await;
fs.clear_operations();
for _ in 0..2 {
fs.fail_next(
TransferOperation::Rename,
FsError::Unsupported("cross-device rename".into()),
);
}
fs.fail_next(TransferOperation::RemoveFile, FsError::PermissionDenied);
let results = execute_trash(
&plan,
&records,
&memory_backend(&fs),
&policy,
&CancellationToken::new(),
)
.await;
assert_eq!(results[0].outcome().phase(), ItemPhase::Failed);
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
assert_eq!(results[0].stage(), MutationStage::TrashMove);
assert_eq!(fs.file_contents(&source).unwrap(), b"source contents");
assert_eq!(
fs.file_contents(records[0].trashed()),
Err(FsError::NotFound)
);
assert_eq!(operation_count(&fs, TransferOperation::RemoveFile), 1);
assert_eq!(operation_count(&fs, TransferOperation::RemoveDir), 0);
}
#[tokio::test]
async fn trash_cancellation_before_or_during_validation_starts_no_mutation() {
for cancel_during_metadata in [false, true] {
let source = Location::local("/sandbox/work/source");
let fs = MemoryTransferFs::local().with_file(source.clone(), b"source");
let (plan, records, policy) = prepare_memory(&fs, vec![source.clone()]).await;
fs.clear_operations();
let cancellation = CancellationToken::new();
let backend = Arc::new(memory_backend(&fs));
let plan = Arc::new(plan);
let records = Arc::new(records);
let policy = Arc::new(policy);
let running = if cancel_during_metadata {
let gate = fs.gate_next(TransferOperation::Metadata);
let task = {
let backend = backend.clone();
let plan = plan.clone();
let records = records.clone();
let policy = policy.clone();
let cancellation = cancellation.clone();
tokio::spawn(async move {
execute_trash(&plan, &records, &backend, &policy, &cancellation).await
})
};
gate.wait_entered().await;
cancellation.cancel();
gate.release();
task
} else {
cancellation.cancel();
tokio::spawn(async move {
execute_trash(&plan, &records, &backend, &policy, &cancellation).await
})
};
let results = running.await.unwrap();
assert_eq!(results[0].outcome().phase(), ItemPhase::Cancelled);
assert_eq!(results[0].outcome().commit(), CommitOutcome::NotAttempted);
assert_eq!(results[0].error(), Some(&FsError::Cancelled));
assert_eq!(fs.file_contents(&source).unwrap(), b"source");
assert!(fs.operations().iter().all(|entry| !matches!(
entry.operation,
TransferOperation::CreateDir
| TransferOperation::OpenPart
| TransferOperation::Write
| TransferOperation::Commit
| TransferOperation::Rename
| TransferOperation::RemoveFile
| TransferOperation::RemoveDir
)));
}
}
#[tokio::test]
async fn trash_planning_rejects_duplicate_and_nested_selected_roots() {
let root = Location::local("/sandbox/work/root");
let child = Location::local("/sandbox/work/root/child");
let fs = MemoryTransferFs::local()
.with_dir(root.clone())
.with_file(child.clone(), b"child");
let backend = memory_backend(&fs);
let policy = policy(Location::local(ROOT), Some(Location::local(SANDBOX)));
for sources in [vec![root.clone(), root.clone()], vec![root, child]] {
let result = prepare_trash(
PlanId::new(75),
PlanGeneration::new(13),
sources,
BTreeMap::new(),
&backend,
&policy,
)
.await;
assert!(result.is_err());
}
assert!(fs.operations().is_empty());
}
#[tokio::test]
async fn trash_rejects_sources_and_record_destinations_outside_sandbox_without_writes() {
let outside = Location::local("/outside/source");
let fs = MemoryTransferFs::local().with_file(outside.clone(), b"outside");
let backend = memory_backend(&fs);
let policy = policy(Location::local(ROOT), Some(Location::local(SANDBOX)));
let result = prepare_trash(
PlanId::new(1),
PlanGeneration::new(1),
vec![outside.clone()],
BTreeMap::new(),
&backend,
&policy,
)
.await;
assert!(result.is_err());
assert!(fs.operations().is_empty());
let source = Location::local("/sandbox/work/source");
let fs = MemoryTransferFs::local().with_file(source.clone(), b"source");
let (plan, mut records, policy) = prepare_memory(&fs, vec![source.clone()]).await;
records[0] = TrashRecord::new(
source.clone(),
Location::local("/outside/escaped"),
records[0].fingerprint().clone(),
records[0].epoch(),
records[0].id(),
)
.unwrap();
fs.clear_operations();
let results = execute_trash(
&plan,
&records,
&memory_backend(&fs),
&policy,
&CancellationToken::new(),
)
.await;
assert_not_moved(&results[0], MutationStage::Validation);
assert_eq!(fs.file_contents(&source).unwrap(), b"source");
assert!(fs.operations().is_empty());
}
#[tokio::test]
async fn trash_observer_orders_events_and_finishes_roots_not_started_after_cancel() {
let first = Location::local("/sandbox/work/a");
let second = Location::local("/sandbox/work/b");
let fs = MemoryTransferFs::local()
.with_file(first.clone(), b"first")
.with_file(second.clone(), b"second");
let (plan, records, policy) = prepare_memory(&fs, vec![first.clone(), second.clone()]).await;
fs.clear_operations();
let first_id = plan.nodes()[0].id();
let second_id = plan.nodes()[1].id();
let cancellation = CancellationToken::new();
let observer_cancellation = cancellation.clone();
let mut events = Vec::new();
let mut observer = |event| {
if matches!(&event, TrashEvent::ItemStarted(id) if *id == first_id) {
observer_cancellation.cancel();
}
events.push((event, fs.operations().len()));
};
let results = execute_trash_observed(
&plan,
&records,
&memory_backend(&fs),
&policy,
&cancellation,
&mut observer,
)
.await;
drop(observer);
assert_eq!(results.len(), 2);
assert_eq!(results[0].outcome().id(), first_id);
assert_eq!(results[1].outcome().id(), second_id);
assert_eq!(results[0].outcome().phase(), ItemPhase::Cancelled);
assert_eq!(results[1].outcome().phase(), ItemPhase::Cancelled);
assert_eq!(results[0].outcome().commit(), CommitOutcome::NotAttempted);
assert_eq!(results[1].outcome().commit(), CommitOutcome::NotAttempted);
assert_eq!(events.len(), 3);
assert_eq!(events[0].0, TrashEvent::ItemStarted(first_id));
assert_eq!(events[0].1, 0, "Started must precede source preflight");
assert_eq!(
events[1].0,
TrashEvent::ItemFinished(results[0].clone()),
"the first Started must be paired immediately after its root completes"
);
assert_eq!(events[2].0, TrashEvent::ItemFinished(results[1].clone()));
assert_eq!(
events[2].1, events[1].1,
"a root skipped after cancellation must not start preflight or setup"
);
assert_eq!(
events[1].1, 1,
"only the started root's read-only preflight ran"
);
assert_eq!(fs.file_contents(&first).unwrap(), b"first");
assert_eq!(fs.file_contents(&second).unwrap(), b"second");
assert_eq!(operation_count(&fs, TransferOperation::Rename), 0);
}