fsevent.rs

  1#![cfg(target_os = "macos")]
  2
  3use bitflags::bitflags;
  4use fsevent_sys::{self as fs, core_foundation as cf};
  5use parking_lot::Mutex;
  6use std::{
  7    convert::AsRef,
  8    ffi::{CStr, OsStr, c_void},
  9    os::unix::ffi::OsStrExt,
 10    path::{Path, PathBuf},
 11    ptr, slice,
 12    sync::Arc,
 13    time::Duration,
 14};
 15
 16#[derive(Clone, Debug)]
 17pub struct Event {
 18    pub event_id: u64,
 19    pub flags: StreamFlags,
 20    pub path: PathBuf,
 21}
 22
 23pub struct EventStream {
 24    lifecycle: Arc<Mutex<Lifecycle>>,
 25    state: Box<State>,
 26}
 27
 28struct State {
 29    latency: Duration,
 30    paths: cf::CFMutableArrayRef,
 31    callback: Option<Box<dyn FnMut(Vec<Event>) -> bool>>,
 32    last_valid_event_id: Option<fs::FSEventStreamEventId>,
 33    stream: fs::FSEventStreamRef,
 34}
 35
 36impl Drop for State {
 37    fn drop(&mut self) {
 38        unsafe {
 39            cf::CFRelease(self.paths);
 40            fs::FSEventStreamStop(self.stream);
 41            fs::FSEventStreamInvalidate(self.stream);
 42            fs::FSEventStreamRelease(self.stream);
 43        }
 44    }
 45}
 46
 47enum Lifecycle {
 48    New,
 49    Running(cf::CFRunLoopRef),
 50    Stopped,
 51}
 52
 53pub struct Handle(Arc<Mutex<Lifecycle>>);
 54
 55unsafe impl Send for EventStream {}
 56unsafe impl Send for Lifecycle {}
 57
 58impl EventStream {
 59    pub fn new(paths: &[&Path], latency: Duration) -> (Self, Handle) {
 60        unsafe {
 61            let cf_paths =
 62                cf::CFArrayCreateMutable(cf::kCFAllocatorDefault, 0, &cf::kCFTypeArrayCallBacks);
 63            assert!(!cf_paths.is_null());
 64
 65            for path in paths {
 66                let path_bytes = path.as_os_str().as_bytes();
 67                let cf_url = cf::CFURLCreateFromFileSystemRepresentation(
 68                    cf::kCFAllocatorDefault,
 69                    path_bytes.as_ptr() as *const i8,
 70                    path_bytes.len() as cf::CFIndex,
 71                    false,
 72                );
 73                let cf_path = cf::CFURLCopyFileSystemPath(cf_url, cf::kCFURLPOSIXPathStyle);
 74                cf::CFArrayAppendValue(cf_paths, cf_path);
 75                cf::CFRelease(cf_path);
 76                cf::CFRelease(cf_url);
 77            }
 78
 79            let mut state = Box::new(State {
 80                latency,
 81                paths: cf_paths,
 82                callback: None,
 83                last_valid_event_id: None,
 84                stream: ptr::null_mut(),
 85            });
 86            let stream_context = fs::FSEventStreamContext {
 87                version: 0,
 88                info: state.as_ref() as *const _ as *mut c_void,
 89                retain: None,
 90                release: None,
 91                copy_description: None,
 92            };
 93            let stream = fs::FSEventStreamCreate(
 94                cf::kCFAllocatorDefault,
 95                Self::trampoline,
 96                &stream_context,
 97                cf_paths,
 98                FSEventsGetCurrentEventId(),
 99                latency.as_secs_f64(),
100                fs::kFSEventStreamCreateFlagFileEvents
101                    | fs::kFSEventStreamCreateFlagNoDefer
102                    | fs::kFSEventStreamCreateFlagWatchRoot,
103            );
104            state.stream = stream;
105
106            let lifecycle = Arc::new(Mutex::new(Lifecycle::New));
107            (
108                EventStream {
109                    lifecycle: lifecycle.clone(),
110                    state,
111                },
112                Handle(lifecycle),
113            )
114        }
115    }
116
117    pub fn run<F>(mut self, f: F)
118    where
119        F: FnMut(Vec<Event>) -> bool + 'static,
120    {
121        self.state.callback = Some(Box::new(f));
122        unsafe {
123            let run_loop =
124                core_foundation::base::CFRetain(cf::CFRunLoopGetCurrent()) as *mut c_void;
125            {
126                let mut state = self.lifecycle.lock();
127                match *state {
128                    Lifecycle::New => *state = Lifecycle::Running(run_loop),
129                    Lifecycle::Running(_) => unreachable!(),
130                    Lifecycle::Stopped => return,
131                }
132            }
133            fs::FSEventStreamScheduleWithRunLoop(
134                self.state.stream,
135                run_loop,
136                cf::kCFRunLoopDefaultMode,
137            );
138            fs::FSEventStreamStart(self.state.stream);
139            cf::CFRunLoopRun();
140        }
141    }
142
143    extern "C" fn trampoline(
144        stream_ref: fs::FSEventStreamRef,
145        info: *mut ::std::os::raw::c_void,
146        num: usize,                                 // size_t numEvents
147        event_paths: *mut ::std::os::raw::c_void,   // void *eventPaths
148        event_flags: *const ::std::os::raw::c_void, // const FSEventStreamEventFlags eventFlags[]
149        event_ids: *const ::std::os::raw::c_void,   // const FSEventStreamEventId eventIds[]
150    ) {
151        unsafe {
152            let event_paths = event_paths as *const *const ::std::os::raw::c_char;
153            let e_ptr = event_flags as *mut u32;
154            let i_ptr = event_ids as *mut u64;
155            let state = (info as *mut State).as_mut().unwrap();
156            let callback = if let Some(callback) = state.callback.as_mut() {
157                callback
158            } else {
159                return;
160            };
161
162            let paths = slice::from_raw_parts(event_paths, num);
163            let flags = slice::from_raw_parts_mut(e_ptr, num);
164            let ids = slice::from_raw_parts_mut(i_ptr, num);
165            let mut stream_restarted = false;
166
167            // Sometimes FSEvents reports a "dropped" event, an indication that either the kernel
168            // or our code couldn't keep up with the sheer volume of file-system events that were
169            // generated. If we observed a valid event before this happens, we'll try to read the
170            // file-system journal by stopping the current stream and creating a new one starting at
171            // such event. Otherwise, we'll let invoke the callback with the dropped event, which
172            // will likely perform a re-scan of one of the root directories.
173            if flags
174                .iter()
175                .copied()
176                .filter_map(StreamFlags::from_bits)
177                .any(|flags| {
178                    flags.contains(StreamFlags::USER_DROPPED)
179                        || flags.contains(StreamFlags::KERNEL_DROPPED)
180                })
181            {
182                if let Some(last_valid_event_id) = state.last_valid_event_id.take() {
183                    fs::FSEventStreamStop(state.stream);
184                    fs::FSEventStreamInvalidate(state.stream);
185                    fs::FSEventStreamRelease(state.stream);
186
187                    let stream_context = fs::FSEventStreamContext {
188                        version: 0,
189                        info,
190                        retain: None,
191                        release: None,
192                        copy_description: None,
193                    };
194                    let stream = fs::FSEventStreamCreate(
195                        cf::kCFAllocatorDefault,
196                        Self::trampoline,
197                        &stream_context,
198                        state.paths,
199                        last_valid_event_id,
200                        state.latency.as_secs_f64(),
201                        fs::kFSEventStreamCreateFlagFileEvents
202                            | fs::kFSEventStreamCreateFlagNoDefer
203                            | fs::kFSEventStreamCreateFlagWatchRoot,
204                    );
205
206                    state.stream = stream;
207                    fs::FSEventStreamScheduleWithRunLoop(
208                        state.stream,
209                        cf::CFRunLoopGetCurrent(),
210                        cf::kCFRunLoopDefaultMode,
211                    );
212                    fs::FSEventStreamStart(state.stream);
213                    stream_restarted = true;
214                }
215            }
216
217            if !stream_restarted {
218                let mut events = Vec::with_capacity(num);
219                for p in 0..num {
220                    if let Some(flag) = StreamFlags::from_bits(flags[p]) {
221                        if !flag.contains(StreamFlags::HISTORY_DONE) {
222                            let path_c_str = CStr::from_ptr(paths[p]);
223                            let path = PathBuf::from(OsStr::from_bytes(path_c_str.to_bytes()));
224                            let event = Event {
225                                event_id: ids[p],
226                                flags: flag,
227                                path,
228                            };
229                            state.last_valid_event_id = Some(event.event_id);
230                            events.push(event);
231                        }
232                    } else {
233                        debug_assert!(false, "unknown flag set for fs event: {}", flags[p]);
234                    }
235                }
236
237                if !events.is_empty() && !callback(events) {
238                    fs::FSEventStreamStop(stream_ref);
239                    cf::CFRunLoopStop(cf::CFRunLoopGetCurrent());
240                }
241            }
242        }
243    }
244}
245
246impl Drop for Handle {
247    fn drop(&mut self) {
248        let mut state = self.0.lock();
249        if let Lifecycle::Running(run_loop) = *state {
250            unsafe {
251                cf::CFRunLoopStop(run_loop);
252                cf::CFRelease(run_loop)
253            }
254        }
255        *state = Lifecycle::Stopped;
256    }
257}
258
259// Synchronize with
260// /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/FSEvents.framework/Versions/A/Headers/FSEvents.h
261bitflags! {
262    #[derive(Debug, PartialEq, Eq, Clone, Copy)]
263  #[repr(C)]
264  pub struct StreamFlags: u32 {
265    const NONE = 0x00000000;
266    const MUST_SCAN_SUBDIRS = 0x00000001;
267    const USER_DROPPED = 0x00000002;
268    const KERNEL_DROPPED = 0x00000004;
269    const IDS_WRAPPED = 0x00000008;
270    const HISTORY_DONE = 0x00000010;
271    const ROOT_CHANGED = 0x00000020;
272    const MOUNT = 0x00000040;
273    const UNMOUNT = 0x00000080;
274    const ITEM_CREATED = 0x00000100;
275    const ITEM_REMOVED = 0x00000200;
276    const INODE_META_MOD = 0x00000400;
277    const ITEM_RENAMED = 0x00000800;
278    const ITEM_MODIFIED = 0x00001000;
279    const FINDER_INFO_MOD = 0x00002000;
280    const ITEM_CHANGE_OWNER = 0x00004000;
281    const ITEM_XATTR_MOD = 0x00008000;
282    const IS_FILE = 0x00010000;
283    const IS_DIR = 0x00020000;
284    const IS_SYMLINK = 0x00040000;
285    const OWN_EVENT = 0x00080000;
286    const IS_HARDLINK = 0x00100000;
287    const IS_LAST_HARDLINK = 0x00200000;
288    const ITEM_CLONED = 0x400000;
289  }
290}
291
292impl std::fmt::Display for StreamFlags {
293    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
294        if self.contains(StreamFlags::MUST_SCAN_SUBDIRS) {
295            let _d = write!(f, "MUST_SCAN_SUBDIRS ");
296        }
297        if self.contains(StreamFlags::USER_DROPPED) {
298            let _d = write!(f, "USER_DROPPED ");
299        }
300        if self.contains(StreamFlags::KERNEL_DROPPED) {
301            let _d = write!(f, "KERNEL_DROPPED ");
302        }
303        if self.contains(StreamFlags::IDS_WRAPPED) {
304            let _d = write!(f, "IDS_WRAPPED ");
305        }
306        if self.contains(StreamFlags::HISTORY_DONE) {
307            let _d = write!(f, "HISTORY_DONE ");
308        }
309        if self.contains(StreamFlags::ROOT_CHANGED) {
310            let _d = write!(f, "ROOT_CHANGED ");
311        }
312        if self.contains(StreamFlags::MOUNT) {
313            let _d = write!(f, "MOUNT ");
314        }
315        if self.contains(StreamFlags::UNMOUNT) {
316            let _d = write!(f, "UNMOUNT ");
317        }
318        if self.contains(StreamFlags::ITEM_CREATED) {
319            let _d = write!(f, "ITEM_CREATED ");
320        }
321        if self.contains(StreamFlags::ITEM_REMOVED) {
322            let _d = write!(f, "ITEM_REMOVED ");
323        }
324        if self.contains(StreamFlags::INODE_META_MOD) {
325            let _d = write!(f, "INODE_META_MOD ");
326        }
327        if self.contains(StreamFlags::ITEM_RENAMED) {
328            let _d = write!(f, "ITEM_RENAMED ");
329        }
330        if self.contains(StreamFlags::ITEM_MODIFIED) {
331            let _d = write!(f, "ITEM_MODIFIED ");
332        }
333        if self.contains(StreamFlags::FINDER_INFO_MOD) {
334            let _d = write!(f, "FINDER_INFO_MOD ");
335        }
336        if self.contains(StreamFlags::ITEM_CHANGE_OWNER) {
337            let _d = write!(f, "ITEM_CHANGE_OWNER ");
338        }
339        if self.contains(StreamFlags::ITEM_XATTR_MOD) {
340            let _d = write!(f, "ITEM_XATTR_MOD ");
341        }
342        if self.contains(StreamFlags::IS_FILE) {
343            let _d = write!(f, "IS_FILE ");
344        }
345        if self.contains(StreamFlags::IS_DIR) {
346            let _d = write!(f, "IS_DIR ");
347        }
348        if self.contains(StreamFlags::IS_SYMLINK) {
349            let _d = write!(f, "IS_SYMLINK ");
350        }
351        if self.contains(StreamFlags::OWN_EVENT) {
352            let _d = write!(f, "OWN_EVENT ");
353        }
354        if self.contains(StreamFlags::IS_LAST_HARDLINK) {
355            let _d = write!(f, "IS_LAST_HARDLINK ");
356        }
357        if self.contains(StreamFlags::IS_HARDLINK) {
358            let _d = write!(f, "IS_HARDLINK ");
359        }
360        if self.contains(StreamFlags::ITEM_CLONED) {
361            let _d = write!(f, "ITEM_CLONED ");
362        }
363        write!(f, "")
364    }
365}
366
367#[link(name = "CoreServices", kind = "framework")]
368unsafe extern "C" {
369    pub fn FSEventsGetCurrentEventId() -> u64;
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375    use std::{fs, sync::mpsc, thread, time::Duration};
376
377    #[test]
378    fn test_event_stream_simple() {
379        for _ in 0..3 {
380            let dir = tempfile::Builder::new()
381                .prefix("test-event-stream")
382                .tempdir()
383                .unwrap();
384            let path = dir.path().canonicalize().unwrap();
385            for i in 0..10 {
386                fs::write(path.join(format!("existing-file-{}", i)), "").unwrap();
387            }
388            flush_historical_events();
389
390            let (tx, rx) = mpsc::channel();
391            let (stream, handle) = EventStream::new(&[&path], Duration::from_millis(50));
392            thread::spawn(move || stream.run(move |events| tx.send(events.to_vec()).is_ok()));
393
394            fs::write(path.join("new-file"), "").unwrap();
395            let events = rx.recv_timeout(Duration::from_secs(2)).unwrap();
396            let event = events.last().unwrap();
397            assert_eq!(event.path, path.join("new-file"));
398            assert!(event.flags.contains(StreamFlags::ITEM_CREATED));
399
400            fs::remove_file(path.join("existing-file-5")).unwrap();
401            let mut events = rx.recv_timeout(Duration::from_secs(2)).unwrap();
402            let mut event = events.last().unwrap();
403            // we see this duplicate about 1/100 test runs.
404            if event.path == path.join("new-file")
405                && event.flags.contains(StreamFlags::ITEM_CREATED)
406            {
407                events = rx.recv_timeout(Duration::from_secs(2)).unwrap();
408                event = events.last().unwrap();
409            }
410            assert_eq!(event.path, path.join("existing-file-5"));
411            assert!(event.flags.contains(StreamFlags::ITEM_REMOVED));
412            drop(handle);
413        }
414    }
415
416    #[test]
417    fn test_event_stream_delayed_start() {
418        for _ in 0..3 {
419            let dir = tempfile::Builder::new()
420                .prefix("test-event-stream")
421                .tempdir()
422                .unwrap();
423            let path = dir.path().canonicalize().unwrap();
424            for i in 0..10 {
425                fs::write(path.join(format!("existing-file-{}", i)), "").unwrap();
426            }
427            flush_historical_events();
428
429            let (tx, rx) = mpsc::channel();
430            let (stream, handle) = EventStream::new(&[&path], Duration::from_millis(50));
431
432            // Delay the call to `run` in order to make sure we don't miss any events that occur
433            // between creating the `EventStream` and calling `run`.
434            thread::spawn(move || {
435                thread::sleep(Duration::from_millis(100));
436                stream.run(move |events| tx.send(events.to_vec()).is_ok())
437            });
438
439            fs::write(path.join("new-file"), "").unwrap();
440            let events = rx.recv_timeout(Duration::from_secs(2)).unwrap();
441            let event = events.last().unwrap();
442            assert_eq!(event.path, path.join("new-file"));
443            assert!(event.flags.contains(StreamFlags::ITEM_CREATED));
444
445            fs::remove_file(path.join("existing-file-5")).unwrap();
446            let events = rx.recv_timeout(Duration::from_secs(2)).unwrap();
447            let event = events.last().unwrap();
448            assert_eq!(event.path, path.join("existing-file-5"));
449            assert!(event.flags.contains(StreamFlags::ITEM_REMOVED));
450            drop(handle);
451        }
452    }
453
454    #[test]
455    fn test_event_stream_shutdown_by_dropping_handle() {
456        let dir = tempfile::Builder::new()
457            .prefix("test-event-stream")
458            .tempdir()
459            .unwrap();
460        let path = dir.path().canonicalize().unwrap();
461        flush_historical_events();
462
463        let (tx, rx) = mpsc::channel();
464        let (stream, handle) = EventStream::new(&[&path], Duration::from_millis(50));
465        thread::spawn(move || {
466            stream.run({
467                let tx = tx.clone();
468                move |_| {
469                    tx.send("running").unwrap();
470                    true
471                }
472            });
473            tx.send("stopped").unwrap();
474        });
475
476        fs::write(path.join("new-file"), "").unwrap();
477        assert_eq!(rx.recv_timeout(Duration::from_secs(2)).unwrap(), "running");
478
479        // Dropping the handle causes `EventStream::run` to return.
480        drop(handle);
481        assert_eq!(rx.recv_timeout(Duration::from_secs(2)).unwrap(), "stopped");
482    }
483
484    #[test]
485    fn test_event_stream_shutdown_before_run() {
486        let dir = tempfile::Builder::new()
487            .prefix("test-event-stream")
488            .tempdir()
489            .unwrap();
490        let path = dir.path().canonicalize().unwrap();
491
492        let (stream, handle) = EventStream::new(&[&path], Duration::from_millis(50));
493        drop(handle);
494
495        // This returns immediately because the handle was already dropped.
496        stream.run(|_| true);
497    }
498
499    fn flush_historical_events() {
500        let duration = if std::env::var("CI").is_ok() {
501            Duration::from_secs(2)
502        } else {
503            Duration::from_millis(500)
504        };
505        thread::sleep(duration);
506    }
507}