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
729                loop {
730                    data_builder.update_timestamp();
731                    watch_data.rescan(&data_builder);
732
733                    // TODO: v7.0 use delay - (Instant::now().saturating_duration_since(start))
734                    let result = if let Some(delay) = delay {
735                        rx.recv_timeout(delay).or_else(|e| match e {
736                            mpsc::RecvTimeoutError::Timeout => Ok(EventLoopMsg::Poll),
737                            mpsc::RecvTimeoutError::Disconnected => Err(mpsc::RecvError),
738                        })
739                    } else {
740                        rx.recv()
741                    };
742                    match result {
743                        Ok(EventLoopMsg::AddWatch(path, mode, resp_tx)) => {
744                            let result = resp_tx.send(watch_data.add_watch(path, mode));
745                            if let Err(e) = result {
746                                tracing::error!(?e, "failed to send AddWatch response");
747                            }
748                        }
749                        Ok(EventLoopMsg::AddWatchMultiple(paths, resp_tx)) => {
750                            let result = resp_tx.send(watch_data.add_watch_multiple(paths));
751                            if let Err(e) = result {
752                                tracing::error!(?e, "failed to send AddWatchMultiple response");
753                            }
754                        }
755                        Ok(EventLoopMsg::RemoveWatch(path, resp_tx)) => {
756                            let result = resp_tx.send(watch_data.remove_watch(&path));
757                            if let Err(e) = result {
758                                tracing::error!(?e, "failed to send RemoveWatch response");
759                            }
760                        }
761                        Ok(EventLoopMsg::Poll) => {
762                            // continue the loop
763                        }
764                        #[cfg(test)]
765                        Ok(EventLoopMsg::WaitNextScan(resp_tx)) => {
766                            let result = resp_tx.send(Ok(()));
767                            if let Err(e) = result {
768                                tracing::error!(?e, "failed to send WaitNextScan response");
769                            }
770                        }
771                        Ok(EventLoopMsg::Shutdown) => {
772                            break;
773                        }
774                        Err(e) => {
775                            tracing::error!(?e, "failed to receive poll message");
776                        }
777                    }
778                }
779            });
780        if let Err(e) = result {
781            tracing::error!(?e, "failed to start poll watcher thread");
782        }
783    }
784
785    /// Watch a path location.
786    fn watch_inner(&self, path: &Path, watch_mode: WatchMode) -> crate::Result<()> {
787        let (tx, rx) = unbounded();
788        self.event_loop_tx
789            .send(EventLoopMsg::AddWatch(path.to_path_buf(), watch_mode, tx))?;
790        rx.recv().unwrap()
791    }
792
793    fn watch_multiple_inner(&self, paths: Vec<(PathBuf, WatchMode)>) -> crate::Result<()> {
794        let (tx, rx) = unbounded();
795        self.event_loop_tx
796            .send(EventLoopMsg::AddWatchMultiple(paths, tx))?;
797        rx.recv().unwrap()
798    }
799
800    /// Unwatch a path.
801    ///
802    /// Return `Err(_)` if given path has't be monitored.
803    fn unwatch_inner(&self, path: &Path) -> crate::Result<()> {
804        let (tx, rx) = unbounded();
805        self.event_loop_tx
806            .send(EventLoopMsg::RemoveWatch(path.to_path_buf(), tx))?;
807        rx.recv().unwrap()
808    }
809}
810
811impl Watcher for PollWatcher {
812    /// Create a new [`PollWatcher`].
813    #[tracing::instrument(level = "debug", skip(event_handler))]
814    fn new<F: EventHandler>(event_handler: F, config: Config) -> crate::Result<Self> {
815        Self::new(event_handler, config)
816    }
817
818    #[tracing::instrument(level = "debug", skip(self))]
819    fn watch(&mut self, path: &Path, watch_mode: WatchMode) -> crate::Result<()> {
820        self.watch_inner(path, watch_mode)
821    }
822
823    #[tracing::instrument(level = "debug", skip(self))]
824    fn paths_mut<'me>(&'me mut self) -> Box<dyn PathsMut + 'me> {
825        Box::new(PollPathsMut::new(self))
826    }
827
828    #[tracing::instrument(level = "debug", skip(self))]
829    fn unwatch(&mut self, path: &Path) -> crate::Result<()> {
830        self.unwatch_inner(path)
831    }
832
833    fn kind() -> crate::WatcherKind {
834        crate::WatcherKind::PollWatcher
835    }
836}
837
838impl Drop for PollWatcher {
839    fn drop(&mut self) {
840        let result = self.event_loop_tx.send(EventLoopMsg::Shutdown);
841        if let Err(e) = result {
842            tracing::error!(?e, "failed to send shutdown message to poll watcher thread");
843        }
844    }
845}
846
847#[cfg(test)]
848mod tests {
849    #[cfg(target_family = "wasm")]
850    use std::thread::sleep;
851    #[cfg(target_family = "wasm")]
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 create_file() {
916        let tmpdir = testdir();
917        let (mut watcher, rx) = watcher();
918        watcher.watch_recursively(&tmpdir);
919        watcher.watcher.wait_next_scan().expect("wait next scan");
920
921        let path = tmpdir.path().join("entry");
922        std::fs::File::create_new(&path).expect("Unable to create");
923
924        rx.sleep_until_parent_contains(&path);
925        rx.sleep_until_exists(&path);
926
927        rx.wait_unordered_exact([
928            expected(&path).create_file(),
929            expected(tmpdir.path()).modify_meta_mtime().optional(),
930        ]);
931    }
932
933    #[test]
934    fn create_self_file() {
935        let tmpdir = testdir();
936        let (mut watcher, rx) = watcher();
937
938        let path = tmpdir.path().join("entry");
939
940        watcher.watch_nonrecursively(&path);
941        watcher.watcher.wait_next_scan().expect("wait next scan");
942
943        std::fs::File::create_new(&path).expect("create");
944
945        rx.sleep_until_exists(&path);
946        rx.wait_ordered_exact([expected(&path).create_file()]);
947    }
948
949    #[test]
950    fn create_self_file_no_track() {
951        let tmpdir = testdir();
952        let (mut watcher, _) = watcher();
953
954        let path = tmpdir.path().join("entry");
955
956        let result = watcher.watcher.watch(
957            &path,
958            WatchMode {
959                recursive_mode: RecursiveMode::NonRecursive,
960                target_mode: TargetMode::NoTrack,
961            },
962        );
963        assert!(matches!(
964            result,
965            Err(Error {
966                paths: _,
967                kind: ErrorKind::PathNotFound
968            })
969        ));
970    }
971
972    #[test]
973    fn create_self_file_nested() {
974        let tmpdir = testdir();
975        let (mut watcher, rx) = watcher();
976
977        let path = tmpdir.path().join("entry/nested");
978
979        watcher.watch_nonrecursively(&path);
980        watcher.watcher.wait_next_scan().expect("wait next scan");
981
982        std::fs::create_dir_all(path.parent().unwrap()).expect("create");
983        std::fs::File::create_new(&path).expect("create");
984
985        rx.wait_ordered_exact([expected(&path).create_file()]);
986    }
987
988    #[test]
989    fn create_dir() {
990        let tmpdir = testdir();
991        let (mut watcher, rx) = watcher();
992        watcher.watch_recursively(&tmpdir);
993        watcher.watcher.wait_next_scan().expect("wait next scan");
994
995        let path = tmpdir.path().join("entry");
996        std::fs::create_dir(&path).expect("Unable to create");
997
998        rx.sleep_until_parent_contains(&path);
999        rx.sleep_until_exists(&path);
1000
1001        rx.wait_unordered_exact([
1002            expected(&path).create_folder(),
1003            expected(tmpdir.path()).modify_meta_mtime().optional(),
1004        ]);
1005    }
1006
1007    #[test]
1008    fn modify_file() {
1009        let tmpdir = testdir();
1010        let (mut watcher, rx) = watcher();
1011        let path = tmpdir.path().join("entry");
1012        std::fs::File::create_new(&path).expect("Unable to create");
1013
1014        rx.sleep_until_parent_contains(&path);
1015
1016        watcher.watch_recursively(&tmpdir);
1017        watcher.watcher.wait_next_scan().expect("wait next scan");
1018        std::fs::write(&path, b"123").expect("Unable to write");
1019
1020        assert!(
1021            rx.sleep_until(|| std::fs::read_to_string(&path).is_ok_and(|content| content == "123")),
1022            "the file wasn't modified"
1023        );
1024        rx.wait_unordered_exact([expected(&path).modify().multiple()]);
1025    }
1026
1027    #[test]
1028    fn rename_file() {
1029        let tmpdir = testdir();
1030        let (mut watcher, rx) = watcher();
1031        let path = tmpdir.path().join("entry");
1032        let new_path = tmpdir.path().join("new_entry");
1033        std::fs::File::create_new(&path).expect("Unable to create");
1034
1035        rx.sleep_until_parent_contains(&path);
1036
1037        watcher.watch_recursively(&tmpdir);
1038
1039        watcher.watcher.wait_next_scan().expect("wait next scan");
1040        std::fs::rename(&path, &new_path).expect("Unable to remove");
1041
1042        rx.sleep_while_exists(&path);
1043        rx.sleep_until_exists(&new_path);
1044
1045        rx.sleep_while_parent_contains(&path);
1046        rx.sleep_until_parent_contains(&new_path);
1047
1048        rx.wait_unordered_exact([
1049            expected(&path).remove_file(),
1050            expected(&new_path).create_file(),
1051            expected(tmpdir.path()).modify_meta_mtime().optional(),
1052        ]);
1053    }
1054
1055    #[test]
1056    fn rename_self_file() {
1057        let tmpdir = testdir();
1058        let (mut watcher, rx) = watcher();
1059
1060        let path = tmpdir.path().join("entry");
1061        std::fs::File::create_new(&path).expect("create");
1062
1063        watcher.watch_nonrecursively(&path);
1064        watcher.watcher.wait_next_scan().expect("wait next scan");
1065        let new_path = tmpdir.path().join("renamed");
1066
1067        std::fs::rename(&path, &new_path).expect("rename");
1068
1069        rx.sleep_while_exists(&path);
1070        rx.sleep_until_exists(&new_path);
1071
1072        rx.wait_unordered_exact([expected(&path).remove_file()])
1073            .ensure_no_tail();
1074
1075        std::fs::rename(&new_path, &path).expect("rename2");
1076        watcher.watcher.wait_next_scan().expect("wait next scan");
1077
1078        rx.sleep_while_exists(&new_path);
1079        rx.sleep_until_exists(&path);
1080
1081        rx.wait_unordered_exact([expected(&path).create_file()])
1082            .ensure_no_tail();
1083    }
1084
1085    #[test]
1086    fn rename_self_file_no_track() {
1087        let tmpdir = testdir();
1088        let (mut watcher, rx) = watcher();
1089
1090        let path = tmpdir.path().join("entry");
1091        std::fs::File::create_new(&path).expect("create");
1092
1093        watcher.watch(
1094            &path,
1095            WatchMode {
1096                recursive_mode: RecursiveMode::NonRecursive,
1097                target_mode: TargetMode::NoTrack,
1098            },
1099        );
1100        watcher.watcher.wait_next_scan().expect("wait next scan");
1101
1102        let new_path = tmpdir.path().join("renamed");
1103
1104        std::fs::rename(&path, &new_path).expect("rename");
1105
1106        rx.sleep_while_exists(&path);
1107        rx.sleep_until_exists(&new_path);
1108
1109        #[cfg(target_family = "wasm")]
1110        sleep(Duration::from_millis(100));
1111
1112        rx.wait_unordered_exact([
1113            expected(&path).modify_data_any().optional(),
1114            expected(&path).remove_file(),
1115        ])
1116        .ensure_no_tail();
1117
1118        let result = watcher.watcher.watch(
1119            &path,
1120            WatchMode {
1121                recursive_mode: RecursiveMode::NonRecursive,
1122                target_mode: TargetMode::NoTrack,
1123            },
1124        );
1125        assert!(matches!(
1126            result,
1127            Err(Error {
1128                paths: _,
1129                kind: ErrorKind::PathNotFound
1130            })
1131        ));
1132    }
1133
1134    #[test]
1135    fn delete_file() {
1136        let tmpdir = testdir();
1137        let (mut watcher, rx) = watcher();
1138        let path = tmpdir.path().join("entry");
1139        std::fs::File::create_new(&path).expect("Unable to create");
1140
1141        rx.sleep_until_parent_contains(&path);
1142
1143        watcher.watch_recursively(&tmpdir);
1144        watcher.watcher.wait_next_scan().expect("wait next scan");
1145
1146        std::fs::remove_file(&path).expect("Unable to remove");
1147
1148        rx.sleep_while_exists(&path);
1149        rx.sleep_while_parent_contains(&path);
1150
1151        rx.wait_unordered_exact([
1152            expected(&path).modify_data_any().optional(),
1153            expected(&path).remove_file(),
1154            expected(tmpdir.path()).modify_meta_mtime().optional(),
1155        ]);
1156    }
1157
1158    #[test]
1159    fn delete_self_file() {
1160        let tmpdir = testdir();
1161        let (mut watcher, rx) = watcher();
1162        let path = tmpdir.path().join("entry");
1163        std::fs::File::create_new(&path).expect("Unable to create");
1164
1165        watcher.watch_nonrecursively(&path);
1166        watcher.watcher.wait_next_scan().expect("wait next scan");
1167
1168        std::fs::remove_file(&path).expect("Unable to remove");
1169
1170        rx.sleep_while_exists(&path);
1171        rx.wait_ordered_exact([
1172            expected(&path).modify_data_any().optional(),
1173            expected(&path).remove_file(),
1174        ]);
1175
1176        std::fs::write(&path, "").expect("write");
1177
1178        rx.sleep_until_exists(&path);
1179        rx.wait_ordered_exact([expected(&path).create_file()]);
1180    }
1181
1182    #[test]
1183    fn delete_self_file_no_track() {
1184        let tmpdir = testdir();
1185        let (mut watcher, rx) = watcher();
1186        let path = tmpdir.path().join("entry");
1187        std::fs::File::create_new(&path).expect("Unable to create");
1188
1189        watcher.watch(
1190            &path,
1191            WatchMode {
1192                recursive_mode: RecursiveMode::NonRecursive,
1193                target_mode: TargetMode::NoTrack,
1194            },
1195        );
1196        watcher.watcher.wait_next_scan().expect("wait next scan");
1197
1198        std::fs::remove_file(&path).expect("Unable to remove");
1199
1200        rx.sleep_while_exists(&path);
1201        rx.wait_ordered_exact([
1202            expected(&path).modify_data_any().optional(),
1203            expected(&path).remove_file(),
1204        ]);
1205
1206        #[cfg(target_family = "wasm")]
1207        sleep(Duration::from_millis(100));
1208
1209        std::fs::write(&path, "").expect("write");
1210
1211        rx.ensure_empty_with_wait();
1212    }
1213
1214    #[test]
1215    fn create_write_overwrite() {
1216        let tmpdir = testdir();
1217        let (mut watcher, rx) = watcher();
1218        let overwritten_file = tmpdir.path().join("overwritten_file");
1219        let overwriting_file = tmpdir.path().join("overwriting_file");
1220        std::fs::write(&overwritten_file, "123").expect("write1");
1221
1222        rx.sleep_until_parent_contains(&overwritten_file);
1223        rx.sleep_until_exists(&overwritten_file);
1224
1225        watcher.watch_nonrecursively(&tmpdir);
1226        watcher.watcher.wait_next_scan().expect("wait next scan");
1227
1228        std::fs::File::create(&overwriting_file).expect("create");
1229        std::fs::write(&overwriting_file, "321").expect("write2");
1230        std::fs::rename(&overwriting_file, &overwritten_file).expect("rename");
1231
1232        rx.sleep_while_exists(&overwriting_file);
1233        rx.sleep_while_parent_contains(&overwriting_file);
1234
1235        assert!(
1236            rx.sleep_until(
1237                || std::fs::read_to_string(&overwritten_file).is_ok_and(|cnt| cnt == "321")
1238            ),
1239            "file {overwritten_file:?} was not replaced"
1240        );
1241
1242        rx.wait_unordered([expected(&overwritten_file).modify()]);
1243    }
1244
1245    fn assert_track_path_continues_after_recreating_file_in_nested_directory(
1246        upgrade_from_no_track: bool,
1247    ) {
1248        let tmpdir = testdir();
1249        let (mut watcher, mut rx) = watcher();
1250        let nested_dir = tmpdir.path().join("nested");
1251        let watched_file = nested_dir.join("watched");
1252        let moved_file = tmpdir.path().join("moved");
1253        std::fs::create_dir(&nested_dir).expect("create nested dir");
1254        std::fs::write(&watched_file, "initial").expect("write watched file");
1255
1256        watcher.watch_nonrecursively(&tmpdir);
1257        if upgrade_from_no_track {
1258            watcher.watch(
1259                &watched_file,
1260                WatchMode {
1261                    recursive_mode: RecursiveMode::NonRecursive,
1262                    target_mode: TargetMode::NoTrack,
1263                },
1264            );
1265        }
1266        watcher.watch_nonrecursively(&watched_file);
1267
1268        std::fs::rename(&watched_file, &moved_file).expect("move watched file");
1269        std::fs::copy(&moved_file, &watched_file).expect("recreate watched file");
1270        std::fs::remove_file(&moved_file).expect("remove moved file");
1271
1272        // Complete a scan, then drain the replacement events before checking the next write.
1273        watcher.watcher.poll().expect("scan replacement");
1274        watcher.watcher.wait_next_scan().expect("wait for scan");
1275        for _ in rx.iter() {}
1276
1277        std::fs::write(&watched_file, "updated").expect("update watched file");
1278        watcher.watcher.poll().expect("scan update");
1279        watcher.watcher.wait_next_scan().expect("wait for scan");
1280        let received_change = rx.iter().any(|event| {
1281            event.paths.iter().any(|path| path == &watched_file)
1282                && matches!(event.kind, EventKind::Create(_) | EventKind::Modify(_))
1283        });
1284
1285        assert!(
1286            received_change,
1287            "expected a change event after recreating the watched file"
1288        );
1289    }
1290
1291    #[test]
1292    fn track_path_continues_after_recreating_file_in_nested_directory() {
1293        assert_track_path_continues_after_recreating_file_in_nested_directory(false);
1294    }
1295
1296    #[test]
1297    fn track_path_upgrade_continues_after_recreating_file_in_nested_directory() {
1298        assert_track_path_continues_after_recreating_file_in_nested_directory(true);
1299    }
1300}