Skip to main content

storage_kit/ns/
watch.rs

1//! Watching a directory: [`Watch`], [`WatchBatch`], [`WatchOpts`], and the std-only polling engine `HostDir` uses.
2//!
3//! The contract, in one paragraph: a batch is **a hint to re-read, not a log**. Each batch carries an `epoch` (chosen
4//! when the watch starts) and a `generation` (one more than the previous batch). **A gap in `generation`, or a
5//! different `epoch`, means batches were lost, and is the same as `rescan`.** So a consumer that ignores everything but
6//! "something changed, go and look" is always correct, and [`WatchCursor`] does the bookkeeping for one that wants to
7//! know whether it *must* look at everything.
8//!
9//! Events carry **namespace paths** only. A host path never reaches the consumer.
10//!
11//! Watch a directory, not a file: editors replace files (write a temp, rename over), so the file's identity changes
12//! and a watch on it would be watching a name that no longer exists.
13
14use std::collections::BTreeMap;
15use std::sync::atomic::{AtomicBool, Ordering};
16use std::sync::mpsc::{
17    Receiver, RecvError, RecvTimeoutError, SyncSender, TryRecvError, TrySendError,
18};
19use std::sync::{mpsc, Arc};
20use std::thread::{self, JoinHandle};
21use std::time::{Duration, Instant};
22
23use super::backend::Kind;
24use super::path::NsPath;
25
26/// The default poll interval.
27pub const DEFAULT_INTERVAL: Duration = Duration::from_millis(250);
28/// The smallest interval a poll is allowed (a smaller request is raised to this).
29pub const MIN_INTERVAL: Duration = Duration::from_millis(10);
30/// The longest poll interval; a longer request is lowered to this. (Also keeps `Instant` arithmetic from overflowing.)
31pub const MAX_INTERVAL: Duration = Duration::from_secs(60 * 60);
32/// The default cap on paths per batch.
33pub const DEFAULT_MAX_ENTRIES: usize = 1024;
34/// The default cap on entries a polling watch tracks in memory (see [`WatchOpts::max_tracked`]).
35pub const DEFAULT_MAX_TRACKED: usize = 262_144;
36/// The default cap on how many directory levels a recursive polling watch descends (see [`WatchOpts::max_depth`]).
37pub const DEFAULT_MAX_DEPTH: usize = 64;
38/// How many undelivered batches a watch queues before it starts dropping them (which shows up as a generation gap).
39/// Bounded so a consumer that stops reading cannot make the producer grow without limit.
40pub const QUEUE_DEPTH: usize = 16;
41
42/// Options for [`Backend::watch`](super::Backend::watch).
43#[derive(Debug, Clone, PartialEq, Eq)]
44#[non_exhaustive]
45pub struct WatchOpts {
46    /// Also report changes below subdirectories. Default `false`: direct children only.
47    pub recursive: bool,
48    /// Poll interval for polling backends. Default 250 ms; values under 10 ms are raised to 10 ms and values over one
49    /// hour ([`MAX_INTERVAL`]) are lowered to it. Ignored by backends that are not polling.
50    pub interval: Duration,
51    /// At most this many paths in one batch. Past it the batch is `rescan: true` with an empty `changed`.
52    pub max_entries: usize,
53    /// At most this many entries a polling backend keeps in memory to compare against (the size of the watched tree).
54    /// A watch that would have to track more is refused at the start (`TooLarge`), and a watch whose tree grows past it
55    /// sends `rescan` and then reports nothing until the tree is small enough again: it is a memory bound, not a
56    /// filter. Unrelated to `max_entries`, which caps one *batch*. Default [`DEFAULT_MAX_TRACKED`].
57    pub max_tracked: usize,
58    /// How many directory levels below the watched directory a **recursive** polling watch descends. Default
59    /// [`DEFAULT_MAX_DEPTH`] (64). The watched directory is level 0, its subdirectories level 1, and so on; with the
60    /// default, a directory 65 levels down is too deep. Ignored when `recursive` is `false` and by backends that do not
61    /// scan.
62    ///
63    /// A tree deeper than this is handled exactly like one with more than [`max_tracked`](Self::max_tracked) entries:
64    /// the scan is *incomplete*, so a watch that would start on one is refused (`TooLarge`), and a watch whose tree
65    /// grows past the limit sends one `rescan` and then reports nothing until the tree is within it again. It is never
66    /// an error mid-watch and never a silent skip of the deep part. Like `max_tracked` it is a bound, not a filter.
67    ///
68    /// It bounds work and descriptors: a scan holds one open directory handle per level on the way down, so at most
69    /// `max_depth + 1` at a time. Do not set it close to the process's descriptor limit; a scan that runs out of
70    /// descriptors is also reported as incomplete.
71    pub max_depth: usize,
72}
73
74impl Default for WatchOpts {
75    fn default() -> Self {
76        WatchOpts {
77            recursive: false,
78            interval: DEFAULT_INTERVAL,
79            max_entries: DEFAULT_MAX_ENTRIES,
80            max_tracked: DEFAULT_MAX_TRACKED,
81            max_depth: DEFAULT_MAX_DEPTH,
82        }
83    }
84}
85
86impl WatchOpts {
87    /// Set [`WatchOpts::recursive`].
88    #[must_use]
89    pub fn recursive(mut self, recursive: bool) -> Self {
90        self.recursive = recursive;
91        self
92    }
93
94    /// Set [`WatchOpts::interval`].
95    #[must_use]
96    pub fn interval(mut self, interval: Duration) -> Self {
97        self.interval = interval;
98        self
99    }
100
101    /// Set [`WatchOpts::max_entries`].
102    #[must_use]
103    pub fn max_entries(mut self, max_entries: usize) -> Self {
104        self.max_entries = max_entries;
105        self
106    }
107
108    /// Set [`WatchOpts::max_tracked`].
109    #[must_use]
110    pub fn max_tracked(mut self, max_tracked: usize) -> Self {
111        self.max_tracked = max_tracked;
112        self
113    }
114
115    /// Set [`WatchOpts::max_depth`].
116    #[must_use]
117    pub fn max_depth(mut self, max_depth: usize) -> Self {
118        self.max_depth = max_depth;
119        self
120    }
121
122    pub(crate) fn effective_interval(&self) -> Duration {
123        self.interval.clamp(MIN_INTERVAL, MAX_INTERVAL)
124    }
125}
126
127/// One notification. See the [module docs](self).
128#[derive(Debug, Clone, PartialEq, Eq)]
129#[non_exhaustive]
130pub struct WatchBatch {
131    /// Chosen when the watch starts. A different epoch than the last batch means the watch was restarted: rescan.
132    pub epoch: u64,
133    /// One more than the previous batch's. The first batch is 1. A gap means batches were dropped: rescan.
134    pub generation: u64,
135    /// The namespace paths that changed: deduplicated, sorted, and empty when `rescan` is set.
136    pub changed: Vec<NsPath>,
137    /// Events were lost or the watched directory went away or came back: re-read everything you care about.
138    pub rescan: bool,
139}
140
141impl WatchBatch {
142    /// Build a batch. For backend authors.
143    pub fn new(epoch: u64, generation: u64, changed: Vec<NsPath>, rescan: bool) -> Self {
144        WatchBatch {
145            epoch,
146            generation,
147            changed,
148            rescan,
149        }
150    }
151}
152
153/// Tracks `(epoch, generation)` across batches and says when a rescan is required.
154///
155/// ```
156/// # #[cfg(feature = "ns")] {
157/// use storage_kit::ns::{WatchBatch, WatchCursor};
158/// let mut cursor = WatchCursor::new();
159/// assert!(!cursor.observe(&WatchBatch::new(7, 1, vec![], false)));
160/// assert!(!cursor.observe(&WatchBatch::new(7, 2, vec![], false)));
161/// assert!(cursor.observe(&WatchBatch::new(7, 4, vec![], false)), "generation 3 was lost");
162/// assert!(cursor.observe(&WatchBatch::new(8, 5, vec![], false)), "a new epoch");
163/// # }
164/// ```
165#[derive(Debug, Default, Clone)]
166pub struct WatchCursor {
167    last: Option<(u64, u64)>,
168}
169
170impl WatchCursor {
171    /// A cursor that has seen nothing; the first batch must be generation 1.
172    pub fn new() -> Self {
173        Self::default()
174    }
175
176    /// Record `batch`. Returns true if the consumer must rescan: the batch says so, the epoch changed, or the
177    /// generation did not advance by exactly one (the first batch must be generation 1).
178    pub fn observe(&mut self, batch: &WatchBatch) -> bool {
179        let continuous = match self.last {
180            None => batch.generation == 1,
181            Some((epoch, generation)) => {
182                epoch == batch.epoch && generation.checked_add(1) == Some(batch.generation)
183            }
184        };
185        self.last = Some((batch.epoch, batch.generation));
186        batch.rescan || !continuous
187    }
188}
189
190type Mapper = Arc<dyn Fn(&NsPath) -> Option<NsPath> + Send + Sync>;
191
192/// A running watch. Owns the receiving end of the batch channel.
193///
194/// **Dropping it stops the watch**, and for a backend with a worker thread, ends and joins that thread before `drop`
195/// returns. Nothing keeps running after it.
196pub struct Watch {
197    rx: Receiver<WatchBatch>,
198    mapper: Option<Mapper>,
199    on_drop: Option<Box<dyn FnOnce() + Send>>,
200}
201
202impl std::fmt::Debug for Watch {
203    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204        f.debug_struct("Watch").finish_non_exhaustive()
205    }
206}
207
208impl Watch {
209    /// Build a watch from a receiver and the action that stops its producer. For backend authors: `on_drop` runs once
210    /// when the `Watch` is dropped and must stop (and, for a thread, join) whatever feeds `rx`.
211    pub fn new(rx: Receiver<WatchBatch>, on_drop: impl FnOnce() + Send + 'static) -> Self {
212        Watch {
213            rx,
214            mapper: None,
215            on_drop: Some(Box::new(on_drop)),
216        }
217    }
218
219    /// Rewrite every path in every batch with `f` as it is received. `f` returns `None` for a path that cannot be
220    /// represented; the batch is then marked `rescan` (a path was lost, so the consumer must look). The
221    /// [`Namespace`](super::Namespace) uses this to turn mount-relative paths into namespace paths.
222    #[must_use]
223    pub fn map_paths(
224        mut self,
225        f: impl Fn(&NsPath) -> Option<NsPath> + Send + Sync + 'static,
226    ) -> Self {
227        self.mapper = Some(match self.mapper.take() {
228            None => Arc::new(f),
229            Some(prev) => Arc::new(move |p: &NsPath| prev(p).and_then(|q| f(&q))),
230        });
231        self
232    }
233
234    fn map(&self, mut batch: WatchBatch) -> WatchBatch {
235        if let Some(m) = &self.mapper {
236            let mut lost = false;
237            let mut out: Vec<NsPath> = batch
238                .changed
239                .iter()
240                .filter_map(|p| {
241                    let mapped = m(p);
242                    lost |= mapped.is_none();
243                    mapped
244                })
245                .collect();
246            out.sort();
247            out.dedup();
248            if lost {
249                batch.rescan = true;
250                out.clear();
251            }
252            batch.changed = out;
253        }
254        batch
255    }
256
257    /// Block until the next batch. `Err` means the watch's producer is gone.
258    pub fn recv(&self) -> Result<WatchBatch, RecvError> {
259        self.rx.recv().map(|b| self.map(b))
260    }
261
262    /// Block for at most `timeout`.
263    pub fn recv_timeout(&self, timeout: Duration) -> Result<WatchBatch, RecvTimeoutError> {
264        self.rx.recv_timeout(timeout).map(|b| self.map(b))
265    }
266
267    /// Return a batch if one is ready.
268    pub fn try_recv(&self) -> Result<WatchBatch, TryRecvError> {
269        self.rx.try_recv().map(|b| self.map(b))
270    }
271}
272
273impl Drop for Watch {
274    fn drop(&mut self) {
275        if let Some(stop) = self.on_drop.take() {
276            stop();
277        }
278    }
279}
280
281/// A fresh epoch: unpredictable enough that two watches (or two runs) do not share one, which is all it is for.
282pub(crate) fn new_epoch() -> u64 {
283    use std::collections::hash_map::RandomState;
284    use std::hash::{BuildHasher, Hasher};
285    let nanos = std::time::SystemTime::now()
286        .duration_since(std::time::UNIX_EPOCH)
287        .map(|d| d.as_nanos() as u64)
288        .unwrap_or(0);
289    RandomState::new().build_hasher().finish() ^ nanos
290}
291
292/// Sort, deduplicate and cap a changed set. Past `max_entries` the result is `(empty, true)`.
293pub(crate) fn finish_changed(mut changed: Vec<NsPath>, max_entries: usize) -> (Vec<NsPath>, bool) {
294    changed.sort();
295    changed.dedup();
296    if changed.len() > max_entries {
297        (Vec::new(), true)
298    } else {
299        (changed, false)
300    }
301}
302
303/// Producer-side bookkeeping shared by the polling thread and the `Memory` backend: numbering and non-blocking send.
304pub(crate) struct BatchSender {
305    tx: SyncSender<WatchBatch>,
306    epoch: u64,
307    generation: u64,
308}
309
310impl BatchSender {
311    pub(crate) fn channel() -> (BatchSender, Receiver<WatchBatch>) {
312        let (tx, rx) = mpsc::sync_channel(QUEUE_DEPTH);
313        (
314            BatchSender {
315                tx,
316                epoch: new_epoch(),
317                generation: 0,
318            },
319            rx,
320        )
321    }
322
323    /// Number and send a batch. A full queue drops it but still consumes the generation number, so the consumer sees
324    /// the gap. Returns false once the receiver is gone.
325    pub(crate) fn send(&mut self, changed: Vec<NsPath>, rescan: bool, max_entries: usize) -> bool {
326        let (changed, over) = if rescan {
327            (Vec::new(), true)
328        } else {
329            finish_changed(changed, max_entries)
330        };
331        self.generation += 1;
332        let batch = WatchBatch::new(self.epoch, self.generation, changed, over);
333        !matches!(self.tx.try_send(batch), Err(TrySendError::Disconnected(_)))
334    }
335}
336
337/// What a poll records about one entry. Equal fingerprints mean "unchanged".
338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339pub(crate) struct Fingerprint {
340    pub kind: Kind,
341    pub len: u64,
342    pub mtime_ns: u128,
343    pub inode: u64,
344}
345
346pub(crate) type Snapshot = BTreeMap<NsPath, Fingerprint>;
347
348/// Paths that differ between two snapshots: created, removed, or fingerprint changed.
349pub(crate) fn diff(old: &Snapshot, new: &Snapshot) -> Vec<NsPath> {
350    let mut out = Vec::new();
351    for (p, fp) in new {
352        if old.get(p) != Some(fp) {
353            out.push(p.clone());
354        }
355    }
356    for p in old.keys() {
357        if !new.contains_key(p) {
358            out.push(p.clone());
359        }
360    }
361    out
362}
363
364/// What one poll found.
365pub(crate) enum ScanOutcome {
366    /// The whole watched tree, as it is now.
367    Complete(Snapshot),
368    /// The watched directory is gone, no longer a directory, or unreadable.
369    Unavailable,
370    /// The scan could not finish (a resource limit, an I/O error, more entries than `max_tracked`, or deeper than `max_depth`): what it saw is
371    /// not a trustworthy picture, so nothing is compared against it.
372    Incomplete,
373}
374
375/// Start the polling thread. `initial` is the baseline (taken synchronously by the caller, so a bad path is an error
376/// from `watch()`, not a silent dead thread); `scan` re-reads the tree.
377///
378/// Behaviour: a change seen on one poll is reported on that poll; any number of writes between two polls are one
379/// batch; if the directory vanishes, becomes unreadable, or cannot be scanned completely, exactly one `rescan` batch is
380/// sent, the watch keeps running, and another `rescan` batch is sent when a complete scan is possible again.
381pub(crate) fn spawn_poller<S>(
382    initial: Snapshot,
383    mut scan: S,
384    opts: &WatchOpts,
385) -> std::io::Result<Watch>
386where
387    S: FnMut() -> ScanOutcome + Send + 'static,
388{
389    let interval = opts.effective_interval();
390    let max_entries = opts.max_entries;
391    let stop = Arc::new(AtomicBool::new(false));
392    let (mut sender, rx) = BatchSender::channel();
393
394    let thread_stop = Arc::clone(&stop);
395    let handle: JoinHandle<()> =
396        thread::Builder::new()
397            .name("ns-watch-poll".into())
398            .spawn(move || {
399                let mut previous: Option<Snapshot> = Some(initial);
400                loop {
401                    // Sleep for one interval, but wake at once when the Watch is dropped (unpark).
402                    let started = Instant::now();
403                    let deadline = started.checked_add(interval).unwrap_or(started);
404                    loop {
405                        if thread_stop.load(Ordering::Acquire) {
406                            return;
407                        }
408                        let now = Instant::now();
409                        if now >= deadline {
410                            break;
411                        }
412                        thread::park_timeout(deadline - now);
413                    }
414                    let current = match scan() {
415                        ScanOutcome::Complete(s) => Some(s),
416                        ScanOutcome::Unavailable | ScanOutcome::Incomplete => None,
417                    };
418                    let alive = match (&previous, &current) {
419                        (Some(old), Some(new)) => {
420                            let changed = diff(old, new);
421                            changed.is_empty() || sender.send(changed, false, max_entries)
422                        }
423                        (Some(_), None) | (None, Some(_)) => {
424                            sender.send(Vec::new(), true, max_entries)
425                        }
426                        (None, None) => true,
427                    };
428                    if !alive {
429                        return;
430                    }
431                    previous = current;
432                }
433            })?;
434
435    let stopper = Arc::clone(&stop);
436    let thread_handle = handle.thread().clone();
437    Ok(Watch::new(rx, move || {
438        stopper.store(true, Ordering::Release);
439        thread_handle.unpark();
440        let _ = handle.join();
441    }))
442}
443
444#[cfg(test)]
445mod tests {
446    use super::*;
447
448    fn p(s: &str) -> NsPath {
449        NsPath::parse(s).unwrap()
450    }
451
452    #[test]
453    fn cursor_flags_gaps_epochs_and_rescans() {
454        let mut c = WatchCursor::new();
455        assert!(
456            c.observe(&WatchBatch::new(1, 2, vec![], false)),
457            "first batch must be generation 1"
458        );
459        let mut c = WatchCursor::new();
460        assert!(!c.observe(&WatchBatch::new(1, 1, vec![], false)));
461        assert!(c.observe(&WatchBatch::new(1, 2, vec![], true)));
462        assert!(!c.observe(&WatchBatch::new(1, 3, vec![], false)));
463        assert!(c.observe(&WatchBatch::new(2, 4, vec![], false)));
464    }
465
466    #[test]
467    fn cap_turns_into_rescan() {
468        let many: Vec<_> = (0..5).map(|i| p(&format!("/f{i}"))).collect();
469        assert_eq!(finish_changed(many.clone(), 5).0.len(), 5);
470        assert_eq!(finish_changed(many, 4), (Vec::new(), true));
471        let dup = vec![p("/b"), p("/a"), p("/b")];
472        assert_eq!(finish_changed(dup, 10).0, vec![p("/a"), p("/b")]);
473    }
474
475    #[test]
476    fn queue_overflow_shows_as_a_generation_gap() {
477        let (mut s, rx) = BatchSender::channel();
478        for _ in 0..QUEUE_DEPTH + 3 {
479            assert!(s.send(vec![p("/x")], false, 10));
480        }
481        let mut c = WatchCursor::new();
482        let got: Vec<_> = rx.try_iter().collect();
483        assert_eq!(got.len(), QUEUE_DEPTH);
484        assert!(
485            got.iter().all(|b| !c.observe(b)),
486            "the delivered prefix is contiguous"
487        );
488        s.send(vec![p("/y")], false, 10);
489        let last = rx.try_recv().unwrap();
490        assert!(c.observe(&last), "dropped batches must surface as a gap");
491    }
492
493    #[test]
494    fn dropping_the_watch_joins_the_poller_thread() {
495        // The closure owns a token; once the thread has been joined the closure is gone and only our clone remains.
496        let token = Arc::new(());
497        let held = Arc::clone(&token);
498        let watch = spawn_poller(
499            Snapshot::new(),
500            move || {
501                let _keep = &held;
502                ScanOutcome::Complete(Snapshot::new())
503            },
504            &WatchOpts::default().interval(Duration::from_secs(30)),
505        )
506        .unwrap();
507        assert_eq!(Arc::strong_count(&token), 2);
508        let started = Instant::now();
509        drop(watch);
510        assert_eq!(
511            Arc::strong_count(&token),
512            1,
513            "the poller thread (and its scan closure) must be gone"
514        );
515        assert!(
516            started.elapsed() < Duration::from_secs(5),
517            "drop must not wait out the 30 s interval"
518        );
519    }
520
521    #[test]
522    fn extreme_intervals_are_clamped_not_overflowed() {
523        let huge = WatchOpts::default().interval(Duration::MAX);
524        assert_eq!(huge.effective_interval(), MAX_INTERVAL);
525        assert_eq!(
526            WatchOpts::default()
527                .interval(Duration::ZERO)
528                .effective_interval(),
529            MIN_INTERVAL
530        );
531        // The poller must start (and stop) with the extreme value; `Instant::now() + Duration::MAX` would panic.
532        let w = spawn_poller(
533            Snapshot::new(),
534            || ScanOutcome::Complete(Snapshot::new()),
535            &huge,
536        )
537        .unwrap();
538        drop(w);
539    }
540
541    #[test]
542    fn mapper_composes_and_flags_lost_paths() {
543        let (mut s, rx) = BatchSender::channel();
544        let w = Watch::new(rx, || {})
545            .map_paths(|p| p.rebase(&p_("/m")).ok())
546            .map_paths(|p| {
547                if p.as_str() == "/m/bad" {
548                    None
549                } else {
550                    Some(p.clone())
551                }
552            });
553        s.send(vec![p("/a")], false, 10);
554        let b = w.recv().unwrap();
555        assert_eq!(b.changed, vec![p("/m/a")]);
556        s.send(vec![p("/a"), p("/bad")], false, 10);
557        let b = w.recv().unwrap();
558        assert!(b.rescan && b.changed.is_empty());
559    }
560
561    fn p_(s: &str) -> NsPath {
562        p(s)
563    }
564}