Skip to main content

ragfs_index/
watcher.rs

1//! File system watcher for detecting changes.
2
3use notify_debouncer_full::notify::{RecommendedWatcher, RecursiveMode};
4use notify_debouncer_full::{DebounceEventResult, Debouncer, RecommendedCache, new_debouncer};
5use ragfs_core::FileEvent;
6use std::path::Path;
7use std::sync::Arc;
8use std::sync::atomic::{AtomicUsize, Ordering};
9use std::sync::mpsc;
10use std::time::Duration;
11use tokio::sync::mpsc as tokio_mpsc;
12use tracing::{debug, error, warn};
13
14use crate::exclude::ExclusionMatcher;
15
16/// File system watcher with debouncing.
17pub struct FileWatcher {
18    debouncer: Debouncer<RecommendedWatcher, RecommendedCache>,
19}
20
21impl FileWatcher {
22    /// Create a new file watcher.
23    pub fn new(
24        event_tx: tokio_mpsc::Sender<FileEvent>,
25        debounce_duration: Duration,
26    ) -> Result<Self, notify::Error> {
27        Self::with_pending(event_tx, debounce_duration, None)
28    }
29
30    /// Create a watcher that increments `pending` for each queued event.
31    pub fn with_pending(
32        event_tx: tokio_mpsc::Sender<FileEvent>,
33        debounce_duration: Duration,
34        pending: Option<Arc<AtomicUsize>>,
35    ) -> Result<Self, notify::Error> {
36        Self::with_filter(event_tx, debounce_duration, pending, None)
37    }
38
39    /// Create a watcher that filters events with the shared exclusion matcher.
40    pub fn with_filter(
41        event_tx: tokio_mpsc::Sender<FileEvent>,
42        debounce_duration: Duration,
43        pending: Option<Arc<AtomicUsize>>,
44        matcher: Option<Arc<ExclusionMatcher>>,
45    ) -> Result<Self, notify::Error> {
46        let (tx, rx) = mpsc::channel();
47
48        let event_tx_clone = event_tx.clone();
49        std::thread::spawn(move || {
50            while let Ok(result) = rx.recv() {
51                if let Err(e) = handle_debounced_events(
52                    result,
53                    &event_tx_clone,
54                    pending.as_deref(),
55                    matcher.as_deref(),
56                ) {
57                    error!("Error handling file events: {e}");
58                }
59            }
60        });
61
62        let debouncer = new_debouncer(debounce_duration, None, move |result| {
63            let _ = tx.send(result);
64        })?;
65
66        Ok(Self { debouncer })
67    }
68
69    /// Start watching a path.
70    pub fn watch(&mut self, path: &Path) -> Result<(), notify_debouncer_full::notify::Error> {
71        debug!("Starting to watch: {:?}", path);
72        self.debouncer.watch(path, RecursiveMode::Recursive)?;
73        Ok(())
74    }
75
76    /// Stop watching a path.
77    pub fn unwatch(&mut self, path: &Path) -> Result<(), notify_debouncer_full::notify::Error> {
78        debug!("Stopping watch: {:?}", path);
79        self.debouncer.unwatch(path)?;
80        Ok(())
81    }
82}
83
84fn handle_debounced_events(
85    result: DebounceEventResult,
86    event_tx: &tokio_mpsc::Sender<FileEvent>,
87    pending: Option<&AtomicUsize>,
88    matcher: Option<&ExclusionMatcher>,
89) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
90    match result {
91        Ok(events) => {
92            for event in events {
93                if let Some(file_event) = convert_event(&event, matcher) {
94                    if let Some(pending) = pending {
95                        pending.fetch_add(1, Ordering::SeqCst);
96                    }
97                    // Use blocking send since we're in a std thread
98                    if event_tx.blocking_send(file_event).is_err() {
99                        if let Some(pending) = pending {
100                            pending.fetch_sub(1, Ordering::SeqCst);
101                        }
102                        warn!("Event channel closed");
103                        break;
104                    }
105                }
106            }
107        }
108        Err(errors) => {
109            for error in errors {
110                error!("Watch error: {error}");
111            }
112        }
113    }
114    Ok(())
115}
116
117fn convert_event(
118    event: &notify_debouncer_full::DebouncedEvent,
119    matcher: Option<&ExclusionMatcher>,
120) -> Option<FileEvent> {
121    use notify_debouncer_full::notify::EventKind;
122
123    let path = event.paths.first()?.clone();
124
125    if let Some(matcher) = matcher {
126        if matcher.is_excluded(&path) {
127            return None;
128        }
129    } else if path.components().any(|component| {
130        let name = component.as_os_str().to_string_lossy();
131        name.starts_with('.') && name != "." && name != ".."
132    }) {
133        // Fail-closed when no matcher is supplied.
134        return None;
135    }
136
137    match &event.kind {
138        EventKind::Create(_) => Some(FileEvent::Created(path)),
139        EventKind::Modify(_) => Some(FileEvent::Modified(path)),
140        EventKind::Remove(_) => Some(FileEvent::Deleted(path)),
141        EventKind::Other => {
142            // Handle rename as "other" event with two paths
143            if event.paths.len() >= 2 {
144                Some(FileEvent::Renamed {
145                    from: event.paths[0].clone(),
146                    to: event.paths[1].clone(),
147                })
148            } else {
149                None
150            }
151        }
152        _ => None,
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159    use crate::exclude::ExclusionOptions;
160    use notify_debouncer_full::DebouncedEvent;
161    use notify_debouncer_full::notify::EventKind;
162    use notify_debouncer_full::notify::event::{CreateKind, ModifyKind, RemoveKind};
163    use std::path::PathBuf;
164    use std::time::Instant;
165
166    fn make_event(kind: EventKind, paths: Vec<PathBuf>) -> DebouncedEvent {
167        DebouncedEvent {
168            event: notify_debouncer_full::notify::Event {
169                kind,
170                paths,
171                attrs: Default::default(),
172            },
173            time: Instant::now(),
174        }
175    }
176
177    #[test]
178    fn test_convert_event_create() {
179        let path = PathBuf::from("/tmp/test.txt");
180        let event = make_event(EventKind::Create(CreateKind::File), vec![path.clone()]);
181
182        let result = convert_event(&event, None);
183        assert!(matches!(result, Some(FileEvent::Created(p)) if p == path));
184    }
185
186    #[test]
187    fn test_convert_event_modify() {
188        use notify_debouncer_full::notify::event::DataChange;
189        let path = PathBuf::from("/tmp/test.txt");
190        let event = make_event(
191            EventKind::Modify(ModifyKind::Data(DataChange::Any)),
192            vec![path.clone()],
193        );
194
195        let result = convert_event(&event, None);
196        assert!(matches!(result, Some(FileEvent::Modified(p)) if p == path));
197    }
198
199    #[test]
200    fn test_convert_event_delete() {
201        let path = PathBuf::from("/tmp/test.txt");
202        let event = make_event(EventKind::Remove(RemoveKind::File), vec![path.clone()]);
203
204        let result = convert_event(&event, None);
205        assert!(matches!(result, Some(FileEvent::Deleted(p)) if p == path));
206    }
207
208    #[test]
209    fn test_hidden_files_skipped() {
210        let path = PathBuf::from("/tmp/.hidden");
211        let event = make_event(EventKind::Create(CreateKind::File), vec![path]);
212
213        let result = convert_event(&event, None);
214        assert!(result.is_none());
215    }
216
217    #[test]
218    fn test_matcher_skips_secret_and_hidden_dir() {
219        let matcher = ExclusionMatcher::new("/proj", ExclusionOptions::default());
220        let secret = make_event(
221            EventKind::Create(CreateKind::File),
222            vec![PathBuf::from("/proj/server.pem")],
223        );
224        let hidden_dir = make_event(
225            EventKind::Create(CreateKind::File),
226            vec![PathBuf::from("/proj/.obsidian/x.md")],
227        );
228        let visible = make_event(
229            EventKind::Create(CreateKind::File),
230            vec![PathBuf::from("/proj/notes/keyboard.md")],
231        );
232        assert!(convert_event(&secret, Some(&matcher)).is_none());
233        assert!(convert_event(&hidden_dir, Some(&matcher)).is_none());
234        assert!(matches!(
235            convert_event(&visible, Some(&matcher)),
236            Some(FileEvent::Created(p)) if p.ends_with("keyboard.md")
237        ));
238    }
239}