1use 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
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 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 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 for root in self.roots.read().await.iter() {
92 let _ = watcher.unwatch(root);
93 }
94 }
95 }
96
97 pub async fn add_root(&mut self, path: PathBuf) -> Result<()> {
99 self.roots.write().await.insert(path.clone());
100
101 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 pub async fn remove_root(&mut self, path: &Path) -> Result<()> {
113 self.roots.write().await.remove(path);
114
115 if let Some(watcher) = &mut self.notify_watcher {
117 let _ = watcher.unwatch(path);
118 }
119
120 Ok(())
121 }
122
123 pub async fn roots(&self) -> Vec<PathBuf> {
125 self.roots.read().await.iter().cloned().collect()
126 }
127
128 fn handle_event(
130 event: Event,
131 roots: Arc<RwLock<HashSet<PathBuf>>>,
132 event_tx: mpsc::Sender<Vec<PathBuf>>,
133 ) {
134 let relevant = matches!(
136 event.kind,
137 EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
138 );
139
140 if !relevant {
141 return;
142 }
143
144 let current_roots = match roots.try_read() {
146 Ok(r) => r.clone(),
147 Err(_) => return, };
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 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; loop {
172 tokio::select! {
173 Some(paths) = event_rx.recv() => {
175 pending_paths.extend(paths);
176 }
177 _ = debounce_timer.tick() => {
179 if !pending_paths.is_empty() {
180 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}