common/walk.rs
1//! Shared primitives for directory-walking operations (copy, link, rm, chmod, cmp).
2//!
3//! This module collects several small, related helpers used by `walk_driver` and the per-tool
4//! visitors:
5//! - `EntryKind` — classifies a directory entry by file type and exposes the per-type bits
6//! (dry-run label, skipped-counter increment) so callers don't re-implement the dispatch.
7//! - entry-admission lifecycle (`PermitKind` / `LeafPermit` / `EntryAdmission` / `AdmittedEntry` /
8//! `AdmittedLeaf` / `classify_entry`) — carries enumeration hints into classification while
9//! keeping classification handles structurally inside their admission lifetime.
10//! - congestion↔throttle bridges (`throttle_side` / `throttle_op` / `meta_resource`) — map the
11//! walk's side/op enums onto the throttle and congestion resource enums.
12//! - metadata-probe wrappers (`next_entry_probed` / `run_metadata_probed`) — wrap the path-based
13//! `ReadDir`/`metadata` calls with the static ops rate gate (deliberately not congestion-probed
14//! — see the function docs). These are the iteration primitive for the PATH-based walks (rcmp and
15//! the `-L`/dereference and remote-source paths); the TOCTOU-hardened copy/link/rm/chmod walks go
16//! through the fd-based `walk_driver` instead.
17//! - filter helpers (`filter_is_dir` / `should_skip_entry`) — apply include/exclude filtering and
18//! entry classification during enumeration.
19//! - root-operand parsing (`split_root_operand` / `root_operand_basename` /
20//! `without_trailing_separators`) — resolve a user-specified source operand (trailing slashes,
21//! `.`/`..`) into its components.
22
23use crate::filter::{FilterResult, FilterSettings};
24use crate::progress::Progress;
25use crate::timing::metadata::{Phase as MetadataTimingPhase, scope as metadata_timing_scope};
26use anyhow::Context;
27
28/// Join paths with capacity for both components and a separator before copying either one.
29///
30/// This preserves [`std::path::Path::join`] semantics, including lexical components, absolute
31/// suffix replacement, and the trailing separator added by an empty suffix. Callers that use an
32/// empty suffix to mean the root verbatim should use [`join_rel`].
33#[must_use]
34pub(crate) fn join_path(base: &std::path::Path, suffix: &std::path::Path) -> std::path::PathBuf {
35 let mut path =
36 std::path::PathBuf::with_capacity(base.as_os_str().len() + 1 + suffix.as_os_str().len());
37 path.push(base);
38 path.push(suffix);
39 path
40}
41
42/// Reconstruct a logical entry path, preserving the root operand verbatim for an empty coordinate.
43#[must_use]
44pub(crate) fn join_rel(root: &std::path::Path, rel_path: &std::path::Path) -> std::path::PathBuf {
45 if rel_path.as_os_str().is_empty() {
46 root.to_path_buf()
47 } else {
48 join_path(root, rel_path)
49 }
50}
51
52/// Classification of a filesystem entry by type.
53///
54/// `Special` covers sockets, FIFOs, block/character devices — anything that
55/// isn't a regular file, directory, or symlink. When a caller has only a best
56/// effort `Option<FileType>` (e.g. `entry.file_type().await.ok()`), an unknown
57/// type is treated as `File` to match historical behavior.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum EntryKind {
60 File,
61 Dir,
62 Symlink,
63 Special,
64}
65
66impl EntryKind {
67 /// Classify from a `Metadata` (root-level entries, where we always have full metadata).
68 #[must_use]
69 pub fn from_metadata(metadata: &std::fs::Metadata) -> Self {
70 if metadata.is_dir() {
71 Self::Dir
72 } else if metadata.is_symlink() {
73 Self::Symlink
74 } else if metadata.is_file() {
75 Self::File
76 } else {
77 Self::Special
78 }
79 }
80 /// Short dry-run label used during directory iteration (`"dir"`, `"symlink"`, `"file"`).
81 /// `Special` maps to `"file"` to match historical behavior — the old bool-triplet
82 /// dispatch in copy/link/rm fell through `is_dir`/`is_symlink` to "file" for any
83 /// other type. The explicit `--skip-specials` path uses its own literal "special"
84 /// string and does not call this helper.
85 #[must_use]
86 pub fn label(self) -> &'static str {
87 match self {
88 Self::Dir => "dir",
89 Self::Symlink => "symlink",
90 Self::File | Self::Special => "file",
91 }
92 }
93 /// Long dry-run label used at the root level (`"directory"` instead of `"dir"`).
94 /// `Special` maps to `"file"` for the same reason as [`Self::label`].
95 #[must_use]
96 pub fn label_long(self) -> &'static str {
97 match self {
98 Self::Dir => "directory",
99 Self::Symlink => "symlink",
100 Self::File | Self::Special => "file",
101 }
102 }
103 /// Increment the skipped counter that matches this entry kind. Special
104 /// files count as `files_skipped` — `specials_skipped` is reserved for
105 /// the explicit `--skip-specials` path, not filter skips.
106 pub fn inc_skipped(self, prog: &Progress) {
107 match self {
108 Self::Dir => prog.directories_skipped.inc(),
109 Self::Symlink => prog.symlinks_skipped.inc(),
110 Self::File | Self::Special => prog.files_skipped.inc(),
111 }
112 }
113}
114
115/// Which backpressure pool a leaf's pre-acquired permit comes from.
116///
117/// The two pools are deliberately distinct (see [`LeafPermit`]) — this enum
118/// selects between them per tool, plus a `None` variant for walks that take no
119/// leaf permit at all.
120///
121/// Unifying the *choice* of pool here — alongside [`LeafPermit`] and
122/// [`preacquire_leaf_permit`] — is what lets the traversal driver own the
123/// "drop the leaf permit before recursing into a directory" invariant in a
124/// single place. Hand-coding that drop at every per-tool branch is the root
125/// cause of the hold-and-wait deadlock class this lifecycle eliminates.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum PermitKind {
128 /// File-descriptor backpressure ([`throttle::open_file_permit`]) — for
129 /// copy/link leaf operations.
130 OpenFile,
131 /// Separate metadata-task backpressure ([`throttle::pending_meta_permit`]) —
132 /// for recursive chmod/rm walks. Keeping this pool distinct lets rm run
133 /// inside a copy overwrite while copy retains its open-file admission.
134 PendingMeta,
135 /// The tool takes no leaf permit (it doesn't gate at the leaf).
136 None,
137}
138
139/// A pre-acquired leaf permit, type-erased over the two distinct backpressure
140/// pools so a single caller (the traversal driver) can hold either uniformly
141/// and drop it in exactly one place before recursing into a directory.
142///
143/// The two pools must stay distinct: [`throttle::OpenFileGuard`] gates fd-bearing
144/// copy/link leaf operations while [`throttle::PendingMetaGuard`] gates in-flight
145/// metadata traversal tasks, some of which retain an `O_PATH` classification
146/// handle. They are separate semaphores, each configured to the same `N`, so a path that composes
147/// the two operations (for example, `copy_file_fd → remove_existing → rm_child` when overwriting a
148/// directory destination) cannot self-deadlock against a saturated OpenFile pool.
149/// This enum unifies only the *lifecycle*, never the pools themselves.
150///
151/// Neither guard is `Clone`; the only shared ownership they expose is an explicit
152/// [`throttle::FdAdmission`] weak reference for non-cancellable blocking work. In the ordinary
153/// path, dropping a `LeafPermit` releases exactly the underlying permit it wraps. The driver drops
154/// it before descending so a directory entry never holds a leaf permit across its recursive walk
155/// — the single home for the invariant that previously lived at 4/7/1/1 per-tool branch sites and
156/// shipped as a deadlock when a single-site tool forgot it.
157pub enum LeafPermit {
158 /// A permit from the open-files pool.
159 OpenFile(throttle::OpenFileGuard),
160 /// A permit from the pending-metadata pool.
161 PendingMeta(throttle::PendingMetaGuard),
162}
163
164/// Admission state carried from directory scheduling into entry classification.
165///
166/// A possible leaf either arrives with a held permit or acquires before its first authoritative
167/// classification. A positive `getdents` directory hint is the sole exception: it may classify
168/// without leaf admission, but a stale hint that resolves to a leaf must close that first handle,
169/// acquire, and classify again. Roots and delegated entries have no enumeration hint and acquire
170/// before classification.
171pub enum EntryAdmission {
172 /// The possible leaf already owns admission from its scheduling loop.
173 Held(LeafPermit),
174 /// A positive `getdents` directory hint permits one unadmitted classification.
175 HintedDirectory,
176 /// A root or delegated entry must acquire before classification.
177 RootOrDelegated,
178}
179
180impl EntryAdmission {
181 /// Construct the unacquired state described by a directory-entry type hint.
182 #[must_use]
183 pub fn from_hint(hint: Option<EntryKind>) -> Self {
184 if hint == Some(EntryKind::Dir) {
185 Self::HintedDirectory
186 } else {
187 Self::RootOrDelegated
188 }
189 }
190
191 /// Require ordinary admission when a decision cannot rely on the directory-hint exception.
192 ///
193 /// A dual-tree operation cannot use one entry's hint to exempt classification of its separate
194 /// counterpart. A destructive filter cannot trust the hinted type before authorizing an
195 /// action. Both discard the exception before classification; already-held admission remains.
196 #[must_use]
197 pub(crate) fn require_admission(self) -> Self {
198 match self {
199 Self::HintedDirectory => Self::RootOrDelegated,
200 Self::Held(_) | Self::RootOrDelegated => self,
201 }
202 }
203
204 /// Borrow the held admission lease, when this entry has acquired one.
205 #[must_use]
206 pub(crate) fn admission(&self) -> Option<throttle::FdAdmission> {
207 match self {
208 Self::Held(permit) => Some(permit.admission()),
209 Self::HintedDirectory | Self::RootOrDelegated => None,
210 }
211 }
212
213 /// Consume the state after classification and recover its leaf permit.
214 #[must_use]
215 pub(crate) fn into_permit(self) -> Option<LeafPermit> {
216 match self {
217 Self::Held(permit) => Some(permit),
218 Self::HintedDirectory | Self::RootOrDelegated => None,
219 }
220 }
221}
222
223impl From<Option<LeafPermit>> for EntryAdmission {
224 fn from(permit: Option<LeafPermit>) -> Self {
225 match permit {
226 Some(permit) => Self::Held(permit),
227 None => Self::RootOrDelegated,
228 }
229 }
230}
231
232impl LeafPermit {
233 /// Obtain a non-owning reference to this entry's admission for blocking work.
234 #[must_use]
235 pub(crate) fn admission(&self) -> throttle::FdAdmission {
236 match self {
237 Self::OpenFile(guard) => guard.admission(),
238 Self::PendingMeta(guard) => guard.admission(),
239 }
240 }
241
242 /// Consume an open-file admission wrapper and return its concrete guard.
243 ///
244 /// `rlink` schedules with the generic wrapper, then transfers the concrete guard into
245 /// `copy_child`; copy's `--dereference` path similarly transfers it into the target root walk.
246 /// A pending-metadata variant here is an internal policy error because neither path draws from
247 /// that pool.
248 pub(crate) fn into_open_file(self) -> throttle::OpenFileGuard {
249 match self {
250 Self::OpenFile(guard) => guard,
251 Self::PendingMeta(_) => {
252 unreachable!("pending-metadata permit used for open-file work")
253 }
254 }
255 }
256}
257
258/// A checked, authoritatively classified non-directory handle.
259#[derive(Debug)]
260struct NonDirectoryHandle(crate::safedir::Handle);
261
262impl TryFrom<crate::safedir::Handle> for NonDirectoryHandle {
263 type Error = crate::safedir::Handle;
264
265 fn try_from(handle: crate::safedir::Handle) -> Result<Self, Self::Error> {
266 if handle.kind() == EntryKind::Dir {
267 Err(handle)
268 } else {
269 Ok(Self(handle))
270 }
271 }
272}
273
274fn take_permit_after_closing_handle<H, P>(
275 handle: &mut Option<H>,
276 permit: &mut Option<P>,
277) -> Option<P> {
278 drop(handle.take());
279 permit.take()
280}
281
282/// One authoritatively classified entry and the admission held while deciding its action.
283///
284/// Destructive filters use this type to transfer the exact classification handle that informed
285/// the filter decision into the shared walk driver. Private handle-then-permit ownership plus the
286/// explicit [`Drop`] implementation close the handle before returning admission on every skipped,
287/// failed, or cancelled path. Only the driver's directory dispatch can deliberately release the
288/// provisional leaf permit while retaining a directory handle for unbudgeted recursion.
289pub(crate) struct AdmittedEntry {
290 handle: Option<crate::safedir::Handle>,
291 permit: Option<LeafPermit>,
292}
293
294impl AdmittedEntry {
295 pub(crate) fn new(handle: crate::safedir::Handle, permit: Option<LeafPermit>) -> Self {
296 Self {
297 handle: Some(handle),
298 permit,
299 }
300 }
301
302 /// Borrow the authoritative classification handle.
303 #[must_use]
304 pub(crate) fn handle(&self) -> &crate::safedir::Handle {
305 self.handle
306 .as_ref()
307 .expect("an admitted entry always owns its handle")
308 }
309
310 /// Return the authoritative entry kind.
311 #[must_use]
312 pub(crate) fn kind(&self) -> EntryKind {
313 self.handle().kind()
314 }
315
316 /// Borrow this entry's weak admission reference, when its visitor uses a pool.
317 #[must_use]
318 pub(crate) fn admission(&self) -> Option<throttle::FdAdmission> {
319 self.permit.as_ref().map(LeafPermit::admission)
320 }
321
322 /// Convert the classified entry into the driver's leaf-or-directory dispatch.
323 ///
324 /// The directory outcome is the sole explicit drop-before-recursion transition: it returns the
325 /// authoritative handle after releasing provisional leaf admission. The leaf outcome preserves
326 /// handle-before-permit ownership in [`AdmittedLeaf`].
327 #[allow(clippy::result_large_err)]
328 pub(crate) fn into_leaf(self) -> Result<AdmittedLeaf, crate::safedir::Handle> {
329 let mut this = self;
330 let handle = this
331 .handle
332 .take()
333 .expect("an admitted entry always owns its handle");
334 match NonDirectoryHandle::try_from(handle) {
335 Ok(handle) => Ok(AdmittedLeaf::new(handle, this.permit.take())),
336 Err(handle) => {
337 drop(this.permit.take());
338 Err(handle)
339 }
340 }
341 }
342}
343
344impl Drop for AdmittedEntry {
345 fn drop(&mut self) {
346 drop(take_permit_after_closing_handle(
347 &mut self.handle,
348 &mut self.permit,
349 ));
350 }
351}
352
353/// An authoritatively classified non-directory and its leaf admission.
354///
355/// The private handle-then-permit fields document the lifetime invariant, while the explicit drop
356/// implementation enforces it in one testable place on every destructing exit: ordinary return,
357/// error, panic unwind, and cancellation. Directory dispatch never constructs this type.
358pub struct AdmittedLeaf {
359 handle: Option<NonDirectoryHandle>,
360 permit: Option<LeafPermit>,
361}
362
363impl AdmittedLeaf {
364 fn new(handle: NonDirectoryHandle, permit: Option<LeafPermit>) -> Self {
365 Self {
366 handle: Some(handle),
367 permit,
368 }
369 }
370
371 /// Check and bundle an authoritative non-directory classification with its admission.
372 ///
373 /// A directory returns its original handle and permit so callers with a multi-entry decision
374 /// can close every related handle before releasing admission. The shared single-entry driver
375 /// instead consumes [`AdmittedEntry`], which centralizes its drop-before-recursion transition.
376 #[allow(clippy::result_large_err)]
377 pub(crate) fn try_new(
378 handle: crate::safedir::Handle,
379 permit: Option<LeafPermit>,
380 ) -> Result<Self, (crate::safedir::Handle, Option<LeafPermit>)> {
381 match NonDirectoryHandle::try_from(handle) {
382 Ok(handle) => Ok(Self::new(handle, permit)),
383 Err(handle) => Err((handle, permit)),
384 }
385 }
386
387 /// Borrow the authoritative classification handle.
388 #[must_use]
389 pub fn handle(&self) -> &crate::safedir::Handle {
390 &self
391 .handle
392 .as_ref()
393 .expect("an admitted leaf always owns its handle")
394 .0
395 }
396
397 /// Return the authoritative entry kind.
398 #[must_use]
399 pub fn kind(&self) -> EntryKind {
400 self.handle().kind()
401 }
402
403 /// Borrow this leaf's weak admission reference, when its visitor uses a pool.
404 #[must_use]
405 pub fn admission(&self) -> Option<throttle::FdAdmission> {
406 self.permit.as_ref().map(LeafPermit::admission)
407 }
408
409 /// Close the classification handle before transferring the admission permit.
410 #[must_use]
411 pub(crate) fn into_permit(mut self) -> Option<LeafPermit> {
412 take_permit_after_closing_handle(&mut self.handle, &mut self.permit)
413 }
414}
415
416impl Drop for AdmittedLeaf {
417 fn drop(&mut self) {
418 drop(take_permit_after_closing_handle(
419 &mut self.handle,
420 &mut self.permit,
421 ));
422 }
423}
424
425/// Pre-acquire a leaf permit for a child about to be spawned.
426///
427/// Returns `None` when `kind == PermitKind::None` or the cheap `getdents` hint positively identifies
428/// a directory. Every known non-directory and `DT_UNKNOWN` entry is admitted provisionally before
429/// spawn. The worker then classifies it authoritatively and drops the permit before recursion if it
430/// proves to be a directory.
431pub async fn preacquire_leaf_permit(
432 kind: PermitKind,
433 hint: Option<EntryKind>,
434) -> Option<LeafPermit> {
435 if kind == PermitKind::None || hint == Some(EntryKind::Dir) {
436 return None;
437 }
438 match kind {
439 PermitKind::OpenFile => Some(LeafPermit::OpenFile(throttle::open_file_permit().await)),
440 PermitKind::PendingMeta => Some(LeafPermit::PendingMeta(
441 throttle::pending_meta_permit().await,
442 )),
443 // unreachable: the early return above already handled `None`.
444 PermitKind::None => None,
445 }
446}
447
448/// Ensure an entry has admission before its fd-bearing authoritative classification.
449///
450/// Spawn loops pass their already-acquired permit here. Root and delegated callers that did not
451/// come through such a loop acquire from the visitor's pool now, before `Dir::child` opens the
452/// entry's `O_PATH` handle. A directory classification releases the provisional permit in the
453/// shared driver's drop-before-recursion branch.
454pub async fn ensure_leaf_permit(
455 kind: PermitKind,
456 permit: Option<LeafPermit>,
457) -> Option<LeafPermit> {
458 if permit.is_some() {
459 return permit;
460 }
461 match kind {
462 PermitKind::OpenFile => Some(LeafPermit::OpenFile(throttle::open_file_permit().await)),
463 PermitKind::PendingMeta => Some(LeafPermit::PendingMeta(
464 throttle::pending_meta_permit().await,
465 )),
466 PermitKind::None => None,
467 }
468}
469
470/// Ensure a root, delegated entry, or possible leaf holds the visitor's selected admission.
471///
472/// `HintedDirectory` deliberately remains unadmitted until classification proves the hint stale.
473/// `PermitKind::None` also remains `RootOrDelegated`, expressing that the visitor opted out of a
474/// leaf pool rather than pretending it holds a permit.
475pub async fn ensure_entry_admission(kind: PermitKind, admission: EntryAdmission) -> EntryAdmission {
476 match admission {
477 EntryAdmission::Held(_) | EntryAdmission::HintedDirectory => admission,
478 EntryAdmission::RootOrDelegated => match ensure_leaf_permit(kind, None).await {
479 Some(permit) => EntryAdmission::Held(permit),
480 None => EntryAdmission::RootOrDelegated,
481 },
482 }
483}
484
485/// Classify an entry within the admission scope selected by its caller.
486///
487/// The shared driver and rlink own the hinted-directory state machine because a stale positive
488/// hint must close its first handle, acquire admission, install a new scope, and keep that scope
489/// through final leaf work. This helper is deliberately only the authoritative fd-based open.
490pub async fn classify_entry(
491 dir: &crate::safedir::Dir,
492 name: &std::ffi::OsStr,
493) -> std::io::Result<crate::safedir::Handle> {
494 dir.child(name).await
495}
496
497/// Classify an entry while transferring its already-acquired admission into one owner.
498///
499/// Callers acquire according to their visitor's pool policy before entering here. The weak
500/// task-local scope lets every fd-bearing await in the classification use the same admission, and
501/// [`AdmittedEntry`] then keeps the handle inside that permit's lifetime until dispatch.
502pub(crate) async fn classify_admitted_entry(
503 dir: &crate::safedir::Dir,
504 name: &std::ffi::OsStr,
505 permit: Option<LeafPermit>,
506) -> std::io::Result<AdmittedEntry> {
507 let admission = permit.as_ref().map(LeafPermit::admission);
508 crate::safedir::with_optional_fd_admission(admission, async move {
509 let handle = classify_entry(dir, name).await?;
510 Ok(AdmittedEntry::new(handle, permit))
511 })
512 .await
513}
514
515/// Resolve the `throttle::Side` from the matching `congestion::Side`.
516///
517/// The two crates carry independent enum definitions to keep `throttle`
518/// free of any congestion dependency; this is the canonical bridge
519/// (paired with [`throttle_op`]) reused everywhere a congestion-side
520/// signal needs to address a throttle resource.
521pub(crate) fn throttle_side(side: congestion::Side) -> throttle::Side {
522 match side {
523 congestion::Side::Source => throttle::Side::Source,
524 congestion::Side::Destination => throttle::Side::Destination,
525 }
526}
527
528/// Resolve the `throttle::MetadataOp` from the matching `congestion::MetadataOp`.
529pub(crate) fn throttle_op(op: congestion::MetadataOp) -> throttle::MetadataOp {
530 match op {
531 congestion::MetadataOp::Stat => throttle::MetadataOp::Stat,
532 congestion::MetadataOp::ReadLink => throttle::MetadataOp::ReadLink,
533 congestion::MetadataOp::MkDir => throttle::MetadataOp::MkDir,
534 congestion::MetadataOp::RmDir => throttle::MetadataOp::RmDir,
535 congestion::MetadataOp::Unlink => throttle::MetadataOp::Unlink,
536 congestion::MetadataOp::HardLink => throttle::MetadataOp::HardLink,
537 congestion::MetadataOp::Symlink => throttle::MetadataOp::Symlink,
538 congestion::MetadataOp::Chmod => throttle::MetadataOp::Chmod,
539 congestion::MetadataOp::OpenCreate => throttle::MetadataOp::OpenCreate,
540 }
541}
542
543/// Resolve the [`throttle::Resource`] for a single per-file metadata
544/// syscall on the given side.
545pub(crate) fn meta_resource(
546 side: congestion::Side,
547 op: congestion::MetadataOp,
548) -> throttle::Resource {
549 throttle::Resource::meta(throttle_side(side), throttle_op(op))
550}
551
552/// Pull the next directory entry, gated only by the static ops rate
553/// gate.
554///
555/// Walks are deliberately not probed: `tokio::fs::ReadDir::next_entry`
556/// returns buffered entries from a prior `getdents` batch without
557/// entering the kernel, so most "walk probes" don't measure filesystem
558/// service time at all. The resulting bimodal latency distribution
559/// (cache hit vs. real `getdents`) collapses any baseline a controller
560/// could derive from it. The fix is to probe only the per-file
561/// metadata syscalls that follow the walk, where each sample reflects
562/// real filesystem work.
563///
564/// The prologue is therefore just:
565///
566/// 1. Await the static ops rate gate.
567/// 2. Call `next_entry()` and, on success, classify via `file_type()`.
568///
569/// `side` is currently unused at runtime but kept on the signature so
570/// callers stay self-documenting and future per-side gating can be
571/// reintroduced without touching every call site.
572///
573/// The error is left as `anyhow::Error` so each caller can wrap it in the
574/// site-specific error type (`copy::Error`, `link::Error`, `rm::Error`)
575/// without this helper needing to be generic over the summary payload.
576pub async fn next_entry_probed<F>(
577 entries: &mut tokio::fs::ReadDir,
578 _side: congestion::Side,
579 context: F,
580) -> anyhow::Result<Option<(tokio::fs::DirEntry, Option<std::fs::FileType>)>>
581where
582 F: FnOnce() -> String,
583{
584 throttle::get_ops_token().await;
585 let maybe_entry = entries.next_entry().await.with_context(context)?;
586 let Some(entry) = maybe_entry else {
587 return Ok(None);
588 };
589 let entry_file_type = entry.file_type().await.ok();
590 Ok(Some((entry, entry_file_type)))
591}
592
593/// Bracket a single metadata-producing future with the full per-op
594/// gating prologue: the static ops rate gate, the cwnd permit for the
595/// matching `(side, op_kind)` resource, and a congestion probe. The
596/// probe completes successfully when `fut` returns `Ok`, and is
597/// discarded on error so error paths don't skew the controller's
598/// latency baseline.
599///
600/// `op_kind` selects which per-syscall controller this call is
601/// reported to and gated by — `Stat`, `MkDir`, `Unlink`, etc. Pick the
602/// variant that matches the underlying syscall (`metadata` /
603/// `symlink_metadata` / `File::open(read)` / `canonicalize` all map to
604/// `Stat`; `create_dir` to `MkDir`; `remove_file` to `Unlink`; and so
605/// on — see [`congestion::MetadataOp`] for the full mapping).
606///
607/// `--ops-throttle` is the shared metadata rate gate, so this helper
608/// acquires it on every call — same as [`next_entry_probed`]. Callers
609/// that already rate-gate upstream (such as filegen, which gates at
610/// per-task spawn time so we don't fan out an unbounded task queue
611/// before any token is consumed) must use
612/// [`run_metadata_probed_no_rate`] instead to avoid double-counting.
613pub async fn run_metadata_probed<F, T, E>(
614 side: congestion::Side,
615 op_kind: congestion::MetadataOp,
616 fut: F,
617) -> Result<T, E>
618where
619 F: std::future::Future<Output = Result<T, E>>,
620{
621 let rate = metadata_timing_scope(side, op_kind, MetadataTimingPhase::Rate);
622 throttle::get_ops_token().await;
623 rate.finish();
624 run_metadata_probed_no_rate(side, op_kind, fut).await
625}
626
627/// Variant of [`run_metadata_probed`] that skips the static ops rate
628/// gate — for callers that already rate-limit at a coarser granularity
629/// upstream and would otherwise consume two tokens per metadata op.
630///
631/// Concretely: `filegen` gates the rate at task-spawn time so an enabled
632/// ops throttle paces creation of `write_file` futures. Their concurrent
633/// backlog is controlled separately by descriptor admission when that is
634/// enabled. The `OpenOptions::open(O_CREAT)` inside the spawned task is the
635/// only metadata syscall in that path; rate-gating it again would halve the
636/// effective rate.
637pub async fn run_metadata_probed_no_rate<F, T, E>(
638 side: congestion::Side,
639 op_kind: congestion::MetadataOp,
640 fut: F,
641) -> Result<T, E>
642where
643 F: std::future::Future<Output = Result<T, E>>,
644{
645 let admission = metadata_timing_scope(side, op_kind, MetadataTimingPhase::Admission);
646 let ops_permit = throttle::ops_in_flight_permit(meta_resource(side, op_kind)).await;
647 admission.finish();
648 let probe = congestion::Probe::start_metadata(side, op_kind);
649 let execution = metadata_timing_scope(side, op_kind, MetadataTimingPhase::Execute);
650 let result = fut.await;
651 match &result {
652 Ok(_) => probe.complete_ok(0),
653 Err(_) => probe.discard(),
654 }
655 drop(ops_permit);
656 execution.finish();
657 result
658}
659
660/// Determine the `is_dir` value to feed an include/exclude FILTER decision for a
661/// directory entry, using the authoritative `fstat` type when the cheap
662/// `getdents` `d_type` hint is unavailable.
663///
664/// `read_entries` returns each entry's `d_type` as a best-effort hint; on
665/// filesystems that don't populate it (NFS, some FUSE mounts) the hint is `None`
666/// (`DT_UNKNOWN`). Treating `None` as "not a directory" for an `is_dir`-dependent
667/// filter (e.g. `--include '/sub/**'`) would wrongly EXCLUDE a real directory and
668/// omit its entire subtree. To match the old path-based walk (which fell back to
669/// an `lstat` via `DirEntry::file_type()`), this resolves the type
670/// AUTHORITATIVELY via `dir.child(name)`'s `fstat` — but ONLY when the hint is
671/// `None` AND the type is actually needed: either a filter is active, or the
672/// caller passes `force_authoritative` because its own control flow depends on
673/// the result (e.g. a dry-run recurse-vs-leaf decision). When the hint is
674/// reliable, or the type is unneeded, the cheap hint is used directly (no extra
675/// syscall), preserving the optimization.
676///
677/// `child(name)` uses `O_PATH|O_NOFOLLOW`, so this never follows a symlink (a
678/// symlink entry classifies as `Symlink`, not `Dir`) or blocks opening a FIFO or
679/// device payload; the metadata lookup itself can still wait on slow storage.
680/// The hardening of the walk below the named root is unaffected. On a `child`
681/// error (e.g. the entry vanished mid-walk), the error is returned. A failed authoritative probe
682/// cannot safely be interpreted as a non-directory because that could defeat directory-only
683/// filtering or delete protection.
684pub async fn filter_is_dir(
685 filter: Option<&FilterSettings>,
686 dir: &crate::safedir::Dir,
687 name: &std::ffi::OsStr,
688 hint: Option<EntryKind>,
689 force_authoritative: bool,
690) -> std::io::Result<bool> {
691 match hint {
692 Some(kind) => Ok(kind == EntryKind::Dir),
693 // DT_UNKNOWN: only pay for the authoritative fstat when the type is actually
694 // needed — a filter needs it, or the caller's control flow depends on it
695 // (`force_authoritative`, e.g. a dry-run recurse-vs-leaf decision). Otherwise
696 // the value is unused, so default cheaply.
697 None if filter.is_some() || force_authoritative => {
698 Ok(dir.child(name).await?.kind() == EntryKind::Dir)
699 }
700 None => Ok(false),
701 }
702}
703
704/// Decide whether an entry should be skipped by the filter, returning the
705/// `FilterResult` that caused the skip. Returns `None` if there is no filter
706/// or the entry is included.
707#[must_use]
708pub fn should_skip_entry(
709 filter: &Option<FilterSettings>,
710 relative_path: &std::path::Path,
711 is_dir: bool,
712) -> Option<FilterResult> {
713 should_skip_entry_ref(filter.as_ref(), relative_path, is_dir)
714}
715
716/// [`should_skip_entry`] taking the filter by `Option<&_>` rather than
717/// `&Option<_>`, so callers that already hold an `Option<&FilterSettings>` (the
718/// traversal driver) don't have to clone it. Identical semantics otherwise.
719#[must_use]
720pub fn should_skip_entry_ref(
721 filter: Option<&FilterSettings>,
722 relative_path: &std::path::Path,
723 is_dir: bool,
724) -> Option<FilterResult> {
725 if let Some(f) = filter {
726 let result = f.should_include(relative_path, is_dir);
727 match result {
728 FilterResult::Included => None,
729 _ => Some(result),
730 }
731 } else {
732 None
733 }
734}
735
736/// Path of `entry` relative to `root` (typically `source_root` or `dest_root` at the call
737/// site), with the `unwrap_or(entry)` defensive fallback rcp uses when `entry` isn't
738/// actually under `root`. Naming the pattern lets call sites read "the entry's path inside
739/// the tree" instead of `entry.strip_prefix(root).unwrap_or(entry)` — and removes a class
740/// of "did I get strip_prefix the right way round?" regressions.
741#[must_use]
742pub fn relative_to_root<'a>(
743 entry: &'a std::path::Path,
744 root: &std::path::Path,
745) -> &'a std::path::Path {
746 entry.strip_prefix(root).unwrap_or(entry)
747}
748
749/// Strip trailing path separators from a root operand. A trailing slash forces the OS to resolve
750/// the final component as a directory, which would dereference a symlink root like `link/`
751/// (following it to its target). Stripping makes `link/` behave like `link` (the symlink itself),
752/// which is then classified/operated on `O_NOFOLLOW` relative to its parent fd.
753#[must_use]
754pub fn without_trailing_separators(path: &std::path::Path) -> std::path::PathBuf {
755 use std::os::unix::ffi::OsStrExt;
756 let bytes = path.as_os_str().as_bytes();
757 let mut end = bytes.len();
758 while end > 1 && bytes[end - 1] == b'/' {
759 end -= 1;
760 }
761 std::path::PathBuf::from(std::ffi::OsStr::from_bytes(&bytes[..end]))
762}
763
764/// A root operand decomposed for the fd-relative walk entry point.
765pub struct RootOperand {
766 /// The operand's parent directory — opened TRUSTED (follows symlinks) via
767 /// [`crate::safedir::Dir::open_parent_dir`].
768 pub parent: std::path::PathBuf,
769 /// The operand's final component — classified `O_NOFOLLOW` via `child(name)` below the parent.
770 pub name: std::ffi::OsString,
771 /// The operand path for diagnostics / `real_path` reconstruction: the operand as typed (with
772 /// trailing slashes stripped) for a normal operand, or the canonicalized path for a `.`/`..`
773 /// operand that had to be resolved.
774 pub display: std::path::PathBuf,
775}
776
777/// Decompose a root operand into the `(parent, final_component)` the fd-relative walk needs (see
778/// [`RootOperand`]): the parent prefix is opened with [`crate::safedir::Dir::open_parent_dir`]
779/// (trusted, follows symlinks) and the final component is then classified `O_NOFOLLOW` via
780/// `child(name)` below it.
781///
782/// Most operands split directly via `parent()` / `file_name()` (an empty parent meaning the current
783/// directory). An operand whose final component is `.` or `..` (e.g. `.`, `tree/..`) has no
784/// `file_name()`, so it is first canonicalized to a concrete path — `.` becomes the current
785/// directory, `tree/..` its grandparent — restoring the behavior of the pre-fd-walk path code,
786/// where `rrm .` / `rchm -R … .` operated on the current tree. (Canonicalizing only this branch
787/// never touches a normal operand, so a symlinked final component on the normal path is still
788/// opened `O_NOFOLLOW`; `.`/`..` are themselves never symlinks.) The filesystem root `/` has no
789/// parent and cannot be expressed as parent + component, so it is rejected with a clear error.
790pub async fn split_root_operand(path: &std::path::Path) -> anyhow::Result<RootOperand> {
791 let stripped = without_trailing_separators(path);
792 if let Some(name) = stripped.file_name() {
793 let parent = match stripped.parent() {
794 Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
795 // empty parent (a single-component relative path) means the current directory.
796 _ => std::path::PathBuf::from("."),
797 };
798 let name = name.to_owned();
799 return Ok(RootOperand {
800 parent,
801 name,
802 display: stripped,
803 });
804 }
805 // final component is `.`/`..` (or the operand is `/`): canonicalize to a concrete path so it can
806 // be split into parent + component.
807 let canonical = tokio::fs::canonicalize(&stripped)
808 .await
809 .with_context(|| format!("cannot resolve operand {stripped:?}"))?;
810 let name = canonical.file_name().map(std::ffi::OsStr::to_owned);
811 let parent = canonical.parent().map(std::path::Path::to_path_buf);
812 let (Some(parent), Some(name)) = (parent, name) else {
813 anyhow::bail!("cannot operate on the filesystem root {canonical:?}");
814 };
815 Ok(RootOperand {
816 parent,
817 name,
818 display: canonical,
819 })
820}
821
822/// The basename a root operand contributes to the trailing-slash "copy INTO directory" rule: the
823/// name of the entry the walk will create for `path`, so a CLI forming `dst/<name>` matches it
824/// exactly (`rcp . out/` / `rlink . out/` -> `out/<cwd-name>`; `… tree/.. out/` ->
825/// `out/<parent-name>`).
826///
827/// This is the synchronous twin of [`split_root_operand`]'s `name`, for the CLI path-resolution
828/// layer (which is not async): a normal operand uses [`std::path::Path::file_name`]; an operand
829/// with no `file_name()` (`.`/`..`/`dir/..`) is canonicalized first, exactly as
830/// [`split_root_operand`] does. The filesystem root has no basename and is rejected. The
831/// `root_operand_basename_matches_split_root_operand` test keeps the two in lock-step.
832pub fn root_operand_basename(path: &std::path::Path) -> anyhow::Result<std::ffi::OsString> {
833 let stripped = without_trailing_separators(path);
834 if let Some(name) = stripped.file_name() {
835 return Ok(name.to_owned());
836 }
837 // final component is `.`/`..` (or the operand is `/`): canonicalize to a concrete path so it
838 // has a real basename — the same resolution `split_root_operand` performs for the walk.
839 let canonical = std::fs::canonicalize(&stripped)
840 .with_context(|| format!("cannot resolve operand {stripped:?}"))?;
841 canonical
842 .file_name()
843 .map(std::ffi::OsStr::to_owned)
844 .ok_or_else(|| anyhow::anyhow!("cannot operate on the filesystem root {canonical:?}"))
845}
846
847#[cfg(test)]
848mod tests {
849 use super::*;
850 use crate::safedir::Dir;
851 use crate::testutils;
852 use std::ffi::OsStr;
853 use std::os::fd::AsRawFd;
854
855 #[test]
856 fn joined_paths_preserve_literal_bytes_and_join_semantics() {
857 use std::os::unix::ffi::OsStrExt;
858 let cases: &[(&[u8], &[u8], &[u8])] = &[
859 (b"", b"", b""),
860 (b"", b"leaf", b"leaf"),
861 (b"root", b"", b"root/"),
862 (b"root/", b"", b"root/"),
863 (b"/", b"leaf", b"/leaf"),
864 (b"/", b"", b"/"),
865 (b"root", b"leaf", b"root/leaf"),
866 (b"root//./", b"branch//../leaf", b"root//./branch//../leaf"),
867 (b"./root/..", b"./leaf/", b"./root/.././leaf/"),
868 (b"root/.", b"leaf", b"root/./leaf"),
869 (b"root", b"/replacement//leaf", b"/replacement//leaf"),
870 (
871 b"root\xfe",
872 b"branch\xff/leaf\xfd",
873 b"root\xfe/branch\xff/leaf\xfd",
874 ),
875 ];
876 for &(base, suffix, expected) in cases {
877 let base = std::path::Path::new(OsStr::from_bytes(base));
878 let suffix = std::path::Path::new(OsStr::from_bytes(suffix));
879 let actual = join_path(base, suffix);
880 assert_eq!(actual.as_os_str().as_bytes(), expected);
881 assert_eq!(actual.as_os_str(), base.join(suffix).as_os_str());
882 }
883 }
884
885 #[test]
886 fn relative_join_preserves_root_operand_and_non_utf8_components() {
887 use std::os::unix::ffi::OsStrExt;
888 for (root, relative, expected) in [
889 (
890 b"file\xff".as_slice(),
891 b"".as_slice(),
892 b"file\xff".as_slice(),
893 ),
894 (b"source//./file\xff", b"", b"source//./file\xff"),
895 (
896 b"source//./",
897 b"branch\xff/leaf\xfe",
898 b"source//./branch\xff/leaf\xfe",
899 ),
900 ] {
901 let joined = join_rel(
902 std::path::Path::new(OsStr::from_bytes(root)),
903 std::path::Path::new(OsStr::from_bytes(relative)),
904 );
905 assert_eq!(joined.as_os_str().as_bytes(), expected);
906 }
907 }
908
909 fn include_filter(pattern: &str) -> Option<FilterSettings> {
910 let mut f = FilterSettings::new();
911 f.add_include(pattern).unwrap();
912 Some(f)
913 }
914
915 // FIX B (PR #247 review): when the getdents `d_type` hint is unavailable (DT_UNKNOWN -> None)
916 // AND a filter is active, the filter `is_dir` decision must come from the AUTHORITATIVE fstat,
917 // not default to non-dir. Otherwise a real directory reported as DT_UNKNOWN would be wrongly
918 // excluded by an is_dir-dependent include filter, omitting its whole subtree. We can't force
919 // DT_UNKNOWN on a normal local fs, so we drive `filter_is_dir` with `hint = None` directly —
920 // exactly the value `read_entries` would yield on NFS/FUSE — to exercise the authoritative path.
921 #[tokio::test]
922 async fn filter_is_dir_authoritatively_classifies_dt_unknown_directory() -> anyhow::Result<()> {
923 let tmp = testutils::setup_test_dir().await?;
924 // fixture: tmp/foo holds `bar` (a real directory) and `0.txt` (a real file).
925 let dir = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
926 let filter = include_filter("/bar/**");
927 // DT_UNKNOWN + active filter on a real DIRECTORY -> must resolve to `true` via fstat, so an
928 // include filter does NOT omit its subtree (the regression this fix closes).
929 assert!(
930 filter_is_dir(filter.as_ref(), &dir, OsStr::new("bar"), None, false).await?,
931 "a real directory reported as DT_UNKNOWN must classify as a directory for the filter"
932 );
933 // DT_UNKNOWN + active filter on a real FILE -> resolves to `false` authoritatively.
934 assert!(
935 !filter_is_dir(filter.as_ref(), &dir, OsStr::new("0.txt"), None, false).await?,
936 "a real file reported as DT_UNKNOWN must classify as a non-directory"
937 );
938 Ok(())
939 }
940
941 // FIX B: a reliable hint is used directly (no fstat), and with no filter active the value is
942 // the cheap default — the optimization is preserved (we never pay an fstat we don't need).
943 #[tokio::test]
944 async fn filter_is_dir_uses_hint_when_available_and_skips_when_no_filter() -> anyhow::Result<()>
945 {
946 let tmp = testutils::setup_test_dir().await?;
947 let dir = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
948 let filter = include_filter("/bar/**");
949 // reliable Dir hint -> true regardless of fstat.
950 assert!(
951 filter_is_dir(
952 filter.as_ref(),
953 &dir,
954 OsStr::new("bar"),
955 Some(EntryKind::Dir),
956 false
957 )
958 .await?
959 );
960 // reliable File hint -> false.
961 assert!(
962 !filter_is_dir(
963 filter.as_ref(),
964 &dir,
965 OsStr::new("0.txt"),
966 Some(EntryKind::File),
967 false
968 )
969 .await?
970 );
971 // DT_UNKNOWN, NO filter, and not forced -> cheap non-dir default (no authoritative fstat
972 // needed); the `name` is never resolved, so it need not even exist.
973 assert!(!filter_is_dir(None, &dir, OsStr::new("does_not_exist"), None, false).await?);
974 Ok(())
975 }
976
977 // force_authoritative (e.g. rlink --dry-run, which uses is_dir for its recurse-vs-leaf
978 // branch): a DT_UNKNOWN hint with NO filter must still classify AUTHORITATIVELY when the
979 // caller's control flow depends on the result, so a dry-run on NFS/FUSE doesn't preview a
980 // real directory as a leaf and skip its subtree.
981 #[tokio::test]
982 async fn filter_is_dir_forces_authoritative_classification_when_requested() -> anyhow::Result<()>
983 {
984 let tmp = testutils::setup_test_dir().await?;
985 let dir = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
986 // DT_UNKNOWN + NO filter, but force_authoritative -> a real directory must classify as dir.
987 assert!(
988 filter_is_dir(None, &dir, OsStr::new("bar"), None, true).await?,
989 "force_authoritative must fstat a DT_UNKNOWN directory even with no filter"
990 );
991 // ...and a real file as non-dir.
992 assert!(
993 !filter_is_dir(None, &dir, OsStr::new("0.txt"), None, true).await?,
994 "force_authoritative must fstat a DT_UNKNOWN file even with no filter"
995 );
996 Ok(())
997 }
998
999 // the leaf-permit lifecycle: `PermitKind::None` and a known directory opt out;
1000 // every possible leaf acquires from the requested pool. The pools are
1001 // process-global; configure a small cap so the OpenFile case exercises a real
1002 // acquire rather than the disabled-pool no-op.
1003 #[tokio::test]
1004 async fn preacquire_leaf_permit_respects_max_files_in_flight_kind_and_hint() {
1005 let admission = crate::testutils::AdmissionLimit::new().await;
1006 admission.set_files_in_flight(4);
1007 // `None` kind never takes a permit, regardless of hint.
1008 assert!(
1009 preacquire_leaf_permit(PermitKind::None, Some(EntryKind::File))
1010 .await
1011 .is_none()
1012 );
1013 // a possible leaf on the OpenFile pool yields an OpenFile permit.
1014 let permit = preacquire_leaf_permit(PermitKind::OpenFile, Some(EntryKind::File)).await;
1015 assert!(matches!(permit, Some(LeafPermit::OpenFile(_))));
1016 drop(permit);
1017 // a known directory opts out even though the pool is configured.
1018 assert!(
1019 preacquire_leaf_permit(PermitKind::OpenFile, Some(EntryKind::Dir))
1020 .await
1021 .is_none()
1022 );
1023 // treat DT_UNKNOWN as a provisional leaf until authoritative classification.
1024 let permit = preacquire_leaf_permit(PermitKind::OpenFile, None).await;
1025 assert!(matches!(permit, Some(LeafPermit::OpenFile(_))));
1026 drop(permit);
1027 }
1028
1029 #[test]
1030 fn leaf_drop_primitive_closes_handle_before_permit() {
1031 let events = testutils::DropEvents::default();
1032 let mut handle = Some(events.probe("handle"));
1033 let mut permit = Some(events.probe("permit"));
1034
1035 let permit = take_permit_after_closing_handle(&mut handle, &mut permit);
1036 assert_eq!(
1037 events.snapshot(),
1038 ["handle"],
1039 "the handle must close before the permit can be returned"
1040 );
1041 drop(permit);
1042 assert_eq!(events.snapshot(), ["handle", "permit"]);
1043 }
1044
1045 #[tokio::test]
1046 async fn directory_handle_conversion_returns_the_original_handle() -> anyhow::Result<()> {
1047 let root = testutils::create_temp_dir().await?;
1048 tokio::fs::create_dir(root.join("directory")).await?;
1049 let parent = Dir::open_parent_dir(&root, congestion::Side::Source)
1050 .await?
1051 .into_tree();
1052 let handle = parent.child(OsStr::new("directory")).await?;
1053 let raw_fd = handle.as_fd().as_raw_fd();
1054 let probe = match testutils::FdIdentityProbe::capture(raw_fd) {
1055 Ok(probe) => probe,
1056 Err(error) => {
1057 drop(handle);
1058 drop(parent);
1059 let cleanup_result = tokio::fs::remove_dir_all(root).await;
1060 return match cleanup_result {
1061 Ok(()) => Err(error.into()),
1062 Err(cleanup_error) => Err(anyhow::Error::new(error).context(format!(
1063 "directory conversion fixture did not clean up: {cleanup_error:#}"
1064 ))),
1065 };
1066 }
1067 };
1068
1069 let directory = match NonDirectoryHandle::try_from(handle) {
1070 Ok(_) => anyhow::bail!("a directory was accepted as a non-directory handle"),
1071 Err(directory) => directory,
1072 };
1073 assert_eq!(directory.kind(), EntryKind::Dir);
1074 assert_eq!(directory.as_fd().as_raw_fd(), raw_fd);
1075 let fd_was_open_before_drop = probe.original_is_closed().map(|closed| !closed);
1076 drop(directory);
1077 let fd_was_closed_after_drop = probe.original_is_closed();
1078 drop(parent);
1079 let cleanup_result = tokio::fs::remove_dir_all(root).await;
1080 let fd_was_open_before_drop = fd_was_open_before_drop?;
1081 let fd_was_closed_after_drop = fd_was_closed_after_drop?;
1082 cleanup_result?;
1083 assert!(fd_was_open_before_drop);
1084 assert!(fd_was_closed_after_drop);
1085 Ok(())
1086 }
1087
1088 #[tokio::test]
1089 async fn into_permit_closes_handle_before_transfer() -> anyhow::Result<()> {
1090 let root = testutils::create_temp_dir().await?;
1091 tokio::fs::write(root.join("leaf"), b"x").await?;
1092 let admission = testutils::AdmissionLimit::new().await;
1093 admission.set_files_in_flight(1);
1094 let parent = Dir::open_parent_dir(&root, congestion::Side::Source)
1095 .await?
1096 .into_tree();
1097 let handle = parent.child(OsStr::new("leaf")).await?;
1098 let raw_fd = handle.as_fd().as_raw_fd();
1099 let probe = match testutils::FdIdentityProbe::capture(raw_fd) {
1100 Ok(probe) => probe,
1101 Err(error) => {
1102 drop(handle);
1103 drop(parent);
1104 drop(admission);
1105 let cleanup_result = tokio::fs::remove_dir_all(root).await;
1106 return match cleanup_result {
1107 Ok(()) => Err(error.into()),
1108 Err(cleanup_error) => Err(anyhow::Error::new(error).context(format!(
1109 "leaf permit fixture did not clean up: {cleanup_error:#}"
1110 ))),
1111 };
1112 }
1113 };
1114 let leaf = AdmittedLeaf::try_new(
1115 handle,
1116 Some(LeafPermit::OpenFile(throttle::open_file_permit().await)),
1117 )
1118 .map_err(|_| anyhow::anyhow!("file classification returned a directory outcome"))?;
1119 assert_eq!(leaf.kind(), EntryKind::File);
1120 assert_eq!(leaf.handle().as_fd().as_raw_fd(), raw_fd);
1121 assert!(leaf.admission().is_some());
1122 let permit = leaf.into_permit();
1123 let fd_was_closed_after_transfer = probe.original_is_closed();
1124 let mut next_permit = Box::pin(throttle::open_file_permit());
1125 assert!(
1126 futures::poll!(next_permit.as_mut()).is_pending(),
1127 "transfer returned admission instead of preserving it"
1128 );
1129 drop(permit);
1130 drop(next_permit.await);
1131 drop(parent);
1132 drop(admission);
1133 let cleanup_result = tokio::fs::remove_dir_all(root).await;
1134 let fd_was_closed_after_transfer = fd_was_closed_after_transfer?;
1135 cleanup_result?;
1136 assert!(
1137 fd_was_closed_after_transfer,
1138 "transfer retained the classification fd"
1139 );
1140 Ok(())
1141 }
1142
1143 // split_root_operand: a normal operand splits via parent()/file_name() (single component ->
1144 // parent "."), a trailing slash is stripped, a trailing `/.` names the directory itself, and —
1145 // the regression fix — a bare `.` or an operand ending in `..` (no file_name()) is canonicalized
1146 // so it still names a directory instead of being rejected. The filesystem root `/` is rejected.
1147 #[tokio::test]
1148 async fn split_root_operand_handles_dot_and_normal_operands() -> anyhow::Result<()> {
1149 use std::ffi::OsStr;
1150 use std::path::Path;
1151 // normal nested operand: split verbatim.
1152 let op = split_root_operand(Path::new("a/b")).await?;
1153 assert_eq!(op.parent, Path::new("a"));
1154 assert_eq!(op.name, OsStr::new("b"));
1155 assert_eq!(op.display, Path::new("a/b"));
1156 // single component: parent defaults to the current directory.
1157 let op = split_root_operand(Path::new("foo")).await?;
1158 assert_eq!(op.parent, Path::new("."));
1159 assert_eq!(op.name, OsStr::new("foo"));
1160 // trailing slash stripped (so a symlink root is classified O_NOFOLLOW, not dereferenced).
1161 let op = split_root_operand(Path::new("foo/")).await?;
1162 assert_eq!(op.name, OsStr::new("foo"));
1163 // trailing `/.` names the directory itself: `file_name()` normalizes the `.` away, so it
1164 // splits verbatim (no canonicalize) — `dir/.` -> parent ".", name "dir"; `a/b/.` -> "a","b".
1165 let op = split_root_operand(Path::new("dir/.")).await?;
1166 assert_eq!(op.parent, Path::new("."));
1167 assert_eq!(op.name, OsStr::new("dir"));
1168 let op = split_root_operand(Path::new("a/b/.")).await?;
1169 assert_eq!(op.parent, Path::new("a"));
1170 assert_eq!(op.name, OsStr::new("b"));
1171 // bare `.` (no file_name): canonicalized to the current directory.
1172 let cwd = tokio::fs::canonicalize(".").await?;
1173 let op = split_root_operand(Path::new(".")).await?;
1174 assert_eq!(op.parent, cwd.parent().unwrap());
1175 assert_eq!(op.name, cwd.file_name().unwrap());
1176 assert_eq!(op.display, cwd);
1177 // operand ending in `..` (no file_name): canonicalized so it still names a directory.
1178 // tmp/sub/.. resolves to tmp — the `rrm .` / `rchm -R … .` regression this fix closes.
1179 let tmp = testutils::create_temp_dir().await?;
1180 let sub = tmp.join("sub");
1181 tokio::fs::create_dir(&sub).await?;
1182 let canonical_tmp = tokio::fs::canonicalize(&tmp).await?;
1183 let op = split_root_operand(&sub.join("..")).await?;
1184 assert_eq!(op.parent, canonical_tmp.parent().unwrap());
1185 assert_eq!(op.name, canonical_tmp.file_name().unwrap());
1186 assert_eq!(op.display, canonical_tmp);
1187 // the filesystem root has no parent and is rejected with a clear error.
1188 assert!(split_root_operand(Path::new("/")).await.is_err());
1189 Ok(())
1190 }
1191
1192 // `root_operand_basename` (the sync CLI helper) must return exactly `split_root_operand`'s
1193 // `name` for every operand shape, so a `dst/<name>` the CLI builds always matches the entry the
1194 // walk creates. This lock-step is what makes the trailing-slash result deterministic.
1195 #[tokio::test]
1196 async fn root_operand_basename_matches_split_root_operand() -> anyhow::Result<()> {
1197 use std::path::Path;
1198 // operands with a real `file_name()` (no canonicalize): both take the lexical basename.
1199 for p in ["a/b", "foo", "foo/", "dir/.", "a/b/."] {
1200 assert_eq!(
1201 root_operand_basename(Path::new(p))?,
1202 split_root_operand(Path::new(p)).await?.name,
1203 "operand {p:?}"
1204 );
1205 }
1206 // `.`/`..`/`dir/..` (no `file_name()`): both canonicalize to a real path first. Use real
1207 // dirs so canonicalize succeeds; assert only that the two helpers agree (the concrete
1208 // basename depends on the cwd / temp path).
1209 let tmp = testutils::create_temp_dir().await?;
1210 let sub = tmp.join("sub");
1211 tokio::fs::create_dir(&sub).await?;
1212 let dot_operands = [
1213 std::path::PathBuf::from("."),
1214 std::path::PathBuf::from(".."),
1215 sub.join(".."),
1216 sub.join("../.."),
1217 ];
1218 for p in &dot_operands {
1219 assert_eq!(
1220 root_operand_basename(p)?,
1221 split_root_operand(p).await?.name,
1222 "operand {p:?}"
1223 );
1224 }
1225 // the filesystem root has no basename: both reject it.
1226 assert!(root_operand_basename(Path::new("/")).is_err());
1227 assert!(split_root_operand(Path::new("/")).await.is_err());
1228 Ok(())
1229 }
1230}