Skip to main content

notify/
poll.rs

1//! Generic Watcher implementation based on polling
2//!
3//! Checks the `watch`ed paths periodically to detect changes. This implementation only uses
4//! Rust stdlib APIs and should work on all of the platforms it supports.
5
6use crate::{
7    Config, Error, EventHandler, IgnoreFilter, PathsMut, Receiver, Result, Sender, WatchMode,
8    Watcher, poll::data::WatchData, unbounded,
9};
10use std::{
11    path::{Path, PathBuf},
12    sync::mpsc,
13    thread,
14    time::Duration,
15};
16
17/// Event sent for registered handlers on initial directory scans
18pub type ScanEvent = crate::Result<PathBuf>;
19
20/// Handler trait for receivers of [`ScanEvent`].
21/// Very much the same as [`EventHandler`], but including the Result.
22///
23/// See the full example for more information.
24pub trait ScanEventHandler: Send + 'static {
25    /// Handles an event.
26    fn handle_event(&mut self, event: ScanEvent);
27}
28
29impl<F> ScanEventHandler for F
30where
31    F: FnMut(ScanEvent) + Send + 'static,
32{
33    fn handle_event(&mut self, event: ScanEvent) {
34        (self)(event);
35    }
36}
37
38#[cfg(feature = "crossbeam-channel")]
39impl ScanEventHandler for crossbeam_channel::Sender<ScanEvent> {
40    fn handle_event(&mut self, event: ScanEvent) {
41        let result = self.send(event);
42        if let Err(e) = result {
43            tracing::error!(?e, "failed to send scan event result");
44        }
45    }
46}
47
48#[cfg(feature = "flume")]
49impl ScanEventHandler for flume::Sender<ScanEvent> {
50    fn handle_event(&mut self, event: ScanEvent) {
51        let result = self.send(event);
52        if let Err(e) = result {
53            tracing::error!(?e, "failed to send scan event result");
54        }
55    }
56}
57
58impl ScanEventHandler for std::sync::mpsc::Sender<ScanEvent> {
59    fn handle_event(&mut self, event: ScanEvent) {
60        let result = self.send(event);
61        if let Err(e) = result {
62            tracing::error!(?e, "failed to send scan event result");
63        }
64    }
65}
66
67impl ScanEventHandler for () {
68    fn handle_event(&mut self, _event: ScanEvent) {}
69}
70
71use data::DataBuilder;
72mod data {
73    use crate::{
74        Error, EventHandler, IgnoreFilter, Result, WatchMode,
75        consolidating_path_trie::ConsolidatingPathTrie,
76        event::{CreateKind, DataChange, Event, EventKind, MetadataKind, ModifyKind, RemoveKind},
77    };
78    use rustc_hash::FxBuildHasher;
79    use std::{
80        cell::RefCell,
81        collections::{HashMap, hash_map::RandomState},
82        fmt::{self, Debug},
83        fs::{File, FileType, Metadata},
84        hash::{BuildHasher, Hasher},
85        io::{self, Read},
86        path::{Path, PathBuf},
87        time::{Instant, SystemTime},
88    };
89    use walkdir::WalkDir;
90
91    use super::ScanEventHandler;
92
93    /// Builder for [`WatchData`] & [`PathData`].
94    pub(super) struct DataBuilder {
95        emitter: EventEmitter,
96        scan_emitter: Option<Box<RefCell<dyn ScanEventHandler>>>,
97
98        // TODO: May allow user setup their custom BuildHasher / BuildHasherDefault
99        // in future.
100        build_hasher: Option<RandomState>,
101
102        // current timestamp for building Data.
103        now: Instant,
104    }
105
106    impl DataBuilder {
107        pub(super) fn new<F, G>(
108            event_handler: F,
109            compare_content: bool,
110            scan_emitter: Option<G>,
111        ) -> Self
112        where
113            F: EventHandler,
114            G: ScanEventHandler,
115        {
116            let scan_emitter = match scan_emitter {
117                None => None,
118                Some(v) => {
119                    // workaround for a weird type resolution bug when directly going to dyn Trait
120                    let intermediate: Box<RefCell<dyn ScanEventHandler>> =
121                        Box::new(RefCell::new(v));
122                    Some(intermediate)
123                }
124            };
125            Self {
126                emitter: EventEmitter::new(event_handler),
127                scan_emitter,
128                build_hasher: compare_content.then(RandomState::default),
129                now: Instant::now(),
130            }
131        }
132
133        /// Update internal timestamp.
134        pub(super) fn update_timestamp(&mut self) {
135            self.now = Instant::now();
136        }
137
138        /// Create [`PathData`].
139        fn build_path_data(&self, meta_path: &MetaPath) -> PathData {
140            PathData::new(self, meta_path)
141        }
142    }
143
144    impl Debug for DataBuilder {
145        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
146            f.debug_struct("DataBuilder")
147                .field("build_hasher", &self.build_hasher)
148                .field("now", &self.now)
149                .finish_non_exhaustive()
150        }
151    }
152
153    type SingleWatchHandlerMap = HashMap<PathBuf, /* recursive */ bool, FxBuildHasher>;
154
155    #[derive(Debug)]
156    struct WatchHandlers {
157        current: SingleWatchHandlerMap,
158        next: SingleWatchHandlerMap,
159        is_stale: bool,
160    }
161
162    impl WatchHandlers {
163        fn new() -> Self {
164            Self {
165                current: HashMap::default(),
166                next: HashMap::default(),
167                is_stale: false,
168            }
169        }
170
171        /// Recalculate from `watches`.
172        fn recalculate(&mut self, watches: &HashMap<PathBuf, WatchMode, FxBuildHasher>) {
173            self.next.clear();
174            self.is_stale = true;
175
176            let mut trie = ConsolidatingPathTrie::new(false, 0);
177            for (path, mode) in watches {
178                if mode.recursive_mode == crate::RecursiveMode::Recursive {
179                    trie.insert(path);
180                }
181            }
182            // insert non-recursive watches that are not covered by recursive watches
183            for (path, mode) in watches {
184                if mode.recursive_mode != crate::RecursiveMode::Recursive {
185                    self.next.insert(path.clone(), false);
186                }
187            }
188            // insert recursive watches
189            for path in trie.values() {
190                self.next.insert(path, true);
191            }
192        }
193
194        fn use_handlers(&mut self) -> (&SingleWatchHandlerMap, Option<SingleWatchHandlerMap>) {
195            if self.is_stale {
196                let old_next = std::mem::take(&mut self.next);
197                let old_current = std::mem::replace(&mut self.current, old_next);
198                self.is_stale = false;
199                return (&self.current, Some(old_current));
200            }
201            (&self.current, None)
202        }
203    }
204
205    #[derive(Debug)]
206    pub(super) struct WatchData {
207        // config part, won't change.
208        follow_symlinks: bool,
209        ignore_filter: IgnoreFilter,
210
211        // current status part.
212        watches: HashMap<PathBuf, WatchMode, FxBuildHasher>,
213        watch_handlers: WatchHandlers,
214        all_path_data: HashMap<PathBuf, PathData, FxBuildHasher>,
215    }
216
217    impl WatchData {
218        /// Create a new `WatchData`.
219        pub fn new(follow_symlinks: bool, ignore_filter: IgnoreFilter) -> Self {
220            Self {
221                follow_symlinks,
222                ignore_filter,
223                watches: HashMap::default(),
224                watch_handlers: WatchHandlers::new(),
225                all_path_data: HashMap::default(),
226            }
227        }
228
229        pub fn add_watch(&mut self, path: PathBuf, mode: WatchMode) -> Result<()> {
230            // an ignored path is not watched
231            if self.ignore_filter.is_path_ignored(&path) {
232                return Ok(());
233            }
234            if mode.target_mode == crate::TargetMode::NoTrack && !path.exists() {
235                return Err(crate::Error::path_not_found().add_path(path));
236            }
237
238            self.watches.insert(path, mode);
239            self.watch_handlers.recalculate(&self.watches);
240            Ok(())
241        }
242
243        pub fn add_watch_multiple(&mut self, paths: Vec<(PathBuf, WatchMode)>) -> Result<()> {
244            for (path, mode) in paths {
245                // an ignored path is not watched
246                if self.ignore_filter.is_path_ignored(&path) {
247                    continue;
248                }
249                if mode.target_mode == crate::TargetMode::NoTrack && !path.exists() {
250                    return Err(crate::Error::path_not_found().add_path(path));
251                }
252
253                self.watches.insert(path, mode);
254            }
255            self.watch_handlers.recalculate(&self.watches);
256            Ok(())
257        }
258
259        pub fn remove_watch(&mut self, path: &Path) -> Result<()> {
260            if self.watches.remove(path).is_none() {
261                // an ignored path is never watched, so unwatching it is not an error
262                return if self.ignore_filter.is_path_ignored(path) {
263                    Ok(())
264                } else {
265                    Err(Error::watch_not_found())
266                };
267            }
268            self.watch_handlers.recalculate(&self.watches);
269            Ok(())
270        }
271
272        /// Rescan filesystem and update this `WatchData`.
273        ///
274        /// # Side effect
275        ///
276        /// This function may emit event by `data_builder.emitter`.
277        pub(super) fn rescan(&mut self, data_builder: &DataBuilder) {
278            let (watch_handlers, old_watch_handlers) = self.watch_handlers.use_handlers();
279
280            // scan current filesystem.
281            for (path, new_path_data) in Self::scan_all_path_data(
282                data_builder,
283                watch_handlers,
284                self.follow_symlinks,
285                &self.ignore_filter,
286            ) {
287                let event_kind = if let Some(old_path_data) = self.all_path_data.get_mut(&path) {
288                    let event_kind =
289                        PathData::compare_to_kind(Some(&*old_path_data), Some(&new_path_data));
290                    *old_path_data = new_path_data;
291                    event_kind
292                } else {
293                    let event_kind = PathData::compare_to_kind(None, Some(&new_path_data));
294                    self.all_path_data.insert(path.clone(), new_path_data);
295                    event_kind
296                };
297
298                let is_initial = old_watch_handlers
299                    .as_ref()
300                    .is_some_and(|old_watch_handlers| {
301                        !old_watch_handlers.contains_key(&path)
302                            && !path.ancestors().skip(1).any(|ancestor| {
303                                old_watch_handlers
304                                    .get(ancestor)
305                                    .is_some_and(|is_recursive| *is_recursive)
306                            })
307                    });
308                if is_initial {
309                    // emit initial scans
310                    if let Some(ref emitter) = data_builder.scan_emitter {
311                        emitter.borrow_mut().handle_event(Ok(path.clone()));
312                    }
313                } else if let Some(event_kind) = event_kind {
314                    let event = Event::new(event_kind).add_path(path);
315                    data_builder.emitter.emit_ok(event);
316                }
317            }
318
319            // scan for disappeared paths.
320            let mut disappeared_paths = Vec::new();
321            for (path, path_data) in &self.all_path_data {
322                if path_data.last_check < data_builder.now {
323                    disappeared_paths.push(path.clone());
324                }
325            }
326
327            // remove disappeared paths
328            for path in disappeared_paths {
329                let old_path_data = self.all_path_data.remove(&path);
330
331                if let Some(event_kind) = PathData::compare_to_kind(old_path_data.as_ref(), None) {
332                    let event = Event::new(event_kind).add_path(path);
333                    data_builder.emitter.emit_ok(event);
334                }
335            }
336        }
337
338        /// Get all `PathData` by given configuration.
339        ///
340        /// # Side Effect
341        ///
342        /// This function may emit some IO Error events by `data_builder.emitter`.
343        fn scan_all_path_data(
344            data_builder: &DataBuilder,
345            watch_handlers: &HashMap<PathBuf, /* recursive */ bool, FxBuildHasher>,
346            follow_symlinks: bool,
347            ignore_filter: &IgnoreFilter,
348        ) -> impl Iterator<Item = (PathBuf, PathData)> {
349            tracing::trace!("rescanning");
350
351            watch_handlers.iter().flat_map(move |(path, is_recursive)| {
352                tracing::trace!(?path, is_recursive, "scanning watch handler");
353
354                // WalkDir return only one entry if root is a file (not a folder),
355                // so we can use single logic to do the both file & dir's jobs.
356                //
357                // See: https://docs.rs/walkdir/2.0.1/walkdir/struct.WalkDir.html#method.new
358                ignore_filter
359                    .walk(
360                        WalkDir::new(path)
361                            .follow_links(follow_symlinks)
362                            .max_depth(if *is_recursive { usize::MAX } else { 1 }),
363                    )
364                    .filter_map(|entry_res| match entry_res {
365                        Ok(entry) => Some(entry),
366                        Err(err) => {
367                            tracing::warn!("walkdir error scanning {err:?}");
368
369                            if let Some(io_error) = err.io_error() {
370                                if io_error.kind() == io::ErrorKind::NotFound {
371                                    return None;
372                                }
373                                // clone an io::Error, so we have to create a new one.
374                                let new_io_error = io::Error::new(io_error.kind(), err.to_string());
375                                data_builder.emitter.emit_io_err(new_io_error, err.path());
376                            } else {
377                                let crate_err =
378                                    Error::new(crate::ErrorKind::Generic(err.to_string()));
379                                data_builder.emitter.emit(Err(crate_err));
380                            }
381                            None
382                        }
383                    })
384                    .filter_map(move |entry| match entry.metadata() {
385                        Ok(metadata) => {
386                            let path = entry.into_path();
387                            let meta_path = MetaPath::from_parts_unchecked(path, metadata);
388                            let data_path = data_builder.build_path_data(&meta_path);
389
390                            Some((meta_path.into_path(), data_path))
391                        }
392                        Err(err) => {
393                            if let Some(io_error) = err.io_error()
394                                && io_error.kind() == io::ErrorKind::NotFound
395                            {
396                                return None;
397                            }
398
399                            // emit event.
400                            let path = entry.into_path();
401                            data_builder.emitter.emit_io_err(err, Some(path));
402
403                            None
404                        }
405                    })
406            })
407        }
408    }
409
410    /// Stored data for a one path locations.
411    ///
412    /// See [`WatchData`] for more detail.
413    #[derive(Debug, Clone)]
414    struct PathData {
415        /// File updated time.
416        mtime: SystemTime,
417
418        file_type: FileType,
419
420        /// Content's hash value, only available if user request compare file
421        /// contents and read successful.
422        hash: Option<u64>,
423
424        /// Checked time.
425        last_check: Instant,
426    }
427
428    impl PathData {
429        /// Create a new `PathData`.
430        fn new(data_builder: &DataBuilder, meta_path: &MetaPath) -> PathData {
431            let metadata = meta_path.metadata();
432
433            PathData {
434                mtime: metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH),
435                file_type: metadata.file_type(),
436                hash: data_builder
437                    .build_hasher
438                    .as_ref()
439                    .filter(|_| metadata.is_file())
440                    .and_then(|build_hasher| {
441                        Self::get_content_hash(build_hasher, meta_path.path()).ok()
442                    }),
443
444                last_check: data_builder.now,
445            }
446        }
447
448        /// Get hash value for the data content in given file `path`.
449        fn get_content_hash(build_hasher: &RandomState, path: &Path) -> io::Result<u64> {
450            let mut hasher = build_hasher.build_hasher();
451            let mut file = File::open(path)?;
452            let mut buf = [0; 512];
453
454            loop {
455                let n = match file.read(&mut buf) {
456                    Ok(0) => break,
457                    Ok(len) => len,
458                    Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
459                    Err(e) => return Err(e),
460                };
461
462                hasher.write(&buf[..n]);
463            }
464
465            Ok(hasher.finish())
466        }
467
468        /// Get `CreateKind` by file type.
469        fn get_create_kind(&self) -> CreateKind {
470            #[expect(clippy::filetype_is_file)]
471            if self.file_type.is_dir() {
472                CreateKind::Folder
473            } else if self.file_type.is_file() {
474                CreateKind::File
475            } else {
476                CreateKind::Any
477            }
478        }
479
480        /// Get `RemoveKind` by file type.
481        fn get_remove_kind(&self) -> RemoveKind {
482            #[expect(clippy::filetype_is_file)]
483            if self.file_type.is_dir() {
484                RemoveKind::Folder
485            } else if self.file_type.is_file() {
486                RemoveKind::File
487            } else {
488                RemoveKind::Any
489            }
490        }
491
492        /// Get [`EventKind`] by compare two optional [`PathData`].
493        fn compare_to_kind(old: Option<&PathData>, new: Option<&PathData>) -> Option<EventKind> {
494            match (old, new) {
495                (Some(old), Some(new)) => {
496                    if new.mtime > old.mtime {
497                        Some(EventKind::Modify(ModifyKind::Metadata(
498                            MetadataKind::WriteTime,
499                        )))
500                    } else if new.hash != old.hash {
501                        Some(EventKind::Modify(ModifyKind::Data(DataChange::Any)))
502                    } else {
503                        None
504                    }
505                }
506                (None, Some(new)) => Some(EventKind::Create(new.get_create_kind())),
507                (Some(old), None) => Some(EventKind::Remove(old.get_remove_kind())),
508                (None, None) => None,
509            }
510        }
511    }
512
513    /// Compose path and its metadata.
514    ///
515    /// This data structure designed for make sure path and its metadata can be
516    /// transferred in consistent way, and may avoid some duplicated
517    /// `fs::metadata()` function call in some situations.
518    #[derive(Debug)]
519    pub(super) struct MetaPath {
520        path: PathBuf,
521        metadata: Metadata,
522    }
523
524    impl MetaPath {
525        /// Create `MetaPath` by given parts.
526        ///
527        /// # Invariant
528        ///
529        /// User must make sure the input `metadata` are associated with `path`.
530        fn from_parts_unchecked(path: PathBuf, metadata: Metadata) -> Self {
531            Self { path, metadata }
532        }
533
534        fn path(&self) -> &Path {
535            &self.path
536        }
537
538        fn metadata(&self) -> &Metadata {
539            &self.metadata
540        }
541
542        fn into_path(self) -> PathBuf {
543            self.path
544        }
545    }
546
547    /// Thin wrapper for outer event handler, for easy to use.
548    struct EventEmitter(
549        // Use `RefCell` to make sure `emit()` only need shared borrow of self (&self).
550        // Use `Box` to make sure EventEmitter is Sized.
551        Box<RefCell<dyn EventHandler>>,
552    );
553
554    impl EventEmitter {
555        fn new<F: EventHandler>(event_handler: F) -> Self {
556            Self(Box::new(RefCell::new(event_handler)))
557        }
558
559        /// Emit single event.
560        fn emit(&self, event: crate::Result<Event>) {
561            self.0.borrow_mut().handle_event(event);
562        }
563
564        /// Emit event.
565        fn emit_ok(&self, event: Event) {
566            self.emit(Ok(event));
567        }
568
569        /// Emit io error event.
570        fn emit_io_err<E, P>(&self, err: E, path: Option<P>)
571        where
572            E: Into<io::Error>,
573            P: Into<PathBuf>,
574        {
575            let e = crate::Error::io(err.into());
576            if let Some(path) = path {
577                self.emit(Err(e.add_path(path.into())));
578            } else {
579                self.emit(Err(e));
580            }
581        }
582    }
583}
584
585enum EventLoopMsg {
586    AddWatch(PathBuf, WatchMode, Sender<Result<()>>),
587    AddWatchMultiple(Vec<(PathBuf, WatchMode)>, Sender<Result<()>>),
588    RemoveWatch(PathBuf, Sender<Result<()>>),
589    #[cfg(test)]
590    WaitNextScan(Sender<Result<()>>),
591    /// currently used only for manual polling
592    Poll,
593    Shutdown,
594}
595
596struct PollPathsMut<'a> {
597    inner: &'a mut PollWatcher,
598    add_paths: Vec<(PathBuf, WatchMode)>,
599}
600impl<'a> PollPathsMut<'a> {
601    fn new(watcher: &'a mut PollWatcher) -> Self {
602        Self {
603            inner: watcher,
604            add_paths: Vec::new(),
605        }
606    }
607}
608impl PathsMut for PollPathsMut<'_> {
609    #[tracing::instrument(level = "debug", skip(self))]
610    fn add(&mut self, path: &Path, watch_mode: WatchMode) -> Result<()> {
611        self.add_paths.push((path.to_owned(), watch_mode));
612        Ok(())
613    }
614
615    #[tracing::instrument(level = "debug", skip(self))]
616    fn remove(&mut self, path: &Path) -> Result<()> {
617        self.inner.unwatch_inner(path)
618    }
619
620    #[tracing::instrument(level = "debug", skip(self))]
621    fn commit(self: Box<Self>) -> Result<()> {
622        let paths = self.add_paths;
623        self.inner.watch_multiple_inner(paths)
624    }
625}
626
627/// Polling based `Watcher` implementation.
628///
629/// By default scans through all files and checks for changed entries based on their change date.
630/// Can also be changed to perform file content change checks.
631///
632/// See [Config] for more details.
633#[derive(Debug)]
634pub struct PollWatcher {
635    delay: Option<Duration>,
636    follow_symlinks: bool,
637    ignore_filter: IgnoreFilter,
638
639    event_loop_tx: Sender<EventLoopMsg>,
640}
641
642impl PollWatcher {
643    /// Create a new [`PollWatcher`], configured as needed.
644    #[expect(clippy::needless_pass_by_value, reason = "public API")]
645    pub fn new<F: EventHandler>(event_handler: F, config: Config) -> crate::Result<PollWatcher> {
646        Ok(Self::with_opt::<_, ()>(event_handler, &config, None))
647    }
648
649    /// Actively poll for changes. Can be combined with a timeout of 0 to perform only manual polling.
650    pub fn poll(&self) -> crate::Result<()> {
651        self.event_loop_tx
652            .send(EventLoopMsg::Poll)
653            .map_err(|_| Error::generic("failed to send poll message"))?;
654        Ok(())
655    }
656
657    #[cfg(test)]
658    pub(crate) fn wait_next_scan(&self) -> crate::Result<()> {
659        let (tx, rx) = unbounded();
660        self.event_loop_tx
661            .send(EventLoopMsg::WaitNextScan(tx))
662            .map_err(|_| Error::generic("failed to send WaitNextScan message"))?;
663        rx.recv().unwrap()
664    }
665
666    /// Returns a sender to initiate changes detection.
667    #[cfg(test)]
668    pub(crate) fn poll_sender(&self) -> Sender<()> {
669        let inner_tx = self.event_loop_tx.clone();
670        let (tx, rx) = unbounded();
671        thread::Builder::new()
672            .name("notify-rs poll loop".to_string())
673            .spawn(move || {
674                for () in &rx {
675                    if let Err(err) = inner_tx.send(EventLoopMsg::Poll) {
676                        tracing::error!(?err, "failed to send poll message");
677                    }
678                }
679            })
680            .unwrap();
681        tx
682    }
683
684    /// Create a new [`PollWatcher`] with an scan event handler.
685    ///
686    /// `scan_fallback` is called on the initial scan with all files seen by the pollwatcher.
687    #[expect(clippy::needless_pass_by_value, reason = "public API")]
688    pub fn with_initial_scan<F: EventHandler, G: ScanEventHandler>(
689        event_handler: F,
690        config: Config,
691        scan_callback: G,
692    ) -> crate::Result<PollWatcher> {
693        Ok(Self::with_opt(event_handler, &config, Some(scan_callback)))
694    }
695
696    /// create a new [`PollWatcher`] with all options.
697    fn with_opt<F: EventHandler, G: ScanEventHandler>(
698        event_handler: F,
699        config: &Config,
700        scan_callback: Option<G>,
701    ) -> PollWatcher {
702        let (tx, rx) = unbounded();
703
704        let poll_watcher = PollWatcher {
705            delay: config.poll_interval(),
706            follow_symlinks: config.follow_symlinks(),
707            ignore_filter: config.ignored().clone(),
708
709            event_loop_tx: tx,
710        };
711
712        let data_builder =
713            DataBuilder::new(event_handler, config.compare_contents(), scan_callback);
714        poll_watcher.run(rx, data_builder);
715
716        poll_watcher
717    }
718
719    fn run(&self, rx: Receiver<EventLoopMsg>, mut data_builder: DataBuilder) {
720        let delay = self.delay;
721        let follow_symlinks = self.follow_symlinks;
722        let ignore_filter = self.ignore_filter.clone();
723
724        let result = thread::Builder::new()
725            .name("notify-rs poll loop".to_string())
726            .spawn(move || {
727                let mut watch_data = WatchData::new(follow_symlinks, ignore_filter);
728                let mut pending_add: Option<(Sender<Result<()>>, Result<()>)> = None;
729
730                loop {
731                    data_builder.update_timestamp();
732                    watch_data.rescan(&data_builder);
733                    // Establish the baseline before returning from watch registration.
734                    if let Some((tx, result)) = pending_add.take()
735                        && let Err(e) = tx.send(result)
736                    {
737                        tracing::error!(?e, "failed to send watch response");
738                    }
739
740                    // TODO: v7.0 use delay - (Instant::now().saturating_duration_since(start))
741                    let result = if let Some(delay) = delay {
742                        rx.recv_timeout(delay).or_else(|e| match e {
743                            mpsc::RecvTimeoutError::Timeout => Ok(EventLoopMsg::Poll),
744                            mpsc::RecvTimeoutError::Disconnected => Err(mpsc::RecvError),
745                        })
746                    } else {
747                        rx.recv()
748                    };
749                    match result {
750                        Ok(EventLoopMsg::AddWatch(path, mode, resp_tx)) => {
751                            pending_add = Some((resp_tx, watch_data.add_watch(path, mode)));
752                        }
753                        Ok(EventLoopMsg::AddWatchMultiple(paths, resp_tx)) => {
754                            pending_add = Some((resp_tx, watch_data.add_watch_multiple(paths)));
755                        }
756                        Ok(EventLoopMsg::RemoveWatch(path, resp_tx)) => {
757                            let result = resp_tx.send(watch_data.remove_watch(&path));
758                            if let Err(e) = result {
759                                tracing::error!(?e, "failed to send RemoveWatch response");
760                            }
761                        }
762                        Ok(EventLoopMsg::Poll) => {
763                            // continue the loop
764                        }
765                        #[cfg(test)]
766                        Ok(EventLoopMsg::WaitNextScan(resp_tx)) => {
767                            let result = resp_tx.send(Ok(()));
768                            if let Err(e) = result {
769                                tracing::error!(?e, "failed to send WaitNextScan response");
770                            }
771                        }
772                        Ok(EventLoopMsg::Shutdown) => {
773                            break;
774                        }
775                        Err(e) => {
776                            tracing::error!(?e, "failed to receive poll message");
777                        }
778                    }
779                }
780            });
781        if let Err(e) = result {
782            tracing::error!(?e, "failed to start poll watcher thread");
783        }
784    }
785
786    /// Watch a path location.
787    fn watch_inner(&self, path: &Path, watch_mode: WatchMode) -> crate::Result<()> {
788        let (tx, rx) = unbounded();
789        self.event_loop_tx
790            .send(EventLoopMsg::AddWatch(path.to_path_buf(), watch_mode, tx))?;
791        rx.recv().unwrap()
792    }
793
794    fn watch_multiple_inner(&self, paths: Vec<(PathBuf, WatchMode)>) -> crate::Result<()> {
795        let (tx, rx) = unbounded();
796        self.event_loop_tx
797            .send(EventLoopMsg::AddWatchMultiple(paths, tx))?;
798        rx.recv().unwrap()
799    }
800
801    /// Unwatch a path.
802    ///
803    /// Return `Err(_)` if given path has't be monitored.
804    fn unwatch_inner(&self, path: &Path) -> crate::Result<()> {
805        let (tx, rx) = unbounded();
806        self.event_loop_tx
807            .send(EventLoopMsg::RemoveWatch(path.to_path_buf(), tx))?;
808        rx.recv().unwrap()
809    }
810}
811
812impl Watcher for PollWatcher {
813    /// Create a new [`PollWatcher`].
814    #[tracing::instrument(level = "debug", skip(event_handler))]
815    fn new<F: EventHandler>(event_handler: F, config: Config) -> crate::Result<Self> {
816        Self::new(event_handler, config)
817    }
818
819    #[tracing::instrument(level = "debug", skip(self))]
820    fn watch(&mut self, path: &Path, watch_mode: WatchMode) -> crate::Result<()> {
821        self.watch_inner(path, watch_mode)
822    }
823
824    #[tracing::instrument(level = "debug", skip(self))]
825    fn paths_mut<'me>(&'me mut self) -> Box<dyn PathsMut + 'me> {
826        Box::new(PollPathsMut::new(self))
827    }
828
829    #[tracing::instrument(level = "debug", skip(self))]
830    fn unwatch(&mut self, path: &Path) -> crate::Result<()> {
831        self.unwatch_inner(path)
832    }
833
834    fn kind() -> crate::WatcherKind {
835        crate::WatcherKind::PollWatcher
836    }
837}
838
839impl Drop for PollWatcher {
840    fn drop(&mut self) {
841        let result = self.event_loop_tx.send(EventLoopMsg::Shutdown);
842        if let Err(e) = result {
843            tracing::error!(?e, "failed to send shutdown message to poll watcher thread");
844        }
845    }
846}
847
848#[cfg(test)]
849mod tests {
850    #[cfg(target_family = "wasm")]
851    use std::thread::sleep;
852    use std::time::Duration;
853
854    use super::PollWatcher;
855    use crate::{
856        Error, ErrorKind, RecursiveMode, TargetMode, WatchMode, Watcher, event::EventKind, test::*,
857    };
858
859    fn watcher() -> (TestWatcher<PollWatcher>, Receiver) {
860        poll_watcher_channel()
861    }
862
863    fn ignoring_watcher() -> (TestWatcher<PollWatcher>, Receiver) {
864        poll_watcher_channel_with_config(
865            ignoring_config()
866                .with_compare_contents(true)
867                .with_manual_polling(),
868        )
869    }
870
871    #[test]
872    fn ignored_directory_is_not_scanned() {
873        let tmpdir = testdir();
874        let ignored = tmpdir.path().join("node_modules/pkg/index.js");
875        std::fs::create_dir_all(ignored.parent().unwrap()).expect("create dir");
876        std::fs::write(&ignored, "").expect("write");
877
878        let (mut watcher, rx) = ignoring_watcher();
879        watcher.watch_recursively(&tmpdir);
880        // watching an ignored path does nothing
881        watcher.watch_recursively(ignored.parent().unwrap());
882        watcher.watcher.wait_next_scan().expect("wait next scan");
883
884        std::fs::write(&ignored, "123").expect("write");
885        let path = tmpdir.path().join("index.js");
886        std::fs::File::create_new(&path).expect("Unable to create");
887
888        rx.sleep_until_parent_contains(&path);
889        rx.sleep_until_exists(&path);
890
891        rx.wait_unordered_exact([
892            expected(&path).create_file(),
893            expected(tmpdir.path()).modify_meta_mtime().optional(),
894        ])
895        .ensure_no_tail();
896
897        watcher
898            .watcher
899            .unwatch(ignored.parent().unwrap())
900            .expect("unwatch");
901        // a path that is neither watched nor ignored is still an error
902        watcher
903            .watcher
904            .unwatch(&tmpdir.path().join("src"))
905            .expect_err("unwatch");
906    }
907
908    #[test]
909    fn poll_watcher_is_send_and_sync() {
910        fn check<T: Send + Sync>() {}
911        check::<PollWatcher>();
912    }
913
914    #[test]
915    fn watch_registration_waits_for_initial_scan() {
916        for multiple in [false, true] {
917            let tmpdir = testdir();
918            let path = tmpdir.path().to_path_buf();
919
920            let (scan_tx, scan_rx) = std::sync::mpsc::channel();
921            let (resume_tx, resume_rx) = std::sync::mpsc::channel();
922            let watcher = PollWatcher::with_initial_scan(
923                |_| {},
924                crate::Config::default().with_manual_polling(),
925                move |event: super::ScanEvent| {
926                    event.expect("initial scan");
927                    scan_tx.send(()).expect("signal initial scan");
928                    resume_rx
929                        .recv_timeout(Duration::from_secs(5))
930                        .expect("resume initial scan");
931                },
932            )
933            .expect("create watcher");
934            let mode = WatchMode::non_recursive();
935            let (response_tx, response_rx) = crate::unbounded();
936            let request = if multiple {
937                super::EventLoopMsg::AddWatchMultiple(vec![(path, mode)], response_tx)
938            } else {
939                super::EventLoopMsg::AddWatch(path, mode, response_tx)
940            };
941            watcher.event_loop_tx.send(request).expect("register watch");
942
943            scan_rx
944                .recv_timeout(Duration::from_secs(5))
945                .expect("initial scan started");
946            let response_during_scan = response_rx.try_recv();
947            resume_tx.send(()).expect("resume scan");
948            assert!(
949                response_during_scan.is_err(),
950                "watch registration returned before the initial scan completed"
951            );
952            response_rx
953                .recv_timeout(Duration::from_secs(5))
954                .expect("watch response")
955                .expect("watch registered");
956        }
957    }
958
959    #[test]
960    fn create_file() {
961        let tmpdir = testdir();
962        let (mut watcher, rx) = watcher();
963        watcher.watch_recursively(&tmpdir);
964        watcher.watcher.wait_next_scan().expect("wait next scan");
965
966        let path = tmpdir.path().join("entry");
967        std::fs::File::create_new(&path).expect("Unable to create");
968
969        rx.sleep_until_parent_contains(&path);
970        rx.sleep_until_exists(&path);
971
972        rx.wait_unordered_exact([
973            expected(&path).create_file(),
974            expected(tmpdir.path()).modify_meta_mtime().optional(),
975        ]);
976    }
977
978    #[test]
979    fn create_self_file() {
980        let tmpdir = testdir();
981        let (mut watcher, rx) = watcher();
982
983        let path = tmpdir.path().join("entry");
984
985        watcher.watch_nonrecursively(&path);
986        watcher.watcher.wait_next_scan().expect("wait next scan");
987
988        std::fs::File::create_new(&path).expect("create");
989
990        rx.sleep_until_exists(&path);
991        rx.wait_ordered_exact([expected(&path).create_file()]);
992    }
993
994    #[test]
995    fn create_self_file_no_track() {
996        let tmpdir = testdir();
997        let (mut watcher, _) = watcher();
998
999        let path = tmpdir.path().join("entry");
1000
1001        let result = watcher.watcher.watch(
1002            &path,
1003            WatchMode {
1004                recursive_mode: RecursiveMode::NonRecursive,
1005                target_mode: TargetMode::NoTrack,
1006            },
1007        );
1008        assert!(matches!(
1009            result,
1010            Err(Error {
1011                paths: _,
1012                kind: ErrorKind::PathNotFound
1013            })
1014        ));
1015    }
1016
1017    #[test]
1018    fn create_self_file_nested() {
1019        let tmpdir = testdir();
1020        let (mut watcher, rx) = watcher();
1021
1022        let path = tmpdir.path().join("entry/nested");
1023
1024        watcher.watch_nonrecursively(&path);
1025        watcher.watcher.wait_next_scan().expect("wait next scan");
1026
1027        std::fs::create_dir_all(path.parent().unwrap()).expect("create");
1028        std::fs::File::create_new(&path).expect("create");
1029
1030        rx.wait_ordered_exact([expected(&path).create_file()]);
1031    }
1032
1033    #[test]
1034    fn create_dir() {
1035        let tmpdir = testdir();
1036        let (mut watcher, rx) = watcher();
1037        watcher.watch_recursively(&tmpdir);
1038        watcher.watcher.wait_next_scan().expect("wait next scan");
1039
1040        let path = tmpdir.path().join("entry");
1041        std::fs::create_dir(&path).expect("Unable to create");
1042
1043        rx.sleep_until_parent_contains(&path);
1044        rx.sleep_until_exists(&path);
1045
1046        rx.wait_unordered_exact([
1047            expected(&path).create_folder(),
1048            expected(tmpdir.path()).modify_meta_mtime().optional(),
1049        ]);
1050    }
1051
1052    #[test]
1053    fn modify_file() {
1054        let tmpdir = testdir();
1055        let (mut watcher, rx) = watcher();
1056        let path = tmpdir.path().join("entry");
1057        std::fs::File::create_new(&path).expect("Unable to create");
1058
1059        rx.sleep_until_parent_contains(&path);
1060
1061        watcher.watch_recursively(&tmpdir);
1062        watcher.watcher.wait_next_scan().expect("wait next scan");
1063        std::fs::write(&path, b"123").expect("Unable to write");
1064
1065        assert!(
1066            rx.sleep_until(|| std::fs::read_to_string(&path).is_ok_and(|content| content == "123")),
1067            "the file wasn't modified"
1068        );
1069        rx.wait_unordered_exact([expected(&path).modify().multiple()]);
1070    }
1071
1072    #[test]
1073    fn rename_file() {
1074        let tmpdir = testdir();
1075        let (mut watcher, rx) = watcher();
1076        let path = tmpdir.path().join("entry");
1077        let new_path = tmpdir.path().join("new_entry");
1078        std::fs::File::create_new(&path).expect("Unable to create");
1079
1080        rx.sleep_until_parent_contains(&path);
1081
1082        watcher.watch_recursively(&tmpdir);
1083
1084        watcher.watcher.wait_next_scan().expect("wait next scan");
1085        std::fs::rename(&path, &new_path).expect("Unable to remove");
1086
1087        rx.sleep_while_exists(&path);
1088        rx.sleep_until_exists(&new_path);
1089
1090        rx.sleep_while_parent_contains(&path);
1091        rx.sleep_until_parent_contains(&new_path);
1092
1093        rx.wait_unordered_exact([
1094            expected(&path).remove_file(),
1095            expected(&new_path).create_file(),
1096            expected(tmpdir.path()).modify_meta_mtime().optional(),
1097        ]);
1098    }
1099
1100    #[test]
1101    fn rename_self_file() {
1102        let tmpdir = testdir();
1103        let (mut watcher, rx) = watcher();
1104
1105        let path = tmpdir.path().join("entry");
1106        std::fs::File::create_new(&path).expect("create");
1107
1108        watcher.watch_nonrecursively(&path);
1109        watcher.watcher.wait_next_scan().expect("wait next scan");
1110        let new_path = tmpdir.path().join("renamed");
1111
1112        std::fs::rename(&path, &new_path).expect("rename");
1113
1114        rx.sleep_while_exists(&path);
1115        rx.sleep_until_exists(&new_path);
1116
1117        rx.wait_unordered_exact([expected(&path).remove_file()])
1118            .ensure_no_tail();
1119
1120        std::fs::rename(&new_path, &path).expect("rename2");
1121        watcher.watcher.wait_next_scan().expect("wait next scan");
1122
1123        rx.sleep_while_exists(&new_path);
1124        rx.sleep_until_exists(&path);
1125
1126        rx.wait_unordered_exact([expected(&path).create_file()])
1127            .ensure_no_tail();
1128    }
1129
1130    #[test]
1131    fn rename_self_file_no_track() {
1132        let tmpdir = testdir();
1133        let (mut watcher, rx) = watcher();
1134
1135        let path = tmpdir.path().join("entry");
1136        std::fs::File::create_new(&path).expect("create");
1137
1138        watcher.watch(
1139            &path,
1140            WatchMode {
1141                recursive_mode: RecursiveMode::NonRecursive,
1142                target_mode: TargetMode::NoTrack,
1143            },
1144        );
1145        watcher.watcher.wait_next_scan().expect("wait next scan");
1146
1147        let new_path = tmpdir.path().join("renamed");
1148
1149        std::fs::rename(&path, &new_path).expect("rename");
1150
1151        rx.sleep_while_exists(&path);
1152        rx.sleep_until_exists(&new_path);
1153
1154        #[cfg(target_family = "wasm")]
1155        sleep(Duration::from_millis(100));
1156
1157        rx.wait_unordered_exact([
1158            expected(&path).modify_data_any().optional(),
1159            expected(&path).remove_file(),
1160        ])
1161        .ensure_no_tail();
1162
1163        let result = watcher.watcher.watch(
1164            &path,
1165            WatchMode {
1166                recursive_mode: RecursiveMode::NonRecursive,
1167                target_mode: TargetMode::NoTrack,
1168            },
1169        );
1170        assert!(matches!(
1171            result,
1172            Err(Error {
1173                paths: _,
1174                kind: ErrorKind::PathNotFound
1175            })
1176        ));
1177    }
1178
1179    #[test]
1180    fn delete_file() {
1181        let tmpdir = testdir();
1182        let (mut watcher, rx) = watcher();
1183        let path = tmpdir.path().join("entry");
1184        std::fs::File::create_new(&path).expect("Unable to create");
1185
1186        rx.sleep_until_parent_contains(&path);
1187
1188        watcher.watch_recursively(&tmpdir);
1189        watcher.watcher.wait_next_scan().expect("wait next scan");
1190
1191        std::fs::remove_file(&path).expect("Unable to remove");
1192
1193        rx.sleep_while_exists(&path);
1194        rx.sleep_while_parent_contains(&path);
1195
1196        rx.wait_unordered_exact([
1197            expected(&path).modify_data_any().optional(),
1198            expected(&path).remove_file(),
1199            expected(tmpdir.path()).modify_meta_mtime().optional(),
1200        ]);
1201    }
1202
1203    #[test]
1204    fn delete_self_file() {
1205        let tmpdir = testdir();
1206        let (mut watcher, rx) = watcher();
1207        let path = tmpdir.path().join("entry");
1208        std::fs::File::create_new(&path).expect("Unable to create");
1209
1210        watcher.watch_nonrecursively(&path);
1211        watcher.watcher.wait_next_scan().expect("wait next scan");
1212
1213        std::fs::remove_file(&path).expect("Unable to remove");
1214
1215        rx.sleep_while_exists(&path);
1216        rx.wait_ordered_exact([
1217            expected(&path).modify_data_any().optional(),
1218            expected(&path).remove_file(),
1219        ]);
1220
1221        std::fs::write(&path, "").expect("write");
1222
1223        rx.sleep_until_exists(&path);
1224        rx.wait_ordered_exact([expected(&path).create_file()]);
1225    }
1226
1227    #[test]
1228    fn delete_self_file_no_track() {
1229        let tmpdir = testdir();
1230        let (mut watcher, rx) = watcher();
1231        let path = tmpdir.path().join("entry");
1232        std::fs::File::create_new(&path).expect("Unable to create");
1233
1234        watcher.watch(
1235            &path,
1236            WatchMode {
1237                recursive_mode: RecursiveMode::NonRecursive,
1238                target_mode: TargetMode::NoTrack,
1239            },
1240        );
1241        watcher.watcher.wait_next_scan().expect("wait next scan");
1242
1243        std::fs::remove_file(&path).expect("Unable to remove");
1244
1245        rx.sleep_while_exists(&path);
1246        rx.wait_ordered_exact([
1247            expected(&path).modify_data_any().optional(),
1248            expected(&path).remove_file(),
1249        ]);
1250
1251        #[cfg(target_family = "wasm")]
1252        sleep(Duration::from_millis(100));
1253
1254        std::fs::write(&path, "").expect("write");
1255
1256        rx.ensure_empty_with_wait();
1257    }
1258
1259    #[test]
1260    fn create_write_overwrite() {
1261        let tmpdir = testdir();
1262        let (mut watcher, rx) = watcher();
1263        let overwritten_file = tmpdir.path().join("overwritten_file");
1264        let overwriting_file = tmpdir.path().join("overwriting_file");
1265        std::fs::write(&overwritten_file, "123").expect("write1");
1266
1267        rx.sleep_until_parent_contains(&overwritten_file);
1268        rx.sleep_until_exists(&overwritten_file);
1269
1270        watcher.watch_nonrecursively(&tmpdir);
1271        watcher.watcher.wait_next_scan().expect("wait next scan");
1272
1273        std::fs::File::create(&overwriting_file).expect("create");
1274        std::fs::write(&overwriting_file, "321").expect("write2");
1275        std::fs::rename(&overwriting_file, &overwritten_file).expect("rename");
1276
1277        rx.sleep_while_exists(&overwriting_file);
1278        rx.sleep_while_parent_contains(&overwriting_file);
1279
1280        assert!(
1281            rx.sleep_until(
1282                || std::fs::read_to_string(&overwritten_file).is_ok_and(|cnt| cnt == "321")
1283            ),
1284            "file {overwritten_file:?} was not replaced"
1285        );
1286
1287        rx.wait_unordered([expected(&overwritten_file).modify()]);
1288    }
1289
1290    fn assert_track_path_continues_after_recreating_file_in_nested_directory(
1291        upgrade_from_no_track: bool,
1292    ) {
1293        let tmpdir = testdir();
1294        let (mut watcher, mut rx) = watcher();
1295        let nested_dir = tmpdir.path().join("nested");
1296        let watched_file = nested_dir.join("watched");
1297        let moved_file = tmpdir.path().join("moved");
1298        std::fs::create_dir(&nested_dir).expect("create nested dir");
1299        std::fs::write(&watched_file, "initial").expect("write watched file");
1300
1301        watcher.watch_nonrecursively(&tmpdir);
1302        if upgrade_from_no_track {
1303            watcher.watch(
1304                &watched_file,
1305                WatchMode {
1306                    recursive_mode: RecursiveMode::NonRecursive,
1307                    target_mode: TargetMode::NoTrack,
1308                },
1309            );
1310        }
1311        watcher.watch_nonrecursively(&watched_file);
1312
1313        std::fs::rename(&watched_file, &moved_file).expect("move watched file");
1314        std::fs::copy(&moved_file, &watched_file).expect("recreate watched file");
1315        std::fs::remove_file(&moved_file).expect("remove moved file");
1316
1317        // Complete a scan, then drain the replacement events before checking the next write.
1318        watcher.watcher.poll().expect("scan replacement");
1319        watcher.watcher.wait_next_scan().expect("wait for scan");
1320        for _ in rx.iter() {}
1321
1322        std::fs::write(&watched_file, "updated").expect("update watched file");
1323        watcher.watcher.poll().expect("scan update");
1324        watcher.watcher.wait_next_scan().expect("wait for scan");
1325        let received_change = rx.iter().any(|event| {
1326            event.paths.iter().any(|path| path == &watched_file)
1327                && matches!(event.kind, EventKind::Create(_) | EventKind::Modify(_))
1328        });
1329
1330        assert!(
1331            received_change,
1332            "expected a change event after recreating the watched file"
1333        );
1334    }
1335
1336    #[test]
1337    fn track_path_continues_after_recreating_file_in_nested_directory() {
1338        assert_track_path_continues_after_recreating_file_in_nested_directory(false);
1339    }
1340
1341    #[test]
1342    fn track_path_upgrade_continues_after_recreating_file_in_nested_directory() {
1343        assert_track_path_continues_after_recreating_file_in_nested_directory(true);
1344    }
1345}