Skip to main content

paper/daemon/
watcher.rs

1//! File system watcher with debouncing.
2//!
3//! Uses `notify` to watch for file changes, debounces events (default 250ms),
4//! and batches them into a single `IndexRoots` request.
5
6use crate::daemon::ipc::DaemonRequest;
7use anyhow::Result;
8use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher as NotifyWatcher};
9use std::collections::HashSet;
10use std::path::{Component, Path, PathBuf};
11use std::sync::Arc;
12use std::time::Duration;
13use tokio::sync::{mpsc, RwLock};
14use tokio::time::interval;
15
16/// File system watcher with debouncing.
17pub struct Watcher {
18    roots: Arc<RwLock<HashSet<PathBuf>>>,
19    debounce_ms: u64,
20    sender: mpsc::Sender<DaemonRequest>,
21    /// Internal notify watcher
22    notify_watcher: Option<RecommendedWatcher>,
23    /// Handle to the debounce task
24    debounce_handle: Option<tokio::task::JoinHandle<()>>,
25}
26
27impl Watcher {
28    /// Create a new watcher.
29    ///
30    /// - `debounce_ms`: Debounce time in milliseconds (default: 250ms)
31    /// - `sender`: Channel to send indexing requests to the daemon
32    pub fn new(debounce_ms: u64, sender: mpsc::Sender<DaemonRequest>) -> Self {
33        Self {
34            roots: Arc::new(RwLock::new(HashSet::new())),
35            debounce_ms,
36            sender,
37            notify_watcher: None,
38            debounce_handle: None,
39        }
40    }
41
42    /// Create a watcher with default settings (250ms debounce).
43    pub fn default(sender: mpsc::Sender<DaemonRequest>) -> Self {
44        Self::new(250, sender)
45    }
46
47    /// Start the watcher.
48    pub async fn start(&mut self) -> Result<()> {
49        let (event_tx, event_rx) = mpsc::channel::<Vec<PathBuf>>(100);
50        let roots = self.roots.clone();
51        let debounce_ms = self.debounce_ms;
52
53        // Create the notify watcher
54        let mut watcher = RecommendedWatcher::new(
55            move |res: Result<Event, notify::Error>| {
56                if let Ok(event) = res {
57                    Self::handle_event(event, roots.clone(), event_tx.clone());
58                }
59            },
60            notify::Config::default(),
61        )?;
62
63        // Watch current roots
64        let current_roots = self.roots.read().await.clone();
65        for root in &current_roots {
66            if root.exists() {
67                watcher.watch(root, RecursiveMode::Recursive)?;
68            }
69        }
70
71        self.notify_watcher = Some(watcher);
72
73        // Start debounce task
74        let sender = self.sender.clone();
75        let roots = self.roots.clone();
76        let debounce_handle = tokio::spawn(async move {
77            Self::debounce_loop(event_rx, sender, roots, Duration::from_millis(debounce_ms)).await;
78        });
79        self.debounce_handle = Some(debounce_handle);
80
81        Ok(())
82    }
83
84    /// Stop the watcher gracefully.
85    pub async fn stop(&mut self) {
86        if let Some(handle) = self.debounce_handle.take() {
87            handle.abort();
88            let _ = handle.await;
89        }
90        if let Some(mut watcher) = self.notify_watcher.take() {
91            // notify has no unwatch_all: remove each watched root explicitly.
92            for root in self.roots.read().await.iter() {
93                let _ = watcher.unwatch(root);
94            }
95        }
96    }
97
98    /// Add a root to watch.
99    pub async fn add_root(&mut self, path: PathBuf) -> Result<()> {
100        self.roots.write().await.insert(path.clone());
101
102        // If watcher is already running, add watch for new root
103        if let Some(watcher) = &mut self.notify_watcher {
104            if path.exists() {
105                watcher.watch(&path, RecursiveMode::Recursive)?;
106            }
107        }
108
109        Ok(())
110    }
111
112    /// Remove a root from watching.
113    pub async fn remove_root(&mut self, path: &Path) -> Result<()> {
114        self.roots.write().await.remove(path);
115
116        // If watcher is already running, remove watch
117        if let Some(watcher) = &mut self.notify_watcher {
118            let _ = watcher.unwatch(path);
119        }
120
121        Ok(())
122    }
123
124    /// Get current watched roots.
125    pub async fn roots(&self) -> Vec<PathBuf> {
126        self.roots.read().await.iter().cloned().collect()
127    }
128
129    /// Handle a notify event and send relevant paths to the event channel.
130    fn handle_event(
131        event: Event,
132        roots: Arc<RwLock<HashSet<PathBuf>>>,
133        event_tx: mpsc::Sender<Vec<PathBuf>>,
134    ) {
135        // Only care about create, modify, remove events
136        let relevant = matches!(
137            event.kind,
138            EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
139        );
140
141        if !relevant {
142            return;
143        }
144
145        // Filter paths to only those under watched roots
146        let current_roots = match roots.try_read() {
147            Ok(r) => r.clone(),
148            Err(_) => return, // Skip if locked
149        };
150
151        let relevant_paths: Vec<PathBuf> = event
152            .paths
153            .into_iter()
154            .filter(|p| current_roots.iter().any(|root| p.starts_with(root)))
155            .collect();
156
157        if !relevant_paths.is_empty() {
158            // `try_send` is non-blocking because `handle_event` runs in the
159            // notify callback thread. Log when the channel is full so dropped
160            // events are visible instead of silent (IL).
161            let count = relevant_paths.len();
162            if event_tx.try_send(relevant_paths).is_err() {
163                tracing::warn!("Watcher: event channel full, dropped {} events", count);
164            }
165        }
166    }
167
168    /// Debounce loop: collect events for debounce_ms, then send batched IndexRoots.
169    async fn debounce_loop(
170        mut event_rx: mpsc::Receiver<Vec<PathBuf>>,
171        sender: mpsc::Sender<DaemonRequest>,
172        roots: Arc<RwLock<HashSet<PathBuf>>>,
173        debounce_duration: Duration,
174    ) {
175        let mut pending_paths = Vec::new();
176        let mut debounce_timer = interval(debounce_duration);
177        debounce_timer.tick().await; // Align to interval
178
179        loop {
180            tokio::select! {
181                // Collect events
182                Some(paths) = event_rx.recv() => {
183                    pending_paths.extend(paths);
184                }
185                // Debounce timer fired - send batched request
186                _ = debounce_timer.tick() => {
187                    if !pending_paths.is_empty() {
188                        // Deduplicate paths
189                        pending_paths.sort();
190                        pending_paths.dedup();
191                        // Checked at send time, not event time, so a folder swapped
192                        // for a symlink during the debounce window is still caught.
193                        let current_roots = roots.read().await.clone();
194                        pending_paths.retain(|p| {
195                            current_roots.iter().any(|root| reachable_from_root(root, p))
196                        });
197                        if pending_paths.is_empty() {
198                            continue;
199                        }
200
201                        tracing::debug!("Watcher: triggering index for {} changed paths", pending_paths.len());
202
203                        let request = DaemonRequest::IndexRoots { roots: pending_paths.clone() };
204                        if sender.send(request).await.is_err() {
205                            tracing::warn!("Watcher: channel closed, stopping");
206                            break;
207                        }
208
209                        pending_paths.clear();
210                    }
211                }
212            }
213        }
214    }
215}
216
217/// True when `path` lies under `root` through real directories only: no `..`
218/// and no symlink at or below the root, because the indexer follows a symlinked
219/// index root out of the watched tree. A prefix that no longer exists passes,
220/// so Remove events still reach the indexer.
221fn reachable_from_root(root: &Path, path: &Path) -> bool {
222    let Ok(rel) = path.strip_prefix(root) else {
223        return false;
224    };
225    let mut cur = root.to_path_buf();
226    rel.components().all(|c| {
227        cur.push(c);
228        matches!(c, Component::Normal(_))
229            && !cur
230                .symlink_metadata()
231                .is_ok_and(|m| m.file_type().is_symlink())
232    })
233}
234
235#[cfg(all(test, unix))]
236mod tests {
237    use super::reachable_from_root;
238
239    #[test]
240    fn only_paths_the_walk_would_reach_become_index_roots() {
241        let tmp = tempfile::tempdir().unwrap();
242        let root = tmp.path().join("root");
243        let outside = tmp.path().join(".config");
244        std::fs::create_dir_all(root.join(".private")).unwrap();
245        std::fs::create_dir_all(&outside).unwrap();
246        std::fs::write(root.join(".private/notes.md"), "x").unwrap();
247        std::os::unix::fs::symlink(&outside, root.join("docs")).unwrap();
248
249        assert!(reachable_from_root(&root, &root.join("a.md")));
250        assert!(reachable_from_root(&root, &root.join(".private/notes.md")));
251        assert!(reachable_from_root(&root, &root.join("gone/deleted.md")));
252        assert!(!reachable_from_root(&root, &root.join("docs")));
253        assert!(!reachable_from_root(&root, &root.join("docs/secret.md")));
254        assert!(!reachable_from_root(&root, &root.join("../.config")));
255        assert!(!reachable_from_root(&root, &outside));
256    }
257}