Skip to main content

staticweaver/
watch.rs

1// Copyright © 2024-2026 StaticWeaver. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! # Watching loader (issue #52)
5//!
6//! [`WatchLoader`](crate::watch::WatchLoader) wraps any
7//! [`TemplateLoader`](crate::engine::TemplateLoader), caches what it loads,
8//! and drops the cache when files under a watched directory change.
9//! Change events from the operating system (via `notify`) are
10//! debounced: a burst of events (an editor's save writes a temporary
11//! file, renames it, touches metadata) becomes one batch once no new
12//! event has arrived for the debounce window, 200 ms by default.
13//!
14//! Each batch also goes to every [`WatchLoader::subscribe`](crate::watch::WatchLoader::subscribe) receiver,
15//! so a host can clear its own caches (for example
16//! [`Engine::clear_cache`](crate::Engine::clear_cache), whose rendered
17//! pages embed partials) and re-render.
18//!
19//! Gated behind the `watch` feature.
20
21use crate::engine::TemplateLoader;
22use crate::EngineError;
23use notify::{Event, EventKind, RecursiveMode, Watcher};
24use std::collections::HashMap;
25use std::fmt;
26use std::io;
27use std::path::{Path, PathBuf};
28use std::sync::atomic::{AtomicU64, Ordering};
29use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
30use std::sync::{Arc, Mutex, PoisonError};
31use std::thread;
32use std::time::Duration;
33
34/// The default debounce window: a batch is delivered once no change
35/// event has arrived for this long.
36///
37/// # Examples
38///
39/// ```
40/// use staticweaver::watch::DEFAULT_DEBOUNCE;
41/// assert_eq!(DEFAULT_DEBOUNCE.as_millis(), 200);
42/// ```
43pub const DEFAULT_DEBOUNCE: Duration = Duration::from_millis(200);
44
45/// State shared with the debounce thread.
46#[derive(Default)]
47struct Shared {
48    cache: Mutex<HashMap<String, String>>,
49    subscribers: Mutex<Vec<Sender<Vec<PathBuf>>>>,
50    generation: AtomicU64,
51}
52
53impl Shared {
54    /// Drops every cached body, bumps the generation and tells the
55    /// subscribers which paths changed. Receivers that hung up are
56    /// forgotten.
57    fn flush(&self, paths: Vec<PathBuf>) {
58        self.cache
59            .lock()
60            .unwrap_or_else(PoisonError::into_inner)
61            .clear();
62        let _ = self.generation.fetch_add(1, Ordering::SeqCst);
63        self.subscribers
64            .lock()
65            .unwrap_or_else(PoisonError::into_inner)
66            .retain(|tx| tx.send(paths.clone()).is_ok());
67    }
68}
69
70/// The paths changed by one debounced burst of events. Access events
71/// (a file being opened or read, which loading a template itself
72/// causes on Linux) are ignored; a watcher error counts as a change
73/// with no path, since something may have been missed.
74#[derive(Default)]
75struct Batch {
76    changed: bool,
77    paths: Vec<PathBuf>,
78}
79
80impl Batch {
81    fn add(&mut self, event: notify::Result<Event>) {
82        match event {
83            Ok(ev) if matches!(ev.kind, EventKind::Access(_)) => {}
84            Ok(ev) => {
85                self.changed = true;
86                self.paths.extend(ev.paths);
87            }
88            Err(_) => self.changed = true,
89        }
90    }
91
92    fn into_paths(mut self) -> Option<Vec<PathBuf>> {
93        if !self.changed {
94            return None;
95        }
96        self.paths.sort();
97        self.paths.dedup();
98        Some(self.paths)
99    }
100}
101
102/// Collects one burst: the first event, then every event that follows
103/// within `debounce` of the previous one. Returns the batch and whether
104/// the event source is still connected.
105fn collect_burst(
106    first: notify::Result<Event>,
107    rx: &Receiver<notify::Result<Event>>,
108    debounce: Duration,
109) -> (Batch, bool) {
110    let mut batch = Batch::default();
111    batch.add(first);
112    loop {
113        match rx.recv_timeout(debounce) {
114            Ok(event) => batch.add(event),
115            Err(RecvTimeoutError::Timeout) => return (batch, true),
116            Err(RecvTimeoutError::Disconnected) => {
117                return (batch, false)
118            }
119        }
120    }
121}
122
123/// The debounce thread: runs until the event source hangs up (the
124/// watcher, owned by the `WatchLoader`, is dropped).
125fn debounce_loop(
126    rx: &Receiver<notify::Result<Event>>,
127    shared: &Shared,
128    debounce: Duration,
129) {
130    while let Ok(first) = rx.recv() {
131        let (batch, connected) = collect_burst(first, rx, debounce);
132        if let Some(paths) = batch.into_paths() {
133            shared.flush(paths);
134        }
135        if !connected {
136            return;
137        }
138    }
139}
140
141/// A [`TemplateLoader`] that caches another loader's templates and
142/// invalidates the cache when files under a watched directory change.
143///
144/// # Examples
145///
146/// ```no_run
147/// use staticweaver::engine::FsLoader;
148/// use staticweaver::watch::WatchLoader;
149/// use staticweaver::{Context, Engine};
150/// use std::sync::Arc;
151/// use std::time::Duration;
152///
153/// let loader = Arc::new(WatchLoader::new(FsLoader::new("templates".into()), "templates")?);
154/// let changes = loader.subscribe();
155/// let engine = Engine::with_loader(loader, Duration::from_secs(60));
156/// for changed in changes {
157///     engine.clear_cache(); // rendered pages embed partials too
158///     println!("{changed:?} changed: {}", engine.render_page(&Context::new(), "index")?);
159/// }
160/// # Ok::<(), staticweaver::EngineError>(())
161/// ```
162pub struct WatchLoader<L> {
163    inner: L,
164    shared: Arc<Shared>,
165    // Dropping the watcher ends the debounce thread. `Mutex` keeps the
166    // loader `Sync` whatever the platform watcher type is.
167    watcher: Mutex<Option<notify::RecommendedWatcher>>,
168}
169
170impl<L> fmt::Debug for WatchLoader<L> {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        f.debug_struct("WatchLoader")
173            .field(
174                "generation",
175                &self.shared.generation.load(Ordering::SeqCst),
176            )
177            .finish_non_exhaustive()
178    }
179}
180
181impl<L: TemplateLoader> WatchLoader<L> {
182    /// Wraps `inner` and watches `root` recursively, with the
183    /// [`DEFAULT_DEBOUNCE`] window.
184    ///
185    /// # Errors
186    ///
187    /// Returns `EngineError::Io` when the platform watcher cannot be
188    /// created or `root` cannot be watched (for example, it does not
189    /// exist).
190    ///
191    /// # Examples
192    ///
193    /// ```
194    /// use staticweaver::engine::FsLoader;
195    /// use staticweaver::watch::WatchLoader;
196    ///
197    /// let dir = tempfile::tempdir().unwrap();
198    /// let loader = WatchLoader::new(FsLoader::new(dir.path().into()), dir.path());
199    /// assert!(loader.is_ok());
200    /// assert!(WatchLoader::new(FsLoader::new("x".into()), "/no/such/dir").is_err());
201    /// ```
202    pub fn new(
203        inner: L,
204        root: impl AsRef<Path>,
205    ) -> Result<Self, EngineError> {
206        Self::with_debounce(inner, root, DEFAULT_DEBOUNCE)
207    }
208
209    /// As [`WatchLoader::new`], with a custom debounce window.
210    ///
211    /// # Errors
212    ///
213    /// As [`WatchLoader::new`].
214    ///
215    /// # Examples
216    ///
217    /// ```
218    /// use staticweaver::engine::FsLoader;
219    /// use staticweaver::watch::WatchLoader;
220    /// use std::time::Duration;
221    ///
222    /// let dir = tempfile::tempdir().unwrap();
223    /// let loader = WatchLoader::with_debounce(
224    ///     FsLoader::new(dir.path().into()),
225    ///     dir.path(),
226    ///     Duration::from_millis(50),
227    /// );
228    /// assert!(loader.is_ok());
229    /// ```
230    pub fn with_debounce(
231        inner: L,
232        root: impl AsRef<Path>,
233        debounce: Duration,
234    ) -> Result<Self, EngineError> {
235        let (tx, rx) = mpsc::channel();
236        let mut watcher =
237            notify::recommended_watcher(tx).map_err(io_error)?;
238        watcher
239            .watch(root.as_ref(), RecursiveMode::Recursive)
240            .map_err(io_error)?;
241        let loader = Self::from_events(inner, rx, debounce);
242        *loader
243            .watcher
244            .lock()
245            .unwrap_or_else(PoisonError::into_inner) = Some(watcher);
246        Ok(loader)
247    }
248
249    /// Builds the loader around an event source and starts the
250    /// debounce thread. The OS watcher (if any) is attached after.
251    fn from_events(
252        inner: L,
253        rx: Receiver<notify::Result<Event>>,
254        debounce: Duration,
255    ) -> Self {
256        let shared = Arc::new(Shared::default());
257        let thread_shared = Arc::clone(&shared);
258        let _ = thread::Builder::new()
259            .name("staticweaver-watch".into())
260            .spawn(move || {
261                debounce_loop(&rx, &thread_shared, debounce)
262            });
263        Self {
264            inner,
265            shared,
266            watcher: Mutex::new(None),
267        }
268    }
269
270    /// Returns a receiver that gets the changed paths of every
271    /// debounced batch (an empty list after a watcher error).
272    ///
273    /// # Examples
274    ///
275    /// ```
276    /// use staticweaver::engine::FsLoader;
277    /// use staticweaver::watch::WatchLoader;
278    /// use std::time::Duration;
279    ///
280    /// let dir = tempfile::tempdir().unwrap();
281    /// let loader = WatchLoader::new(FsLoader::new(dir.path().into()), dir.path()).unwrap();
282    /// let changes = loader.subscribe();
283    /// // Nothing has changed yet.
284    /// assert!(changes.recv_timeout(Duration::from_millis(10)).is_err());
285    /// ```
286    pub fn subscribe(&self) -> Receiver<Vec<PathBuf>> {
287        let (tx, rx) = mpsc::channel();
288        self.shared
289            .subscribers
290            .lock()
291            .unwrap_or_else(PoisonError::into_inner)
292            .push(tx);
293        rx
294    }
295
296    /// The number of debounced batches delivered so far.
297    ///
298    /// # Examples
299    ///
300    /// ```
301    /// use staticweaver::engine::FsLoader;
302    /// use staticweaver::watch::WatchLoader;
303    ///
304    /// let dir = tempfile::tempdir().unwrap();
305    /// let loader = WatchLoader::new(FsLoader::new(dir.path().into()), dir.path()).unwrap();
306    /// assert_eq!(loader.generation(), 0);
307    /// ```
308    #[must_use]
309    pub fn generation(&self) -> u64 {
310        self.shared.generation.load(Ordering::SeqCst)
311    }
312
313    /// Drops every cached template now, as if a change had been seen.
314    /// Subscribers are told with an empty path list.
315    ///
316    /// # Examples
317    ///
318    /// ```
319    /// use staticweaver::engine::FsLoader;
320    /// use staticweaver::watch::WatchLoader;
321    ///
322    /// let dir = tempfile::tempdir().unwrap();
323    /// let loader = WatchLoader::new(FsLoader::new(dir.path().into()), dir.path()).unwrap();
324    /// loader.invalidate();
325    /// assert_eq!(loader.generation(), 1);
326    /// ```
327    pub fn invalidate(&self) {
328        self.shared.flush(Vec::new());
329    }
330}
331
332impl<L: TemplateLoader> TemplateLoader for WatchLoader<L> {
333    fn load(&self, name: &str) -> Result<String, EngineError> {
334        if let Some(body) = self
335            .shared
336            .cache
337            .lock()
338            .unwrap_or_else(PoisonError::into_inner)
339            .get(name)
340        {
341            return Ok(body.clone());
342        }
343        // Only cache what was read before any invalidation that ran
344        // while we were reading: otherwise a stale body could outlive
345        // the change that should have evicted it.
346        let before = self.generation();
347        let body = self.inner.load(name)?;
348        let mut cache = self
349            .shared
350            .cache
351            .lock()
352            .unwrap_or_else(PoisonError::into_inner);
353        if self.generation() == before {
354            let _ = cache.insert(name.to_string(), body.clone());
355        }
356        Ok(body)
357    }
358}
359
360fn io_error(e: notify::Error) -> EngineError {
361    EngineError::Io(io::Error::other(e))
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367    use crate::engine::MemoryLoader;
368    use std::sync::atomic::AtomicUsize;
369
370    /// Counts loads so tests can see whether the cache answered.
371    struct Counting {
372        inner: MemoryLoader,
373        loads: AtomicUsize,
374    }
375
376    impl TemplateLoader for Counting {
377        fn load(&self, name: &str) -> Result<String, EngineError> {
378            let _ = self.loads.fetch_add(1, Ordering::SeqCst);
379            self.inner.load(name)
380        }
381    }
382
383    fn loader(
384        debounce: Duration,
385    ) -> (WatchLoader<Counting>, Sender<notify::Result<Event>>) {
386        let mut inner = MemoryLoader::default();
387        let _ = inner.insert("page", "v1");
388        let (tx, rx) = mpsc::channel();
389        let counting = Counting {
390            inner,
391            loads: AtomicUsize::new(0),
392        };
393        (WatchLoader::from_events(counting, rx, debounce), tx)
394    }
395
396    fn modify(path: &str) -> notify::Result<Event> {
397        Ok(Event::new(EventKind::Modify(
398            notify::event::ModifyKind::Any,
399        ))
400        .add_path(PathBuf::from(path)))
401    }
402
403    fn access(path: &str) -> notify::Result<Event> {
404        Ok(Event::new(EventKind::Access(
405            notify::event::AccessKind::Any,
406        ))
407        .add_path(PathBuf::from(path)))
408    }
409
410    /// Generous: the debounce window here is 20 ms.
411    const WAIT: Duration = Duration::from_secs(10);
412
413    #[test]
414    fn caches_until_a_change_arrives() {
415        let (l, tx) = loader(Duration::from_millis(20));
416        let changes = l.subscribe();
417        assert_eq!(l.load("page").unwrap(), "v1");
418        assert_eq!(l.load("page").unwrap(), "v1");
419        assert_eq!(l.inner.loads.load(Ordering::SeqCst), 1);
420
421        tx.send(modify("t/page.html")).unwrap();
422        let batch = changes.recv_timeout(WAIT).unwrap();
423        assert_eq!(batch, vec![PathBuf::from("t/page.html")]);
424        assert_eq!(l.generation(), 1);
425
426        assert_eq!(l.load("page").unwrap(), "v1");
427        assert_eq!(l.inner.loads.load(Ordering::SeqCst), 2);
428    }
429
430    #[test]
431    fn a_burst_becomes_one_batch() {
432        let (l, tx) = loader(Duration::from_millis(300));
433        let changes = l.subscribe();
434        for p in ["t/b.html", "t/a.html", "t/b.html"] {
435            tx.send(modify(p)).unwrap();
436        }
437        let batch = changes.recv_timeout(WAIT).unwrap();
438        assert_eq!(
439            batch,
440            vec![PathBuf::from("t/a.html"), PathBuf::from("t/b.html")]
441        );
442        assert_eq!(l.generation(), 1);
443    }
444
445    #[test]
446    fn access_events_do_not_invalidate() {
447        let (l, tx) = loader(Duration::from_millis(20));
448        let changes = l.subscribe();
449        tx.send(access("t/page.html")).unwrap();
450        // A real change afterwards is the first batch delivered.
451        tx.send(modify("t/x.html")).unwrap();
452        let batch = changes.recv_timeout(WAIT).unwrap();
453        assert_eq!(batch, vec![PathBuf::from("t/x.html")]);
454        assert_eq!(l.generation(), 1);
455    }
456
457    #[test]
458    fn an_access_only_burst_is_dropped() {
459        let (l, tx) = loader(Duration::from_millis(20));
460        let changes = l.subscribe();
461        tx.send(access("t/page.html")).unwrap();
462        drop(tx);
463        // The thread exits once the source hangs up, without a batch.
464        // (A short wait: a late batch would make this pass wrongly,
465        // never fail spuriously.)
466        assert!(changes
467            .recv_timeout(Duration::from_millis(300))
468            .is_err());
469        assert_eq!(l.generation(), 0);
470    }
471
472    #[test]
473    fn a_watcher_error_invalidates_with_no_paths() {
474        let (l, tx) = loader(Duration::from_millis(20));
475        let changes = l.subscribe();
476        tx.send(Err(notify::Error::generic("lost events"))).unwrap();
477        assert_eq!(
478            changes.recv_timeout(WAIT).unwrap(),
479            Vec::<PathBuf>::new()
480        );
481    }
482
483    #[test]
484    fn a_pending_burst_is_flushed_when_the_source_hangs_up() {
485        let (l, tx) = loader(Duration::from_secs(60));
486        let changes = l.subscribe();
487        tx.send(modify("t/page.html")).unwrap();
488        drop(tx);
489        assert_eq!(changes.recv_timeout(WAIT).unwrap().len(), 1);
490    }
491
492    #[test]
493    fn dropped_subscribers_are_forgotten() {
494        let (l, _tx) = loader(Duration::from_millis(20));
495        drop(l.subscribe());
496        l.invalidate();
497        assert!(l.shared.subscribers.lock().unwrap().is_empty());
498    }
499
500    #[test]
501    fn load_errors_pass_through_uncached() {
502        let (l, _tx) = loader(Duration::from_millis(20));
503        assert!(l.load("missing").is_err());
504        assert!(l.shared.cache.lock().unwrap().is_empty());
505        assert!(format!("{l:?}").contains("WatchLoader"));
506    }
507
508    #[test]
509    fn io_errors_wrap_notify_errors() {
510        let e = io_error(notify::Error::generic("boom"));
511        assert!(matches!(e, EngineError::Io(_)), "{e:?}");
512    }
513}