tributary_fs/os/mod.rs
1//! The platform seam between the async driver and the OS watch primitive.
2//!
3//! Every platform module exposes the same surface: [`Source::spawn`] starts the
4//! native watch and hands back a [`SourceHandle`] plus the ONE ordered queue
5//! it reports on. `Batch`, `Overflow`, and `Fatal` all ride that single
6//! unbounded FIFO, so per-source ordering between data and the loss/death
7//! signals covering it holds by construction, and a signal send can never
8//! fail for capacity — a loss can never be recorded without a message left to
9//! observe it, and no signal can overtake the batches it postdates. Memory is
10//! bounded not by the queue but by the batch budget
11//! (`transport::TransportState`, compiled only where a backend drives it): an
12//! over-budget batch is dropped at the callback and degrades to the same
13//! in-order `Overflow`.
14//!
15//! Of the queue the seam assumes exactly three properties — FIFO delivery,
16//! unbounded capacity, and a `Closed` signal once the receiver is gone — all
17//! of which `async_channel::unbounded` provides.
18
19use std::{io, num::NonZeroUsize, path::PathBuf, time::Duration};
20
21pub(crate) mod fsevent;
22pub(crate) mod linux;
23pub(crate) mod transport;
24pub(crate) mod windows;
25
26#[cfg(all(target_os = "macos", not(miri)))]
27mod macos;
28#[cfg(all(target_os = "macos", not(miri)))]
29pub(crate) use macos::{Source, SourceHandle, mounts_under};
30
31#[cfg(all(target_os = "linux", not(miri)))]
32pub(crate) use linux::{Source, SourceHandle, mounts_under};
33
34#[cfg(all(target_os = "windows", not(miri)))]
35pub(crate) use windows::{Source, SourceHandle, mounts_under};
36
37#[cfg(any(
38 not(any(target_os = "macos", target_os = "linux", target_os = "windows")),
39 miri
40))]
41mod unsupported;
42#[cfg(any(
43 not(any(target_os = "macos", target_os = "linux", target_os = "windows")),
44 miri
45))]
46pub(crate) use unsupported::{Source, SourceHandle, mounts_under};
47
48pub(crate) use fsevent::{FsEventFlags, RawOsEvent};
49
50/// Which watch primitive a spawned source is backed by — the capability
51/// report [`Watcher::backend_of`](crate::Watcher::backend_of) surfaces for a
52/// live root. The core confirms the per-scope lowering profile the
53/// registration intended against it, and the `Backend::Auto` probe records the
54/// selection it settled on here.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56#[non_exhaustive]
57pub enum BackendKind {
58 /// macOS FSEvents — kernel-recursive; flag words are hints.
59 FsEvents,
60 /// Linux inotify — per-directory (descending); precise verbs, unprivileged.
61 Inotify,
62 /// Linux fanotify-FILESYSTEM — kernel-recursive; precise verbs, membership-only
63 /// admission (no node identity — design §4.9). Privileged (`CAP_SYS_ADMIN`);
64 /// selected by `Backend::Auto` when its preconditions hold, or forced by
65 /// [`Backend::Fanotify`].
66 Fanotify,
67 /// Windows `ReadDirectoryChangesW` — kernel-recursive, unprivileged; the
68 /// per-volume fallback when the USN journal is unusable, or forced by
69 /// [`Backend::Rdcw`].
70 Rdcw,
71 /// Windows USN change journal — kernel-recursive, journal-cursor sourced;
72 /// volume-handle access effectively requires elevation. Selected by
73 /// `Backend::Auto` when its per-volume preconditions hold, or forced by
74 /// [`Backend::UsnJournal`].
75 UsnJournal,
76}
77
78impl BackendKind {
79 /// The stable lowercase tag of this backend, for logs and diagnostics.
80 #[must_use]
81 pub const fn as_str(&self) -> &'static str {
82 match self {
83 Self::FsEvents => "fsevents",
84 Self::Inotify => "inotify",
85 Self::Fanotify => "fanotify",
86 Self::Rdcw => "rdcw",
87 Self::UsnJournal => "usn-journal",
88 }
89 }
90
91 /// Whether this backend is kernel-recursive (one mark covers the whole root),
92 /// as opposed to the descending, per-directory inotify profile.
93 #[must_use]
94 pub const fn is_kernel_recursive(&self) -> bool {
95 matches!(
96 self,
97 Self::FsEvents | Self::Fanotify | Self::Rdcw | Self::UsnJournal
98 )
99 }
100}
101
102impl core::fmt::Display for BackendKind {
103 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
104 f.write_str(self.as_str())
105 }
106}
107
108/// A lightweight, pollable snapshot of one backend's live internals — the
109/// observability the operator owes a tripwire on (design §4.9). Surfaced per
110/// watched root by
111/// [`Watcher::backend_stats`](crate::Watcher::backend_stats); only the fanotify
112/// backend populates it (every other backend has no equivalent state), so a
113/// non-fanotify root reports `None` rather than a zeroed struct.
114///
115/// A snapshot, not a live handle: each accessor returns the value at the moment
116/// the query read the backend's counters. `#[non_exhaustive]` so more counters
117/// can land without a breaking change.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119#[non_exhaustive]
120pub struct BackendStats {
121 directories: usize,
122 memo_generation: u64,
123 seed_walk_last_micros: u64,
124 seed_walk_count: u64,
125 reseeds: u64,
126 memo_hits: u64,
127 memo_misses: u64,
128}
129
130impl BackendStats {
131 /// The number of directories currently in the fanotify admission map — its
132 /// live O(directories) footprint (design §4.9: ~250 B/dir, so ~2.5–4 GB at
133 /// 10 M directories).
134 #[must_use]
135 pub const fn directories(&self) -> usize {
136 self.directories
137 }
138
139 /// The admission map's mutation generation — the batch memo's invalidation
140 /// token, monotone across the map's lifetime (a coarse mutation counter).
141 #[must_use]
142 pub const fn memo_generation(&self) -> u64 {
143 self.memo_generation
144 }
145
146 /// Microseconds the LAST seed or reseed walk took (0 before the first walk) —
147 /// the map-rebuild cost the operator sizes the directory cap against.
148 #[must_use]
149 pub const fn seed_walk_last_micros(&self) -> u64 {
150 self.seed_walk_last_micros
151 }
152
153 /// How many seed/reseed walks have completed (the spawn seed plus every
154 /// loss-triggered reseed and moved-in subtree walk).
155 #[must_use]
156 pub const fn seed_walk_count(&self) -> u64 {
157 self.seed_walk_count
158 }
159
160 /// How many loss-triggered map reseeds have run — a rescan-pressure signal.
161 #[must_use]
162 pub const fn reseeds(&self) -> u64 {
163 self.reseeds
164 }
165
166 /// Cumulative batch-memo hits: admitted directory resolutions served from the
167 /// per-batch cache rather than a fresh map walk.
168 #[must_use]
169 pub const fn memo_hits(&self) -> u64 {
170 self.memo_hits
171 }
172
173 /// Cumulative batch-memo misses: resolutions that fell through to the map
174 /// (a cold directory, or a stale entry after a same-batch mutation).
175 #[must_use]
176 pub const fn memo_misses(&self) -> u64 {
177 self.memo_misses
178 }
179}
180
181/// The shared, atomic backing store the fanotify reader writes and the watcher
182/// snapshots — the live counters behind [`BackendStats`]. Kept OS-agnostic
183/// (pure atomics, no FFI) so the cross-platform watcher can read it, and behind
184/// an `Arc` so the reader thread and the registry entry share one instance. A
185/// non-fanotify backend never mints one, so its [`backend_stats`] is `None`.
186///
187/// [`backend_stats`]: crate::driver::SourceControl::backend_stats
188#[derive(Debug, Default)]
189pub(crate) struct BackendStatsShared {
190 directories: core::sync::atomic::AtomicUsize,
191 memo_generation: core::sync::atomic::AtomicU64,
192 seed_walk_last_micros: core::sync::atomic::AtomicU64,
193 seed_walk_count: core::sync::atomic::AtomicU64,
194 reseeds: core::sync::atomic::AtomicU64,
195 memo_hits: core::sync::atomic::AtomicU64,
196 memo_misses: core::sync::atomic::AtomicU64,
197}
198
199// Only the fanotify reader (cfg linux, not miri) writes these; the setters are
200// dead on every other build, but gating them would fracture the shared type.
201#[cfg_attr(not(all(target_os = "linux", not(miri))), allow(dead_code))]
202impl BackendStatsShared {
203 /// A consistent-enough snapshot for an operator poll. The counters are read
204 /// `Relaxed` and independently, so a snapshot may straddle a reader update
205 /// (e.g. `memo_hits` newer than `directories`); for tripwire observability
206 /// that skew is immaterial, and no store here gates a correctness decision.
207 pub(crate) fn snapshot(&self) -> BackendStats {
208 use core::sync::atomic::Ordering::Relaxed;
209 BackendStats {
210 directories: self.directories.load(Relaxed),
211 memo_generation: self.memo_generation.load(Relaxed),
212 seed_walk_last_micros: self.seed_walk_last_micros.load(Relaxed),
213 seed_walk_count: self.seed_walk_count.load(Relaxed),
214 reseeds: self.reseeds.load(Relaxed),
215 memo_hits: self.memo_hits.load(Relaxed),
216 memo_misses: self.memo_misses.load(Relaxed),
217 }
218 }
219
220 /// Publishes the map's live footprint (its directory count and generation)
221 /// after a batch or a walk.
222 pub(crate) fn set_map(&self, directories: usize, memo_generation: u64) {
223 use core::sync::atomic::Ordering::Relaxed;
224 self.directories.store(directories, Relaxed);
225 self.memo_generation.store(memo_generation, Relaxed);
226 }
227
228 /// Records one completed seed/reseed walk's duration and bumps the walk count.
229 pub(crate) fn record_walk(&self, micros: u64) {
230 use core::sync::atomic::Ordering::Relaxed;
231 self.seed_walk_last_micros.store(micros, Relaxed);
232 self.seed_walk_count.fetch_add(1, Relaxed);
233 }
234
235 /// Bumps the loss-triggered reseed counter.
236 pub(crate) fn record_reseed(&self) {
237 self
238 .reseeds
239 .fetch_add(1, core::sync::atomic::Ordering::Relaxed);
240 }
241
242 /// Adds one batch's memo hit/miss tallies to the cumulative counters.
243 pub(crate) fn add_memo(&self, hits: u64, misses: u64) {
244 use core::sync::atomic::Ordering::Relaxed;
245 self.memo_hits.fetch_add(hits, Relaxed);
246 self.memo_misses.fetch_add(misses, Relaxed);
247 }
248}
249
250/// The clonable handle the driver threads from a live source into the registry
251/// so [`Watcher::backend_stats`](crate::Watcher::backend_stats) can snapshot it.
252/// `Some` only for a fanotify source.
253pub(crate) type BackendStatsHandle = std::sync::Arc<BackendStatsShared>;
254
255/// The watch primitive a [`Watcher`](crate::Watcher) should use for each
256/// root, chosen through [`WatcherOptions::backend`](crate::WatcherOptions::backend).
257///
258/// [`Auto`](Self::Auto) is the default and is native on every platform: the
259/// spawn barrier resolves it to the host's primitive — Linux probes for
260/// fanotify-FILESYSTEM (privileged, kernel-recursive) and falls back to inotify
261/// (unprivileged, the Linux 4.11 baseline) at the first failing probe; macOS
262/// resolves to FSEvents; Windows prefers the USN journal per volume and falls
263/// back to `ReadDirectoryChangesW` — a per-root decision made once, before the
264/// stream goes live, never retried.
265///
266/// An explicit variant pins one platform's primitive. On the platform that owns
267/// it, forcing either skips the probe (inotify, RDCW) or hardens it (fanotify,
268/// USN journal — the first failing precondition is a typed spawn error, never a
269/// fallback). On any other platform a forced variant fails the spawn with
270/// [`ForeignBackend`](SourceError::ForeignBackend) — never a silent ignore.
271#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
272#[non_exhaustive]
273pub enum Backend {
274 /// Resolve the host's primitive at the spawn barrier — the per-root default.
275 #[default]
276 Auto,
277 /// Linux inotify — per-directory, unprivileged; the probe is skipped.
278 Inotify,
279 /// Linux fanotify-FILESYSTEM — kernel-recursive, privileged; a failing
280 /// precondition is a typed spawn error, not a fallback.
281 Fanotify,
282 /// Windows `ReadDirectoryChangesW` — kernel-recursive, unprivileged.
283 Rdcw,
284 /// Windows USN change journal — kernel-recursive; volume-handle access
285 /// effectively requires elevation, and a failing precondition is a typed
286 /// spawn error, not a fallback.
287 UsnJournal,
288}
289
290impl Backend {
291 /// The stable lowercase tag of this backend selection.
292 #[must_use]
293 pub const fn as_str(&self) -> &'static str {
294 match self {
295 Self::Auto => "auto",
296 Self::Inotify => "inotify",
297 Self::Fanotify => "fanotify",
298 Self::Rdcw => "rdcw",
299 Self::UsnJournal => "usn-journal",
300 }
301 }
302
303 /// Whether the selection is [`Auto`](Self::Auto) (the barrier decides).
304 #[must_use]
305 pub const fn is_auto(&self) -> bool {
306 matches!(self, Self::Auto)
307 }
308
309 /// Whether the selection forces inotify.
310 #[must_use]
311 pub const fn is_inotify(&self) -> bool {
312 matches!(self, Self::Inotify)
313 }
314
315 /// Whether the selection forces fanotify.
316 #[must_use]
317 pub const fn is_fanotify(&self) -> bool {
318 matches!(self, Self::Fanotify)
319 }
320
321 /// Whether the selection forces `ReadDirectoryChangesW`.
322 #[must_use]
323 pub const fn is_rdcw(&self) -> bool {
324 matches!(self, Self::Rdcw)
325 }
326
327 /// Whether the selection forces the USN change journal.
328 #[must_use]
329 pub const fn is_usn_journal(&self) -> bool {
330 matches!(self, Self::UsnJournal)
331 }
332
333 /// Whether this selection can start on the compiling host platform:
334 /// [`Auto`](Self::Auto) everywhere (the barrier resolves it), an explicit
335 /// variant only on the platform whose primitive it names. The real spawn
336 /// seam rejects a foreign selection with
337 /// [`SourceError::ForeignBackend`] before any platform code reads it.
338 #[must_use]
339 pub const fn native_to_host(&self) -> bool {
340 match self {
341 Self::Auto => true,
342 Self::Inotify | Self::Fanotify => cfg!(target_os = "linux"),
343 Self::Rdcw | Self::UsnJournal => cfg!(target_os = "windows"),
344 }
345 }
346}
347
348impl core::fmt::Display for Backend {
349 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
350 f.write_str(self.as_str())
351 }
352}
353
354/// The clonable arm/disarm port of one scope's live source, extracted at
355/// spawn time so the blocking-pool executors can reach the reader without
356/// holding the (teardown-owning) handle. Kernel-recursive backends have no
357/// arm traffic and report [`Inert`](Self::Inert); a descending executor
358/// meeting `Inert` answers a typed failure — the honest impossible-arm
359/// outcome — never a silent success.
360#[derive(Debug, Clone)]
361pub(crate) enum ScopePort {
362 /// A live inotify reader's control port.
363 #[cfg(all(target_os = "linux", not(miri)))]
364 Inotify(linux::ControlPort),
365 /// No arm traffic is possible (kernel-recursive source, or a fake).
366 Inert,
367}
368
369/// The ONE seam payload every source reports: each backend wraps its own
370/// decode into this at forward time, so the queue, the driver, and the core
371/// name a single event type on every platform — and the hermetic suites can
372/// inject either backend's events on any host.
373#[derive(Debug, Clone, PartialEq, Eq)]
374pub(crate) enum SourceEvent {
375 /// One decoded FSEvents record.
376 FsEvents(RawOsEvent),
377 /// One decoded, anchor-attributed Linux record.
378 Linux(linux::RawLinuxEvent),
379 /// One decoded, pump-paired Windows record.
380 Windows(windows::RawWindowsEvent),
381}
382
383impl From<RawOsEvent> for SourceEvent {
384 fn from(value: RawOsEvent) -> Self {
385 Self::FsEvents(value)
386 }
387}
388
389impl From<linux::RawLinuxEvent> for SourceEvent {
390 fn from(value: linux::RawLinuxEvent) -> Self {
391 Self::Linux(value)
392 }
393}
394
395/// One producer batch of [`SourceEvent`]s plus its budget slot.
396pub(crate) type BatchPayload = transport::BatchPayload<SourceEvent>;
397
398/// One message from the OS producer to the driver task, on the source's
399/// single ordered queue.
400pub(crate) type SourceMessage = transport::SourceMessage<SourceEvent>;
401
402/// The driver's receiving end of a source's messages.
403pub(crate) type EventReceiver = transport::EventReceiver<SourceEvent>;
404
405/// The most exclusion directories one native stream honors
406/// (`FSEventStreamSetExclusionPaths` accepts at most eight).
407pub(crate) const MAX_EXCLUSIONS: usize = 8;
408
409/// A filesystem object's identity: its `(device, inode)` pair.
410///
411/// Two paths name the same object iff their identities are equal — a
412/// comparison no byte form can stand in for on volumes where several
413/// spellings (case aliases, Unicode-normalization aliases) reach one object.
414/// On a case-SENSITIVE volume two spellings are genuinely different objects
415/// with different inodes, so identity comparison is volume-correct by
416/// construction, with no case-fold tables and no volume-capability lookup.
417#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
418pub(crate) struct RootIdentity {
419 dev: u64,
420 ino: u128,
421}
422
423impl RootIdentity {
424 /// Wraps a stat-read `(device, inode)` pair. Identities are read off Unix
425 /// metadata or minted by test harnesses; on a platform with neither the
426 /// wrapped pair is the harmless `(0, 0)` its callers already synthesize
427 /// (`dev_of`/`ino_of`/`identity_of`), and no real stream ever mints one.
428 pub(crate) const fn new(dev: u64, ino: u128) -> Self {
429 Self { dev, ino }
430 }
431
432 /// The device the identified object lives on.
433 pub(crate) const fn dev(&self) -> u64 {
434 self.dev
435 }
436
437 /// The identified object's inode (or 128-bit file id — ReFS ids exceed
438 /// 64 bits, and a folded id would re-open the collision the registry's
439 /// disjointness rests on; Unix inodes zero-extend).
440 pub(crate) const fn ino(&self) -> u128 {
441 self.ino
442 }
443}
444
445/// What a source's spawn learned about its root — finalized strictly BEFORE
446/// the stream can enqueue its first event, so nothing here can postdate a
447/// message the source delivers, and no fallible metadata path exists after
448/// start. Only [`Source::spawn`] mints a `RootMeta`.
449///
450/// The mount seed is deliberately NOT an authority: a mount appearing between
451/// the seed read and stream start lands in neither the seed nor the event
452/// stream, so a pre-start snapshot can never prove a path is root-device. The
453/// seed only ever REDUCES trust (its prefixes are foreign) and steers probes;
454/// authority is installed exclusively by the driver's post-live mount refresh,
455/// whose read the live stream orders against every later mount transition.
456#[derive(Debug, Clone, PartialEq, Eq)]
457pub(crate) struct RootMeta {
458 /// The canonicalized root — the byte-exact prefix event paths arrive under.
459 pub(crate) root: PathBuf,
460 /// The device the root lives on.
461 pub(crate) root_dev: u64,
462 /// The root's MOUNT id (from `statx(STATX_MNT_ID)` on the pinned root), or
463 /// `None` when the source could not read one (below Linux 5.8 where the field
464 /// is absent, or a non-Linux backend — FSEvents has no mount id). The core
465 /// fences descent across a differing mount id: a `mount --bind` of a
466 /// same-device directory shares [`root_dev`](Self::root_dev), so the device
467 /// alone cannot mark it a boundary. `None` degrades to the device check.
468 pub(crate) root_mnt_id: Option<u64>,
469 /// The trust-reducing mount seed: mount points observed strictly under the
470 /// root before the stream started (empty when the table could not be read —
471 /// either way, event-side trust stays closed until the post-live refresh).
472 pub(crate) mounts: Vec<PathBuf>,
473 /// The root object's identity — what root disjointness is decided on
474 /// (spelling-aliased paths share it; distinct objects never do).
475 pub(crate) identity: RootIdentity,
476 /// The identities of every strict ancestor of the canonical root, so
477 /// containment ("is this root inside that one, under ANY spelling") is
478 /// answerable by pure membership tests with no further syscalls.
479 pub(crate) ancestors: Vec<RootIdentity>,
480 /// The primitive backing this source — the core confirms its per-scope
481 /// lowering profile against it.
482 pub(crate) backend: BackendKind,
483}
484
485/// Everything a platform source needs to start watching.
486#[derive(Debug, Clone)]
487pub(crate) struct SourceConfig {
488 /// The watched roots. One stream may carry several, but the driver spawns
489 /// one source per root so root add/remove is a pure spawn/teardown.
490 // Only a real backend's spawn reads the roots and the resume point; the
491 // stub rejects the whole config unread, so backend-less builds see the
492 // fields as dead. Gating them would fracture the seam type.
493 #[cfg_attr(
494 not(all(any(target_os = "macos", target_os = "linux"), not(miri))),
495 allow(dead_code)
496 )]
497 pub(crate) roots: Vec<PathBuf>,
498 /// Load-shedding exclusion directories (at most [`MAX_EXCLUSIONS`]);
499 /// correctness never depends on them.
500 pub(crate) exclusions: Vec<PathBuf>,
501 /// Resume point from a previous stream generation; `None` = live-only.
502 // Only the FSEvents backend consumes resume points today (inotify has no
503 // journal to resume from), so every other build sees the field as dead.
504 #[cfg_attr(not(all(target_os = "macos", not(miri))), allow(dead_code))]
505 pub(crate) since: Option<ResumeToken>,
506 /// The OS event-coalescing latency.
507 pub(crate) latency: Duration,
508 /// Capacity of the callback→driver channel, in callback batches.
509 pub(crate) channel_capacity: NonZeroUsize,
510 /// The per-root backend selection the spawn barrier honors. The real spawn
511 /// seam rejects a selection foreign to the host
512 /// ([`SourceError::ForeignBackend`]) before any platform code reads it; on
513 /// Linux [`Backend::Auto`] probes for fanotify and falls back to inotify,
514 /// while the explicit variants pin the choice.
515 pub(crate) backend: Backend,
516 /// The fanotify admission-map directory cap (design §4.9); `None` = uncapped.
517 /// A seed/reseed walk that would exceed it makes fanotify unviable (fall back
518 /// under `Backend::Auto`, typed error when forced); a live create/move-in
519 /// growing the map past it kills the scope (never OOM). Only the fanotify
520 /// backend reads it.
521 #[cfg_attr(not(all(target_os = "linux", not(miri))), allow(dead_code))]
522 pub(crate) max_map_directories: Option<usize>,
523}
524
525impl SourceConfig {
526 /// A live-only configuration watching `roots` with the crate defaults
527 /// ([`Backend::Auto`] on Linux — probe for fanotify, fall back to inotify).
528 pub(crate) fn new(roots: Vec<PathBuf>) -> Self {
529 Self {
530 roots,
531 exclusions: Vec::new(),
532 since: None,
533 latency: Duration::from_millis(10),
534 channel_capacity: NonZeroUsize::new(64).expect("64 is nonzero"),
535 backend: Backend::Auto,
536 max_map_directories: None,
537 }
538 }
539}
540
541/// Which `Backend::Auto` probe stage decided the selection (design §5, rows
542/// 2–5). Carried by [`SourceError::BackendProbeFailed`] on a forced
543/// [`Backend::Fanotify`] whose preconditions did not hold, so the caller learns
544/// exactly which one failed. A pure enum (no FFI), so it is available on every
545/// platform the error type is.
546#[derive(Debug, Clone, Copy, PartialEq, Eq)]
547#[non_exhaustive]
548pub enum ProbeStage {
549 /// `fanotify_init` with the full 5.17 composite flag set was refused — the
550 /// kernel/filesystem is too old for the composite, or the process lacks the
551 /// notification class (`EINVAL`/`EPERM`).
552 Init,
553 /// The `FAN_MARK_ADD | FAN_MARK_FILESYSTEM` mark was refused — the real
554 /// privilege discriminator (`EPERM` = no `CAP_SYS_ADMIN`), or the filesystem
555 /// does not support the superblock mark (`EINVAL`/`EOPNOTSUPP`/`ENODEV`/
556 /// `EXDEV`).
557 Mark,
558 /// `name_to_handle_at` on the root was refused — the filesystem cannot export
559 /// file handles, so FID identity is impossible (`EOPNOTSUPP`).
560 Handle,
561 /// The volume device hosting the root could not be opened (the USN arm's
562 /// privilege discriminator — `\\.\X:` effectively requires elevation), or
563 /// the root has no drive letter to name one.
564 VolumeAccess,
565 /// The volume's change journal is absent, deleted, or speaks no record
566 /// version this backend reads (2..=3).
567 JournalActive,
568 /// The seed walk could not fully enumerate the tree under the root: an
569 /// EXISTING in-root directory could not be read or handle-encoded (`EACCES`
570 /// and friends), so the FID map would be born blind to that subtree and later
571 /// events under it would drop as outside-root with no loss signal. fanotify's
572 /// admission model requires a COMPLETE directory map, so an unwalkable tree is
573 /// a viability failure — `Backend::Auto` falls back to inotify (which surfaces
574 /// an unreadable directory natively through its per-directory arms), while a
575 /// forced [`Backend::Fanotify`] surfaces this. A directory that merely VANISHED
576 /// mid-walk (a benign race) never lands here — the walk skips it and proceeds.
577 Walk,
578}
579
580impl ProbeStage {
581 /// A stable tag naming the failed syscall stage.
582 #[must_use]
583 pub const fn as_str(&self) -> &'static str {
584 match self {
585 Self::Init => "fanotify_init",
586 Self::Mark => "fanotify_mark(FAN_MARK_FILESYSTEM)",
587 Self::Handle => "name_to_handle_at",
588 Self::VolumeAccess => "volume open",
589 Self::JournalActive => "FSCTL_QUERY_USN_JOURNAL",
590 Self::Walk => "seed-walk completeness",
591 }
592 }
593}
594
595impl core::fmt::Display for ProbeStage {
596 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
597 f.write_str(self.as_str())
598 }
599}
600
601/// Why a platform source could not start, or died.
602///
603/// Surfaced publicly through
604/// [`WatchRootError::Source`](crate::WatchRootError::Source): everything after
605/// a root is live arrives as in-band events, so this is the only backend error
606/// shape a consumer ever sees.
607#[derive(Debug, thiserror::Error)]
608#[non_exhaustive]
609pub enum SourceError {
610 /// This platform has no watch backend (or the build cannot run FFI).
611 #[error("filesystem watching is not supported on this platform")]
612 Unsupported,
613 /// No watch root was supplied.
614 #[error("a source needs at least one watch root")]
615 NoRoots,
616 /// A watch root does not exist or could not be resolved.
617 #[error("watch root {} is unavailable", root.display())]
618 RootUnavailable {
619 /// The root as the caller supplied it.
620 root: PathBuf,
621 /// The underlying resolution failure.
622 #[source]
623 source: io::Error,
624 },
625 /// The FINAL canonical root is not a directory. The backend re-resolves the
626 /// root at spawn, so a path retargeted to a regular file between the
627 /// watcher's own check and the pre-start barrier is caught here — a
628 /// recursive stream must never be committed for a non-directory.
629 #[error("watch root {} is not a directory", root.display())]
630 NotADirectory {
631 /// The final canonical root the spawn resolved.
632 root: PathBuf,
633 },
634 /// The root OBJECT changed between the pre-start metadata capture and the
635 /// stream going live: the path kept its bytes but now names a different
636 /// `(dev, ino)`. The just-started stream was torn down — committing it
637 /// would anchor coverage and registry identity to two different objects.
638 #[error("watch root {} was replaced while the stream was starting", root.display())]
639 RootReplaced {
640 /// The final canonical root whose object changed.
641 root: PathBuf,
642 },
643 /// More exclusion paths than the OS honors were supplied.
644 #[error("{supplied} exclusion paths exceed the OS limit of {MAX_EXCLUSIONS}")]
645 TooManyExclusions {
646 /// How many exclusions the configuration carried.
647 supplied: usize,
648 },
649 /// The OS rejected the exclusion path set.
650 #[error("the OS rejected the exclusion paths")]
651 ExclusionRejected,
652 /// The OS could not create the event stream.
653 #[error("the OS could not create the event stream")]
654 CreateFailed,
655 /// The per-user watch-instance ceiling was hit (`EMFILE`: the process fd
656 /// limit or `fs.inotify.max_user_instances` — one instance per root is the
657 /// overflow-isolation trade).
658 #[error("the per-user watch-instance limit was reached")]
659 InstanceLimit,
660 /// The stream's read loop failed; the stream is dead.
661 #[error("reading the event stream failed")]
662 ReadFailed {
663 /// The underlying read failure.
664 #[source]
665 source: io::Error,
666 },
667 /// The OS could not start the event stream.
668 #[error("the OS could not start the event stream")]
669 StartFailed,
670 /// A forced privileged backend ([`Backend::Fanotify`], [`Backend::UsnJournal`])
671 /// failed a precondition: the named stage was refused, or the seed walk found
672 /// the tree not fully walkable (`Walk` — an existing in-root directory the
673 /// map could not admit), so the backend cannot start. `Backend::Auto` falls
674 /// back to the unprivileged arm instead of surfacing this.
675 #[error("the probed backend is unavailable: {stage} was refused")]
676 BackendProbeFailed {
677 /// The precondition stage that failed.
678 stage: ProbeStage,
679 },
680 /// The forced backend names another platform's primitive, so it can never
681 /// start on this host. [`Backend::Auto`] is never foreign — the spawn
682 /// barrier resolves it to the host's own primitive.
683 #[error("the {} backend does not exist on this platform", requested.as_str())]
684 ForeignBackend {
685 /// The foreign selection.
686 requested: Backend,
687 },
688 /// The decode callback panicked; the stream is poisoned.
689 #[error("the event callback panicked")]
690 CallbackPanic,
691}
692
693/// Where a dead stream's successor can resume from: the last in-sync journal
694/// event id plus the device UUID that scopes its validity.
695///
696/// A root replacement consumes one: the driver takes the retiring stream's
697/// token at command time and hands it to the replacement's spawn, so the
698/// backend replays the swap window from the journal instead of leaving it to
699/// the commit `Rescan` alone. The replay is best-effort by construction — a
700/// wrapped id space mints no token, a purged journal replays nothing, and a
701/// token is only ever honored against its own device — so the `Rescan` still
702/// stands and the consumer contract is unchanged: delivery only gets denser.
703#[derive(Debug, Clone, Copy, PartialEq, Eq)]
704pub(crate) struct ResumeToken {
705 last_good: u64,
706 device_uuid: Option<[u8; 16]>,
707}
708
709// The journal-replay token is consumed by the macOS FSEvents backend (and, for
710// `new`, the cross-platform driver resume tests); on every other target the type
711// is interface scaffolding — `SourceControl::resume_token` returns `Option<Self>`
712// uniformly — so its accessors are legitimately unused there.
713#[cfg_attr(not(all(target_os = "macos", not(miri))), allow(dead_code))]
714impl ResumeToken {
715 /// Builds a token from a last-good event id and its device UUID.
716 pub(crate) const fn new(last_good: u64, device_uuid: Option<[u8; 16]>) -> Self {
717 Self {
718 last_good,
719 device_uuid,
720 }
721 }
722
723 /// The highest journal event id observed while the stream was in sync.
724 pub(crate) const fn last_good(&self) -> u64 {
725 self.last_good
726 }
727
728 /// The UUID of the device the id belongs to, if the OS could supply one.
729 /// A token is only valid for resuming against the identical UUID.
730 pub(crate) const fn device_uuid(&self) -> Option<[u8; 16]> {
731 self.device_uuid
732 }
733}
734
735#[cfg(test)]
736mod tests {
737 use super::{Backend, BackendKind};
738
739 #[test]
740 fn backend_tags_are_stable() {
741 assert_eq!(Backend::Auto.as_str(), "auto");
742 assert_eq!(Backend::Inotify.as_str(), "inotify");
743 assert_eq!(Backend::Fanotify.as_str(), "fanotify");
744 assert_eq!(Backend::Rdcw.as_str(), "rdcw");
745 assert_eq!(Backend::UsnJournal.as_str(), "usn-journal");
746 assert_eq!(BackendKind::FsEvents.as_str(), "fsevents");
747 assert_eq!(BackendKind::Inotify.as_str(), "inotify");
748 assert_eq!(BackendKind::Fanotify.as_str(), "fanotify");
749 assert_eq!(BackendKind::Rdcw.as_str(), "rdcw");
750 assert_eq!(BackendKind::UsnJournal.as_str(), "usn-journal");
751 }
752
753 #[test]
754 fn inotify_is_the_one_descending_profile() {
755 assert!(BackendKind::FsEvents.is_kernel_recursive());
756 assert!(!BackendKind::Inotify.is_kernel_recursive());
757 assert!(BackendKind::Fanotify.is_kernel_recursive());
758 assert!(BackendKind::Rdcw.is_kernel_recursive());
759 assert!(BackendKind::UsnJournal.is_kernel_recursive());
760 }
761
762 #[test]
763 fn auto_is_native_everywhere_and_explicit_variants_are_host_scoped() {
764 assert!(Backend::Auto.native_to_host());
765 let linux = cfg!(target_os = "linux");
766 let windows = cfg!(target_os = "windows");
767 assert_eq!(Backend::Inotify.native_to_host(), linux);
768 assert_eq!(Backend::Fanotify.native_to_host(), linux);
769 assert_eq!(Backend::Rdcw.native_to_host(), windows);
770 assert_eq!(Backend::UsnJournal.native_to_host(), windows);
771 }
772
773 #[test]
774 fn predicates_name_their_variant() {
775 assert!(Backend::Auto.is_auto());
776 assert!(Backend::Inotify.is_inotify());
777 assert!(Backend::Fanotify.is_fanotify());
778 assert!(Backend::Rdcw.is_rdcw());
779 assert!(Backend::UsnJournal.is_usn_journal());
780 assert!(!Backend::Auto.is_rdcw());
781 assert!(!Backend::Rdcw.is_usn_journal());
782 }
783}