1use 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
16pub struct Watcher {
18 roots: Arc<RwLock<HashSet<PathBuf>>>,
19 debounce_ms: u64,
20 sender: mpsc::Sender<DaemonRequest>,
21 notify_watcher: Option<RecommendedWatcher>,
23 debounce_handle: Option<tokio::task::JoinHandle<()>>,
25}
26
27impl Watcher {
28 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 pub fn default(sender: mpsc::Sender<DaemonRequest>) -> Self {
44 Self::new(250, sender)
45 }
46
47 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 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 let current_roots = self.roots.read().await.clone();
65 for root in ¤t_roots {
66 if root.exists() {
67 watcher.watch(root, RecursiveMode::Recursive)?;
68 }
69 }
70
71 self.notify_watcher = Some(watcher);
72
73 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 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 for root in self.roots.read().await.iter() {
93 let _ = watcher.unwatch(root);
94 }
95 }
96 }
97
98 pub async fn add_root(&mut self, path: PathBuf) -> Result<()> {
100 self.roots.write().await.insert(path.clone());
101
102 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 pub async fn remove_root(&mut self, path: &Path) -> Result<()> {
114 self.roots.write().await.remove(path);
115
116 if let Some(watcher) = &mut self.notify_watcher {
118 let _ = watcher.unwatch(path);
119 }
120
121 Ok(())
122 }
123
124 pub async fn roots(&self) -> Vec<PathBuf> {
126 self.roots.read().await.iter().cloned().collect()
127 }
128
129 fn handle_event(
131 event: Event,
132 roots: Arc<RwLock<HashSet<PathBuf>>>,
133 event_tx: mpsc::Sender<Vec<PathBuf>>,
134 ) {
135 let relevant = matches!(
137 event.kind,
138 EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
139 );
140
141 if !relevant {
142 return;
143 }
144
145 let current_roots = match roots.try_read() {
147 Ok(r) => r.clone(),
148 Err(_) => return, };
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 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 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; loop {
180 tokio::select! {
181 Some(paths) = event_rx.recv() => {
183 pending_paths.extend(paths);
184 }
185 _ = debounce_timer.tick() => {
187 if !pending_paths.is_empty() {
188 pending_paths.sort();
190 pending_paths.dedup();
191 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
217fn 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}