rcom/src/actions/trash.rs
2026-12-05 23:30:06 +03:00

1378 lines
47 KiB
Rust

//! Read-only trash planning and execution of endpoint-local, confirmed moves.
//!
//! Every source has a preallocated UUID and restore record. Metadata is fully written and closed
//! before the source move starts. Failed staging, ambiguous renames, and incomplete cross-device
//! cleanup never trigger implicit retries or deletion of either the source or residual trash files.
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};
use chrono::Local;
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
use crate::domain::{Entry, EntryKind, Location, SourceId};
use crate::fs::{BackendHandle, FsError, PartFile, TransferItemResult, execute_prepared_copy_move};
use crate::operations::{
CollisionDecision, CollisionPolicy, CommitOutcome, EntryFingerprint, ItemId, OperationKind,
OperationPlan, PlanGeneration, PlanId, PlannedItem, PreparedOperation, SourceCleanupOutcome,
SourceItem,
};
use super::executor::{ActionResult, MutationStage};
use super::{
EntryMutationKind, EntryMutationNode, EntryMutationPlan, TrashPolicy, TrashRecord,
validate_entry_name,
};
/// Captures selected roots and every descendant without writing to trash or following symlinks.
///
/// All roots must be siblings on the selected backend's endpoint. IDs are assigned in deterministic
/// lexical pre-order, independently of selection and listing order. The returned records are only
/// restore *inputs*: callers must retain them for undo only when every corresponding execution
/// result is fully successful.
pub async fn prepare_trash(
id: PlanId,
generation: PlanGeneration,
sources: Vec<Location>,
endpoint_epochs: BTreeMap<SourceId, u64>,
backend: &BackendHandle,
policy: &TrashPolicy,
) -> Result<(EntryMutationPlan, Vec<TrashRecord>), FsError> {
let parent = validate_sources(&sources, backend, policy)?;
let mut sources = sources;
sources.sort_by(|left, right| left.path().cmp(right.path()));
let mut nodes = Vec::new();
let mut records = Vec::with_capacity(sources.len());
let mut record_ids = BTreeSet::new();
let mut next_id = 1_u64;
for source in sources {
let entry = backend.transfer.metadata(&source, false).await?;
if entry.kind == EntryKind::Symlink {
return Err(FsError::Unsupported(
"symbolic links cannot be moved to trash".into(),
));
}
let fingerprint = EntryFingerprint::from(&entry);
let name = source
.file_name_owned()
.ok_or_else(|| FsError::Other("trash source has no final file name".into()))?;
let root_id = allocate_item_id(&mut next_id)?;
let mut record_id = Uuid::new_v4();
while !record_ids.insert(record_id) {
record_id = Uuid::new_v4();
}
let trashed = files_root(policy).join(record_id.to_string());
let epoch = endpoint_epochs
.get(source.source())
.copied()
.unwrap_or_default();
records.push(
TrashRecord::new(source.clone(), trashed, fingerprint, epoch, record_id).map_err(
|error| FsError::Other(format!("invalid trash restore record: {error}")),
)?,
);
// Capture a deterministic lexical pre-order. Every child is re-read no-follow instead of
// trusting listing metadata, and no execution-time discovery can extend this snapshot.
let mut pending = vec![PendingTrashNode {
id: Some(root_id),
location: source,
relative: PathBuf::from(name),
entry: Some(entry),
}];
while let Some(pending_node) = pending.pop() {
let id = match pending_node.id {
Some(id) => id,
None => allocate_item_id(&mut next_id)?,
};
let entry = match pending_node.entry {
Some(entry) => entry,
None => {
backend
.transfer
.metadata(&pending_node.location, false)
.await?
}
};
let is_directory = entry.kind == EntryKind::Directory;
nodes.push(EntryMutationNode::new(
id,
pending_node.location.clone(),
pending_node.relative.clone(),
Some(EntryFingerprint::from(&entry)),
));
if is_directory {
let mut children = backend.read.list(&pending_node.location).await?;
children.sort_by(|left, right| left.name.cmp(&right.name));
let mut child_names = BTreeSet::new();
for child in &children {
validate_entry_name(&child.name).map_err(|error| {
FsError::Other(format!(
"directory listing returned an unsafe entry name: {error}"
))
})?;
if !child_names.insert(child.name.clone()) {
return Err(FsError::Other(
"directory listing returned a duplicate entry name".into(),
));
}
}
for child in children.into_iter().rev() {
pending.push(PendingTrashNode {
id: None,
location: pending_node.location.join(&child.name),
relative: pending_node.relative.join(&child.name),
entry: None,
});
}
}
}
}
let plan = EntryMutationPlan::new(
id,
generation,
EntryMutationKind::Trash,
parent,
Some(policy.root().clone()),
nodes,
endpoint_epochs,
)
.map_err(|error| FsError::Other(format!("invalid trash plan: {error}")))?;
Ok((plan, records))
}
struct PendingTrashNode {
id: Option<ItemId>,
location: Location,
relative: PathBuf,
entry: Option<Entry>,
}
fn allocate_item_id(next: &mut u64) -> Result<ItemId, FsError> {
let id = ItemId::new(*next);
*next = next
.checked_add(1)
.ok_or_else(|| FsError::Other("the trash plan contains too many items".into()))?;
Ok(id)
}
fn validate_sources(
sources: &[Location],
backend: &BackendHandle,
policy: &TrashPolicy,
) -> Result<Location, FsError> {
let first = sources
.first()
.ok_or_else(|| FsError::Other("trash requires at least one source".into()))?;
validate_policy(policy, backend)?;
let parent = first
.parent()
.ok_or_else(|| FsError::Other("trash source has no parent directory".into()))?;
let mut unique = BTreeSet::new();
for source in sources {
if source.source() != backend.source_id() || source.parent().as_ref() != Some(&parent) {
return Err(FsError::Other(
"all trash sources must share one parent and the backend endpoint".into(),
));
}
policy.validate_source(source).map_err(|error| {
FsError::Other(format!("trash policy rejected its source: {error}"))
})?;
validate_source_sandbox(source, policy)?;
validate_entry_name(
source
.file_name()
.ok_or_else(|| FsError::Other("trash source has no final file name".into()))?,
)
.map_err(|error| FsError::Other(format!("unsafe trash source name: {error}")))?;
if !unique.insert(source.path()) {
return Err(FsError::Other(
"trash sources must not contain duplicates".into(),
));
}
let source_path = normalize_lexically(source.path());
let trash_path = normalize_lexically(policy.root().path());
if source_path == trash_path
|| source_path.starts_with(&trash_path)
|| trash_path.starts_with(&source_path)
{
return Err(FsError::Other(
"a trash source must not contain or be contained by the trash root".into(),
));
}
}
let mut selected: Vec<_> = sources
.iter()
.map(|source| normalize_lexically(source.path()))
.collect();
selected.sort();
if selected
.windows(2)
.any(|pair| pair[1].starts_with(&pair[0]))
{
return Err(FsError::Other(
"trash sources must not contain nested or aliased selected roots".into(),
));
}
Ok(parent)
}
/// Root-scoped execution events. `ItemStarted` precedes the source metadata recheck and all trash
/// setup, allowing the task manager to retain a root even if cancellation arrives during preflight.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TrashEvent {
ItemStarted(ItemId),
ItemFinished(ActionResult),
}
/// Executes each confirmed trash root sequentially.
pub async fn execute_trash(
plan: &EntryMutationPlan,
records: &[TrashRecord],
backend: &BackendHandle,
policy: &TrashPolicy,
cancellation: &CancellationToken,
) -> Vec<ActionResult> {
let mut observer = |_| {};
execute_trash_observed(plan, records, backend, policy, cancellation, &mut observer).await
}
/// Observed trash execution with exactly one `ItemFinished` for every result.
///
/// Roots skipped by pre-existing cancellation, an earlier ambiguous move, or a shared setup failure
/// produce only `ItemFinished`. `TrashInfo` covers directory/metadata staging; `TrashMove` covers
/// the source rename or prepared cross-device move. A failed result with `Committed` means the
/// destination committed but source cleanup did not complete. Residuals are never removed here.
pub async fn execute_trash_observed(
plan: &EntryMutationPlan,
records: &[TrashRecord],
backend: &BackendHandle,
policy: &TrashPolicy,
cancellation: &CancellationToken,
observer: &mut (dyn FnMut(TrashEvent) + Send),
) -> Vec<ActionResult> {
let items = match validate_execution(plan, records, backend, policy) {
Ok(items) => items,
Err(error) => {
let results = invalid_plan_results(plan, error);
for result in results.iter().cloned() {
observer(TrashEvent::ItemFinished(result));
}
return results;
}
};
let mut results = Vec::with_capacity(items.len());
let mut directories = None;
let mut setup_error: Option<FsError> = None;
let mut stopped = false;
for item in items {
if stopped {
let result = ActionResult::failed(
item.id(),
MutationStage::Validation,
FsError::Other("trash root was not started after an earlier ambiguous move".into()),
CommitOutcome::NotAttempted,
);
record_trash_result(&mut results, observer, result);
continue;
}
if cancellation.is_cancelled() {
let result = ActionResult::cancelled(item.id(), MutationStage::Validation);
record_trash_result(&mut results, observer, result);
continue;
}
if let Some(error) = &setup_error {
let result = ActionResult::failed(
item.id(),
MutationStage::TrashInfo,
error.clone(),
CommitOutcome::NotAttempted,
);
record_trash_result(&mut results, observer, result);
continue;
}
observer(TrashEvent::ItemStarted(item.id()));
if let Err(error) = verify_source(item.node, backend).await {
let result = ActionResult::failed(
item.id(),
MutationStage::SourceFingerprint,
error,
CommitOutcome::NotAttempted,
);
record_trash_result(&mut results, observer, result);
continue;
}
if cancellation.is_cancelled() {
let result = ActionResult::cancelled(item.id(), MutationStage::TrashInfo);
record_trash_result(&mut results, observer, result);
continue;
}
if directories.is_none() {
match ensure_trash_directories(backend, policy, cancellation).await {
Ok(created) => directories = Some(created),
Err(error) => {
let result = if error == FsError::Cancelled {
ActionResult::cancelled(item.id(), MutationStage::TrashInfo)
} else {
setup_error = Some(error.clone());
ActionResult::failed(
item.id(),
MutationStage::TrashInfo,
error,
CommitOutcome::NotAttempted,
)
};
record_trash_result(&mut results, observer, result);
continue;
}
}
}
let directories = directories
.as_ref()
.expect("trash directories were initialized above");
let (result, stop) = execute_item(item, directories, plan, backend, cancellation).await;
stopped = stop;
record_trash_result(&mut results, observer, result);
}
results
}
fn record_trash_result(
results: &mut Vec<ActionResult>,
observer: &mut dyn FnMut(TrashEvent),
result: ActionResult,
) {
observer(TrashEvent::ItemFinished(result.clone()));
results.push(result);
}
#[derive(Clone, Debug)]
struct TrashDirectories {
files: Location,
}
struct TrashItem<'a> {
node: &'a EntryMutationNode,
nodes: &'a [EntryMutationNode],
record: &'a TrashRecord,
info: Location,
}
impl TrashItem<'_> {
fn id(&self) -> ItemId {
self.node.id()
}
}
fn validate_execution<'a>(
plan: &'a EntryMutationPlan,
records: &'a [TrashRecord],
backend: &BackendHandle,
policy: &TrashPolicy,
) -> Result<Vec<TrashItem<'a>>, FsError> {
if plan.kind() != EntryMutationKind::Trash
|| plan.destination() != Some(policy.root())
|| plan.source().source() != backend.source_id()
{
return Err(FsError::Other(
"trash plan, destination, policy, and backend differ".into(),
));
}
validate_policy(policy, backend)?;
policy
.validate_source(plan.source())
.map_err(|error| FsError::Other(format!("trash policy rejected its source: {error}")))?;
validate_source_sandbox(plan.source(), policy)?;
let roots: Vec<_> = plan
.nodes()
.iter()
.enumerate()
.filter(|(_, node)| node.relative_path().components().count() == 1)
.map(|(index, _)| index)
.collect();
if roots.is_empty() || roots[0] != 0 || records.len() != roots.len() {
return Err(FsError::Other(
"trash plan roots and restore record counts differ".into(),
));
}
let files = files_root(policy);
let info = info_root(policy);
validate_generated_location(&files, policy)?;
validate_generated_location(&info, policy)?;
let mut by_original = BTreeMap::new();
let mut ids = BTreeSet::new();
let mut destinations = BTreeSet::new();
for record in records {
if !ids.insert(record.id()) || !destinations.insert(record.trashed().clone()) {
return Err(FsError::Other(
"trash restore record IDs and destinations must be unique".into(),
));
}
if by_original
.insert(record.original().clone(), record)
.is_some()
{
return Err(FsError::Other(
"trash restore records contain a duplicate original".into(),
));
}
}
let mut unique_nodes = BTreeSet::new();
for node in plan.nodes() {
if node.location().source() != backend.source_id()
|| node.location() != &plan.source().join(node.relative_path())
|| !unique_nodes.insert(node.location())
{
return Err(FsError::Other(
"trash nodes contain an endpoint, location, or duplicate-path mismatch".into(),
));
}
policy
.validate_source(node.location())
.map_err(|error| FsError::Other(format!("trash policy rejected a node: {error}")))?;
validate_source_sandbox(node.location(), policy)?;
let source_path = normalize_lexically(node.location().path());
let trash_path = normalize_lexically(policy.root().path());
if source_path == trash_path
|| source_path.starts_with(&trash_path)
|| trash_path.starts_with(&source_path)
{
return Err(FsError::Other(
"a trash node overlaps the trash root".into(),
));
}
}
let mut items = Vec::with_capacity(roots.len());
for (root_index, start) in roots.iter().copied().enumerate() {
let end = roots
.get(root_index + 1)
.copied()
.unwrap_or(plan.nodes().len());
let nodes = &plan.nodes()[start..end];
let node = &nodes[0];
if node.location().parent().as_ref() != Some(plan.source()) {
return Err(FsError::Other(
"trash roots must be direct children of the confirmed parent".into(),
));
}
if nodes[1..].iter().any(|child| {
child.relative_path().components().count() == 1
|| !child.relative_path().starts_with(node.relative_path())
}) {
return Err(FsError::Other(
"trash nodes do not form disjoint pre-order roots".into(),
));
}
if nodes.len() > 1
&& node
.fingerprint()
.expect("EntryMutationPlan validates trash fingerprints")
.kind()
!= EntryKind::Directory
{
return Err(FsError::Other(
"a trash root with descendants is not a directory".into(),
));
}
let directories: BTreeSet<&Path> = nodes
.iter()
.filter(|node| {
node.fingerprint()
.expect("EntryMutationPlan validates trash fingerprints")
.kind()
== EntryKind::Directory
})
.map(|node| node.relative_path())
.collect();
for child in &nodes[1..] {
let parent = child
.relative_path()
.parent()
.unwrap_or_else(|| Path::new(""));
if !directories.contains(parent) {
return Err(FsError::Other(
"a confirmed trash tree is missing a parent directory".into(),
));
}
}
let record = by_original
.remove(node.location())
.ok_or_else(|| FsError::Other("a trash root has no restore record".into()))?;
let expected_destination = files.join(record.id().to_string());
let expected_info = info.join(format!("{}.trashinfo", record.id()));
let expected_epoch = plan
.endpoint_epoch(node.location().source())
.unwrap_or_default();
if record.trashed() != &expected_destination
|| record.fingerprint()
!= node
.fingerprint()
.expect("EntryMutationPlan validates trash fingerprints")
|| record.epoch() != expected_epoch
{
return Err(FsError::Other(
"trash restore record differs from its confirmed root".into(),
));
}
validate_generated_location(record.trashed(), policy)?;
validate_generated_location(&expected_info, policy)?;
items.push(TrashItem {
node,
nodes,
record,
info: expected_info,
});
}
if !by_original.is_empty() {
return Err(FsError::Other(
"trash restore records contain an unexpected original".into(),
));
}
Ok(items)
}
async fn execute_item(
item: TrashItem<'_>,
directories: &TrashDirectories,
plan: &EntryMutationPlan,
backend: &BackendHandle,
cancellation: &CancellationToken,
) -> (ActionResult, bool) {
if let Err(error) = verify_source_parent(item.node.location(), backend, policy_root(plan)).await
{
return (
ActionResult::failed(
item.id(),
MutationStage::Validation,
error,
CommitOutcome::NotAttempted,
),
false,
);
}
if let Err(error) = ensure_absent(backend, item.record.trashed()).await {
return (
ActionResult::failed(
item.id(),
MutationStage::Destination,
error,
CommitOutcome::NotAttempted,
),
false,
);
}
if let Err(error) = ensure_absent(backend, &item.info).await {
return (
ActionResult::failed(
item.id(),
MutationStage::Destination,
error,
CommitOutcome::NotAttempted,
),
false,
);
}
if let Err(error) = write_trash_info(&item, backend, cancellation).await {
let cancelled = error == FsError::Cancelled;
let error = with_residual(error, Some(&item.info), std::iter::empty());
let result = if cancelled {
ActionResult::cancelled(item.id(), MutationStage::TrashInfo)
} else {
ActionResult::failed(
item.id(),
MutationStage::TrashInfo,
error,
CommitOutcome::NotAttempted,
)
};
return (result, false);
}
if let Err(error) = verify_source(item.node, backend).await {
return (
ActionResult::failed(
item.id(),
MutationStage::SourceFingerprint,
with_residual(error, Some(&item.info), std::iter::empty()),
CommitOutcome::NotAttempted,
),
false,
);
}
if let Err(error) = ensure_absent(backend, item.record.trashed()).await {
return (
ActionResult::failed(
item.id(),
MutationStage::Destination,
with_residual(error, Some(&item.info), std::iter::empty()),
CommitOutcome::NotAttempted,
),
false,
);
}
if cancellation.is_cancelled() {
return (
ActionResult::cancelled(item.id(), MutationStage::TrashMove),
false,
);
}
match backend
.transfer
.rename(item.node.location(), item.record.trashed())
.await
{
Ok(()) => (
ActionResult::committed(item.id(), MutationStage::TrashMove),
false,
),
Err(error) if is_cross_device(&error) => {
execute_cross_device(item, directories, plan, backend, cancellation).await
}
Err(error) => {
let (result, stop) = reconcile_direct_rename(item, backend, error).await;
(result, stop)
}
}
}
fn policy_root(plan: &EntryMutationPlan) -> &Location {
plan.destination()
.expect("validated trash plan has a destination")
}
async fn reconcile_direct_rename(
item: TrashItem<'_>,
backend: &BackendHandle,
error: FsError,
) -> (ActionResult, bool) {
let source = backend.transfer.metadata(item.node.location(), false).await;
let destination = backend
.transfer
.metadata(item.record.trashed(), false)
.await;
let expected = item
.node
.fingerprint()
.expect("validated trash fingerprint");
match (source, destination) {
(Err(FsError::NotFound), Ok(destination))
if EntryFingerprint::from(&destination) == *expected =>
{
(
ActionResult::committed(item.id(), MutationStage::Reconcile),
false,
)
}
(Ok(source), Err(FsError::NotFound)) if EntryFingerprint::from(&source) == *expected => (
ActionResult::failed(
item.id(),
MutationStage::TrashMove,
with_residual(error, Some(&item.info), std::iter::empty()),
CommitOutcome::NotCommitted,
),
false,
),
_ => (
ActionResult::failed(
item.id(),
MutationStage::TrashMove,
with_residual(error, Some(&item.info), std::iter::empty()),
CommitOutcome::Unknown,
),
true,
),
}
}
async fn execute_cross_device(
item: TrashItem<'_>,
directories: &TrashDirectories,
plan: &EntryMutationPlan,
backend: &BackendHandle,
cancellation: &CancellationToken,
) -> (ActionResult, bool) {
// The shared prepared executor appends the source name to OperationPlan::destination. A unique
// sibling staging root therefore preserves the public files/<uuid> restore destination.
let staging = directories
.files
.join(format!(".rcom-trash-staging-{}", item.record.id()));
if let Err(error) = ensure_absent(backend, &staging).await {
return (
ActionResult::failed(
item.id(),
MutationStage::TrashMove,
with_residual(error, Some(&item.info), std::iter::once(&staging)),
CommitOutcome::NotAttempted,
),
false,
);
}
if cancellation.is_cancelled() {
return (
ActionResult::cancelled(item.id(), MutationStage::TrashMove),
false,
);
}
if let Err(error) = backend.transfer.create_dir(&staging).await {
return (
ActionResult::failed(
item.id(),
MutationStage::TrashMove,
with_residual(error, Some(&item.info), std::iter::once(&staging)),
CommitOutcome::NotAttempted,
),
false,
);
}
if let Err(error) = ensure_real_directory(backend, &staging).await {
return (
ActionResult::failed(
item.id(),
MutationStage::TrashMove,
with_residual(error, Some(&item.info), std::iter::once(&staging)),
CommitOutcome::NotAttempted,
),
false,
);
}
let prepared = match prepare_confirmed_cross_device(&item, plan, backend, &staging).await {
Ok(prepared) => prepared,
Err(error) => {
return (
ActionResult::failed(
item.id(),
MutationStage::TrashMove,
with_residual(error, Some(&item.info), std::iter::once(&staging)),
CommitOutcome::NotAttempted,
),
false,
);
}
};
let transferred = execute_prepared_copy_move(&prepared, backend, backend, cancellation).await;
let Some(transferred) = transferred.first() else {
return (
ActionResult::failed(
item.id(),
MutationStage::TrashMove,
with_residual(
FsError::Other("cross-device move returned no item result".into()),
Some(&item.info),
std::iter::once(&staging),
),
CommitOutcome::Unknown,
),
true,
);
};
if !transfer_is_fully_moved(transferred) {
return convert_transfer_result(item, transferred, &staging);
}
let staged = staging.join(
item.node
.location()
.file_name()
.expect("validated trash root has a final file name"),
);
finish_cross_device(item, backend, &staging, &staged, cancellation).await
}
async fn prepare_confirmed_cross_device(
item: &TrashItem<'_>,
plan: &EntryMutationPlan,
backend: &BackendHandle,
staging: &Location,
) -> Result<PreparedOperation, FsError> {
let destination = staging.clone();
let destination_entry = backend.transfer.metadata(&destination, false).await?;
if destination_entry.kind != EntryKind::Directory {
return Err(FsError::Other(
"the cross-device trash destination is not a directory".into(),
));
}
let root_relative = item.node.relative_path();
let root_destination = destination.join(item.node.location().file_name().ok_or_else(|| {
FsError::Other("cross-device trash source has no final file name".into())
})?);
let mut items = Vec::with_capacity(item.nodes.len());
let mut expected_items = Some(0_u64);
let mut expected_bytes = Some(0_u64);
for node in item.nodes {
let relative = node
.relative_path()
.strip_prefix(root_relative)
.map_err(|_| FsError::Other("a trash descendant escaped its selected root".into()))?;
let fingerprint = node
.fingerprint()
.expect("validated trash nodes have fingerprints")
.clone();
if fingerprint.kind() == EntryKind::File {
expected_items = expected_items.and_then(|total| total.checked_add(1));
expected_bytes = match (expected_bytes, fingerprint.size()) {
(Some(total), Some(size)) => total.checked_add(size),
_ => None,
};
}
items.push(
PlannedItem::new(
node.id(),
node.location().clone(),
root_destination.join(relative),
fingerprint.kind(),
fingerprint.size(),
fingerprint,
CollisionDecision::Create,
)
.map_err(|error| {
FsError::Other(format!(
"invalid confirmed cross-device trash item: {error}"
))
})?,
);
}
let operation = OperationPlan::new(
plan.id(),
plan.generation(),
OperationKind::Move,
vec![SourceItem::new(
item.node.id(),
item.node.location().clone(),
)],
destination,
CollisionPolicy::Ask,
expected_items,
expected_bytes,
plan.endpoint_epochs().clone(),
)
.map_err(|error| FsError::Other(format!("invalid cross-device trash root: {error}")))?;
PreparedOperation::new(operation, items, EntryFingerprint::from(&destination_entry)).map_err(
|error| {
FsError::Other(format!(
"invalid confirmed cross-device trash tree: {error}"
))
},
)
}
fn transfer_is_fully_moved(transferred: &TransferItemResult) -> bool {
let outcome = transferred.outcome();
outcome.phase() == crate::operations::ItemPhase::Succeeded
&& outcome.commit() == CommitOutcome::Committed
&& outcome.source_cleanup() == SourceCleanupOutcome::Removed
}
fn convert_transfer_result(
item: TrashItem<'_>,
transferred: &TransferItemResult,
staging: &Location,
) -> (ActionResult, bool) {
let outcome = transferred.outcome();
let commit = outcome.commit();
let error = transferred.error().cloned().unwrap_or_else(|| {
if commit == CommitOutcome::Committed {
FsError::Other(format!(
"trash destination committed but source cleanup is {:?}",
outcome.source_cleanup()
))
} else {
FsError::Other("cross-device trash move did not commit".into())
}
});
let ambiguous = commit == CommitOutcome::Unknown
|| matches!(&error, FsError::Timeout | FsError::Disconnected);
let error = with_residual(
error,
Some(&item.info),
std::iter::once(staging).chain(transferred.residual_locations()),
);
let result = if outcome.phase() == crate::operations::ItemPhase::Cancelled {
if commit == CommitOutcome::Committed {
ActionResult::new(
item.id(),
crate::operations::ItemPhase::Cancelled,
CommitOutcome::Committed,
MutationStage::TrashMove,
)
} else {
ActionResult::cancelled(item.id(), MutationStage::TrashMove)
}
} else {
// The shared ActionResult API has no cleanup setter. Committed plus Failed is therefore
// intentional: it distinguishes destination commit from incomplete source cleanup.
ActionResult::failed(item.id(), MutationStage::TrashMove, error, commit)
};
(result, ambiguous)
}
async fn finish_cross_device(
item: TrashItem<'_>,
backend: &BackendHandle,
staging: &Location,
staged: &Location,
cancellation: &CancellationToken,
) -> (ActionResult, bool) {
// The prepared move has committed and removed the original source. From here on, no error is
// reported as NotAttempted and no failed final rename is retried or cleaned up recursively.
if cancellation.is_cancelled() {
return (committed_cancellation(item.id()), false);
}
if let Err(error) = ensure_absent(backend, item.record.trashed()).await {
return (
ActionResult::failed(
item.id(),
MutationStage::TrashMove,
with_residual(error, Some(&item.info), [staging, staged]),
CommitOutcome::Committed,
),
false,
);
}
if cancellation.is_cancelled() {
return (committed_cancellation(item.id()), false);
}
match backend.transfer.rename(staged, item.record.trashed()).await {
Ok(()) => {}
Err(error) => {
let staged_metadata = backend.transfer.metadata(staged, false).await;
let final_metadata = backend
.transfer
.metadata(item.record.trashed(), false)
.await;
match (staged_metadata, final_metadata) {
(Err(FsError::NotFound), Ok(current))
if EntryFingerprint::from(&current) == *item.record.fingerprint() => {}
(Ok(current), Err(FsError::NotFound))
if EntryFingerprint::from(&current) == *item.record.fingerprint() =>
{
return (
ActionResult::failed(
item.id(),
MutationStage::TrashMove,
with_residual(error, Some(&item.info), [staging, staged]),
CommitOutcome::Committed,
),
false,
);
}
_ => {
return (
ActionResult::failed(
item.id(),
MutationStage::TrashMove,
with_residual(error, Some(&item.info), [staging, staged]),
CommitOutcome::Unknown,
),
true,
);
}
}
}
}
if cancellation.is_cancelled() {
return (committed_cancellation(item.id()), false);
}
match backend.transfer.remove_dir(staging).await {
Ok(()) => (
ActionResult::committed(item.id(), MutationStage::TrashMove),
false,
),
Err(error) => {
let stop = matches!(&error, FsError::Timeout | FsError::Disconnected);
(
ActionResult::failed(
item.id(),
MutationStage::TrashMove,
with_residual(error, Some(&item.info), std::iter::once(staging)),
CommitOutcome::Committed,
),
stop,
)
}
}
}
fn committed_cancellation(id: ItemId) -> ActionResult {
// Match the permanent-delete executor: once a commit is known, cancellation must not reset its
// commit outcome to NotAttempted. The residual staging path remains available in the backend
// journal and no further mutation is attempted.
ActionResult::new(
id,
crate::operations::ItemPhase::Cancelled,
CommitOutcome::Committed,
MutationStage::TrashMove,
)
}
async fn write_trash_info(
item: &TrashItem<'_>,
backend: &BackendHandle,
cancellation: &CancellationToken,
) -> Result<(), FsError> {
if cancellation.is_cancelled() {
return Err(FsError::Cancelled);
}
let mut writer = backend.transfer.open_part(&item.info).await?;
let partial = writer.part().clone();
let contents = trash_info_contents(item.record);
if cancellation.is_cancelled() {
return Err(FsError::Cancelled);
}
backend
.transfer
.write_part(&mut writer, contents.as_bytes())
.await
.map_err(|error| residual_error(error, &partial))?;
if cancellation.is_cancelled() {
return Err(FsError::Cancelled);
}
let closed = backend
.transfer
.flush_and_close(writer)
.await
.map_err(|error| residual_error(error, &partial))?;
ensure_absent(backend, &item.info)
.await
.map_err(|error| residual_error(error, &partial))?;
if cancellation.is_cancelled() {
return Err(FsError::Cancelled);
}
backend
.transfer
.commit_part(closed)
.await
.map_err(|error| residual_error(error, &partial))
}
fn trash_info_contents(record: &TrashRecord) -> String {
format!(
"[Trash Info]\nPath={}\nDeletionDate={}\n",
percent_encode_path(record.original().path()),
Local::now().format("%Y-%m-%dT%H:%M:%S")
)
}
fn percent_encode_path(path: &Path) -> String {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
percent_encode(path.as_os_str().as_bytes())
}
#[cfg(not(unix))]
{
percent_encode(path.as_os_str().to_string_lossy().as_bytes())
}
}
fn percent_encode(bytes: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789ABCDEF";
let mut encoded = String::with_capacity(bytes.len());
for &byte in bytes {
if byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'-' | b'.' | b'_' | b'~') {
encoded.push(char::from(byte));
} else {
encoded.push('%');
encoded.push(char::from(HEX[usize::from(byte >> 4)]));
encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
}
}
encoded
}
async fn ensure_trash_directories(
backend: &BackendHandle,
policy: &TrashPolicy,
cancellation: &CancellationToken,
) -> Result<TrashDirectories, FsError> {
if let Some(sandbox) = policy.accepted_sandbox_root() {
ensure_real_directory(backend, sandbox).await?;
}
ensure_directory(backend, policy.root(), policy, cancellation).await?;
let files = files_root(policy);
let info = info_root(policy);
ensure_directory(backend, &files, policy, cancellation).await?;
ensure_directory(backend, &info, policy, cancellation).await?;
Ok(TrashDirectories { files })
}
async fn ensure_directory(
backend: &BackendHandle,
location: &Location,
policy: &TrashPolicy,
cancellation: &CancellationToken,
) -> Result<(), FsError> {
let mut missing = Vec::new();
let mut current = location.clone();
loop {
match backend.transfer.metadata(&current, false).await {
Ok(entry) if entry.kind == EntryKind::Directory => {
ensure_real_directory(backend, &current).await?;
break;
}
Ok(_) => {
return Err(FsError::Other(
"a trash directory path exists but is not a directory".into(),
));
}
Err(FsError::NotFound) => {
validate_root_creation_path(&current, policy)?;
missing.push(current.clone());
}
Err(error) => return Err(error),
}
current = current
.parent()
.ok_or_else(|| FsError::Other("trash root has no existing parent".into()))?;
}
for path in missing.into_iter().rev() {
if cancellation.is_cancelled() {
return Err(FsError::Cancelled);
}
backend.transfer.create_dir(&path).await?;
ensure_real_directory(backend, &path).await?;
}
Ok(())
}
async fn ensure_real_directory(
backend: &BackendHandle,
location: &Location,
) -> Result<(), FsError> {
let entry = backend.transfer.metadata(location, false).await?;
if entry.kind != EntryKind::Directory {
return Err(FsError::Other(
"trash sandbox/root is not a real directory".into(),
));
}
let canonical = backend.transfer.canonicalize(location).await?;
if &canonical != location {
return Err(FsError::Other(
"trash sandbox/root differs from its canonical directory".into(),
));
}
Ok(())
}
async fn verify_source_parent(
source: &Location,
backend: &BackendHandle,
trash_root: &Location,
) -> Result<(), FsError> {
let parent = source
.parent()
.ok_or_else(|| FsError::Other("trash source has no parent directory".into()))?;
let canonical = backend.transfer.canonicalize(&parent).await?;
if canonical != parent {
return Err(FsError::Other(
"trash source parent differs from its canonical directory".into(),
));
}
let source_path = normalize_lexically(source.path());
let trash_path = normalize_lexically(trash_root.path());
if source_path == trash_path
|| source_path.starts_with(&trash_path)
|| trash_path.starts_with(&source_path)
{
return Err(FsError::Other("trash source and trash root overlap".into()));
}
Ok(())
}
async fn verify_source(node: &EntryMutationNode, backend: &BackendHandle) -> Result<(), FsError> {
let current = backend.transfer.metadata(node.location(), false).await?;
if current.kind == EntryKind::Symlink {
return Err(FsError::Unsupported(
"a symbolic link cannot be moved to trash".into(),
));
}
if EntryFingerprint::from(&current)
!= *node
.fingerprint()
.expect("validated trash nodes have fingerprints")
{
return Err(FsError::Other(
"trash source changed after confirmation; source move was not started".into(),
));
}
Ok(())
}
async fn ensure_absent(backend: &BackendHandle, location: &Location) -> Result<(), FsError> {
match backend.transfer.metadata(location, false).await {
Ok(_) => Err(FsError::Other(
"trash destination or info record already exists".into(),
)),
Err(FsError::NotFound) => Ok(()),
Err(error) => Err(error),
}
}
fn validate_policy(policy: &TrashPolicy, backend: &BackendHandle) -> Result<(), FsError> {
if policy.root().source() != backend.source_id() {
return Err(FsError::Other(
"trash root and backend endpoints differ".into(),
));
}
if let Some(sandbox) = policy.accepted_sandbox_root()
&& (sandbox.source() != backend.source_id()
|| !path_is_within(policy.root().path(), sandbox.path()))
{
return Err(FsError::Other(
"trash root is outside the accepted sandbox".into(),
));
}
Ok(())
}
fn validate_source_sandbox(source: &Location, policy: &TrashPolicy) -> Result<(), FsError> {
if policy
.accepted_sandbox_root()
.is_some_and(|sandbox| !path_is_within(source.path(), sandbox.path()))
{
return Err(FsError::Other(
"trash source is outside the accepted sandbox".into(),
));
}
Ok(())
}
fn validate_root_creation_path(location: &Location, policy: &TrashPolicy) -> Result<(), FsError> {
let root = policy.root();
if location.source() != root.source()
|| !(path_is_within(location.path(), root.path())
|| path_is_within(root.path(), location.path()))
|| policy
.accepted_sandbox_root()
.is_some_and(|sandbox| !path_is_within(location.path(), sandbox.path()))
{
return Err(FsError::Other(
"trash directory creation escapes its endpoint or accepted sandbox".into(),
));
}
Ok(())
}
fn validate_generated_location(location: &Location, policy: &TrashPolicy) -> Result<(), FsError> {
if location.source() != policy.root().source()
|| !path_is_within(location.path(), policy.root().path())
|| policy
.accepted_sandbox_root()
.is_some_and(|sandbox| !path_is_within(location.path(), sandbox.path()))
{
return Err(FsError::Other(
"trash mutation path escapes its policy root or accepted sandbox".into(),
));
}
Ok(())
}
fn path_is_within(path: &Path, root: &Path) -> bool {
normalize_lexically(path).starts_with(normalize_lexically(root))
}
fn normalize_lexically(path: &Path) -> PathBuf {
let mut normalized = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
Component::RootDir | Component::CurDir => normalized.push(component.as_os_str()),
Component::ParentDir => {
normalized.pop();
}
Component::Normal(name) => normalized.push(name),
}
}
normalized
}
fn files_root(policy: &TrashPolicy) -> Location {
policy.root().join("files")
}
fn info_root(policy: &TrashPolicy) -> Location {
policy.root().join("info")
}
fn is_cross_device(error: &FsError) -> bool {
matches!(error, FsError::Unsupported(message) if message == "cross-device rename")
}
fn residual_error(error: FsError, partial: &PartFile) -> FsError {
with_residual(
error,
Some(partial.destination()),
std::iter::once(partial.location()),
)
}
fn with_residual<'a>(
error: FsError,
info: Option<&'a Location>,
residuals: impl IntoIterator<Item = &'a Location>,
) -> FsError {
let mut locations = Vec::new();
if let Some(info) = info {
locations.push(info);
}
locations.extend(residuals);
if locations.is_empty() {
return error;
}
let paths = locations
.into_iter()
.map(|location| location.path().display().to_string())
.collect::<Vec<_>>()
.join(", ");
FsError::Other(format!(
"{error}; residual trash metadata/staging retained for diagnosis: {paths}"
))
}
fn invalid_plan_results(plan: &EntryMutationPlan, error: FsError) -> Vec<ActionResult> {
let mut ids: Vec<_> = plan
.nodes()
.iter()
.filter(|node| node.relative_path().components().count() == 1)
.map(EntryMutationNode::id)
.collect();
if ids.is_empty() {
ids.extend(plan.nodes().first().map(EntryMutationNode::id));
}
ids.into_iter()
.map(|id| {
ActionResult::failed(
id,
MutationStage::Validation,
error.clone(),
CommitOutcome::NotAttempted,
)
})
.collect()
}