Skip to main content

windows_file_watcher/
session.rs

1// Copyright (c) 2026 Mike Grier
2//! A client's handle on the monitor: what it submits requests through, and where
3//! everything it subscribes to is delivered.
4//!
5//! # Why one object carries both halves
6//!
7//! A session bundles the request-submission handle with the notification sender
8//! (D-2/D-11) rather than leaving them separate, because that is what makes the
9//! binding between a subscription and its destination structural. Every watch
10//! created through a session delivers to that session's sender, so a client
11//! chooses its routing once -- at session creation -- instead of restating it per
12//! subscription and hoping the two agree. A client that wants several independent
13//! streams opens several sessions; one that wants everything in one place opens
14//! one and clones it.
15//!
16//! # The sender is concrete, not a trait
17//!
18//! Delivery is an enqueue *the crate performs* onto storage the crate owns. There
19//! is no sink trait and no client closure anywhere on this path, so nothing a
20//! client does -- blocking, panicking, being slow -- can stall or unwind a
21//! completion callback (D-2/D-11). The client only ever receives, on whatever
22//! thread it likes.
23//!
24//! # Outliving the monitor
25//!
26//! A session holds the servicing path alive, but that is an allocation, not a
27//! lifetime: `Monitor::Drop` shuts the path down whatever sessions still exist
28//! (D-20), after which a surviving session reports itself closed and hands back
29//! any request it is given. The alternative -- letting a forgotten session keep a
30//! monitor and its watchers running -- would make teardown depend on the client
31//! having dropped everything in the right order.
32
33use std::io;
34use std::path::Path;
35use std::sync::Arc;
36use std::time::Duration;
37
38use crate::monitor::{Core, Request};
39use crate::queue::{Sender, WatchId};
40use crate::servicing::Rejected;
41use crate::watch::{VolumeChangeDecision, Watch, WatchOptions};
42
43/// A client's connection to a monitor.
44///
45/// Obtained from [`Monitor::session`](crate::monitor::Monitor::session), which
46/// returns it together with the receiver its notifications arrive on.
47///
48/// Cloning is how a client gets the multi-producer submission D-11 requires:
49/// every clone submits to the same servicing path and delivers to the same
50/// receiver, so several client threads can share one stream without coordinating.
51#[derive(Clone)]
52pub struct Session {
53    core: Arc<Core>,
54    sink: Sender,
55}
56
57impl Session {
58    pub(crate) fn new(core: Arc<Core>, sink: Sender) -> Self {
59        Self { core, sink }
60    }
61
62    /// Watch `path`, delivering to this session's receiver.
63    ///
64    /// Registration is asynchronous: this returns as soon as the request is
65    /// queued, and the watch begins on the monitor's own servicing path. The
66    /// returned handle owns the subscription's lifetime -- dropping it cancels --
67    /// so it must be kept for as long as the client wants notifications.
68    ///
69    /// `path` reaches Win32 **verbatim** (D-85). It may be relative, may use
70    /// forward slashes, and may contain `.` or `..`, because this crate does not
71    /// prepend `\\?\` on a caller's behalf -- that prefix selects a different
72    /// path parsing mode in which none of those resolve.
73    ///
74    /// The consequence worth knowing: a path longer than `MAX_PATH` opens only
75    /// by one of two escapes, and **only the first is available to a relative
76    /// path**.
77    ///
78    /// - **Long-path opt-in -- works for relative and absolute alike.** If
79    ///   **your** application declares `longPathAware` in its manifest *and*
80    ///   the machine has `LongPathsEnabled` set, `CreateFileW` is one of the
81    ///   functions Windows lists as no longer carrying a `MAX_PATH`
82    ///   restriction, and that is a property of the call rather than of the
83    ///   shape of the path.
84    /// - **The `\\?\` prefix -- absolute only.** Windows states that a
85    ///   relative path is limited to `MAX_PATH` *because the prefix cannot be
86    ///   applied to one*: the prefix means "pass this through with minimal
87    ///   modification", so there is nothing left to resolve it against. That
88    ///   limit is a consequence of the prefix route, not a separate ceiling
89    ///   the opt-in leaves standing.
90    ///
91    /// So a long relative path is fine in a long-path-aware process, and has
92    /// no escape at all in one that has not opted in.
93    ///
94    /// **Measured, not inferred.** `probe-long-path-aware` and
95    /// `probe-long-path-unaware` in `windows-platform-probes` are the same code
96    /// differing only in whether their manifest declares `longPathAware`. They
97    /// open a file through a relative path of 429 characters, from a short
98    /// current directory, with no prefix. With the opt-in every shape opens;
99    /// without it every shape is refused with `ERROR_PATH_NOT_FOUND` while the
100    /// same shapes at 78 characters open, which is the length refusal rather
101    /// than a missing file -- the probe creates each target first.
102    ///
103    /// The measurement also answers a question the documentation does not.
104    /// A plausible implementation of the opt-in would be to regularize the path
105    /// and prepend `\\?\`, and that prefix is exactly what disables `.`, `..`
106    /// and forward-slash translation -- so a relative path using any of those
107    /// could have resolved under `MAX_PATH` and failed over it. **It does
108    /// not.** Both shapes resolve past the ceiling exactly as they do below it,
109    /// so the opt-in lifts the length check without re-parsing, and this crate
110    /// passing paths verbatim exposes no edge at that boundary.
111    ///
112    /// # Errors
113    ///
114    /// Returns [`io::ErrorKind::WouldBlock`] if the notification queue has no
115    /// room to guarantee this subscription's registration and cancellation
116    /// completions (D-33) -- backpressure lands here, synchronously, rather
117    /// than at a later delivery that has no safe way to fail. Returns
118    /// [`io::ErrorKind::NotConnected`] if the monitor has already shut down.
119    /// A path that cannot be watched is not reported by either of those:
120    /// whether it can be is not known until the monitor tries, and arrives
121    /// asynchronously as a [`Notification::Completion`](crate::Notification::Completion)
122    /// (D-30).
123    pub fn subscribe(&self, path: impl AsRef<Path>, options: WatchOptions) -> io::Result<Watch> {
124        crate::watch::subscribe(self, path.as_ref(), options)
125    }
126
127    /// Answer an interactive subscription's [`Notification::RetryQuestion`](crate::Notification::RetryQuestion)
128    /// (D-27): `Some(delay)` names the next retry delay, `None` declines and is
129    /// counted at the failing operation's default. Not itself a request with a
130    /// lifecycle -- it is a response to one the crate posed -- so it carries no
131    /// completion and simply does nothing if `watch` is not currently awaiting
132    /// an answer (already resolved, already cancelled, or never asked).
133    pub fn answer(&self, watch: WatchId, delay: Option<Duration>) {
134        let _ = self.submit(Request::Answer { watch, delay });
135    }
136
137    /// Answer a subscription's [`Notification::VolumeChanged`](crate::Notification::VolumeChanged)
138    /// question (D-78/M12): [`VolumeChangeDecision::Continue`] keeps the
139    /// subscription running against the new volume,
140    /// [`VolumeChangeDecision::Stop`] removes it. Not itself a request with a
141    /// lifecycle, so it carries no completion and simply does nothing if
142    /// `watch` is not currently awaiting an answer.
143    pub fn answer_volume_change(&self, watch: WatchId, decision: VolumeChangeDecision) {
144        let _ = self.submit(Request::AnswerVolumeChange { watch, decision });
145    }
146
147    /// Submit a request to the monitor.
148    ///
149    /// Crate-internal; see [`Request`] for why.
150    pub(crate) fn submit(&self, request: Request) -> Result<(), Rejected<Request>> {
151        self.core.submit(request)
152    }
153
154    /// Whether the monitor behind this session is still accepting requests.
155    #[must_use]
156    pub fn is_open(&self) -> bool {
157        self.core.is_open()
158    }
159
160    /// Mint the next subscription identifier.
161    pub(crate) fn next_watch(&self) -> WatchId {
162        self.core.next_watch()
163    }
164
165    /// The sender every watch created through this session delivers to.
166    ///
167    /// Crate-internal: a client never sends, only receives (D-11).
168    pub(crate) fn sink(&self) -> &Sender {
169        &self.sink
170    }
171}
172
173impl std::fmt::Debug for Session {
174    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
175        f.debug_struct("Session")
176            .field("open", &self.is_open())
177            .finish_non_exhaustive()
178    }
179}
180
181#[cfg(test)]
182mod tests;