Skip to main content

windows_file_watcher/
lib.rs

1// Copyright (c) 2026 Mike Grier
2//! Memory-safe Windows path-change watching with full `ReadDirectoryChangesW`
3//! fidelity and a `FindFirstChangeNotification` coarse fallback.
4//!
5//! This crate is Windows-only: every item is gated behind `cfg(windows)`, so it
6//! resolves to an empty crate on other targets. Platform-independent watching is
7//! meant to be built at a higher layer -- this crate is about excellent Windows
8//! behaviour (path-name and notification-limitation fidelity) with memory safety.
9//!
10//! # The model
11//!
12//! A [`Monitor`] owns the watching. It hands out [`Session`]s, each of which
13//! bundles a way to make requests with the destination every subscription made
14//! through it delivers to; [`Monitor::session`] returns one together with the
15//! [`Receiver`] its notifications arrive on. [`Session::subscribe`] registers a
16//! path and returns an affine [`Watch`] that cancels when dropped.
17//!
18//! ```no_run
19//! use windows_file_watcher::{Monitor, Notification, WatchOptions};
20//!
21//! let monitor = Monitor::new()?;
22//! let (session, receiver) = monitor.session();
23//! let watch = session.subscribe(r"C:\some\directory", WatchOptions::new())?;
24//!
25//! while let Some(notification) = receiver.recv() {
26//!     match notification {
27//!         Notification::Batch { changes, .. } => println!("{} change(s)", changes.len()),
28//!         Notification::Desync { cause, .. } => println!("re-scan: {cause:?}"),
29//!         Notification::Completion { outcome, .. } => println!("request: {outcome:?}"),
30//!         // Suspended/Resumed/Established/RetryQuestion are opt-in (D-13/D-27)
31//!         // and never arrive unless requested through `WatchOptions`.
32//!         _ => {}
33//!     }
34//! }
35//! # drop(watch);
36//! # Ok::<(), std::io::Error>(())
37//! ```
38//!
39//! # Everything is queued, in both directions
40//!
41//! The crate never calls into client code. A request is something the client
42//! enqueues (the request queue); a notification is something the crate enqueues
43//! and the client collects (the notification queue). So nothing a client does --
44//! blocking, panicking, being slow -- can stall or unwind the crate's own
45//! cadence, and that holds by construction rather than by asking a callback to
46//! behave.
47//!
48//! Which thread a client drains the notification queue on is entirely its own
49//! business. A client that does not want to dedicate one to [`Receiver::recv`]
50//! can take [`Receiver::doorbell`] -- a manual-reset event, created lazily -- and
51//! wait on it from its own thread pool, including from a `ThreadpoolWait`
52//! callback of its own: ringing a doorbell is crate-owned queue signaling, not a
53//! callback carrying client data, so this is not an exception to "the crate
54//! never calls into client code" -- there is no exception.
55//!
56//! # Losses are reported, never silent
57//!
58//! `ReadDirectoryChangesW` can lose changes -- its buffer overflows under a burst
59//! -- and so can a client that stops draining. Both, and every other hole, are
60//! reported as one cause-tagged [`Notification::Desync`] meaning *re-scan*.
61//! Honest reporting of that limitation is a core requirement of this crate rather
62//! than an afterthought.
63//!
64//! # Faults recover on their own, or on your terms
65//!
66//! An open failure or a live-watch fault is never terminal (D-14): the monitor
67//! retries indefinitely, and only a target that can genuinely never become
68//! watchable is reported permanently rather than retried forever. Recovery
69//! timing is chosen per subscription, through [`WatchOptions::retry`]:
70//!
71//! - [`RetryMode::Defaults`] (the default) retries autonomously at a fixed
72//!   500ms delay.
73//! - [`RetryMode::Interactive`] asks: a [`Notification::RetryQuestion`] names
74//!   the failing operation, and [`Session::answer`] supplies the next delay
75//!   (clamped to a 50ms floor); an explicit `answer(watch, None)` declines,
76//!   which is what counts at the default -- never answering at all leaves the
77//!   question outstanding indefinitely. Several subscriptions sharing a
78//!   coalesced directory watcher take the earliest answer.
79//!
80//! Opting a subscription into [`WatchOptions::report_liveness`] additionally
81//! delivers `Suspended`/`Resumed` brackets around an outage and an
82//! `Established { mode }` report naming which tier -- detailed
83//! (`ReadDirectoryChangesW`) or the coarse `FindFirstChangeNotification`
84//! fallback for volumes that do not support the detailed API -- is actually
85//! watching.
86//!
87//! # Testing your consumer code
88//!
89//! The code you build on top of this crate reacts to [`Notification`]s drained
90//! from a [`Receiver`]. You can test that reaction logic with no real filesystem
91//! and no thread pool by constructing a `Receiver` yourself and feeding it
92//! synthetic notifications, instead of obtaining one from [`Monitor::session`].
93//! This "goes below" the [`Monitor`]: you substitute the OS ingest while keeping
94//! the delivery model -- `Notification`, `Receiver`, queue ordering, the
95//! doorbell -- exactly as in production. Because your test decides what arrives
96//! and when, it is deterministic; this crate ships no scheduler for you to steer.
97//!
98//! The always-public pieces are the identity minter [`WatchId::from_raw`] and
99//! every boundary type. The feedable channel (`channel_with_bound`, its
100//! `Sender`, and `Sender::send`), the builders for the two boundary types a
101//! consumer cannot otherwise construct (`RelativeName::for_test` and
102//! `VolumeIdentity::for_test`, for a [`Change`] and a
103//! [`Notification::VolumeChanged`] respectively), and
104//! [`ContractChecker`] all live behind the
105//! off-by-default `test-util` feature, so none of the *injection* surface
106//! reaches a production build. Three ordinary predicates are unconditional,
107//! because they answer questions a production handler asks:
108//! [`Receiver::has_pending`], [`DesyncCause::is_terminal`] and
109//! [`DesyncCause::is_reachable_in`].
110//!
111//! ```
112//! # fn main() {
113//! #[cfg(all(windows, feature = "test-util"))]
114//! {
115//!     use windows_file_watcher::{
116//!         channel_with_bound, DesyncCause, Notification, Outcome, WatchId, DEFAULT_BOUND,
117//!     };
118//!
119//!     // The consumer reaction logic under test, in isolation.
120//!     fn handle(notification: &Notification, rescans: &mut u32, ended: &mut bool) {
121//!         if let Notification::Desync { cause, .. } = notification {
122//!             // Ask the cause, rather than naming the terminal one: a re-scan
123//!             // cannot resynchronize a stopped watch.
124//!             if cause.is_terminal() {
125//!                 *ended = true;
126//!             } else {
127//!                 *rescans += 1;
128//!             }
129//!         }
130//!     }
131//!
132//!     let (sender, receiver) = channel_with_bound(DEFAULT_BOUND);
133//!     let watch = WatchId::from_raw(1);
134//!
135//!     // A scripted, deterministic sequence -- no OS involved.
136//!     let _ = sender.send(Notification::Completion { watch, outcome: Outcome::Subscribed });
137//!     let _ = sender.send(Notification::Desync { watch, cause: DesyncCause::Overflow });
138//!     let _ = sender.send(Notification::Desync { watch, cause: DesyncCause::Stopped });
139//!
140//!     let mut rescans = 0;
141//!     let mut ended = false;
142//!     while let Some(notification) = receiver.try_recv() {
143//!         handle(&notification, &mut rescans, &mut ended);
144//!     }
145//!     assert_eq!(rescans, 1);
146//!     assert!(ended);
147//! }
148//! # }
149//! ```
150//!
151//! The surface tests your *reactions*, not whether this crate would ever emit a
152//! given sequence: the builders are valid-by-construction only in the
153//! type-safety sense (memory-safe, lossless) -- `RelativeName::for_test_units`
154//! still accepts a unit sequence the kernel never reports, an interior NUL
155//! included. An impossible ordering, or an impossible relationship between two
156//! otherwise valid values (a `VolumeChanged` with equal `previous`/`current`
157//! serials, say), is likewise yours to avoid.
158
159#![warn(missing_docs)]
160
161// The crate's markdown documentation is compiled as doctests, so an example that
162// a contract change invalidates breaks the build instead of quietly teaching the
163// old answer. `cfg(doctest)` means these items exist only while rustdoc collects
164// tests, so they cost an ordinary build nothing.
165#[cfg(all(doctest, windows))]
166#[doc = include_str!("../README.md")]
167struct ReadmeDoctests;
168
169#[cfg(all(doctest, windows, feature = "test-util"))]
170#[doc = include_str!("../TESTING.md")]
171struct TestingDoctests;
172
173#[cfg(windows)]
174mod directory;
175
176#[cfg(windows)]
177mod coarse;
178
179/// Validating a notification stream against the delivery contract.
180#[cfg(all(windows, feature = "test-util"))]
181pub mod contract;
182
183#[cfg(windows)]
184mod monitor;
185
186#[cfg(windows)]
187mod notify;
188
189#[cfg(windows)]
190mod queue;
191
192#[cfg(windows)]
193mod route;
194
195#[cfg(windows)]
196mod retry;
197
198#[cfg(windows)]
199mod servicing;
200
201#[cfg(windows)]
202mod session;
203
204// M9.5: the data-driven scenario stress model/harness, shared by the
205// `run-scenario` binary and the `scenario_stress` integration test. `pub`
206// because a `[[bin]]` target can only reach it through the library's public
207// surface (D-72) -- see the module's own docs for why its JSON schema is
208// nonetheless not part of this crate's semver contract.
209#[cfg(all(windows, feature = "scenario-tool"))]
210pub mod scenario;
211
212#[cfg(all(windows, test))]
213mod testing;
214
215#[cfg(windows)]
216mod watch;
217
218#[cfg(windows)]
219mod watcher;
220
221#[cfg(windows)]
222pub use directory::{FailureCode, FaultDetail, OpenFailure, VolumeIdentity};
223#[cfg(windows)]
224pub use monitor::Monitor;
225#[cfg(windows)]
226pub use notify::{Change, ChangeKind, DecodedBatch, DesyncCause, RelativeName, decode_batch};
227#[cfg(windows)]
228pub use queue::{DEFAULT_BOUND, Notification, Outcome, Receiver, WatchId};
229// The feedable channel is the consumer test seam (D-81/D-82): `channel_with_bound`
230// and its `Sender`/`Delivery`/`Reservation` are `pub` inside the private `queue`
231// module, so a downstream consumer can reach them only through this re-export,
232// gated on the off-by-default `test-util` feature so the production public surface
233// is unchanged.
234#[cfg(all(windows, feature = "test-util"))]
235pub use contract::{ContractChecker, ContractViolation, Terminator};
236
237#[cfg(all(windows, feature = "test-util"))]
238pub use queue::{Delivery, Reservation, Sender, channel_with_bound};
239#[cfg(windows)]
240pub use retry::{FaultOperation, WatchMode};
241#[cfg(windows)]
242pub use session::Session;
243#[cfg(windows)]
244pub use watch::{RetryMode, VolumeChangeDecision, VolumeChangePolicy, Watch, WatchOptions};