use crate::daemon::ipc::DaemonRequest;
use anyhow::Result;
use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher as NotifyWatcher};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, RwLock};
use tokio::time::interval;
pub struct Watcher {
roots: Arc<RwLock<HashSet<PathBuf>>>,
debounce_ms: u64,
sender: mpsc::Sender<DaemonRequest>,
notify_watcher: Option<RecommendedWatcher>,
debounce_handle: Option<tokio::task::JoinHandle<()>>,
}
impl Watcher {
pub fn new(debounce_ms: u64, sender: mpsc::Sender<DaemonRequest>) -> Self {
Self {
roots: Arc::new(RwLock::new(HashSet::new())),
debounce_ms,
sender,
notify_watcher: None,
debounce_handle: None,
}
}
pub fn default(sender: mpsc::Sender<DaemonRequest>) -> Self {
Self::new(250, sender)
}
pub async fn start(&mut self) -> Result<()> {
let (event_tx, event_rx) = mpsc::channel::<Vec<PathBuf>>(100);
let roots = self.roots.clone();
let debounce_ms = self.debounce_ms;
let mut watcher = RecommendedWatcher::new(
move |res: Result<Event, notify::Error>| {
if let Ok(event) = res {
Self::handle_event(event, roots.clone(), event_tx.clone());
}
},
notify::Config::default(),
)?;
let current_roots = self.roots.read().await.clone();
for root in ¤t_roots {
if root.exists() {
watcher.watch(root, RecursiveMode::Recursive)?;
}
}
self.notify_watcher = Some(watcher);
let sender = self.sender.clone();
let debounce_handle = tokio::spawn(async move {
Self::debounce_loop(event_rx, sender, Duration::from_millis(debounce_ms)).await;
});
self.debounce_handle = Some(debounce_handle);
Ok(())
}
pub async fn stop(&mut self) {
if let Some(handle) = self.debounce_handle.take() {
handle.abort();
let _ = handle.await;
}
if let Some(mut watcher) = self.notify_watcher.take() {
for root in self.roots.read().await.iter() {
let _ = watcher.unwatch(root);
}
}
}
pub async fn add_root(&mut self, path: PathBuf) -> Result<()> {
self.roots.write().await.insert(path.clone());
if let Some(watcher) = &mut self.notify_watcher {
if path.exists() {
watcher.watch(&path, RecursiveMode::Recursive)?;
}
}
Ok(())
}
pub async fn remove_root(&mut self, path: &Path) -> Result<()> {
self.roots.write().await.remove(path);
if let Some(watcher) = &mut self.notify_watcher {
let _ = watcher.unwatch(path);
}
Ok(())
}
pub async fn roots(&self) -> Vec<PathBuf> {
self.roots.read().await.iter().cloned().collect()
}
fn handle_event(
event: Event,
roots: Arc<RwLock<HashSet<PathBuf>>>,
event_tx: mpsc::Sender<Vec<PathBuf>>,
) {
let relevant = matches!(
event.kind,
EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
);
if !relevant {
return;
}
let current_roots = match roots.try_read() {
Ok(r) => r.clone(),
Err(_) => return, };
let relevant_paths: Vec<PathBuf> = event
.paths
.into_iter()
.filter(|p| current_roots.iter().any(|root| p.starts_with(root)))
.collect();
if !relevant_paths.is_empty() {
let _ = event_tx.try_send(relevant_paths);
}
}
async fn debounce_loop(
mut event_rx: mpsc::Receiver<Vec<PathBuf>>,
sender: mpsc::Sender<DaemonRequest>,
debounce_duration: Duration,
) {
let mut pending_paths = Vec::new();
let mut debounce_timer = interval(debounce_duration);
debounce_timer.tick().await;
loop {
tokio::select! {
Some(paths) = event_rx.recv() => {
pending_paths.extend(paths);
}
_ = debounce_timer.tick() => {
if !pending_paths.is_empty() {
pending_paths.sort();
pending_paths.dedup();
tracing::debug!("Watcher: triggering index for {} changed paths", pending_paths.len());
let request = DaemonRequest::IndexRoots { roots: pending_paths.clone() };
if sender.send(request).await.is_err() {
tracing::warn!("Watcher: channel closed, stopping");
break;
}
pending_paths.clear();
}
}
}
}
}
}