//! Apple `FSEvents` live filesystem watcher and dirty-path coalescer. use crate::domain::RelPath; #[cfg(not(target_os = "macos"))] use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher}; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; use thiserror::Error; use tokio::sync::mpsc; #[cfg(target_os = "macos")] const FSEVENTS_COALESCING_LATENCY_SECS: f64 = 2.0; /// Errors returned by filesystem watchers. #[derive(Debug, Error)] pub enum WatcherError { /// Failed to initialize or start the underlying watcher. #[error("filesystem watcher error: {0}")] Notify(#[from] notify::Error), /// Failed to initialize or start macOS `FSEvents`. #[error("FSEvents watcher error: {0}")] Fsevents(String), } /// Raw filesystem change event emitted by an [`FsWatcher`]. #[derive(Debug, Clone)] pub struct RawFsEvent { pub paths: Vec, pub recursive_hint: bool, pub is_dir_change: bool, } /// Coalesced dirty-path action ready for cache reconciliation. #[derive(Debug, Clone, PartialEq, Eq)] pub enum DirtyAction { /// Re-scan only the direct files of this directory (`O(depth)` delta). DirectDir(RelPath), /// Re-scan the entire subtree rooted here (or prune if deleted). Subtree(RelPath), } /// Seam for filesystem watching (macOS `FSEvents` vs. fake channel injector). pub trait FsWatcher: Send + Sync { /// Start watching `home_root` recursively and send events to `tx`. /// Paths under `excluded_dirs` are filtered early in the watcher callback. /// Sets `overflow` to `true` if bounded channel capacity is exceeded. /// Dropping the returned guard stops the watcher. fn start( &self, home_root: &Path, excluded_dirs: &[PathBuf], tx: mpsc::Sender, overflow: Arc, ) -> Result, WatcherError>; } /// Production native filesystem watcher (`FSEvents` with 2.0s coalescing latency on macOS; /// `notify` on Linux/Windows with `ENOSPC` periodic-rescan fallback on Linux). #[derive(Debug, Default)] pub struct NativeFsWatcher; /// Backward-compatible alias for [`NativeFsWatcher`]. pub type MacFsEventsWatcher = NativeFsWatcher; impl NativeFsWatcher { /// Create a new [`NativeFsWatcher`]. #[must_use] pub const fn new() -> Self { Self } } /// Returns `true` when `notify` failed because the OS watch-descriptor limit /// (e.g. Linux `fs.inotify.max_user_watches` / `ENOSPC`) was exhausted. #[must_use] pub fn is_watch_limit_error(err: ¬ify::Error) -> bool { #[cfg(unix)] if let notify::ErrorKind::Io(io_err) = &err.kind && io_err.raw_os_error() == Some(libc::ENOSPC) { return true; } matches!(err.kind, notify::ErrorKind::MaxFilesWatch) } #[cfg(not(target_os = "macos"))] struct PeriodicRescanGuard { stop: Arc, handle: Option>, } #[cfg(not(target_os = "macos"))] impl Drop for PeriodicRescanGuard { fn drop(&mut self) { self.stop.store(true, Ordering::Release); if let Some(h) = self.handle.take() { let _ = h.join(); } } } #[cfg(not(target_os = "macos"))] fn spawn_periodic_rescan_fallback(overflow: Arc, interval: Duration) -> Box { let stop = Arc::new(AtomicBool::new(false)); let stop_flag = Arc::clone(&stop); let handle = std::thread::Builder::new() .name("getael-rescan-fallback".to_string()) .spawn(move || { let tick = Duration::from_secs(1); let mut elapsed = Duration::ZERO; while !stop_flag.load(Ordering::Acquire) { std::thread::sleep(tick); elapsed += tick; if elapsed >= interval { elapsed = Duration::ZERO; overflow.store(true, Ordering::Release); } } }) .ok(); Box::new(PeriodicRescanGuard { stop, handle }) } fn is_real_dir(path: &Path) -> bool { std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_dir()) } #[cfg(target_os = "macos")] mod macos_fsevents { use super::{FSEVENTS_COALESCING_LATENCY_SECS, RawFsEvent, WatcherError}; use objc2_core_foundation as cf; use objc2_core_services as fs; use std::ffi::CStr; use std::path::{Path, PathBuf}; use std::ptr::NonNull; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use tokio::sync::mpsc; struct StreamContextInfo { raw_home: PathBuf, canon_home: PathBuf, excluded_dirs: Vec, tx: mpsc::Sender, overflow: Arc, } struct CFRunLoopSendWrapper(cf::CFRetained); // SAFETY: Apple's `CFRunLoop` is documented as thread-safe for `CFRunLoopStop` // and `CFRunLoopIsWaiting` across threads. unsafe impl Send for CFRunLoopSendWrapper {} struct FSEventStreamSendWrapper(fs::FSEventStreamRef); // SAFETY: Ownership of `FSEventStreamRef` is transferred once to the dedicated // `CFRunLoop` worker thread before starting and invalidated/released on that thread. unsafe impl Send for FSEventStreamSendWrapper {} pub(super) struct FseventsGuard { runloop: CFRunLoopSendWrapper, thread_handle: Option>, } impl Drop for FseventsGuard { fn drop(&mut self) { while !self.runloop.0.is_waiting() { std::thread::yield_now(); } self.runloop.0.stop(); if let Some(handle) = self.thread_handle.take() { let _ = handle.join(); } } } unsafe extern "C-unwind" fn release_context(info: *const libc::c_void) { // SAFETY: `info` was created via `Box::into_raw(Box::new(StreamContextInfo { .. }))` // and `FSEvents` invokes `release` exactly once when the stream is deallocated. unsafe { drop(Box::from_raw(info.cast::().cast_mut())); } } unsafe extern "C-unwind" fn fsevents_callback( _stream_ref: fs::ConstFSEventStreamRef, info: *mut libc::c_void, num_events: libc::size_t, event_paths: NonNull, event_flags: NonNull, _event_ids: NonNull, ) { // SAFETY: `info` points to a live `StreamContextInfo` until `release_context` runs, // and `FSEvents` passes `num_events` valid C-string pointers and `FSEventStreamEventFlags`. unsafe { callback_impl(info, num_events, event_paths, event_flags); } } unsafe fn callback_impl( info: *mut libc::c_void, num_events: libc::size_t, event_paths: NonNull, event_flags: NonNull, ) { // SAFETY: `info` is a valid non-null `*const StreamContextInfo` owned by the stream. let ctx = unsafe { &*info.cast::() }; let paths_ptr = event_paths.as_ptr().cast::<*const libc::c_char>(); let flags_ptr = event_flags.as_ptr(); // Batch events by `(recursive_hint, is_dir_change)` to avoid per-file channel sends. let mut buckets: [Vec; 4] = [Vec::new(), Vec::new(), Vec::new(), Vec::new()]; let mut saw_overflow = false; let rescan_mask = fs::kFSEventStreamEventFlagMustScanSubDirs | fs::kFSEventStreamEventFlagUserDropped | fs::kFSEventStreamEventFlagKernelDropped | fs::kFSEventStreamEventFlagEventIdsWrapped | fs::kFSEventStreamEventFlagRootChanged | fs::kFSEventStreamEventFlagMount | fs::kFSEventStreamEventFlagUnmount; let overflow_mask = fs::kFSEventStreamEventFlagUserDropped | fs::kFSEventStreamEventFlagKernelDropped | fs::kFSEventStreamEventFlagEventIdsWrapped; for idx in 0..num_events { // SAFETY: `idx < num_events`, so `paths_ptr.add(idx)` and `flags_ptr.add(idx)` are in bounds. let (raw_cstr, flag) = unsafe { (*paths_ptr.add(idx), *flags_ptr.add(idx)) }; if (flag & fs::kFSEventStreamEventFlagHistoryDone) != 0 { continue; } if (flag & overflow_mask) != 0 { saw_overflow = true; } if raw_cstr.is_null() { continue; } // SAFETY: `raw_cstr` is a valid NUL-terminated UTF-8 path string from FSEvents. let Ok(path_str) = unsafe { CStr::from_ptr(raw_cstr) }.to_str() else { continue; }; let raw_path = Path::new(path_str); if ctx.excluded_dirs.iter().any(|ex| raw_path.starts_with(ex)) { continue; } let normalized = if ctx.canon_home != ctx.raw_home && let Ok(rel) = raw_path.strip_prefix(&ctx.canon_home) { ctx.raw_home.join(rel) } else { raw_path.to_path_buf() }; if ctx .excluded_dirs .iter() .any(|ex| normalized.starts_with(ex)) { continue; } let recursive_hint = (flag & rescan_mask) != 0; let is_dir_change = (flag & fs::kFSEventStreamEventFlagItemIsDir) != 0; let bucket_idx = (usize::from(recursive_hint) << 1) | usize::from(is_dir_change); buckets[bucket_idx].push(normalized); } for (bucket_idx, paths) in buckets.into_iter().enumerate() { if paths.is_empty() { continue; } let recursive_hint = (bucket_idx & 2) != 0; let is_dir_change = (bucket_idx & 1) != 0; if let Err(mpsc::error::TrySendError::Full(_)) = ctx.tx.try_send(RawFsEvent { paths, recursive_hint, is_dir_change, }) { ctx.overflow.store(true, Ordering::Release); } } if saw_overflow { ctx.overflow.store(true, Ordering::Release); let _ = ctx.tx.try_send(RawFsEvent { paths: vec![ctx.raw_home.clone()], recursive_hint: true, is_dir_change: true, }); } } fn expand_excluded_dirs( home_root: &Path, canon_home: &Path, excluded_dirs: &[PathBuf], ) -> Vec { let mut all_excluded = Vec::with_capacity(excluded_dirs.len() * 2); for ex in excluded_dirs { all_excluded.push(ex.clone()); if let Ok(canon_ex) = ex.canonicalize() && canon_ex != *ex { all_excluded.push(canon_ex); } else if canon_home != home_root && let Ok(rel) = ex.strip_prefix(home_root) { all_excluded.push(canon_home.join(rel)); } } all_excluded } pub(super) fn start_stream( home_root: &Path, excluded_dirs: &[PathBuf], tx: mpsc::Sender, overflow: Arc, ) -> Result, WatcherError> { if !home_root.exists() { return Err(WatcherError::Fsevents(format!( "watch root does not exist: {}", home_root.display() ))); } let canon_home = home_root .canonicalize() .unwrap_or_else(|_| home_root.to_path_buf()); let all_excluded = expand_excluded_dirs(home_root, &canon_home, excluded_dirs); let watch_str = canon_home.to_str().ok_or_else(|| { WatcherError::Fsevents("watch root path is not valid UTF-8".to_string()) })?; let cf_path = cf::CFString::from_str(watch_str); let paths = cf::CFMutableArray::::empty(); paths.append(&cf_path); let context_ptr = Box::into_raw(Box::new(StreamContextInfo { raw_home: home_root.to_path_buf(), canon_home, excluded_dirs: all_excluded, tx, overflow, })); let stream_context = fs::FSEventStreamContext { version: 0, info: context_ptr.cast::(), retain: None, release: Some(release_context), copyDescription: None, }; // SAFETY: `paths` is a valid CFArray of CFString, `stream_context` has a valid // `release` callback owning `context_ptr`, and `kFSEventStreamCreateFlagFileEvents` // without `NoDefer` enables native 2.0s kernel/daemon coalescing. let stream = unsafe { fs::FSEventStreamCreate( cf::kCFAllocatorDefault, Some(fsevents_callback), (&raw const stream_context).cast_mut(), paths.as_opaque(), fs::kFSEventStreamEventIdSinceNow, FSEVENTS_COALESCING_LATENCY_SECS, fs::kFSEventStreamCreateFlagFileEvents, ) }; if stream.is_null() { // SAFETY: `FSEventStreamCreate` failed, so `release_context` will not run; free `context_ptr`. unsafe { release_context(context_ptr.cast::()); } return Err(WatcherError::Fsevents( "FSEventStreamCreate returned null".to_string(), )); } let stream_wrap = FSEventStreamSendWrapper(stream); let (rl_tx, rl_rx) = std::sync::mpsc::sync_channel::>(1); let thread_handle = std::thread::Builder::new() .name("getael-fsevents".to_string()) .spawn(move || { let stream_wrap = stream_wrap; let stream = stream_wrap.0; // SAFETY: Running on the dedicated `CFRunLoop` thread; `CFRunLoop::current()` // and `kCFRunLoopDefaultMode` are valid on macOS, and `stream` is valid until released. unsafe { let Some(cur_runloop) = cf::CFRunLoop::current() else { fs::FSEventStreamInvalidate(stream); fs::FSEventStreamRelease(stream); let _ = rl_tx.send(Err("failed to acquire CFRunLoop::current".to_string())); return; }; let Some(mode) = cf::kCFRunLoopDefaultMode else { fs::FSEventStreamInvalidate(stream); fs::FSEventStreamRelease(stream); let _ = rl_tx.send(Err("missing kCFRunLoopDefaultMode".to_string())); return; }; #[allow(deprecated)] fs::FSEventStreamScheduleWithRunLoop(stream, &cur_runloop, mode); if !fs::FSEventStreamStart(stream) { fs::FSEventStreamInvalidate(stream); fs::FSEventStreamRelease(stream); let _ = rl_tx.send(Err("FSEventStreamStart returned false".to_string())); return; } let _ = rl_tx.send(Ok(CFRunLoopSendWrapper(cur_runloop))); cf::CFRunLoop::run(); fs::FSEventStreamStop(stream); fs::FSEventStreamInvalidate(stream); fs::FSEventStreamRelease(stream); } }) .map_err(|err| { // SAFETY: Thread failed to spawn before taking ownership of `stream`. unsafe { fs::FSEventStreamInvalidate(stream); fs::FSEventStreamRelease(stream); } WatcherError::Fsevents(format!("failed to spawn FSEvents thread: {err}")) })?; let runloop = rl_rx .recv() .map_err(|_| WatcherError::Fsevents("FSEvents thread exited unexpectedly".to_string()))? .map_err(WatcherError::Fsevents)?; Ok(Box::new(FseventsGuard { runloop, thread_handle: Some(thread_handle), })) } } impl FsWatcher for NativeFsWatcher { #[cfg(target_os = "macos")] fn start( &self, home_root: &Path, excluded_dirs: &[PathBuf], tx: mpsc::Sender, overflow: Arc, ) -> Result, WatcherError> { macos_fsevents::start_stream(home_root, excluded_dirs, tx, overflow) } #[cfg(not(target_os = "macos"))] fn start( &self, home_root: &Path, excluded_dirs: &[PathBuf], tx: mpsc::Sender, overflow: Arc, ) -> Result, WatcherError> { let cb_overflow = Arc::clone(&overflow); let excluded = excluded_dirs.to_vec(); let watch_root = home_root.to_path_buf(); let mut watcher = RecommendedWatcher::new( move |res: Result| { if let Ok(ev) = res { let recursive_hint = matches!(ev.attrs.flag(), Some(notify::event::Flag::Rescan)); if recursive_hint && ev.paths.is_empty() { cb_overflow.store(true, Ordering::Release); let _ = tx.try_send(RawFsEvent { paths: vec![watch_root.clone()], recursive_hint: true, is_dir_change: true, }); return; } let filtered_paths: Vec = ev .paths .into_iter() .filter(|p| !excluded.iter().any(|ex| p.starts_with(ex))) .collect(); if filtered_paths.is_empty() { return; } let is_dir_change = matches!( ev.kind, EventKind::Create(notify::event::CreateKind::Folder) | EventKind::Remove(notify::event::RemoveKind::Folder) ) || (matches!( ev.kind, EventKind::Modify(notify::event::ModifyKind::Name(_)) ) && filtered_paths.iter().any(|p| is_real_dir(p))); let raw = RawFsEvent { paths: filtered_paths, recursive_hint, is_dir_change, }; if let Err(mpsc::error::TrySendError::Full(_)) = tx.try_send(raw) { cb_overflow.store(true, Ordering::Release); } } }, notify::Config::default(), )?; if let Err(err) = watcher.watch(home_root, RecursiveMode::Recursive) { if is_watch_limit_error(&err) { tracing::warn!( error = %err, "OS filesystem watch limit reached (e.g. fs.inotify.max_user_watches). \ Falling back to periodic rescanning. On Linux, raise the limit with: \ sudo sysctl -w fs.inotify.max_user_watches=524288" ); return Ok(spawn_periodic_rescan_fallback( overflow, Duration::from_secs(300), )); } return Err(WatcherError::Notify(err)); } Ok(Box::new(watcher)) } } /// Deterministic channel-backed [`FsWatcher`] for tests. #[derive(Debug, Clone)] pub struct FakeWatcher { sender_slot: Arc>>>, overflow_slot: Arc>>>, } impl FakeWatcher { /// Create a new [`FakeWatcher`]. #[must_use] pub fn new() -> Self { Self { sender_slot: Arc::new(std::sync::Mutex::new(None)), overflow_slot: Arc::new(std::sync::Mutex::new(None)), } } /// Inject a raw filesystem event into the running engine. pub fn push_event(&self, event: RawFsEvent) { if let Some(tx) = self .sender_slot .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .as_ref() && let Err(mpsc::error::TrySendError::Full(_)) = tx.try_send(event) && let Some(flag) = self .overflow_slot .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .as_ref() { flag.store(true, Ordering::Release); } } } impl Default for FakeWatcher { fn default() -> Self { Self::new() } } impl FsWatcher for FakeWatcher { fn start( &self, _home_root: &Path, _excluded_dirs: &[PathBuf], tx: mpsc::Sender, overflow: Arc, ) -> Result, WatcherError> { *self .sender_slot .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(tx); *self .overflow_slot .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(overflow); Ok(Box::new(())) } } /// Debounces, filters, and collapses bursty filesystem events into [`DirtyAction`]s. #[derive(Debug)] pub struct DirtyCoalescer { home_root: PathBuf, excluded_dirs: Vec, debounce: Duration, pending: BTreeMap, } impl DirtyCoalescer { /// Create a new [`DirtyCoalescer`] excluding `excluded_dir` (e.g. `~/Library/Caches/getael`). #[must_use] pub fn new(home_root: PathBuf, excluded_dir: PathBuf, debounce: Duration) -> Self { Self::with_excluded_dirs(home_root, vec![excluded_dir], debounce) } /// Create a new [`DirtyCoalescer`] excluding all directories in `excluded_dirs`. #[must_use] pub fn with_excluded_dirs( home_root: PathBuf, excluded_dirs: Vec, debounce: Duration, ) -> Self { Self { home_root, excluded_dirs, debounce, pending: BTreeMap::new(), } } /// Ingest a raw event, stripping excluded/external paths and deduplicating bursts /// without performing per-event filesystem `lstat` calls. pub fn ingest(&mut self, event: &RawFsEvent, now: Instant) { let needs_subtree = event.recursive_hint || event.is_dir_change; for path in &event.paths { if self.excluded_dirs.iter().any(|ex| path.starts_with(ex)) { continue; } let Ok(rel) = path.strip_prefix(&self.home_root) else { continue; }; let rel_str = rel.to_string_lossy(); let normalized = match RelPath::parse(&rel_str) { Ok(r) => r.as_str().to_string(), Err(_) => continue, }; self.pending .entry(normalized) .and_modify(|(sub, ts)| { *sub |= needs_subtree; *ts = now; }) .or_insert((needs_subtree, now)); } } /// Whether any dirty paths are queued. #[must_use] pub fn is_empty(&self) -> bool { self.pending.is_empty() } /// Return the earliest instant when at least one pending path becomes ready to drain. #[must_use] pub fn next_ready_deadline(&self) -> Option { self.pending .values() .map(|(_, ts)| *ts + self.debounce) .min() } /// Drain actions whose trailing debounce window has elapsed, resolving file-vs-dir /// ownership once per debounced path and collapsing nested paths under any ancestor /// marked for subtree rescan. pub fn drain_ready(&mut self, now: Instant) -> Vec { let ready_keys: Vec = self .pending .iter() .filter(|&(_, (_, ts))| now.duration_since(*ts) >= self.debounce) .map(|(k, _)| k.clone()) .collect(); if ready_keys.is_empty() { return Vec::new(); } let mut ready_map: BTreeMap = BTreeMap::new(); for key in ready_keys { if let Some((is_sub, _)) = self.pending.remove(&key) { let target_key = if is_sub { key } else if let Ok(rel) = RelPath::parse(&key) { if is_real_dir(&rel.to_fs_path(&self.home_root)) { key } else { rel.parent() .map_or_else(String::new, |p| p.as_str().to_string()) } } else { continue; }; ready_map .entry(target_key) .and_modify(|sub| *sub |= is_sub) .or_insert(is_sub); } } // Collapse descendants when an ancestor is scheduled for Subtree rescan. let subtree_roots: Vec = ready_map .iter() .filter(|&(_, &is_sub)| is_sub) .map(|(k, _)| k.clone()) .collect(); let mut actions = Vec::new(); for (path, is_sub) in ready_map { let covered_by_ancestor = subtree_roots.iter().any(|root| { if root == &path { return false; } if root.is_empty() { return true; } path.starts_with(&format!("{root}/")) }); if covered_by_ancestor { continue; } if let Ok(rel) = RelPath::parse(&path) { if is_sub { actions.push(DirtyAction::Subtree(rel)); } else { actions.push(DirtyAction::DirectDir(rel)); } } } actions } } #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { use super::*; use tempfile::TempDir; #[test] fn coalescer_excludes_cache_dir_and_collapses_subtrees() { let home = PathBuf::from("/Users/test"); let cache = PathBuf::from("/Users/test/Library/Caches/getael"); let mut coalescer = DirtyCoalescer::new(home.clone(), cache.clone(), Duration::from_millis(500)); let t0 = Instant::now(); // Excluded cache write coalescer.ingest( &RawFsEvent { paths: vec![cache.join("cache.sqlite3-wal")], recursive_hint: false, is_dir_change: false, }, t0, ); assert!(coalescer.is_empty()); assert_eq!(coalescer.next_ready_deadline(), None); // Burst of file writes + parent subtree change coalescer.ingest( &RawFsEvent { paths: vec![ home.join("Projects/app/src/main.rs"), home.join("Projects/app/src/lib.rs"), ], recursive_hint: false, is_dir_change: false, }, t0, ); assert_eq!( coalescer.next_ready_deadline(), Some(t0 + Duration::from_millis(500)) ); coalescer.ingest( &RawFsEvent { paths: vec![home.join("Projects/app")], recursive_hint: true, is_dir_change: true, }, t0, ); assert_eq!( coalescer.drain_ready(t0 + Duration::from_millis(100)), Vec::::new() ); let actions = coalescer.drain_ready(t0 + Duration::from_millis(600)); assert_eq!( actions, vec![DirtyAction::Subtree( RelPath::parse("Projects/app").unwrap() )] ); assert_eq!(coalescer.next_ready_deadline(), None); } #[test] fn coalescer_defers_dir_resolution_and_treats_deleted_dir_as_subtree() { let tmp = TempDir::new().unwrap(); let home = tmp.path().to_path_buf(); let dir_path = home.join("Projects/app"); std::fs::create_dir_all(&dir_path).unwrap(); let file_path = dir_path.join("main.rs"); std::fs::write(&file_path, b"hi").unwrap(); let mut coalescer = DirtyCoalescer::new( home.clone(), home.join("Library/Caches/getael"), Duration::from_millis(200), ); let t0 = Instant::now(); // Direct file change resolves to parent DirectDir("Projects/app") on drain_ready coalescer.ingest( &RawFsEvent { paths: vec![file_path], recursive_hint: false, is_dir_change: false, }, t0, ); // Deleted folder signaled via is_dir_change=true becomes Subtree even after removal coalescer.ingest( &RawFsEvent { paths: vec![home.join("Projects/deleted_dir")], recursive_hint: false, is_dir_change: true, }, t0 + Duration::from_millis(50), ); assert_eq!( coalescer.next_ready_deadline(), Some(t0 + Duration::from_millis(200)) ); let first = coalescer.drain_ready(t0 + Duration::from_millis(210)); assert_eq!( first, vec![DirtyAction::DirectDir( RelPath::parse("Projects/app").unwrap() )] ); assert_eq!( coalescer.next_ready_deadline(), Some(t0 + Duration::from_millis(250)) ); let second = coalescer.drain_ready(t0 + Duration::from_millis(260)); assert_eq!( second, vec![DirtyAction::Subtree( RelPath::parse("Projects/deleted_dir").unwrap() )] ); assert!(coalescer.is_empty()); } #[tokio::test] async fn native_watcher_excludes_configured_directories_early() { let tmp = TempDir::new().unwrap(); let home = tmp.path().to_path_buf(); let excluded = home.join("Library/Caches/getael"); let target_dir = home.join("Projects"); std::fs::create_dir_all(&excluded).unwrap(); std::fs::create_dir_all(&target_dir).unwrap(); let (tx, mut rx) = mpsc::channel(64); let overflow = Arc::new(AtomicBool::new(false)); let watcher = NativeFsWatcher::new(); let _guard = watcher .start(&home, std::slice::from_ref(&excluded), tx, overflow) .unwrap(); // Wait briefly for stream startup, then write in excluded and non-excluded dirs tokio::time::sleep(Duration::from_millis(200)).await; std::fs::write(excluded.join("cache.sqlite3-wal"), b"noise").unwrap(); std::fs::write(target_dir.join("real.txt"), b"signal").unwrap(); let mut saw_real = false; let deadline = tokio::time::Instant::now() + Duration::from_secs(6); while tokio::time::Instant::now() < deadline { if let Ok(Some(ev)) = tokio::time::timeout(Duration::from_millis(300), rx.recv()).await { for p in &ev.paths { assert!( !p.starts_with(&excluded), "excluded path leaked through watcher callback: {}", p.display() ); if p.ends_with("real.txt") { saw_real = true; } } if saw_real { break; } } } assert!(saw_real, "expected real.txt event from NativeFsWatcher"); } #[test] fn detects_inotify_watch_limit_errors() { let max_watch = notify::Error::new(notify::ErrorKind::MaxFilesWatch); assert!(is_watch_limit_error(&max_watch)); let generic = notify::Error::new(notify::ErrorKind::Generic("other".to_string())); assert!(!is_watch_limit_error(&generic)); #[cfg(unix)] { let enospc = notify::Error::new(notify::ErrorKind::Io( std::io::Error::from_raw_os_error(libc::ENOSPC), )); assert!(is_watch_limit_error(&enospc)); } } }