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::{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 debounce_handle = tokio::spawn(async move {
76            Self::debounce_loop(event_rx, sender, Duration::from_millis(debounce_ms)).await;
77        });
78        self.debounce_handle = Some(debounce_handle);
79
80        Ok(())
81    }
82
83    /// Stop the watcher gracefully.
84    pub async fn stop(&mut self) {
85        if let Some(handle) = self.debounce_handle.take() {
86            handle.abort();
87            let _ = handle.await;
88        }
89        if let Some(mut watcher) = self.notify_watcher.take() {
90            // notify has no unwatch_all: remove each watched root explicitly.
91            for root in self.roots.read().await.iter() {
92                let _ = watcher.unwatch(root);
93            }
94        }
95    }
96
97    /// Add a root to watch.
98    pub async fn add_root(&mut self, path: PathBuf) -> Result<()> {
99        self.roots.write().await.insert(path.clone());
100
101        // If watcher is already running, add watch for new root
102        if let Some(watcher) = &mut self.notify_watcher {
103            if path.exists() {
104                watcher.watch(&path, RecursiveMode::Recursive)?;
105            }
106        }
107
108        Ok(())
109    }
110
111    /// Remove a root from watching.
112    pub async fn remove_root(&mut self, path: &Path) -> Result<()> {
113        self.roots.write().await.remove(path);
114
115        // If watcher is already running, remove watch
116        if let Some(watcher) = &mut self.notify_watcher {
117            let _ = watcher.unwatch(path);
118        }
119
120        Ok(())
121    }
122
123    /// Get current watched roots.
124    pub async fn roots(&self) -> Vec<PathBuf> {
125        self.roots.read().await.iter().cloned().collect()
126    }
127
128    /// Handle a notify event and send relevant paths to the event channel.
129    fn handle_event(
130        event: Event,
131        roots: Arc<RwLock<HashSet<PathBuf>>>,
132        event_tx: mpsc::Sender<Vec<PathBuf>>,
133    ) {
134        // Only care about create, modify, remove events
135        let relevant = matches!(
136            event.kind,
137            EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
138        );
139
140        if !relevant {
141            return;
142        }
143
144        // Filter paths to only those under watched roots
145        let current_roots = match roots.try_read() {
146            Ok(r) => r.clone(),
147            Err(_) => return, // Skip if locked
148        };
149
150        let relevant_paths: Vec<PathBuf> = event
151            .paths
152            .into_iter()
153            .filter(|p| current_roots.iter().any(|root| p.starts_with(root)))
154            .collect();
155
156        if !relevant_paths.is_empty() {
157            let _ = event_tx.try_send(relevant_paths);
158        }
159    }
160
161    /// Debounce loop: collect events for debounce_ms, then send batched IndexRoots.
162    async fn debounce_loop(
163        mut event_rx: mpsc::Receiver<Vec<PathBuf>>,
164        sender: mpsc::Sender<DaemonRequest>,
165        debounce_duration: Duration,
166    ) {
167        let mut pending_paths = Vec::new();
168        let mut debounce_timer = interval(debounce_duration);
169        debounce_timer.tick().await; // Align to interval
170
171        loop {
172            tokio::select! {
173                // Collect events
174                Some(paths) = event_rx.recv() => {
175                    pending_paths.extend(paths);
176                }
177                // Debounce timer fired - send batched request
178                _ = debounce_timer.tick() => {
179                    if !pending_paths.is_empty() {
180                        // Deduplicate paths
181                        pending_paths.sort();
182                        pending_paths.dedup();
183
184                        tracing::debug!("Watcher: triggering index for {} changed paths", pending_paths.len());
185
186                        let request = DaemonRequest::IndexRoots { roots: pending_paths.clone() };
187                        if sender.send(request).await.is_err() {
188                            tracing::warn!("Watcher: channel closed, stopping");
189                            break;
190                        }
191
192                        pending_paths.clear();
193                    }
194                }
195            }
196        }
197    }
198}