Skip to main content

windows_file_watcher/
watch.rs

1// Copyright (c) 2026 Mike Grier
2//! The affine subscription handle, and what a client states when it registers
3//! one.
4//!
5//! # Affine, not linear
6//!
7//! A [`Watch`] owns a subscription's lifetime (D-5). Dropping it cancels;
8//! [`Watch::cancel`] is the same thing said explicitly, for a caller that wants
9//! the cancellation issued at a point it chooses rather than wherever the value
10//! happens to fall out of scope. Rust is affine by nature -- a value can be
11//! dropped without being used -- and true linearity is neither available nor
12//! needed here, because "dropped" has a correct meaning: stop watching.
13//!
14//! It is `#[must_use]` for the case that meaning makes surprising:
15//! `session.subscribe(...)` with the result discarded reads as "start watching"
16//! and does the opposite, since the temporary is dropped at the end of the
17//! statement and cancels immediately.
18//!
19//! Cancellation is *enqueued*, not performed inline: it is a request like any
20//! other, serviced on the monitor's own path (D-2). So `cancel` and `drop` return
21//! before the watch has actually stopped, and a notification already in the queue
22//! still reaches the client. A [`crate::queue::Notification::Completion`] with
23//! [`crate::queue::Outcome::Cancelled`] then tells the client exactly where the
24//! cancellation fell in its stream (D-30).
25//!
26//! # The retry mode is stated at registration
27//!
28//! Recovery behaviour is a property of the *subscription*, not of the monitor
29//! (D-27), and registration is the only place a client can state it -- so
30//! [`WatchOptions`] carries it from the start. The monitor's fault machinery
31//! reads it on every fault (D-27's interactive retry protocol): an
32//! `Interactive` subscription is asked how long to wait before the next
33//! attempt via a [`crate::queue::Notification::RetryQuestion`], while a
34//! `Defaults` one retries autonomously at a fixed delay.
35
36use std::io;
37use std::path::Path;
38
39use crate::monitor::Request;
40use crate::queue::{Reservation, WatchId};
41use crate::session::Session;
42
43/// How the monitor should recover a subscription from a fault (D-27).
44///
45/// The choice is per subscription because a directory's single coalesced watcher
46/// (D-6) may be shared by subscriptions that want different things, and the
47/// monitor reconciles them by taking the earliest answer.
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
49pub enum RetryMode {
50    /// The monitor retries autonomously and indefinitely, asking nothing.
51    ///
52    /// The default, which is what keeps D-14's "no terminal fault state" true for
53    /// a client that says nothing.
54    #[default]
55    Defaults,
56    /// On fault the monitor asks this subscription how long to wait before trying
57    /// again, and waits for the answer before scheduling anything.
58    ///
59    /// The cost is stated plainly: recovery then depends on the client answering.
60    /// That is why it is opt-in rather than the default.
61    Interactive,
62}
63
64/// A subscription's answer to a [`crate::Notification::VolumeChanged`] question
65/// (D-78/M12).
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
67pub enum VolumeChangeDecision {
68    /// Keep this subscription running against the new volume.
69    Continue,
70    /// Remove this subscription.
71    Stop,
72}
73
74/// Whether a subscription wants to be told, and asked to decide, when a reopen
75/// lands on a different volume than the one it started on (D-78).
76///
77/// A reopen is by *path*, and nothing guarantees the path still names the same
78/// volume it did before -- removable media can be ejected and replaced with
79/// different media mounted at the same path. `AutoContinue` (the default)
80/// matches every prior release's behavior for a subscription that does not
81/// ask: the watch keeps running against whatever is at the path now. `Confirm`
82/// is opt-in for a subscription that wants to decide instead.
83#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
84pub enum VolumeChangePolicy {
85    /// Keep going without being asked. The default.
86    #[default]
87    AutoContinue,
88    /// On a volume change, ask via [`crate::Notification::VolumeChanged`] and
89    /// wait for an answer (through
90    /// [`crate::Session::answer_volume_change`]) before arming continues.
91    Confirm,
92}
93
94/// What a client states when it registers a subscription.
95///
96/// Non-exhaustive so that a future additive option is not a breaking change:
97/// build one with [`WatchOptions::new`] and the setters rather than a struct
98/// literal.
99///
100/// There is deliberately **no change-type filter** here, and none is planned.
101/// This crate's contract is completeness: a change notification is positive
102/// evidence that a file was *not* finished, never evidence that it was, so a
103/// client can only decide "is it done yet?" by watching the change traffic go
104/// quiet. A filter would discard exactly that evidence, and under the crate's
105/// per-directory coalescing it could not even be applied faithfully -- the five
106/// content-ish change classes all arrive as one indistinguishable
107/// [`ChangeKind::Modified`](crate::ChangeKind::Modified) action. See D-77 in the
108/// crate's design notes.
109#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
110#[non_exhaustive]
111pub struct WatchOptions {
112    /// Whether changes below the target are reported as well.
113    pub subtree: bool,
114    /// How this subscription should be recovered from faults.
115    pub retry: RetryMode,
116    /// Whether `Suspended`/`Resumed`/`Established` are reported (D-13). Off by
117    /// default: a subscription that only wants change data need not think about
118    /// the fault machine's liveness brackets at all.
119    pub report_liveness: bool,
120    /// Whether to be asked before continuing when a reopen lands on a
121    /// different volume than this subscription started on (D-78).
122    pub on_volume_change: VolumeChangePolicy,
123}
124
125impl WatchOptions {
126    /// A non-recursive watch that the monitor recovers autonomously.
127    #[must_use]
128    pub fn new() -> Self {
129        Self::default()
130    }
131
132    /// Report changes below the target as well.
133    #[must_use]
134    pub fn subtree(mut self, subtree: bool) -> Self {
135        self.subtree = subtree;
136        self
137    }
138
139    /// Choose how faults are recovered from (D-27).
140    #[must_use]
141    pub fn retry(mut self, retry: RetryMode) -> Self {
142        self.retry = retry;
143        self
144    }
145
146    /// Opt in to `Suspended`/`Resumed`/`Established` (D-13).
147    #[must_use]
148    pub fn report_liveness(mut self, report_liveness: bool) -> Self {
149        self.report_liveness = report_liveness;
150        self
151    }
152
153    /// Choose whether a volume change on reopen needs this subscription's
154    /// confirmation (D-78).
155    #[must_use]
156    pub fn on_volume_change(mut self, policy: VolumeChangePolicy) -> Self {
157        self.on_volume_change = policy;
158        self
159    }
160}
161
162/// An owned subscription.
163///
164/// Dropping it cancels; see the module docs for why that makes `#[must_use]`
165/// load-bearing rather than decorative.
166#[must_use = "a Watch cancels its subscription when dropped, so discarding one here stops the watch immediately"]
167#[derive(Debug)]
168pub struct Watch {
169    id: WatchId,
170    session: Session,
171    /// The queue slot the cancellation completion will occupy, reserved at
172    /// registration.
173    ///
174    /// Held for the whole life of the subscription because `Drop` is a
175    /// cancellation path with nowhere to report a refused reservation: taking
176    /// the room up front is what makes "dropping cancels" reliable rather than
177    /// best-effort (D-33). Taken when the cancellation is enqueued, so `None`
178    /// also records that this watch has already been cancelled and `Drop` must
179    /// not enqueue a second one.
180    cancellation: Option<Reservation>,
181}
182
183impl Watch {
184    pub(crate) fn new(id: WatchId, session: Session, cancellation: Reservation) -> Self {
185        Self {
186            id,
187            session,
188            cancellation: Some(cancellation),
189        }
190    }
191
192    /// The correlation token every notification from this subscription carries.
193    ///
194    /// `Copy`, so a client can keep it to route or aggregate without holding the
195    /// subscription's lifetime (D-5).
196    #[must_use]
197    pub fn id(&self) -> WatchId {
198        self.id
199    }
200
201    /// Stop watching.
202    ///
203    /// The same operation `Drop` performs, said explicitly. It returns once the
204    /// cancellation is *enqueued*, not once it has taken effect, so a
205    /// notification already in the client's queue still arrives. The
206    /// `Cancelled` completion marks where the watch actually ended (D-30).
207    pub fn cancel(mut self) {
208        self.enqueue_cancel();
209    }
210
211    /// Enqueue the cancellation exactly once.
212    fn enqueue_cancel(&mut self) {
213        let Some(completion) = self.cancellation.take() else {
214            return;
215        };
216        // A shut-down monitor has already torn every watcher down, so there is
217        // nothing left for this request to do; the rejection is not an error, and
218        // dropping the rejected request releases the reserved slot.
219        let _ = self.session.submit(Request::Cancel {
220            watch: self.id,
221            completion,
222        });
223    }
224}
225
226impl Drop for Watch {
227    fn drop(&mut self) {
228        self.enqueue_cancel();
229    }
230}
231
232/// Register a subscription and hand back its handle.
233///
234/// Crate-internal: the client-facing entry point is
235/// [`Session::subscribe`](crate::session::Session::subscribe), which is where the
236/// session's sink is bound to the subscription.
237pub(crate) fn subscribe(
238    session: &Session,
239    path: &Path,
240    options: WatchOptions,
241) -> io::Result<Watch> {
242    // Both slots are taken before the request is submitted, which is what makes
243    // the two completions undroppable (D-33). Reserving the cancellation slot
244    // here rather than at cancellation time is what lets `Drop` cancel reliably:
245    // it has nowhere to report a refusal.
246    let completion = session.sink().reserve().ok_or_else(saturated)?;
247    let cancellation = session.sink().reserve().ok_or_else(saturated)?;
248
249    // A standing fault-question slot (D-27/D-28), taken once here rather than
250    // per fault, so asking never competes with the queue's best-effort traffic.
251    // Reused for `VolumeChanged` (D-78/M12): the two questions are never
252    // outstanding at once for one subscription (a volume-change question is
253    // only ever raised by a path-based reopen that already succeeded, which
254    // only happens after any current fault question was already answered), so
255    // one standing reservation safely serves both. Only `Interactive` or
256    // `Confirm` needs one at all (D-57): `Suspended`/`Resumed`/`Established`
257    // ride the ordinary best-effort queue like any other observation, so a
258    // `report_liveness`-only subscription with neither reserves nothing extra.
259    let fault_slot = if options.retry == RetryMode::Interactive
260        || options.on_volume_change == VolumeChangePolicy::Confirm
261    {
262        Some(session.sink().reserve_standing().ok_or_else(saturated)?)
263    } else {
264        None
265    };
266
267    let id = session.next_watch();
268    let request = Request::Subscribe {
269        watch: id,
270        path: path.to_path_buf(),
271        options,
272        // The session's own sink travels with the request, which is what binds
273        // every notification from this subscription to the receiver the client
274        // got alongside the session (D-11).
275        sink: session.sink().clone(),
276        completion,
277        fault_slot,
278    };
279    session.submit(request).map_err(|_| {
280        io::Error::new(
281            io::ErrorKind::NotConnected,
282            "the monitor has shut down, so no new subscription can be registered",
283        )
284    })?;
285    Ok(Watch::new(id, session.clone(), cancellation))
286}
287
288/// The notification queue has no room to promise this subscription's completions.
289///
290/// This is where backpressure is meant to land: on the client's own thread, at
291/// the call that asked for the work, rather than at a delivery with no safe way
292/// to fail (D-29/D-33).
293fn saturated() -> io::Error {
294    io::Error::new(
295        io::ErrorKind::WouldBlock,
296        "the notification queue is full, so a subscription's completions cannot be guaranteed",
297    )
298}
299
300#[cfg(test)]
301mod tests;