use notify::{Event, RecommendedWatcher, RecursiveMode, Watcher, recommended_watcher};
use std::path::Path;
use std::time::Duration;
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
pub(crate) const MAX_COALESCE: Duration = Duration::from_secs(10);
pub(crate) const SYNC_ERROR_BACKOFF: Duration = Duration::from_secs(5);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BurstWait {
Ready,
ChannelClosed,
Aborted,
}
pub(crate) async fn wait_debounce(
changes: &mut UnboundedReceiver<()>,
delay: Duration,
abort: impl core::future::Future<Output = crate::Result<()>>,
) -> crate::Result<BurstWait> {
let window_start = tokio::time::Instant::now();
let mut abort = core::pin::pin!(abort);
loop {
tokio::select! {
res = changes.recv() => {
if res.is_none() {
return Ok(BurstWait::ChannelClosed);
}
}
() = tokio::time::sleep(delay) => return Ok(BurstWait::Ready),
() = tokio::time::sleep_until(window_start + MAX_COALESCE) => return Ok(BurstWait::Ready),
res = &mut abort => {
res?;
return Ok(BurstWait::Aborted);
}
}
}
}
pub(crate) fn start_watcher(
root: &Path,
tx: UnboundedSender<()>,
) -> notify::Result<RecommendedWatcher> {
let mut watcher = recommended_watcher(move |res: notify::Result<Event>| {
if let Ok(event) = res
&& event_is_syncworthy(&event)
{
let _ = tx.send(());
}
})?;
watcher.watch(root, RecursiveMode::Recursive)?;
Ok(watcher)
}
fn event_is_syncworthy(event: &Event) -> bool {
!event.kind.is_access()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn access_events_are_ignored() {
use notify::EventKind;
let access = Event {
kind: EventKind::Access(notify::event::AccessKind::Read),
paths: vec![],
attrs: notify::event::EventAttributes::default(),
};
let modify = Event {
kind: EventKind::Modify(notify::event::ModifyKind::Data(
notify::event::DataChange::Any,
)),
paths: vec![],
attrs: notify::event::EventAttributes::default(),
};
let create = Event {
kind: EventKind::Create(notify::event::CreateKind::File),
paths: vec![],
attrs: notify::event::EventAttributes::default(),
};
assert!(!event_is_syncworthy(&access));
assert!(event_is_syncworthy(&modify));
assert!(event_is_syncworthy(&create));
}
#[cfg(unix)]
#[tokio::test]
async fn watcher_fires_on_write() {
let dir = tempfile::tempdir().unwrap();
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<()>();
let _watcher = start_watcher(dir.path(), tx).unwrap();
tokio::fs::write(dir.path().join("f.txt"), b"x")
.await
.unwrap();
let got = tokio::time::timeout(Duration::from_secs(5), rx.recv()).await;
assert!(
matches!(got, Ok(Some(()))),
"write must produce a sync-worthy event, got {got:?}"
);
}
}