use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{
Receiver, RecvError, RecvTimeoutError, SyncSender, TryRecvError, TrySendError,
};
use std::sync::{mpsc, Arc};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use super::backend::Kind;
use super::path::NsPath;
pub const DEFAULT_INTERVAL: Duration = Duration::from_millis(250);
pub const MIN_INTERVAL: Duration = Duration::from_millis(10);
pub const MAX_INTERVAL: Duration = Duration::from_secs(60 * 60);
pub const DEFAULT_MAX_ENTRIES: usize = 1024;
pub const DEFAULT_MAX_TRACKED: usize = 262_144;
pub const DEFAULT_MAX_DEPTH: usize = 64;
pub const QUEUE_DEPTH: usize = 16;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct WatchOpts {
pub recursive: bool,
pub interval: Duration,
pub max_entries: usize,
pub max_tracked: usize,
pub max_depth: usize,
}
impl Default for WatchOpts {
fn default() -> Self {
WatchOpts {
recursive: false,
interval: DEFAULT_INTERVAL,
max_entries: DEFAULT_MAX_ENTRIES,
max_tracked: DEFAULT_MAX_TRACKED,
max_depth: DEFAULT_MAX_DEPTH,
}
}
}
impl WatchOpts {
#[must_use]
pub fn recursive(mut self, recursive: bool) -> Self {
self.recursive = recursive;
self
}
#[must_use]
pub fn interval(mut self, interval: Duration) -> Self {
self.interval = interval;
self
}
#[must_use]
pub fn max_entries(mut self, max_entries: usize) -> Self {
self.max_entries = max_entries;
self
}
#[must_use]
pub fn max_tracked(mut self, max_tracked: usize) -> Self {
self.max_tracked = max_tracked;
self
}
#[must_use]
pub fn max_depth(mut self, max_depth: usize) -> Self {
self.max_depth = max_depth;
self
}
pub(crate) fn effective_interval(&self) -> Duration {
self.interval.clamp(MIN_INTERVAL, MAX_INTERVAL)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct WatchBatch {
pub epoch: u64,
pub generation: u64,
pub changed: Vec<NsPath>,
pub rescan: bool,
}
impl WatchBatch {
pub fn new(epoch: u64, generation: u64, changed: Vec<NsPath>, rescan: bool) -> Self {
WatchBatch {
epoch,
generation,
changed,
rescan,
}
}
}
#[derive(Debug, Default, Clone)]
pub struct WatchCursor {
last: Option<(u64, u64)>,
}
impl WatchCursor {
pub fn new() -> Self {
Self::default()
}
pub fn observe(&mut self, batch: &WatchBatch) -> bool {
let continuous = match self.last {
None => batch.generation == 1,
Some((epoch, generation)) => {
epoch == batch.epoch && generation.checked_add(1) == Some(batch.generation)
}
};
self.last = Some((batch.epoch, batch.generation));
batch.rescan || !continuous
}
}
type Mapper = Arc<dyn Fn(&NsPath) -> Option<NsPath> + Send + Sync>;
pub struct Watch {
rx: Receiver<WatchBatch>,
mapper: Option<Mapper>,
on_drop: Option<Box<dyn FnOnce() + Send>>,
}
impl std::fmt::Debug for Watch {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Watch").finish_non_exhaustive()
}
}
impl Watch {
pub fn new(rx: Receiver<WatchBatch>, on_drop: impl FnOnce() + Send + 'static) -> Self {
Watch {
rx,
mapper: None,
on_drop: Some(Box::new(on_drop)),
}
}
#[must_use]
pub fn map_paths(
mut self,
f: impl Fn(&NsPath) -> Option<NsPath> + Send + Sync + 'static,
) -> Self {
self.mapper = Some(match self.mapper.take() {
None => Arc::new(f),
Some(prev) => Arc::new(move |p: &NsPath| prev(p).and_then(|q| f(&q))),
});
self
}
fn map(&self, mut batch: WatchBatch) -> WatchBatch {
if let Some(m) = &self.mapper {
let mut lost = false;
let mut out: Vec<NsPath> = batch
.changed
.iter()
.filter_map(|p| {
let mapped = m(p);
lost |= mapped.is_none();
mapped
})
.collect();
out.sort();
out.dedup();
if lost {
batch.rescan = true;
out.clear();
}
batch.changed = out;
}
batch
}
pub fn recv(&self) -> Result<WatchBatch, RecvError> {
self.rx.recv().map(|b| self.map(b))
}
pub fn recv_timeout(&self, timeout: Duration) -> Result<WatchBatch, RecvTimeoutError> {
self.rx.recv_timeout(timeout).map(|b| self.map(b))
}
pub fn try_recv(&self) -> Result<WatchBatch, TryRecvError> {
self.rx.try_recv().map(|b| self.map(b))
}
}
impl Drop for Watch {
fn drop(&mut self) {
if let Some(stop) = self.on_drop.take() {
stop();
}
}
}
pub(crate) fn new_epoch() -> u64 {
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hasher};
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0);
RandomState::new().build_hasher().finish() ^ nanos
}
pub(crate) fn finish_changed(mut changed: Vec<NsPath>, max_entries: usize) -> (Vec<NsPath>, bool) {
changed.sort();
changed.dedup();
if changed.len() > max_entries {
(Vec::new(), true)
} else {
(changed, false)
}
}
pub(crate) struct BatchSender {
tx: SyncSender<WatchBatch>,
epoch: u64,
generation: u64,
}
impl BatchSender {
pub(crate) fn channel() -> (BatchSender, Receiver<WatchBatch>) {
let (tx, rx) = mpsc::sync_channel(QUEUE_DEPTH);
(
BatchSender {
tx,
epoch: new_epoch(),
generation: 0,
},
rx,
)
}
pub(crate) fn send(&mut self, changed: Vec<NsPath>, rescan: bool, max_entries: usize) -> bool {
let (changed, over) = if rescan {
(Vec::new(), true)
} else {
finish_changed(changed, max_entries)
};
self.generation += 1;
let batch = WatchBatch::new(self.epoch, self.generation, changed, over);
!matches!(self.tx.try_send(batch), Err(TrySendError::Disconnected(_)))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Fingerprint {
pub kind: Kind,
pub len: u64,
pub mtime_ns: u128,
pub inode: u64,
}
pub(crate) type Snapshot = BTreeMap<NsPath, Fingerprint>;
pub(crate) fn diff(old: &Snapshot, new: &Snapshot) -> Vec<NsPath> {
let mut out = Vec::new();
for (p, fp) in new {
if old.get(p) != Some(fp) {
out.push(p.clone());
}
}
for p in old.keys() {
if !new.contains_key(p) {
out.push(p.clone());
}
}
out
}
pub(crate) enum ScanOutcome {
Complete(Snapshot),
Unavailable,
Incomplete,
}
pub(crate) fn spawn_poller<S>(
initial: Snapshot,
mut scan: S,
opts: &WatchOpts,
) -> std::io::Result<Watch>
where
S: FnMut() -> ScanOutcome + Send + 'static,
{
let interval = opts.effective_interval();
let max_entries = opts.max_entries;
let stop = Arc::new(AtomicBool::new(false));
let (mut sender, rx) = BatchSender::channel();
let thread_stop = Arc::clone(&stop);
let handle: JoinHandle<()> =
thread::Builder::new()
.name("ns-watch-poll".into())
.spawn(move || {
let mut previous: Option<Snapshot> = Some(initial);
loop {
let started = Instant::now();
let deadline = started.checked_add(interval).unwrap_or(started);
loop {
if thread_stop.load(Ordering::Acquire) {
return;
}
let now = Instant::now();
if now >= deadline {
break;
}
thread::park_timeout(deadline - now);
}
let current = match scan() {
ScanOutcome::Complete(s) => Some(s),
ScanOutcome::Unavailable | ScanOutcome::Incomplete => None,
};
let alive = match (&previous, ¤t) {
(Some(old), Some(new)) => {
let changed = diff(old, new);
changed.is_empty() || sender.send(changed, false, max_entries)
}
(Some(_), None) | (None, Some(_)) => {
sender.send(Vec::new(), true, max_entries)
}
(None, None) => true,
};
if !alive {
return;
}
previous = current;
}
})?;
let stopper = Arc::clone(&stop);
let thread_handle = handle.thread().clone();
Ok(Watch::new(rx, move || {
stopper.store(true, Ordering::Release);
thread_handle.unpark();
let _ = handle.join();
}))
}
#[cfg(test)]
mod tests {
use super::*;
fn p(s: &str) -> NsPath {
NsPath::parse(s).unwrap()
}
#[test]
fn cursor_flags_gaps_epochs_and_rescans() {
let mut c = WatchCursor::new();
assert!(
c.observe(&WatchBatch::new(1, 2, vec![], false)),
"first batch must be generation 1"
);
let mut c = WatchCursor::new();
assert!(!c.observe(&WatchBatch::new(1, 1, vec![], false)));
assert!(c.observe(&WatchBatch::new(1, 2, vec![], true)));
assert!(!c.observe(&WatchBatch::new(1, 3, vec![], false)));
assert!(c.observe(&WatchBatch::new(2, 4, vec![], false)));
}
#[test]
fn cap_turns_into_rescan() {
let many: Vec<_> = (0..5).map(|i| p(&format!("/f{i}"))).collect();
assert_eq!(finish_changed(many.clone(), 5).0.len(), 5);
assert_eq!(finish_changed(many, 4), (Vec::new(), true));
let dup = vec![p("/b"), p("/a"), p("/b")];
assert_eq!(finish_changed(dup, 10).0, vec![p("/a"), p("/b")]);
}
#[test]
fn queue_overflow_shows_as_a_generation_gap() {
let (mut s, rx) = BatchSender::channel();
for _ in 0..QUEUE_DEPTH + 3 {
assert!(s.send(vec![p("/x")], false, 10));
}
let mut c = WatchCursor::new();
let got: Vec<_> = rx.try_iter().collect();
assert_eq!(got.len(), QUEUE_DEPTH);
assert!(
got.iter().all(|b| !c.observe(b)),
"the delivered prefix is contiguous"
);
s.send(vec![p("/y")], false, 10);
let last = rx.try_recv().unwrap();
assert!(c.observe(&last), "dropped batches must surface as a gap");
}
#[test]
fn dropping_the_watch_joins_the_poller_thread() {
let token = Arc::new(());
let held = Arc::clone(&token);
let watch = spawn_poller(
Snapshot::new(),
move || {
let _keep = &held;
ScanOutcome::Complete(Snapshot::new())
},
&WatchOpts::default().interval(Duration::from_secs(30)),
)
.unwrap();
assert_eq!(Arc::strong_count(&token), 2);
let started = Instant::now();
drop(watch);
assert_eq!(
Arc::strong_count(&token),
1,
"the poller thread (and its scan closure) must be gone"
);
assert!(
started.elapsed() < Duration::from_secs(5),
"drop must not wait out the 30 s interval"
);
}
#[test]
fn extreme_intervals_are_clamped_not_overflowed() {
let huge = WatchOpts::default().interval(Duration::MAX);
assert_eq!(huge.effective_interval(), MAX_INTERVAL);
assert_eq!(
WatchOpts::default()
.interval(Duration::ZERO)
.effective_interval(),
MIN_INTERVAL
);
let w = spawn_poller(
Snapshot::new(),
|| ScanOutcome::Complete(Snapshot::new()),
&huge,
)
.unwrap();
drop(w);
}
#[test]
fn mapper_composes_and_flags_lost_paths() {
let (mut s, rx) = BatchSender::channel();
let w = Watch::new(rx, || {})
.map_paths(|p| p.rebase(&p_("/m")).ok())
.map_paths(|p| {
if p.as_str() == "/m/bad" {
None
} else {
Some(p.clone())
}
});
s.send(vec![p("/a")], false, 10);
let b = w.recv().unwrap();
assert_eq!(b.changed, vec![p("/m/a")]);
s.send(vec![p("/a"), p("/bad")], false, 10);
let b = w.recv().unwrap();
assert!(b.rescan && b.changed.is_empty());
}
fn p_(s: &str) -> NsPath {
p(s)
}
}