use std::path::Path;
use std::time::{Duration, Instant};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecvOutcome {
Hint,
Overflow,
Timeout,
Closed,
}
pub trait EventSource {
fn recv(&mut self, timeout_ms: u64) -> RecvOutcome;
}
pub trait Clock {
fn now_ms(&self) -> u64;
}
pub struct RealClock(Instant);
impl RealClock {
pub fn new() -> Self {
Self(Instant::now())
}
}
impl Default for RealClock {
fn default() -> Self {
Self::new()
}
}
impl Clock for RealClock {
fn now_ms(&self) -> u64 {
self.0.elapsed().as_millis() as u64
}
}
pub struct NotifySource {
rx: std::sync::mpsc::Receiver<notify::Result<notify::Event>>,
_watcher: notify::RecommendedWatcher,
}
impl NotifySource {
pub fn watch(root: &Path) -> notify::Result<Self> {
use notify::Watcher;
let (tx, rx) = std::sync::mpsc::channel();
let mut watcher = notify::recommended_watcher(move |res| {
let _ = tx.send(res);
})?;
watcher.watch(root, notify::RecursiveMode::Recursive)?;
Ok(Self { rx, _watcher: watcher })
}
}
impl EventSource for NotifySource {
fn recv(&mut self, timeout_ms: u64) -> RecvOutcome {
use std::sync::mpsc::RecvTimeoutError;
match self.rx.recv_timeout(Duration::from_millis(timeout_ms)) {
Ok(Ok(_event)) => {
while self.rx.try_recv().is_ok() {} RecvOutcome::Hint
}
Ok(Err(e)) => {
log::warn!("watcher: {e}; reconciling the whole root");
RecvOutcome::Overflow
}
Err(RecvTimeoutError::Timeout) => RecvOutcome::Timeout,
Err(RecvTimeoutError::Disconnected) => RecvOutcome::Closed,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct WatchConfig {
pub debounce_ms: u64,
pub periodic_reconcile_ms: u64,
}
impl Default for WatchConfig {
fn default() -> Self {
Self { debounce_ms: 500, periodic_reconcile_ms: 10 * 60 * 1000 }
}
}
pub fn run(
source: &mut dyn EventSource,
clock: &dyn Clock,
cfg: &WatchConfig,
mut should_stop: impl FnMut() -> bool,
mut on_trigger: impl FnMut(),
) {
on_trigger();
let mut last_trigger = clock.now_ms();
loop {
if should_stop() {
return;
}
let elapsed = clock.now_ms().saturating_sub(last_trigger);
let wait = cfg.periodic_reconcile_ms.saturating_sub(elapsed);
match source.recv(wait) {
RecvOutcome::Closed => return,
RecvOutcome::Timeout => {
on_trigger();
last_trigger = clock.now_ms();
}
RecvOutcome::Hint | RecvOutcome::Overflow => {
while matches!(source.recv(cfg.debounce_ms), RecvOutcome::Hint | RecvOutcome::Overflow) {}
on_trigger();
last_trigger = clock.now_ms();
}
}
}
}
pub mod test_support {
use super::*;
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Default)]
pub struct FakeClock(AtomicU64);
impl FakeClock {
pub fn new() -> Self {
Self(AtomicU64::new(0))
}
pub fn advance(&self, ms: u64) {
self.0.fetch_add(ms, Ordering::SeqCst);
}
}
impl Clock for FakeClock {
fn now_ms(&self) -> u64 {
self.0.load(Ordering::SeqCst)
}
}
pub struct ScriptedSource<'a> {
clock: &'a FakeClock,
script: VecDeque<(u64, RecvOutcome)>,
}
impl<'a> ScriptedSource<'a> {
pub fn new(clock: &'a FakeClock, script: Vec<(u64, RecvOutcome)>) -> Self {
Self { clock, script: script.into() }
}
}
impl EventSource for ScriptedSource<'_> {
fn recv(&mut self, timeout_ms: u64) -> RecvOutcome {
match self.script.pop_front() {
Some((advance, outcome)) => {
self.clock.advance(advance);
outcome
}
None => {
self.clock.advance(timeout_ms);
RecvOutcome::Timeout
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::test_support::*;
use super::*;
use std::cell::Cell;
fn run_script(script: Vec<(u64, RecvOutcome)>, cfg: WatchConfig, stop_after: u32) -> u32 {
let clock = FakeClock::new();
let mut source = ScriptedSource::new(&clock, script);
let count = Cell::new(0u32);
run(&mut source, &clock, &cfg, || count.get() >= stop_after, || count.set(count.get() + 1));
count.get()
}
#[test]
fn always_reconciles_once_at_startup_even_with_no_events() {
let n = run_script(vec![], WatchConfig { periodic_reconcile_ms: 1_000_000, ..Default::default() }, 1);
assert_eq!(n, 1);
}
#[test]
fn a_burst_of_hints_becomes_one_trigger() {
let script = vec![
(0, RecvOutcome::Hint),
(10, RecvOutcome::Hint),
(10, RecvOutcome::Hint),
(10, RecvOutcome::Hint),
(10, RecvOutcome::Hint),
];
let n = run_script(script, WatchConfig::default(), 2);
assert_eq!(n, 2);
}
#[test]
fn overflow_is_treated_exactly_like_a_hint() {
let n = run_script(vec![(0, RecvOutcome::Overflow)], WatchConfig::default(), 2);
assert_eq!(n, 2);
}
#[test]
fn widely_spaced_hints_are_separate_triggers() {
let script = vec![(0, RecvOutcome::Hint), (1_000, RecvOutcome::Hint)];
let n = run_script(script, WatchConfig::default(), 3);
assert_eq!(n, 3); }
#[test]
fn no_events_at_all_still_reconciles_periodically() {
let cfg = WatchConfig { debounce_ms: 500, periodic_reconcile_ms: 60_000 };
let n = run_script(vec![], cfg, 4); assert_eq!(n, 4);
}
#[test]
fn stops_promptly_when_asked() {
let clock = FakeClock::new();
let mut source = ScriptedSource::new(&clock, vec![]);
let count = Cell::new(0u32);
run(&mut source, &clock, &WatchConfig::default(), || true, || count.set(count.get() + 1));
assert_eq!(count.get(), 1); }
#[test]
fn closed_source_ends_the_run() {
let clock = FakeClock::new();
let mut source = ScriptedSource::new(&clock, vec![(0, RecvOutcome::Closed)]);
let count = Cell::new(0u32);
run(&mut source, &clock, &WatchConfig::default(), || false, || count.set(count.get() + 1));
assert_eq!(count.get(), 1); }
}