1use std::collections::BTreeMap;
15use std::sync::atomic::{AtomicBool, Ordering};
16use std::sync::mpsc::{
17 Receiver, RecvError, RecvTimeoutError, SyncSender, TryRecvError, TrySendError,
18};
19use std::sync::{mpsc, Arc};
20use std::thread::{self, JoinHandle};
21use std::time::{Duration, Instant};
22
23use super::backend::Kind;
24use super::path::NsPath;
25
26pub const DEFAULT_INTERVAL: Duration = Duration::from_millis(250);
28pub const MIN_INTERVAL: Duration = Duration::from_millis(10);
30pub const MAX_INTERVAL: Duration = Duration::from_secs(60 * 60);
32pub const DEFAULT_MAX_ENTRIES: usize = 1024;
34pub const DEFAULT_MAX_TRACKED: usize = 262_144;
36pub const DEFAULT_MAX_DEPTH: usize = 64;
38pub const QUEUE_DEPTH: usize = 16;
41
42#[derive(Debug, Clone, PartialEq, Eq)]
44#[non_exhaustive]
45pub struct WatchOpts {
46 pub recursive: bool,
48 pub interval: Duration,
51 pub max_entries: usize,
53 pub max_tracked: usize,
58 pub max_depth: usize,
72}
73
74impl Default for WatchOpts {
75 fn default() -> Self {
76 WatchOpts {
77 recursive: false,
78 interval: DEFAULT_INTERVAL,
79 max_entries: DEFAULT_MAX_ENTRIES,
80 max_tracked: DEFAULT_MAX_TRACKED,
81 max_depth: DEFAULT_MAX_DEPTH,
82 }
83 }
84}
85
86impl WatchOpts {
87 #[must_use]
89 pub fn recursive(mut self, recursive: bool) -> Self {
90 self.recursive = recursive;
91 self
92 }
93
94 #[must_use]
96 pub fn interval(mut self, interval: Duration) -> Self {
97 self.interval = interval;
98 self
99 }
100
101 #[must_use]
103 pub fn max_entries(mut self, max_entries: usize) -> Self {
104 self.max_entries = max_entries;
105 self
106 }
107
108 #[must_use]
110 pub fn max_tracked(mut self, max_tracked: usize) -> Self {
111 self.max_tracked = max_tracked;
112 self
113 }
114
115 #[must_use]
117 pub fn max_depth(mut self, max_depth: usize) -> Self {
118 self.max_depth = max_depth;
119 self
120 }
121
122 pub(crate) fn effective_interval(&self) -> Duration {
123 self.interval.clamp(MIN_INTERVAL, MAX_INTERVAL)
124 }
125}
126
127#[derive(Debug, Clone, PartialEq, Eq)]
129#[non_exhaustive]
130pub struct WatchBatch {
131 pub epoch: u64,
133 pub generation: u64,
135 pub changed: Vec<NsPath>,
137 pub rescan: bool,
139}
140
141impl WatchBatch {
142 pub fn new(epoch: u64, generation: u64, changed: Vec<NsPath>, rescan: bool) -> Self {
144 WatchBatch {
145 epoch,
146 generation,
147 changed,
148 rescan,
149 }
150 }
151}
152
153#[derive(Debug, Default, Clone)]
166pub struct WatchCursor {
167 last: Option<(u64, u64)>,
168}
169
170impl WatchCursor {
171 pub fn new() -> Self {
173 Self::default()
174 }
175
176 pub fn observe(&mut self, batch: &WatchBatch) -> bool {
179 let continuous = match self.last {
180 None => batch.generation == 1,
181 Some((epoch, generation)) => {
182 epoch == batch.epoch && generation.checked_add(1) == Some(batch.generation)
183 }
184 };
185 self.last = Some((batch.epoch, batch.generation));
186 batch.rescan || !continuous
187 }
188}
189
190type Mapper = Arc<dyn Fn(&NsPath) -> Option<NsPath> + Send + Sync>;
191
192pub struct Watch {
197 rx: Receiver<WatchBatch>,
198 mapper: Option<Mapper>,
199 on_drop: Option<Box<dyn FnOnce() + Send>>,
200}
201
202impl std::fmt::Debug for Watch {
203 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204 f.debug_struct("Watch").finish_non_exhaustive()
205 }
206}
207
208impl Watch {
209 pub fn new(rx: Receiver<WatchBatch>, on_drop: impl FnOnce() + Send + 'static) -> Self {
212 Watch {
213 rx,
214 mapper: None,
215 on_drop: Some(Box::new(on_drop)),
216 }
217 }
218
219 #[must_use]
223 pub fn map_paths(
224 mut self,
225 f: impl Fn(&NsPath) -> Option<NsPath> + Send + Sync + 'static,
226 ) -> Self {
227 self.mapper = Some(match self.mapper.take() {
228 None => Arc::new(f),
229 Some(prev) => Arc::new(move |p: &NsPath| prev(p).and_then(|q| f(&q))),
230 });
231 self
232 }
233
234 fn map(&self, mut batch: WatchBatch) -> WatchBatch {
235 if let Some(m) = &self.mapper {
236 let mut lost = false;
237 let mut out: Vec<NsPath> = batch
238 .changed
239 .iter()
240 .filter_map(|p| {
241 let mapped = m(p);
242 lost |= mapped.is_none();
243 mapped
244 })
245 .collect();
246 out.sort();
247 out.dedup();
248 if lost {
249 batch.rescan = true;
250 out.clear();
251 }
252 batch.changed = out;
253 }
254 batch
255 }
256
257 pub fn recv(&self) -> Result<WatchBatch, RecvError> {
259 self.rx.recv().map(|b| self.map(b))
260 }
261
262 pub fn recv_timeout(&self, timeout: Duration) -> Result<WatchBatch, RecvTimeoutError> {
264 self.rx.recv_timeout(timeout).map(|b| self.map(b))
265 }
266
267 pub fn try_recv(&self) -> Result<WatchBatch, TryRecvError> {
269 self.rx.try_recv().map(|b| self.map(b))
270 }
271}
272
273impl Drop for Watch {
274 fn drop(&mut self) {
275 if let Some(stop) = self.on_drop.take() {
276 stop();
277 }
278 }
279}
280
281pub(crate) fn new_epoch() -> u64 {
283 use std::collections::hash_map::RandomState;
284 use std::hash::{BuildHasher, Hasher};
285 let nanos = std::time::SystemTime::now()
286 .duration_since(std::time::UNIX_EPOCH)
287 .map(|d| d.as_nanos() as u64)
288 .unwrap_or(0);
289 RandomState::new().build_hasher().finish() ^ nanos
290}
291
292pub(crate) fn finish_changed(mut changed: Vec<NsPath>, max_entries: usize) -> (Vec<NsPath>, bool) {
294 changed.sort();
295 changed.dedup();
296 if changed.len() > max_entries {
297 (Vec::new(), true)
298 } else {
299 (changed, false)
300 }
301}
302
303pub(crate) struct BatchSender {
305 tx: SyncSender<WatchBatch>,
306 epoch: u64,
307 generation: u64,
308}
309
310impl BatchSender {
311 pub(crate) fn channel() -> (BatchSender, Receiver<WatchBatch>) {
312 let (tx, rx) = mpsc::sync_channel(QUEUE_DEPTH);
313 (
314 BatchSender {
315 tx,
316 epoch: new_epoch(),
317 generation: 0,
318 },
319 rx,
320 )
321 }
322
323 pub(crate) fn send(&mut self, changed: Vec<NsPath>, rescan: bool, max_entries: usize) -> bool {
326 let (changed, over) = if rescan {
327 (Vec::new(), true)
328 } else {
329 finish_changed(changed, max_entries)
330 };
331 self.generation += 1;
332 let batch = WatchBatch::new(self.epoch, self.generation, changed, over);
333 !matches!(self.tx.try_send(batch), Err(TrySendError::Disconnected(_)))
334 }
335}
336
337#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339pub(crate) struct Fingerprint {
340 pub kind: Kind,
341 pub len: u64,
342 pub mtime_ns: u128,
343 pub inode: u64,
344}
345
346pub(crate) type Snapshot = BTreeMap<NsPath, Fingerprint>;
347
348pub(crate) fn diff(old: &Snapshot, new: &Snapshot) -> Vec<NsPath> {
350 let mut out = Vec::new();
351 for (p, fp) in new {
352 if old.get(p) != Some(fp) {
353 out.push(p.clone());
354 }
355 }
356 for p in old.keys() {
357 if !new.contains_key(p) {
358 out.push(p.clone());
359 }
360 }
361 out
362}
363
364pub(crate) enum ScanOutcome {
366 Complete(Snapshot),
368 Unavailable,
370 Incomplete,
373}
374
375pub(crate) fn spawn_poller<S>(
382 initial: Snapshot,
383 mut scan: S,
384 opts: &WatchOpts,
385) -> std::io::Result<Watch>
386where
387 S: FnMut() -> ScanOutcome + Send + 'static,
388{
389 let interval = opts.effective_interval();
390 let max_entries = opts.max_entries;
391 let stop = Arc::new(AtomicBool::new(false));
392 let (mut sender, rx) = BatchSender::channel();
393
394 let thread_stop = Arc::clone(&stop);
395 let handle: JoinHandle<()> =
396 thread::Builder::new()
397 .name("ns-watch-poll".into())
398 .spawn(move || {
399 let mut previous: Option<Snapshot> = Some(initial);
400 loop {
401 let started = Instant::now();
403 let deadline = started.checked_add(interval).unwrap_or(started);
404 loop {
405 if thread_stop.load(Ordering::Acquire) {
406 return;
407 }
408 let now = Instant::now();
409 if now >= deadline {
410 break;
411 }
412 thread::park_timeout(deadline - now);
413 }
414 let current = match scan() {
415 ScanOutcome::Complete(s) => Some(s),
416 ScanOutcome::Unavailable | ScanOutcome::Incomplete => None,
417 };
418 let alive = match (&previous, ¤t) {
419 (Some(old), Some(new)) => {
420 let changed = diff(old, new);
421 changed.is_empty() || sender.send(changed, false, max_entries)
422 }
423 (Some(_), None) | (None, Some(_)) => {
424 sender.send(Vec::new(), true, max_entries)
425 }
426 (None, None) => true,
427 };
428 if !alive {
429 return;
430 }
431 previous = current;
432 }
433 })?;
434
435 let stopper = Arc::clone(&stop);
436 let thread_handle = handle.thread().clone();
437 Ok(Watch::new(rx, move || {
438 stopper.store(true, Ordering::Release);
439 thread_handle.unpark();
440 let _ = handle.join();
441 }))
442}
443
444#[cfg(test)]
445mod tests {
446 use super::*;
447
448 fn p(s: &str) -> NsPath {
449 NsPath::parse(s).unwrap()
450 }
451
452 #[test]
453 fn cursor_flags_gaps_epochs_and_rescans() {
454 let mut c = WatchCursor::new();
455 assert!(
456 c.observe(&WatchBatch::new(1, 2, vec![], false)),
457 "first batch must be generation 1"
458 );
459 let mut c = WatchCursor::new();
460 assert!(!c.observe(&WatchBatch::new(1, 1, vec![], false)));
461 assert!(c.observe(&WatchBatch::new(1, 2, vec![], true)));
462 assert!(!c.observe(&WatchBatch::new(1, 3, vec![], false)));
463 assert!(c.observe(&WatchBatch::new(2, 4, vec![], false)));
464 }
465
466 #[test]
467 fn cap_turns_into_rescan() {
468 let many: Vec<_> = (0..5).map(|i| p(&format!("/f{i}"))).collect();
469 assert_eq!(finish_changed(many.clone(), 5).0.len(), 5);
470 assert_eq!(finish_changed(many, 4), (Vec::new(), true));
471 let dup = vec![p("/b"), p("/a"), p("/b")];
472 assert_eq!(finish_changed(dup, 10).0, vec![p("/a"), p("/b")]);
473 }
474
475 #[test]
476 fn queue_overflow_shows_as_a_generation_gap() {
477 let (mut s, rx) = BatchSender::channel();
478 for _ in 0..QUEUE_DEPTH + 3 {
479 assert!(s.send(vec![p("/x")], false, 10));
480 }
481 let mut c = WatchCursor::new();
482 let got: Vec<_> = rx.try_iter().collect();
483 assert_eq!(got.len(), QUEUE_DEPTH);
484 assert!(
485 got.iter().all(|b| !c.observe(b)),
486 "the delivered prefix is contiguous"
487 );
488 s.send(vec![p("/y")], false, 10);
489 let last = rx.try_recv().unwrap();
490 assert!(c.observe(&last), "dropped batches must surface as a gap");
491 }
492
493 #[test]
494 fn dropping_the_watch_joins_the_poller_thread() {
495 let token = Arc::new(());
497 let held = Arc::clone(&token);
498 let watch = spawn_poller(
499 Snapshot::new(),
500 move || {
501 let _keep = &held;
502 ScanOutcome::Complete(Snapshot::new())
503 },
504 &WatchOpts::default().interval(Duration::from_secs(30)),
505 )
506 .unwrap();
507 assert_eq!(Arc::strong_count(&token), 2);
508 let started = Instant::now();
509 drop(watch);
510 assert_eq!(
511 Arc::strong_count(&token),
512 1,
513 "the poller thread (and its scan closure) must be gone"
514 );
515 assert!(
516 started.elapsed() < Duration::from_secs(5),
517 "drop must not wait out the 30 s interval"
518 );
519 }
520
521 #[test]
522 fn extreme_intervals_are_clamped_not_overflowed() {
523 let huge = WatchOpts::default().interval(Duration::MAX);
524 assert_eq!(huge.effective_interval(), MAX_INTERVAL);
525 assert_eq!(
526 WatchOpts::default()
527 .interval(Duration::ZERO)
528 .effective_interval(),
529 MIN_INTERVAL
530 );
531 let w = spawn_poller(
533 Snapshot::new(),
534 || ScanOutcome::Complete(Snapshot::new()),
535 &huge,
536 )
537 .unwrap();
538 drop(w);
539 }
540
541 #[test]
542 fn mapper_composes_and_flags_lost_paths() {
543 let (mut s, rx) = BatchSender::channel();
544 let w = Watch::new(rx, || {})
545 .map_paths(|p| p.rebase(&p_("/m")).ok())
546 .map_paths(|p| {
547 if p.as_str() == "/m/bad" {
548 None
549 } else {
550 Some(p.clone())
551 }
552 });
553 s.send(vec![p("/a")], false, 10);
554 let b = w.recv().unwrap();
555 assert_eq!(b.changed, vec![p("/m/a")]);
556 s.send(vec![p("/a"), p("/bad")], false, 10);
557 let b = w.recv().unwrap();
558 assert!(b.rescan && b.changed.is_empty());
559 }
560
561 fn p_(s: &str) -> NsPath {
562 p(s)
563 }
564}