Expand description
Memory-safe Windows path-change watching with full ReadDirectoryChangesW
fidelity and a FindFirstChangeNotification coarse fallback.
This crate is Windows-only: every item is gated behind cfg(windows), so it
resolves to an empty crate on other targets. Platform-independent watching is
meant to be built at a higher layer – this crate is about excellent Windows
behaviour (path-name and notification-limitation fidelity) with memory safety.
§The model
A Monitor owns the watching. It hands out Sessions, each of which
bundles a way to make requests with the destination every subscription made
through it delivers to; Monitor::session returns one together with the
Receiver its notifications arrive on. Session::subscribe registers a
path and returns an affine Watch that cancels when dropped.
use windows_file_watcher::{Monitor, Notification, WatchOptions};
let monitor = Monitor::new()?;
let (session, receiver) = monitor.session();
let watch = session.subscribe(r"C:\some\directory", WatchOptions::new())?;
while let Some(notification) = receiver.recv() {
match notification {
Notification::Batch { changes, .. } => println!("{} change(s)", changes.len()),
Notification::Desync { cause, .. } => println!("re-scan: {cause:?}"),
Notification::Completion { outcome, .. } => println!("request: {outcome:?}"),
// Suspended/Resumed/Established/RetryQuestion are opt-in (D-13/D-27)
// and never arrive unless requested through `WatchOptions`.
_ => {}
}
}§Everything is queued, in both directions
The crate never calls into client code. A request is something the client enqueues (the request queue); a notification is something the crate enqueues and the client collects (the notification queue). So nothing a client does – blocking, panicking, being slow – can stall or unwind the crate’s own cadence, and that holds by construction rather than by asking a callback to behave.
Which thread a client drains the notification queue on is entirely its own
business. A client that does not want to dedicate one to Receiver::recv
can take Receiver::doorbell – a manual-reset event, created lazily – and
wait on it from its own thread pool, including from a ThreadpoolWait
callback of its own: ringing a doorbell is crate-owned queue signaling, not a
callback carrying client data, so this is not an exception to “the crate
never calls into client code” – there is no exception.
§Losses are reported, never silent
ReadDirectoryChangesW can lose changes – its buffer overflows under a burst
– and so can a client that stops draining. Both, and every other hole, are
reported as one cause-tagged Notification::Desync meaning re-scan.
Honest reporting of that limitation is a core requirement of this crate rather
than an afterthought.
§Faults recover on their own, or on your terms
An open failure or a live-watch fault is never terminal (D-14): the monitor
retries indefinitely, and only a target that can genuinely never become
watchable is reported permanently rather than retried forever. Recovery
timing is chosen per subscription, through WatchOptions::retry:
RetryMode::Defaults(the default) retries autonomously at a fixed 500ms delay.RetryMode::Interactiveasks: aNotification::RetryQuestionnames the failing operation, andSession::answersupplies the next delay (clamped to a 50ms floor); an explicitanswer(watch, None)declines, which is what counts at the default – never answering at all leaves the question outstanding indefinitely. Several subscriptions sharing a coalesced directory watcher take the earliest answer.
Opting a subscription into WatchOptions::report_liveness additionally
delivers Suspended/Resumed brackets around an outage and an
Established { mode } report naming which tier – detailed
(ReadDirectoryChangesW) or the coarse FindFirstChangeNotification
fallback for volumes that do not support the detailed API – is actually
watching.
§Testing your consumer code
The code you build on top of this crate reacts to Notifications drained
from a Receiver. You can test that reaction logic with no real filesystem
and no thread pool by constructing a Receiver yourself and feeding it
synthetic notifications, instead of obtaining one from Monitor::session.
This “goes below” the Monitor: you substitute the OS ingest while keeping
the delivery model – Notification, Receiver, queue ordering, the
doorbell – exactly as in production. Because your test decides what arrives
and when, it is deterministic; this crate ships no scheduler for you to steer.
The always-public pieces are the identity minter WatchId::from_raw and
every boundary type. The feedable channel (channel_with_bound, its
Sender, and Sender::send), the builders for the two boundary types a
consumer cannot otherwise construct (RelativeName::for_test and
VolumeIdentity::for_test, for a Change and a
Notification::VolumeChanged respectively), and
ContractChecker all live behind the
off-by-default test-util feature, so none of the injection surface
reaches a production build. Three ordinary predicates are unconditional,
because they answer questions a production handler asks:
Receiver::has_pending, DesyncCause::is_terminal and
DesyncCause::is_reachable_in.
#[cfg(all(windows, feature = "test-util"))]
{
use windows_file_watcher::{
channel_with_bound, DesyncCause, Notification, Outcome, WatchId, DEFAULT_BOUND,
};
// The consumer reaction logic under test, in isolation.
fn handle(notification: &Notification, rescans: &mut u32, ended: &mut bool) {
if let Notification::Desync { cause, .. } = notification {
// Ask the cause, rather than naming the terminal one: a re-scan
// cannot resynchronize a stopped watch.
if cause.is_terminal() {
*ended = true;
} else {
*rescans += 1;
}
}
}
let (sender, receiver) = channel_with_bound(DEFAULT_BOUND);
let watch = WatchId::from_raw(1);
// A scripted, deterministic sequence -- no OS involved.
let _ = sender.send(Notification::Completion { watch, outcome: Outcome::Subscribed });
let _ = sender.send(Notification::Desync { watch, cause: DesyncCause::Overflow });
let _ = sender.send(Notification::Desync { watch, cause: DesyncCause::Stopped });
let mut rescans = 0;
let mut ended = false;
while let Some(notification) = receiver.try_recv() {
handle(¬ification, &mut rescans, &mut ended);
}
assert_eq!(rescans, 1);
assert!(ended);
}The surface tests your reactions, not whether this crate would ever emit a
given sequence: the builders are valid-by-construction only in the
type-safety sense (memory-safe, lossless) – RelativeName::for_test_units
still accepts a unit sequence the kernel never reports, an interior NUL
included. An impossible ordering, or an impossible relationship between two
otherwise valid values (a VolumeChanged with equal previous/current
serials, say), is likewise yours to avoid.
Re-exports§
pub use contract::ContractChecker;pub use contract::ContractViolation;pub use contract::Terminator;
Modules§
- contract
- Validating a notification stream against the delivery contract. Validating a notification stream against this crate’s delivery contract.
Structs§
- Change
- One decoded change: its
ChangeKindand theRelativeNameit applies to. - Fault
Detail OpenFailure’s classification plus the raw code behind it (D-79), carried by every fault report and permanent failure so a client can act on more than which kind of thing failed.- Monitor
- Owns the servicing path and every watcher created through it.
- Receiver
- The client-side half: the only way to observe notifications.
- Relative
Name - A file name reported by
ReadDirectoryChangesW, relative to the watched directory, preserved as raw UTF-16 so no information is lost. - Reservation
- A claimed slot in the notification queue.
- Sender
- The crate-side half: enqueues, never blocks.
- Session
- A client’s connection to a monitor.
- Volume
Identity - A directory’s volume-level identity (D-78): the volume serial number,
plus the filesystem name and volume label kept only as descriptive data
for
crate::Notification::VolumeChanged. Compared only when a path-based reopen fallback succeeds (M11.3) – aReOpenFilesuccess is structurally guaranteed to still be on the same volume – to notice removable media swapped for different media mounted at the same path. - Watch
- An owned subscription.
- WatchId
- Identifies the subscription a notification belongs to.
- Watch
Options - What a client states when it registers a subscription.
Enums§
- Change
Kind - The kind of change a
FILE_ACTION_*code names. - Decoded
Batch - The result of decoding one
ReadDirectoryChangesWcompletion. - Delivery
- What became of a best-effort notification.
- Desync
Cause - Why a
DecodedBatch::Desync– a “you may have missed changes, re-scan” signal – was raised. - Failure
Code - A Win32 error code or an HRESULT, kept in the currency it actually arrived in (D-79).
- Fault
Operation - Which failing operation a fault arose from, matching D-15’s reopen-retry / rearm-retry split. Each has its own default delay.
- Notification
- One item a client receives, always tagged with the subscription it belongs to.
- Open
Failure - What a failed open means for the retry policy.
- Outcome
- How a request turned out.
- Retry
Mode - How the monitor should recover a subscription from a fault (D-27).
- Volume
Change Decision - A subscription’s answer to a
crate::Notification::VolumeChangedquestion (D-78/M12). - Volume
Change Policy - Whether a subscription wants to be told, and asked to decide, when a reopen lands on a different volume than the one it started on (D-78).
- Watch
Mode - The mode a watch is established in (D-13/D-17).
Constants§
- DEFAULT_
BOUND - The bound used when a caller does not choose one.
Functions§
- channel_
with_ bound - Create a connected sender/receiver pair holding at most
boundnotifications. - decode_
batch - Decode one
ReadDirectoryChangesWcompletion buffer into a batch.