mdo_cli/watch.rs
1//! Watch-mode mechanics, behind one interface: folder watching, event
2//! relevance, and the trailing-edge debounce.
3//!
4//! The module owns exactly the three mechanics `mdo --watch` needs; the
5//! render itself and how the CLI reports it belong to the caller, passed as
6//! a render callback. `watch::run` registers the watch, runs the callback
7//! once immediately, and then once per settled quiet window whenever the
8//! watched file plausibly changed content. A callback `Err` (e.g. a
9//! transient filesystem state mid-rename) is ignored and never ends watch
10//! mode, matching the CLI's contract; channel death ends the watch
11//! gracefully.
12//!
13//! Both the debounce timing and the loop clock are injectable at the pump
14//! level, so unit tests script fake event channels with a virtual clock and
15//! cover burst collapse, late events, sibling noise, watcher error storms,
16//! and channel death cross-platform by construction.
17
18use std::ffi::OsStr;
19use std::path::{Path, PathBuf};
20use std::sync::mpsc::{self, channel, RecvError, RecvTimeoutError};
21use std::time::{Duration, Instant};
22
23use notify::{recommended_watcher, Event, EventKind, RecursiveMode, Watcher};
24
25use crate::RenderError;
26
27/// Trailing-edge debounce window: once a relevant event arrives the pump
28/// keeps draining/absorbing further relevant events for this long before
29/// rendering, so a burst (e.g. truncate + write, or temp-file write +
30/// rename) collapses into exactly one render of the final content. This is
31/// unlike a leading-edge "ignore anything for N ms after the last render"
32/// debounce, which can drop the trailing event of a burst if the burst runs
33/// longer than the window.
34const DEFAULT_DEBOUNCE: Duration = Duration::from_millis(200);
35
36/// Run watch mode for `input`: register a parent-directory watch, run
37/// `render` once immediately, then re-run it once per settled burst of
38/// events that plausibly changed the file's content.
39///
40/// `render` runs once immediately — before any event is seen — so callers
41/// that must do a one-time thing after the initial render (e.g. the
42/// `--open` browser launch) guard that in their own callback state. Its
43/// `Err` is ignored: a failed render must never end watch mode.
44///
45/// Errors propagate only from registration itself, before any render: a
46/// watch we cannot deliver aborts up front rather than rendering once and
47/// failing later. Once pumping, the loop returns `Ok(())` only when the
48/// watcher channel dies; it otherwise runs until killed.
49pub fn run<F: FnMut() -> Result<(), RenderError>>(
50 input: &Path,
51 render: &mut F,
52) -> notify::Result<()> {
53 // Watch the parent DIRECTORY rather than the file itself. Editors that
54 // save atomically (write a temp file, then rename it over the target)
55 // replace the target's inode; a watch on the file itself goes dead the
56 // moment that happens because the inode/handle notify was watching is
57 // gone. Watching the directory survives renames, deletes, and recreates
58 // — we just have to filter directory events down to ones that touch our
59 // target file.
60 //
61 // Resolve the target once, up front. Comparing later events against
62 // this fixed absolute path — rather than re-canonicalizing each event's
63 // path — matters because the target may momentarily not exist
64 // mid-rename, which would make canonicalize fail and misclassify a
65 // perfectly relevant event.
66 //
67 // Known limitation: canonicalizing a symlinked input means we watch the
68 // TARGET's parent, so edits made through the link are seen, but an
69 // editor atomically replacing the symlink itself is not. Watching both
70 // parents isn't worth the complexity until someone actually hits this.
71 let input_absolute = std::fs::canonicalize(input).unwrap_or_else(|_| {
72 std::env::current_dir()
73 .map(|cwd| cwd.join(input))
74 .unwrap_or_else(|_| input.to_path_buf())
75 });
76 let watch_dir = input_absolute
77 .parent()
78 .map(PathBuf::from)
79 .unwrap_or_else(|| PathBuf::from("."));
80 let target_file_name = input_absolute.file_name().map(|n| n.to_os_string());
81
82 // Register the watch BEFORE the initial render so a save that lands
83 // while that render runs is queued by the watcher rather than silently
84 // lost; the pump below drains it and re-renders. Registration
85 // failure aborts before any rendering, which is fine — the user asked
86 // for a watch we cannot deliver.
87
88 let (tx, rx) = channel();
89 let mut watcher = recommended_watcher(tx)?;
90 watcher.watch(&watch_dir, RecursiveMode::NonRecursive)?;
91
92 let _ = render();
93
94 // Still named after the file, not the directory: that's what the user
95 // asked to watch, even though the underlying notify watch is scoped one
96 // level up.
97 println!("👀 Watching {:?} for changes... (Ctrl+C to stop)", input);
98
99 pump(
100 &rx,
101 &watch_dir,
102 target_file_name.as_deref(),
103 render,
104 DEFAULT_DEBOUNCE,
105 &SystemClock,
106 );
107 Ok(())
108}
109
110/// The event pump: block for the next event, skip everything that isn't a
111/// relevant change to the target file, drain/absorb bursts through the
112/// trailing-edge debounce window, then render once per settled burst.
113///
114/// `debounce` and `clock` are the injectable timing seams (unit tests
115/// script relative arrival times against a virtual clock; production uses
116/// the system monotonic clock).
117fn pump<R: EventRx, F: FnMut() -> Result<(), RenderError>, C: Clock>(
118 rx: &R,
119 watch_dir: &Path,
120 target_file_name: Option<&OsStr>,
121 render: &mut F,
122 debounce: Duration,
123 clock: &C,
124) {
125 loop {
126 // Block for the next event. Anything that isn't a relevant,
127 // content-changing event (wrong file, Access events, watcher
128 // errors) is skipped without starting a debounce window.
129 let event = match rx.recv() {
130 Ok(Ok(event)) => event,
131 Ok(Err(e)) => {
132 eprintln!("⚠️ Watcher error: {}", e);
133 continue;
134 }
135 Err(_) => return, // watcher/channel gone; nothing left to watch
136 };
137
138 if !is_relevant_event(&event, target_file_name, watch_dir) {
139 continue;
140 }
141
142 // Drain/absorb further relevant events for a quiet window, then
143 // render once. This covers direct writes, truncate+rewrite, and
144 // atomic saves (temp file write followed by a rename onto the
145 // target) uniformly: whichever event kinds the editor and platform
146 // happen to emit (Create, Modify, Rename-as-Modify(Name), Remove
147 // followed by a Create), each just extends the quiet window until
148 // the burst settles. Only RELEVANT events extend the deadline:
149 // sibling-file noise merely waits out the remaining window, so a
150 // busy directory (a build churning artifacts next to the watched
151 // file) cannot postpone the render indefinitely.
152 let mut deadline = clock.now() + debounce;
153 loop {
154 let remaining = deadline.saturating_duration_since(clock.now());
155 if remaining.is_zero() {
156 break;
157 }
158 match rx.recv_timeout(remaining) {
159 Ok(Ok(event)) => {
160 if is_relevant_event(&event, target_file_name, watch_dir) {
161 deadline = clock.now() + debounce;
162 }
163 // Irrelevant events neither extend nor cut the window.
164 }
165 Ok(Err(e)) => eprintln!("⚠️ Watcher error: {}", e),
166 Err(_) => break, // quiet window elapsed (or channel closed)
167 }
168 }
169
170 println!("🔁 File changed, re-rendering...");
171 // A failed render (e.g. one that ran while the file was momentarily
172 // absent mid-rename) must not end watch mode; its reporting already
173 // happened inside the callback, so just loop and wait for the next
174 // event.
175 let _ = render();
176 }
177}
178
179/// True if `event` plausibly changed the content of the file named
180/// `target_file_name` inside `watch_dir`. We match by file name (and, when
181/// notify reports one, by parent directory) rather than canonicalizing the
182/// event's path, since the target can momentarily not exist mid-rename.
183/// Access events (reads, permission-bit-only changes) are excluded; every
184/// other kind (Create, Modify, Remove, Any, Other) is treated as a possible
185/// content change so recreation-after-remove and atomic renames are all
186/// covered by the same check.
187fn is_relevant_event(event: &Event, target_file_name: Option<&OsStr>, watch_dir: &Path) -> bool {
188 if matches!(event.kind, EventKind::Access(_)) {
189 return false;
190 }
191
192 let Some(target_file_name) = target_file_name else {
193 return false;
194 };
195
196 event.paths.iter().any(|p| {
197 p.file_name() == Some(target_file_name)
198 && match p.parent() {
199 Some(parent) => parent == watch_dir,
200 None => true,
201 }
202 })
203}
204
205/// One item on the watch event channel: a real event, or a watcher-level
206/// error delivered as a channel payload (the queue keeps flowing either
207/// way).
208type EventItem = Result<Event, notify::Error>;
209
210/// The receiving half of the watch event channel narrowed to the exact
211/// shape the pump uses. Abstracted so unit tests script fake sequences.
212trait EventRx {
213 fn recv(&self) -> Result<EventItem, RecvError>;
214 fn recv_timeout(&self, timeout: Duration) -> Result<EventItem, RecvTimeoutError>;
215}
216
217impl EventRx for mpsc::Receiver<EventItem> {
218 fn recv(&self) -> Result<EventItem, RecvError> {
219 mpsc::Receiver::recv(self)
220 }
221
222 fn recv_timeout(&self, timeout: Duration) -> Result<EventItem, RecvTimeoutError> {
223 mpsc::Receiver::recv_timeout(self, timeout)
224 }
225}
226
227/// Where the pump reads its clock. Production uses the system monotonic
228/// clock; tests inject a virtual one.
229trait Clock {
230 fn now(&self) -> Instant;
231}
232
233struct SystemClock;
234
235impl Clock for SystemClock {
236 fn now(&self) -> Instant {
237 Instant::now()
238 }
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244 use std::cell::Cell;
245 use std::cell::RefCell;
246 use std::collections::VecDeque;
247 use std::rc::Rc;
248
249 use notify::event::{AccessKind, ModifyKind};
250
251 /// Virtual monotonic clock shared with the fake channel: entries in a
252 /// script declare how long after "now" their payload is ready.
253 #[derive(Clone)]
254 struct VirtualClock(Rc<Cell<Instant>>);
255
256 impl VirtualClock {
257 fn new() -> Self {
258 Self(Rc::new(Cell::new(Instant::now())))
259 }
260
261 fn advance(&self, by: Duration) {
262 self.0.set(self.0.get() + by);
263 }
264 }
265
266 impl Clock for VirtualClock {
267 fn now(&self) -> Instant {
268 self.0.get()
269 }
270 }
271
272 /// One scripted channel entry: a payload plus how long after the
273 /// current virtual time it becomes available.
274 struct Scripted {
275 ready_after: Duration,
276 payload: EventItem,
277 }
278
279 /// Fake channel half driving `pump` from a script. Events ready within
280 /// the polled timeout are delivered on that poll; anything later goes
281 /// past the window (timed out), exactly as a real channel would.
282 struct FakeRx {
283 clock: VirtualClock,
284 script: RefCell<VecDeque<Scripted>>,
285 }
286
287 impl FakeRx {
288 fn now_or_elapsed(&self, timeout: Duration) -> Result<EventItem, RecvTimeoutError> {
289 let next = self.script.borrow().front().map(|s| s.ready_after);
290 match next {
291 Some(ready_after) if ready_after <= timeout => {
292 self.clock.advance(ready_after);
293 let scripted = self
294 .script
295 .borrow_mut()
296 .pop_front()
297 .expect("front checked above");
298 Ok(scripted.payload)
299 }
300 _ => {
301 self.clock.advance(timeout);
302 Err(RecvTimeoutError::Timeout)
303 }
304 }
305 }
306 }
307
308 impl EventRx for FakeRx {
309 fn recv(&self) -> Result<EventItem, RecvError> {
310 match self.script.borrow_mut().pop_front() {
311 Some(scripted) => {
312 self.clock.advance(scripted.ready_after);
313 Ok(scripted.payload)
314 }
315 None => Err(RecvError),
316 }
317 }
318
319 fn recv_timeout(&self, timeout: Duration) -> Result<EventItem, RecvTimeoutError> {
320 self.now_or_elapsed(timeout)
321 }
322 }
323
324 fn event_ready_after(ready_after: u64, kind: EventKind, path: PathBuf) -> Scripted {
325 Scripted {
326 ready_after: Duration::from_millis(ready_after),
327 payload: Ok(Event::new(kind).add_path(path)),
328 }
329 }
330
331 fn watcher_error_after(ready_after: u64) -> Scripted {
332 Scripted {
333 ready_after: Duration::from_millis(ready_after),
334 payload: Err(notify::Error::io(std::io::Error::other("watcher failed"))),
335 }
336 }
337
338 /// A content-changing event for `name` inside `watch_dir`.
339 fn modify(name: &str, watch_dir: &Path, ready_after: u64) -> Scripted {
340 event_ready_after(
341 ready_after,
342 EventKind::Modify(ModifyKind::Any),
343 watch_dir.join(name),
344 )
345 }
346
347 /// A change to a file that is not the watched target.
348 fn sibling(name: &str, watch_dir: &Path, ready_after: u64) -> Scripted {
349 event_ready_after(
350 ready_after,
351 EventKind::Modify(ModifyKind::Any),
352 watch_dir.join(name),
353 )
354 }
355
356 fn access(watch_dir: &Path, ready_after: u64) -> Scripted {
357 event_ready_after(
358 ready_after,
359 EventKind::Access(AccessKind::Any),
360 watch_dir.join("sample.md"),
361 )
362 }
363
364 /// Pump over a script, counting renders in the callback.
365 fn pump_scripted(script: Vec<Scripted>) -> (usize, VirtualClock) {
366 let clock = VirtualClock::new();
367 let renders = Rc::new(Cell::new(0_usize));
368 let rx = FakeRx {
369 clock: clock.clone(),
370 script: RefCell::new(script.into()),
371 };
372 pump(
373 &rx,
374 Path::new("/watch"),
375 Some(OsStr::new("sample.md")),
376 &mut || {
377 renders.set(renders.get() + 1);
378 Ok(())
379 },
380 Duration::from_millis(200),
381 &clock,
382 );
383 (renders.get(), clock)
384 }
385
386 #[test]
387 fn burst_collapses_into_one_render() {
388 // Three events inside one window: one render of the final content.
389 let (renders, _clock) = pump_scripted(vec![
390 modify("sample.md", Path::new("/watch"), 50),
391 modify("sample.md", Path::new("/watch"), 70),
392 modify("sample.md", Path::new("/watch"), 60),
393 ]);
394 assert_eq!(renders, 1, "a settled burst renders exactly once");
395 }
396
397 #[test]
398 fn burst_running_longer_than_window_still_renders_the_trailing_event() {
399 // Events every 80ms outrun a 200ms quiet window for a while; no
400 // render fires mid-burst — the trailing event is never dropped.
401 let (renders, _clock) = pump_scripted(vec![
402 modify("sample.md", Path::new("/watch"), 50),
403 modify("sample.md", Path::new("/watch"), 80),
404 modify("sample.md", Path::new("/watch"), 80),
405 modify("sample.md", Path::new("/watch"), 80),
406 modify("sample.md", Path::new("/watch"), 80),
407 ]);
408 assert_eq!(renders, 1, "a long burst settles into exactly one render");
409 }
410
411 #[test]
412 fn event_after_the_window_renders_again() {
413 // One burst, then quiet past the window, then another event: the
414 // first event settles into render one; the late event is NOT
415 // dropped — it becomes the next outer event and renders again.
416 let (renders, _clock) = pump_scripted(vec![
417 modify("sample.md", Path::new("/watch"), 50),
418 modify("sample.md", Path::new("/watch"), 700),
419 ]);
420 assert_eq!(renders, 2, "events after the window are fresh triggers");
421 }
422
423 #[test]
424 fn sibling_noise_renders_nothing() {
425 // Sibling-file churn alone never triggers or extends a window.
426 let (renders, _clock) = pump_scripted(vec![
427 sibling("other.md", Path::new("/watch"), 50),
428 sibling("build.log", Path::new("/watch"), 80),
429 ]);
430 assert_eq!(renders, 0, "no target file in any event, no render");
431 }
432
433 #[test]
434 fn sibling_noise_waits_out_but_does_not_extend_the_window() {
435 // A sibling event arriving well past the current window cannot
436 // extend the deadline: the pump waits out only the remaining window
437 // (bounded by one debounce) and renders; the sibling is then seen
438 // as the next outer event, classified irrelevant, and skipped.
439 let (renders, _clock) = pump_scripted(vec![
440 modify("sample.md", Path::new("/watch"), 50),
441 sibling("other.md", Path::new("/watch"), 1000),
442 ]);
443 assert_eq!(renders, 1, "the sibling burst never postponed the render");
444 }
445
446 #[test]
447 fn access_events_are_never_relevant() {
448 let (renders, _clock) = pump_scripted(vec![access(Path::new("/watch"), 50)]);
449 assert_eq!(renders, 0, "Access events are excluded");
450 }
451
452 #[test]
453 fn channel_death_before_any_event_ends_the_watch_gracefully() {
454 let (renders, _clock) = pump_scripted(vec![]);
455 assert_eq!(renders, 0);
456 }
457
458 #[test]
459 fn channel_death_during_drain_renders_and_exits() {
460 // An event lands, the window is open, the channel dies: the
461 // pending burst still renders, then the watch ends.
462 let (renders, _clock) = pump_scripted(vec![modify("sample.md", Path::new("/watch"), 50)]);
463 assert_eq!(renders, 1);
464 }
465
466 #[test]
467 fn watcher_error_storm_renders_nothing_and_survives() {
468 let script: Vec<Scripted> = (0..50u64)
469 .map(|i| watcher_error_after(i * 10 + 1))
470 .collect();
471 let (renders, _clock) = pump_scripted(script);
472 assert_eq!(renders, 0, "watcher errors are not renders");
473 }
474
475 #[test]
476 fn watcher_errors_inside_the_drain_do_not_extend_the_window() {
477 // Errors arriving inside a window neither extend nor cut it: they
478 // wait out the remaining window like any other noise.
479 let script = vec![
480 modify("sample.md", Path::new("/watch"), 50),
481 watcher_error_after(60),
482 watcher_error_after(60),
483 ];
484 let (renders, _clock) = pump_scripted(script);
485 assert_eq!(renders, 1);
486 }
487
488 #[test]
489 fn callback_errors_never_end_watch_mode() {
490 // A render callback that reports a transient filesystem failure
491 // (e.g. the file was absent mid-rename) must not end watch mode.
492 let clock = VirtualClock::new();
493 let renders = Rc::new(Cell::new(0_usize));
494 let failures = Rc::new(Cell::new(0_usize));
495 let rx = FakeRx {
496 clock: clock.clone(),
497 script: RefCell::new(
498 vec![
499 // Two bursts separated past the window: render One and
500 // render two must BOTH happen for the errors never to
501 // have ended watch mode.
502 modify("sample.md", Path::new("/watch"), 50),
503 modify("sample.md", Path::new("/watch"), 700),
504 ]
505 .into(),
506 ),
507 };
508 let renders_flag = renders.clone();
509 let failures_flag = failures.clone();
510 pump(
511 &rx,
512 Path::new("/watch"),
513 Some(OsStr::new("sample.md")),
514 &mut || {
515 renders_flag.set(renders_flag.get() + 1);
516 failures_flag.set(failures_flag.get() + 1);
517 Err(RenderError::Read {
518 path: PathBuf::from("/watch/sample.md"),
519 source: std::io::Error::other("transient"),
520 })
521 },
522 Duration::from_millis(200),
523 &clock,
524 );
525 assert_eq!(renders.get(), 2, "every burst was rendered");
526 assert_eq!(failures.get(), 2, "every callback Err surfaced to it");
527 }
528
529 #[test]
530 fn relevance_requires_name_and_parent_match() {
531 let watch_dir = Path::new("/watch");
532 let named = Some(OsStr::new("sample.md"));
533
534 let same_dir =
535 Event::new(EventKind::Modify(ModifyKind::Any)).add_path(watch_dir.join("sample.md"));
536 assert!(is_relevant_event(&same_dir, named, watch_dir));
537
538 // A bare relative path has parent Some("") — never equal to a real
539 // watch dir, so it is not relevant. Real events carry absolute
540 // paths, so this only matters to the filter's strictness, not to
541 // production labeling.
542 let bare_relative =
543 Event::new(EventKind::Modify(ModifyKind::Any)).add_path(PathBuf::from("sample.md"));
544 assert!(!is_relevant_event(&bare_relative, named, watch_dir));
545
546 let other_dir = Event::new(EventKind::Modify(ModifyKind::Any))
547 .add_path(PathBuf::from("/elsewhere/sample.md"));
548 assert!(!is_relevant_event(&other_dir, named, watch_dir));
549
550 let other_name =
551 Event::new(EventKind::Modify(ModifyKind::Any)).add_path(watch_dir.join("other.md"));
552 assert!(!is_relevant_event(&other_name, named, watch_dir));
553
554 // No resolvable target: nothing is ever relevant.
555 let none: Option<&OsStr> = None;
556 assert!(!is_relevant_event(&same_dir, none, watch_dir));
557 }
558}