mago_database/
watcher.rs

1//! Database watcher for real-time file change monitoring.
2
3use std::borrow::Cow;
4use std::collections::HashMap;
5use std::collections::HashSet;
6use std::mem::ManuallyDrop;
7use std::path::Path;
8use std::path::PathBuf;
9use std::sync::mpsc;
10use std::sync::mpsc::Receiver;
11use std::sync::mpsc::RecvTimeoutError;
12use std::time::Duration;
13
14use globset::Glob;
15use globset::GlobSet;
16use globset::GlobSetBuilder;
17use notify::Config;
18use notify::Event;
19use notify::EventKind;
20use notify::RecommendedWatcher;
21use notify::RecursiveMode;
22use notify::Watcher as NotifyWatcher;
23use notify::event::ModifyKind;
24
25use crate::Database;
26use crate::DatabaseReader;
27use crate::ReadDatabase;
28use crate::error::DatabaseError;
29use crate::exclusion::Exclusion;
30use crate::file::File;
31use crate::file::FileId;
32use crate::file::FileType;
33
34const DEFAULT_POLL_INTERVAL_MS: u64 = 1000;
35
36#[derive(Debug, Clone, PartialEq, Eq, Hash)]
37struct ChangedFile {
38    id: FileId,
39    path: PathBuf,
40}
41
42/// Options for configuring the file system watcher.
43#[derive(Debug, Clone)]
44pub struct WatchOptions {
45    pub poll_interval: Option<Duration>,
46    pub additional_excludes: Vec<Exclusion<'static>>,
47}
48
49impl Default for WatchOptions {
50    fn default() -> Self {
51        Self { poll_interval: Some(Duration::from_millis(DEFAULT_POLL_INTERVAL_MS)), additional_excludes: vec![] }
52    }
53}
54
55/// Database watcher service that monitors file changes and updates the database.
56pub struct DatabaseWatcher<'a> {
57    database: Database<'a>,
58    watcher: Option<RecommendedWatcher>,
59    watched_paths: Vec<PathBuf>,
60    receiver: Option<Receiver<Vec<ChangedFile>>>,
61}
62
63impl<'a> DatabaseWatcher<'a> {
64    pub fn new(database: Database<'a>) -> Self {
65        Self { database, watcher: None, watched_paths: Vec::new(), receiver: None }
66    }
67
68    pub fn watch(&mut self, options: WatchOptions) -> Result<(), DatabaseError> {
69        self.stop();
70
71        let config = &self.database.configuration;
72
73        let (tx, rx) = mpsc::channel();
74
75        let mut all_exclusions = vec![
76            Exclusion::Pattern(Cow::Borrowed("**/node_modules/**")),
77            Exclusion::Pattern(Cow::Borrowed("**/.git/**")),
78            Exclusion::Pattern(Cow::Borrowed("**/.idea/**")),
79            Exclusion::Pattern(Cow::Borrowed("**/vendor/**")),
80        ];
81        all_exclusions.extend(config.excludes.iter().cloned());
82        all_exclusions.extend(options.additional_excludes);
83
84        let mut glob_builder = GlobSetBuilder::new();
85        for ex in &all_exclusions {
86            if let Exclusion::Pattern(pat) = ex {
87                glob_builder.add(Glob::new(pat)?);
88            }
89        }
90        let glob_excludes = glob_builder.build()?;
91
92        let path_excludes: HashSet<PathBuf> = all_exclusions
93            .iter()
94            .filter_map(|ex| match ex {
95                Exclusion::Path(p) => Some(p.as_ref().to_path_buf()),
96                _ => None,
97            })
98            .collect();
99
100        let extensions: HashSet<String> = config.extensions.iter().map(|s| s.to_string()).collect();
101        let workspace = config.workspace.as_ref().to_path_buf();
102
103        let mut watcher = RecommendedWatcher::new(
104            move |res: Result<Event, notify::Error>| {
105                if let Ok(event) = res
106                    && let Some(changed) =
107                        Self::handle_event(event, &workspace, &glob_excludes, &path_excludes, &extensions)
108                {
109                    let _ = tx.send(changed);
110                }
111            },
112            Config::default()
113                .with_poll_interval(options.poll_interval.unwrap_or(Duration::from_millis(DEFAULT_POLL_INTERVAL_MS))),
114        )
115        .map_err(DatabaseError::WatcherInit)?;
116
117        let mut unique_watch_paths = HashSet::new();
118
119        for path in &config.paths {
120            let watch_path = Self::extract_watch_path(path.as_ref());
121            let absolute_path = if watch_path.is_absolute() { watch_path } else { config.workspace.join(watch_path) };
122
123            unique_watch_paths.insert(absolute_path);
124        }
125
126        for path in &config.includes {
127            let watch_path = Self::extract_watch_path(path.as_ref());
128            let absolute_path = if watch_path.is_absolute() { watch_path } else { config.workspace.join(watch_path) };
129
130            unique_watch_paths.insert(absolute_path);
131        }
132
133        let mut watched_paths = Vec::new();
134        for path in unique_watch_paths {
135            watcher.watch(&path, RecursiveMode::Recursive).map_err(DatabaseError::WatcherWatch)?;
136            watched_paths.push(path.clone());
137            tracing::debug!("Watching path: {}", path.display());
138        }
139
140        tracing::info!("Database watcher started for workspace: {}", config.workspace.display());
141
142        self.watcher = Some(watcher);
143        self.watched_paths = watched_paths;
144        self.receiver = Some(rx);
145
146        Ok(())
147    }
148
149    /// Stops watching if currently active.
150    pub fn stop(&mut self) {
151        if let Some(mut watcher) = self.watcher.take() {
152            for path in &self.watched_paths {
153                let _ = watcher.unwatch(path);
154                tracing::debug!("Stopped watching: {}", path.display());
155            }
156        }
157        self.watched_paths.clear();
158        self.receiver = None;
159    }
160
161    /// Checks if the watcher is currently active.
162    pub fn is_watching(&self) -> bool {
163        self.watcher.is_some()
164    }
165
166    /// Extracts the base directory path from a potentially glob-pattern path.
167    ///
168    /// For glob patterns (containing *, ?, [, {), this returns the directory portion
169    /// before the first glob metacharacter. For regular paths, returns the path as-is.
170    ///
171    /// # Examples
172    ///
173    /// - `"src/**/*.php"` → `"src"`
174    /// - `"lib/*/foo.php"` → `"lib"`
175    /// - `"tests/fixtures"` → `"tests/fixtures"` (unchanged)
176    fn extract_watch_path(pattern: &str) -> PathBuf {
177        let is_glob = pattern.contains('*') || pattern.contains('?') || pattern.contains('[') || pattern.contains('{');
178
179        if !is_glob {
180            return PathBuf::from(pattern);
181        }
182
183        let first_glob_pos = pattern.find(['*', '?', '[', '{']).unwrap_or(pattern.len());
184
185        let base = &pattern[..first_glob_pos];
186
187        let base = base.trim_end_matches('/').trim_end_matches('\\');
188
189        if base.is_empty() { PathBuf::from(".") } else { PathBuf::from(base) }
190    }
191
192    fn handle_event(
193        event: Event,
194        workspace: &Path,
195        glob_excludes: &GlobSet,
196        path_excludes: &HashSet<PathBuf>,
197        extensions: &HashSet<String>,
198    ) -> Option<Vec<ChangedFile>> {
199        tracing::debug!("Watcher received event: kind={:?}, paths={:?}", event.kind, event.paths);
200
201        if let EventKind::Other | EventKind::Any | EventKind::Access(_) | EventKind::Modify(ModifyKind::Metadata(_)) =
202            event.kind
203        {
204            tracing::debug!("Ignoring non-modification event: {:?}", event.kind);
205
206            return None;
207        }
208
209        let mut changed_files = Vec::new();
210
211        for path in event.paths {
212            // Check if file has a valid extension
213            if let Some(ext) = path.extension() {
214                if !extensions.contains(ext.to_string_lossy().as_ref()) {
215                    continue;
216                }
217            } else {
218                continue;
219            }
220
221            // Check glob pattern exclusions
222            if glob_excludes.is_match(&path) {
223                tracing::debug!("Skipping path excluded by pattern: {}", path.display());
224                continue;
225            }
226
227            // Check exact path exclusions
228            if path_excludes.contains(&path) {
229                tracing::debug!("Skipping excluded path: {}", path.display());
230                continue;
231            }
232
233            // Check if any parent directory is in path_excludes
234            let mut should_skip = false;
235            for ancestor in path.ancestors().skip(1) {
236                if path_excludes.contains(ancestor) {
237                    tracing::debug!("Skipping path under excluded directory: {}", path.display());
238                    should_skip = true;
239                    break;
240                }
241            }
242            if should_skip {
243                continue;
244            }
245
246            let logical_name = path.strip_prefix(workspace).unwrap_or(&path).to_string_lossy();
247            let file_id = FileId::new(logical_name.as_ref());
248
249            changed_files.push(ChangedFile { id: file_id, path: path.clone() });
250        }
251
252        if changed_files.is_empty() { None } else { Some(changed_files) }
253    }
254
255    /// Waits for file changes and updates the database.
256    ///
257    /// This method blocks until file changes are detected, then updates the database
258    /// in place and returns the IDs of changed files.
259    ///
260    /// # Returns
261    ///
262    /// - `Ok(file_ids)` - The IDs of files that were changed (empty if no changes)
263    /// - `Err(DatabaseError::WatcherNotActive)` - If the watcher is not currently watching
264    /// - `Err(e)` - If updating the database failed
265    pub fn wait(&mut self) -> Result<Vec<FileId>, DatabaseError> {
266        let Some(receiver) = &self.receiver else {
267            return Err(DatabaseError::WatcherNotActive);
268        };
269
270        let config = &self.database.configuration;
271        let workspace = config.workspace.as_ref().to_path_buf();
272
273        match receiver.recv_timeout(Duration::from_millis(100)) {
274            Ok(changed_files) => {
275                std::thread::sleep(Duration::from_millis(250));
276                let mut all_changed = changed_files;
277                while let Ok(more) = receiver.try_recv() {
278                    all_changed.extend(more);
279                }
280
281                let mut latest_changes: HashMap<FileId, ChangedFile> = HashMap::new();
282                for changed in all_changed {
283                    latest_changes.insert(changed.id, changed);
284                }
285                let all_changed: Vec<ChangedFile> = latest_changes.into_values().collect();
286                let mut changed_ids = Vec::new();
287
288                for changed_file in &all_changed {
289                    changed_ids.push(changed_file.id);
290
291                    match self.database.get(&changed_file.id) {
292                        Ok(file) => {
293                            if changed_file.path.exists() {
294                                match std::fs::read_to_string(&changed_file.path) {
295                                    Ok(contents) => {
296                                        self.database.update(changed_file.id, Cow::Owned(contents));
297                                        tracing::trace!("Updated file in database: {}", file.name);
298                                    }
299                                    Err(e) => {
300                                        tracing::error!("Failed to read file {}: {}", changed_file.path.display(), e);
301                                    }
302                                }
303                            } else {
304                                self.database.delete(changed_file.id);
305                                tracing::trace!("Deleted file from database: {}", file.name);
306                            }
307                        }
308                        Err(_) => {
309                            if changed_file.path.exists() {
310                                match File::read(&workspace, &changed_file.path, FileType::Host) {
311                                    Ok(file) => {
312                                        self.database.add(file);
313                                        tracing::debug!("Added new file to database: {}", changed_file.path.display());
314                                    }
315                                    Err(e) => {
316                                        tracing::error!(
317                                            "Failed to load new file {}: {}",
318                                            changed_file.path.display(),
319                                            e
320                                        );
321                                    }
322                                }
323                            }
324                        }
325                    }
326                }
327
328                Ok(changed_ids)
329            }
330            Err(RecvTimeoutError::Timeout) => Ok(Vec::new()),
331            Err(RecvTimeoutError::Disconnected) => {
332                self.stop();
333                Err(DatabaseError::WatcherNotActive)
334            }
335        }
336    }
337
338    /// Returns a reference to the database.
339    pub fn database(&self) -> &Database<'a> {
340        &self.database
341    }
342
343    /// Returns a reference to the database.
344    pub fn read_only_database(&self) -> ReadDatabase {
345        self.database.read_only()
346    }
347
348    /// Returns a mutable reference to the database.
349    pub fn database_mut(&mut self) -> &mut Database<'a> {
350        &mut self.database
351    }
352
353    /// Provides temporary mutable access to the database through a closure.
354    ///
355    /// This method helps Rust's borrow checker understand that the mutable borrow
356    /// of the database is scoped to just the closure execution, allowing the watcher
357    /// to be used again after the closure returns.
358    ///
359    /// The closure is bounded with for<'x> to explicitly show that the database
360    /// reference lifetime is scoped to the closure execution only.
361    pub fn with_database_mut<F, R>(&mut self, f: F) -> R
362    where
363        F: for<'x> FnOnce(&'x mut Database<'a>) -> R,
364    {
365        f(&mut self.database)
366    }
367
368    /// Consumes the watcher and returns the database.
369    pub fn into_database(self) -> Database<'a> {
370        let mut md = ManuallyDrop::new(self);
371        md.stop();
372        unsafe { std::ptr::read(&md.database) }
373    }
374}
375
376impl<'a> Drop for DatabaseWatcher<'a> {
377    fn drop(&mut self) {
378        self.stop();
379    }
380}