1use 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
34pub const DEFAULT_DEBOUNCE: Duration = Duration::from_millis(200);
44
45#[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 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#[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
102fn 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
123fn 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
141pub struct WatchLoader<L> {
163 inner: L,
164 shared: Arc<Shared>,
165 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 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 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 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 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 #[must_use]
309 pub fn generation(&self) -> u64 {
310 self.shared.generation.load(Ordering::SeqCst)
311 }
312
313 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 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 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 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 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 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}