config_lib/hot_reload.rs
1//! Configuration Hot Reloading System
2//!
3//! Production-grade hot reloading with:
4//!
5//! - **Event-driven file watching** via the [`notify`](https://docs.rs/notify)
6//! crate (default in v0.9.6+ via the `hot-reload` Cargo feature).
7//! `notify` is a cross-platform wrapper over the kernel's native
8//! filesystem event APIs: `inotify` on Linux, `FSEvents` on macOS,
9//! and `ReadDirectoryChangesW` on Windows. Detection latency is
10//! typically a few milliseconds — well under the 100 ms target the
11//! v1.0 stability contract commits to.
12//! - **Atomic-write debouncing.** Many editors save by writing to a
13//! temporary file and atomically renaming it over the target. This
14//! produces a flurry of events (create, modify, delete, modify) in
15//! rapid succession. The reloader collapses any burst within the
16//! debounce window (default 100 ms, configurable) to one
17//! `Reloaded` notification.
18//! - **`Arc<RwLock<Config>>` swap** for zero-downtime updates —
19//! readers never block while the reloader parses the new file.
20//! - **Lock-free in-process notification dispatch** (v1.0.0+). Register
21//! handlers via `HotReloadConfig::on_change` / `HotReloadHandle::on_change`;
22//! the reloader thread invokes every registered handler inline with
23//! no channel allocation and no cross-thread wakeup. Backed by
24//! `ArcSwap<Vec<Handler>>` — snapshot reads cost a single atomic
25//! pointer load (~5 ns) regardless of how many handlers are
26//! registered. See `docs/PERFORMANCE.md` for measured numbers.
27//! - **Panic isolation.** Each handler invocation is wrapped in
28//! `catch_unwind` so one bad handler can't take down the watcher
29//! or other handlers.
30//! - **Polling fallback** (always available, used as the default when
31//! the `hot-reload` feature is disabled, or available as an opt-in
32//! on top of event-driven watching for environments where the kernel
33//! APIs are known-broken — network filesystems, some container
34//! layers).
35
36use crate::config::Config;
37use crate::error::{Error, Result};
38use arc_swap::ArcSwap;
39use std::panic::{catch_unwind, AssertUnwindSafe};
40use std::path::{Path, PathBuf};
41use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
42use std::sync::mpsc::{self, Receiver};
43use std::sync::{Arc, RwLock, Weak};
44use std::thread;
45use std::time::{Duration, SystemTime};
46
47/// Configuration change event types.
48///
49/// **Stability:** `ConfigChangeEvent` is `#[non_exhaustive]` so the
50/// v1.x SemVer contract can add new variants (e.g. `Renamed`,
51/// `PermissionDenied`) in MINOR releases without breaking user code.
52/// Callers must use a wildcard arm when pattern-matching.
53#[derive(Debug, Clone)]
54#[non_exhaustive]
55pub enum ConfigChangeEvent {
56 /// Configuration successfully reloaded
57 Reloaded {
58 /// Path to the configuration file that was reloaded
59 path: PathBuf,
60 /// Timestamp when the reload completed
61 timestamp: SystemTime,
62 },
63 /// Configuration reload failed
64 ReloadFailed {
65 /// Path to the configuration file that failed to reload
66 path: PathBuf,
67 /// Error message describing what went wrong
68 error: String,
69 /// Timestamp when the error occurred
70 timestamp: SystemTime,
71 },
72 /// Configuration file was modified
73 FileModified {
74 /// Path to the configuration file that was modified
75 path: PathBuf,
76 /// Timestamp when the modification was detected
77 timestamp: SystemTime,
78 },
79 /// Configuration file was deleted
80 FileDeleted {
81 /// Path to the configuration file that was deleted
82 path: PathBuf,
83 /// Timestamp when the deletion was detected
84 timestamp: SystemTime,
85 },
86}
87
88/// Default debounce window applied to file-change events before
89/// triggering a reload. Sized to cover the editor "save via atomic
90/// rename" pattern (where a single save fires multiple kernel events
91/// within ~10–50 ms).
92const DEFAULT_DEBOUNCE: Duration = Duration::from_millis(100);
93
94// =========================================================================
95// HandlerList — lock-free in-process notification dispatch (v1.0.0+)
96// =========================================================================
97
98/// Boxed handler closure. `Arc` so that an iteration snapshot can
99/// outlive registration / unregistration of the same handler without
100/// invalidating the in-flight call.
101type Handler = Arc<dyn Fn(&ConfigChangeEvent) + Send + Sync + 'static>;
102
103/// Lock-free handler list backing [`HotReloadConfig::on_change`].
104///
105/// Reads (the dispatch path on the reloader thread) take a snapshot
106/// of the current handler vector via one `ArcSwap::load` — a single
107/// relaxed atomic pointer load. Writes (register / unregister)
108/// allocate a new vector, copy the old contents minus/plus one
109/// handler, and atomic-swap the pointer (`rcu`-style update). Writes
110/// never block reads.
111///
112/// The handler list is shared between [`HotReloadConfig`] and its
113/// spawned worker thread via `Arc<HandlerList>`, so handlers can be
114/// registered before *or* after [`HotReloadConfig::start_watching`]
115/// — see [`HotReloadHandle::on_change`].
116pub(crate) struct HandlerList {
117 handlers: ArcSwap<Vec<(u64, Handler)>>,
118 next_id: AtomicU64,
119}
120
121impl HandlerList {
122 fn new() -> Self {
123 Self {
124 handlers: ArcSwap::from_pointee(Vec::new()),
125 next_id: AtomicU64::new(0),
126 }
127 }
128
129 /// Dispatch an event to every registered handler.
130 ///
131 /// Each handler is invoked inline on the calling thread. Panic
132 /// isolation: a handler that panics is caught via `catch_unwind`
133 /// so subsequent handlers still run and the reloader thread is
134 /// not torn down.
135 fn dispatch(&self, event: &ConfigChangeEvent) {
136 // Single atomic pointer load — the dispatch hot path.
137 let snapshot = self.handlers.load();
138 for (_id, handler) in snapshot.iter() {
139 // Clone the Arc<dyn Fn> so the handler stays alive even
140 // if it's concurrently unregistered during this loop
141 // iteration. Refcount bump, no allocation.
142 let h = Arc::clone(handler);
143 // REPS-AUDIT: handlers are user-supplied; one panicking
144 // handler must not break the watcher or other handlers.
145 // `catch_unwind` swallows the panic and we discard the
146 // payload (handlers are best-effort observers).
147 let _ = catch_unwind(AssertUnwindSafe(move || {
148 h(event);
149 }));
150 }
151 }
152
153 /// Register a new handler, returning its assigned id.
154 fn register(&self, handler: Handler) -> u64 {
155 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
156 self.handlers.rcu(|current| {
157 let mut next = Vec::with_capacity(current.len() + 1);
158 next.extend(current.iter().cloned());
159 next.push((id, Arc::clone(&handler)));
160 next
161 });
162 id
163 }
164
165 /// Remove the handler with the given id, if present. Idempotent.
166 fn unregister(&self, id: u64) {
167 self.handlers.rcu(|current| {
168 current
169 .iter()
170 .filter(|(other_id, _)| *other_id != id)
171 .cloned()
172 .collect::<Vec<_>>()
173 });
174 }
175}
176
177/// RAII handle for a registered change-notification handler.
178///
179/// Returned by [`HotReloadConfig::on_change`] /
180/// [`HotReloadHandle::on_change`]. Drop the `Subscription` to
181/// unregister the handler. The watcher itself outlives any individual
182/// subscription — multiple subscriptions can come and go without
183/// touching the underlying [`HotReloadConfig`].
184///
185/// # Example
186///
187/// ```rust,no_run
188/// use config_lib::hot_reload::{HotReloadConfig, ConfigChangeEvent};
189///
190/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
191/// let hot = HotReloadConfig::from_file("app.conf")?;
192/// let _subscription = hot.on_change(|event: &ConfigChangeEvent| {
193/// println!("config changed: {event:?}");
194/// });
195/// // Drop `_subscription` (e.g. at end of scope) to unregister.
196/// # Ok(())
197/// # }
198/// ```
199#[must_use = "dropping the Subscription immediately unregisters the handler; bind to a name (`let _sub = ...`) or call `.forget()` to keep the handler alive"]
200pub struct Subscription {
201 list: Weak<HandlerList>,
202 id: u64,
203}
204
205impl Subscription {
206 /// Detach the subscription from its drop-based unregistration
207 /// hook. The handler stays registered for the lifetime of the
208 /// underlying watcher (until the [`HotReloadConfig`] or
209 /// [`HotReloadHandle`] that produced it is dropped).
210 ///
211 /// Useful for global / process-lifetime handlers where the
212 /// caller has no convenient owning scope to hold the
213 /// `Subscription`.
214 pub fn forget(mut self) {
215 // Clear the weak reference so Drop becomes a no-op.
216 self.list = Weak::new();
217 }
218}
219
220impl Drop for Subscription {
221 fn drop(&mut self) {
222 if let Some(list) = self.list.upgrade() {
223 list.unregister(self.id);
224 }
225 }
226}
227
228impl std::fmt::Debug for Subscription {
229 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
230 f.debug_struct("Subscription")
231 .field("id", &self.id)
232 .field("alive", &(self.list.strong_count() > 0))
233 .finish()
234 }
235}
236
237// =========================================================================
238// HotReloadConfig
239// =========================================================================
240
241/// Hot-reloadable configuration container.
242///
243/// Construct with [`HotReloadConfig::from_file`], then either drive
244/// reloads manually with [`HotReloadConfig::reload`] or hand off to a
245/// background watcher with [`HotReloadConfig::start_watching`].
246///
247/// Configurable knobs (all consuming-builder style, intended for
248/// fluent construction):
249///
250/// - [`HotReloadConfig::on_change`] — register a change handler
251/// (v1.0.0+; the recommended notification API).
252/// - [`HotReloadConfig::with_change_notifications`] — receive
253/// [`ConfigChangeEvent`]s on an `mpsc` channel (deprecated since
254/// v1.0.0; kept as a bridge for backwards compatibility).
255/// - [`HotReloadConfig::with_debounce`] — adjust the debounce window
256/// (default 100 ms).
257/// - [`HotReloadConfig::with_poll_interval`] — set the polling
258/// interval. Used directly when the `hot-reload` feature is off;
259/// used as the watchdog interval when the feature is on.
260/// - [`HotReloadConfig::with_polling_fallback`] — opt into a
261/// parallel polling watchdog *in addition to* the event-driven
262/// watcher, for environments where the kernel watcher is known
263/// unreliable.
264pub struct HotReloadConfig {
265 /// Current configuration (thread-safe)
266 current: Arc<RwLock<Config>>,
267 /// File path being watched
268 file_path: PathBuf,
269 /// Last known modification time
270 last_modified: SystemTime,
271 /// Lock-free handler list. Shared with the worker thread via
272 /// `Arc<HandlerList>` once `start_watching` is called.
273 handlers: Arc<HandlerList>,
274 /// Bridge subscriptions kept alive by the deprecated
275 /// `with_change_notifications` API. Each entry registers a
276 /// closure that forwards events to the corresponding
277 /// `mpsc::Sender`; dropping the subscription stops the
278 /// forwarding. Stored here so the bridge lives at least as
279 /// long as the `HotReloadConfig` itself, and is moved into the
280 /// [`HotReloadHandle`] when `start_watching` consumes self.
281 bridges: Vec<Subscription>,
282 /// Polling interval — used as primary cadence when the
283 /// `hot-reload` feature is off, or as the watchdog interval when
284 /// the feature is on and `polling_fallback_enabled` is set.
285 poll_interval: Duration,
286 /// Debounce window applied to clustered file-change events.
287 debounce: Duration,
288 /// Whether to run the polling watchdog *in addition to* the
289 /// event-driven watcher. Useful on network filesystems.
290 polling_fallback_enabled: bool,
291}
292
293impl HotReloadConfig {
294 /// Create a new hot-reloadable configuration from a file.
295 ///
296 /// # Errors
297 ///
298 /// Returns an error if the file cannot be read, parsed, or stat'd
299 /// for its modification time.
300 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
301 let path = path.as_ref().to_path_buf();
302 let config = Config::from_file(&path)?;
303
304 let last_modified = std::fs::metadata(&path)
305 .map_err(|e| Error::io(path.display().to_string(), e))?
306 .modified()
307 .map_err(|e| Error::io(path.display().to_string(), e))?;
308
309 Ok(Self {
310 current: Arc::new(RwLock::new(config)),
311 file_path: path,
312 last_modified,
313 handlers: Arc::new(HandlerList::new()),
314 bridges: Vec::new(),
315 poll_interval: Duration::from_secs(1),
316 debounce: DEFAULT_DEBOUNCE,
317 polling_fallback_enabled: false,
318 })
319 }
320
321 /// Set the polling interval for file change detection.
322 ///
323 /// When the `hot-reload` feature is enabled (the default in v0.9.6+),
324 /// the primary watcher is event-driven and this interval is only
325 /// consulted as the watchdog cadence if `with_polling_fallback`
326 /// has been called.
327 ///
328 /// When the `hot-reload` feature is disabled, this is the actual
329 /// polling cadence of the background thread.
330 pub fn with_poll_interval(mut self, interval: Duration) -> Self {
331 self.poll_interval = interval;
332 self
333 }
334
335 /// Override the debounce window applied to clustered file-change
336 /// events.
337 ///
338 /// Editors that save via "write-to-tmp + atomic-rename" generate
339 /// multiple kernel events for a single user save. The debounce
340 /// collapses any burst within this window to a single reload.
341 /// Default: 100 ms.
342 pub fn with_debounce(mut self, debounce: Duration) -> Self {
343 self.debounce = debounce;
344 self
345 }
346
347 /// Opt into running a polling watchdog *in addition to* the
348 /// event-driven watcher.
349 ///
350 /// Network filesystems (SMB, NFS), some container overlay
351 /// filesystems, and a handful of edge-case kernel configurations
352 /// drop or delay events that `notify` would normally surface.
353 /// Enabling the polling fallback re-derives changes from periodic
354 /// `stat(2)` calls on the watched path, at the
355 /// [`HotReloadConfig::with_poll_interval`] cadence.
356 ///
357 /// Has no effect (and costs nothing) when the `hot-reload` Cargo
358 /// feature is disabled — the watcher is already polling in that
359 /// configuration.
360 pub fn with_polling_fallback(mut self) -> Self {
361 self.polling_fallback_enabled = true;
362 self
363 }
364
365 /// Register a change handler. **Recommended notification API**
366 /// (v1.0.0+).
367 ///
368 /// The handler is invoked inline on the reloader thread every
369 /// time a [`ConfigChangeEvent`] is produced — typically a few
370 /// milliseconds after the underlying filesystem event, plus the
371 /// debounce window. Dispatch overhead is a single atomic pointer
372 /// load (~5 ns) plus the handler's own cost; multiple handlers
373 /// are called in registration order with no per-handler channel
374 /// allocation.
375 ///
376 /// Returns a [`Subscription`] whose `Drop` unregisters the
377 /// handler. Bind to a `let _sub = ...` if you want the handler
378 /// to live for the surrounding scope, or call
379 /// [`Subscription::forget`] to detach the drop hook.
380 ///
381 /// # Panics
382 ///
383 /// If the handler itself panics, the panic is caught via
384 /// `catch_unwind` and discarded — other handlers continue to
385 /// receive the event and the reloader thread is not torn down.
386 /// Handler authors should avoid panicking, but a buggy handler
387 /// won't take down the whole library.
388 ///
389 /// # Example
390 ///
391 /// ```rust,no_run
392 /// use config_lib::hot_reload::{HotReloadConfig, ConfigChangeEvent};
393 ///
394 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
395 /// let hot = HotReloadConfig::from_file("app.conf")?;
396 /// let _sub = hot.on_change(|event: &ConfigChangeEvent| {
397 /// if let ConfigChangeEvent::Reloaded { path, .. } = event {
398 /// println!("reloaded {}", path.display());
399 /// }
400 /// });
401 /// let _handle = hot.start_watching();
402 /// // ... `_sub` and `_handle` are alive for the rest of the scope
403 /// # Ok(())
404 /// # }
405 /// ```
406 pub fn on_change<F>(&self, handler: F) -> Subscription
407 where
408 F: Fn(&ConfigChangeEvent) + Send + Sync + 'static,
409 {
410 let id = self.handlers.register(Arc::new(handler));
411 Subscription {
412 list: Arc::downgrade(&self.handlers),
413 id,
414 }
415 }
416
417 /// Enable channel-based change notifications. **Deprecated since
418 /// v1.0.0** — prefer [`HotReloadConfig::on_change`].
419 ///
420 /// Internally bridges to the same lock-free handler list as
421 /// `on_change` by registering a closure that forwards events
422 /// to an `mpsc::Sender`. The bridge subscription is held by
423 /// `self` so the channel keeps receiving events for the
424 /// lifetime of the watcher.
425 ///
426 /// The bridge pays one extra `mpsc::Sender::send` per event
427 /// (~100–200 ns) on top of the lock-free dispatch cost — the
428 /// inverse of why `on_change` exists. Existing code using
429 /// `Receiver<ConfigChangeEvent>` continues to work unchanged.
430 #[deprecated(
431 since = "1.0.0",
432 note = "use `on_change` for lock-free dispatch; this method continues to work but pays an mpsc allocation per event"
433 )]
434 pub fn with_change_notifications(mut self) -> (Self, Receiver<ConfigChangeEvent>) {
435 let (tx, rx) = mpsc::channel();
436 let bridge = self.on_change(move |event| {
437 let _ = tx.send(event.clone());
438 });
439 self.bridges.push(bridge);
440 (self, rx)
441 }
442
443 /// Get a thread-safe reference to the current configuration.
444 pub fn config(&self) -> Arc<RwLock<Config>> {
445 Arc::clone(&self.current)
446 }
447
448 /// Get a freshly-reparsed snapshot of the configuration file as
449 /// it exists on disk *right now*.
450 ///
451 /// This is distinct from reading the current `Arc<RwLock<Config>>`
452 /// — it bypasses the watcher and re-reads the file. Useful for
453 /// "what would I see if I reloaded now" inspection.
454 ///
455 /// # Errors
456 ///
457 /// Returns an error if the file cannot be read or parsed.
458 pub fn snapshot(&self) -> Result<Config> {
459 Config::from_file(&self.file_path)
460 }
461
462 /// Manually trigger a reload check.
463 ///
464 /// Re-stats the file, compares mtime against the last-known
465 /// modification time, and re-parses if newer. Dispatches a
466 /// [`ConfigChangeEvent::Reloaded`] or
467 /// [`ConfigChangeEvent::ReloadFailed`] notification through the
468 /// handler list.
469 ///
470 /// Returns `Ok(true)` if a reload was performed, `Ok(false)` if
471 /// the file was unchanged since the last check.
472 ///
473 /// # Errors
474 ///
475 /// Returns an error if the file cannot be stat'd, read, or parsed.
476 pub fn reload(&mut self) -> Result<bool> {
477 let metadata = std::fs::metadata(&self.file_path)
478 .map_err(|e| Error::io(self.file_path.display().to_string(), e))?;
479
480 let modified = metadata
481 .modified()
482 .map_err(|e| Error::io(self.file_path.display().to_string(), e))?;
483
484 if modified <= self.last_modified {
485 return Ok(false);
486 }
487
488 match Config::from_file(&self.file_path) {
489 Ok(new_config) => {
490 {
491 let mut config = self.current.write().map_err(|_| {
492 Error::concurrency("Failed to acquire write lock".to_string())
493 })?;
494 *config = new_config;
495 }
496 self.last_modified = modified;
497
498 self.handlers.dispatch(&ConfigChangeEvent::Reloaded {
499 path: self.file_path.clone(),
500 timestamp: SystemTime::now(),
501 });
502 Ok(true)
503 }
504 Err(e) => {
505 self.handlers.dispatch(&ConfigChangeEvent::ReloadFailed {
506 path: self.file_path.clone(),
507 error: e.to_string(),
508 timestamp: SystemTime::now(),
509 });
510 Err(e)
511 }
512 }
513 }
514
515 /// Start automatic hot reloading in a background thread.
516 ///
517 /// With the `hot-reload` Cargo feature enabled (the default in
518 /// v0.9.6+), the background worker registers a
519 /// `notify::RecommendedWatcher` on the file's parent directory
520 /// and reacts to kernel events. Otherwise it falls back to a
521 /// `poll_interval`-cadence polling thread (the v0.9.5 behavior).
522 pub fn start_watching(self) -> HotReloadHandle {
523 #[cfg(feature = "hot-reload")]
524 {
525 self.start_watching_event_driven()
526 }
527 #[cfg(not(feature = "hot-reload"))]
528 {
529 self.start_watching_polling()
530 }
531 }
532
533 /// Get the file path being watched.
534 pub fn file_path(&self) -> &Path {
535 &self.file_path
536 }
537
538 /// Get the last modification time.
539 pub fn last_modified(&self) -> SystemTime {
540 self.last_modified
541 }
542
543 // -----------------------------------------------------------------
544 // Polling watcher — used as the primary watcher when the
545 // `hot-reload` Cargo feature is disabled. (When the feature is on,
546 // the event-driven path covers all environments where the kernel
547 // event API works; opt-in polling-as-watchdog alongside the
548 // event-driven watcher is reserved for a follow-up release.)
549 // -----------------------------------------------------------------
550
551 #[cfg(not(feature = "hot-reload"))]
552 fn start_watching_polling(self) -> HotReloadHandle {
553 let stop = Arc::new(AtomicBool::new(false));
554 let stop_clone = Arc::clone(&stop);
555
556 let current = Arc::clone(&self.current);
557 let file_path = self.file_path.clone();
558 let handlers = Arc::clone(&self.handlers);
559 let poll_interval = self.poll_interval;
560 let mut last_modified = self.last_modified;
561 // The size is compared too: a file read while it was being written
562 // (truncated, then filled) can keep the same modification time when
563 // the rest of the write lands within the file system's time
564 // resolution, and comparing only the time would then keep the
565 // half-written configuration until the next edit.
566 let mut last_len = std::fs::metadata(&file_path).map(|m| m.len()).ok();
567
568 let handle = thread::spawn(move || {
569 while !stop_clone.load(Ordering::Relaxed) {
570 if let Ok(metadata) = std::fs::metadata(&file_path) {
571 if let Ok(modified) = metadata.modified() {
572 let len = Some(metadata.len());
573 if modified > last_modified || len != last_len {
574 handlers.dispatch(&ConfigChangeEvent::FileModified {
575 path: file_path.clone(),
576 timestamp: SystemTime::now(),
577 });
578
579 match Config::from_file(&file_path) {
580 Ok(new_config) => {
581 if let Ok(mut config) = current.write() {
582 *config = new_config;
583 last_modified = modified;
584 last_len = len;
585 handlers.dispatch(&ConfigChangeEvent::Reloaded {
586 path: file_path.clone(),
587 timestamp: SystemTime::now(),
588 });
589 }
590 }
591 Err(e) => {
592 handlers.dispatch(&ConfigChangeEvent::ReloadFailed {
593 path: file_path.clone(),
594 error: e.to_string(),
595 timestamp: SystemTime::now(),
596 });
597 }
598 }
599 }
600 }
601 }
602 thread::sleep(poll_interval);
603 }
604 });
605
606 HotReloadHandle {
607 handle: Some(handle),
608 stop,
609 handlers: self.handlers,
610 _bridges: self.bridges,
611 }
612 }
613
614 // -----------------------------------------------------------------
615 // Event-driven watcher — gated on the `hot-reload` feature.
616 // -----------------------------------------------------------------
617
618 #[cfg(feature = "hot-reload")]
619 fn start_watching_event_driven(self) -> HotReloadHandle {
620 use notify::{Event, RecursiveMode, Watcher};
621
622 let stop = Arc::new(AtomicBool::new(false));
623 let current = Arc::clone(&self.current);
624 let file_path = self.file_path.clone();
625 let handlers = Arc::clone(&self.handlers);
626 let debounce = self.debounce;
627 let poll_interval = self.poll_interval;
628 let polling_fallback = self.polling_fallback_enabled;
629 let initial_modified = self.last_modified;
630
631 // Channel from the notify callback to the reload worker.
632 // This `mpsc` is purely internal — between the notify
633 // callback (which runs on `notify`'s own thread) and our
634 // worker thread. It is NOT the user-facing notification
635 // channel; that path is via `HandlerList::dispatch`.
636 let (tx, rx) = mpsc::channel::<Event>();
637
638 // Build the watcher. We watch the *parent* directory (not the
639 // file itself) so that atomic-rename saves — where the file's
640 // inode is replaced — still surface as events on our target.
641 let watcher_dir = file_path
642 .parent()
643 .map(Path::to_path_buf)
644 .unwrap_or_else(|| PathBuf::from("."));
645
646 let watcher_result = notify::RecommendedWatcher::new(
647 move |res: notify::Result<Event>| {
648 if let Ok(event) = res {
649 let _ = tx.send(event);
650 }
651 },
652 notify::Config::default(),
653 )
654 .and_then(|mut w| {
655 w.watch(&watcher_dir, RecursiveMode::NonRecursive)?;
656 Ok(w)
657 });
658
659 let watcher = match watcher_result {
660 Ok(w) => Some(w),
661 Err(e) => {
662 // Watcher construction failed — likely the platform
663 // event API is unavailable (rare). Surface a
664 // `ReloadFailed` so the caller knows.
665 handlers.dispatch(&ConfigChangeEvent::ReloadFailed {
666 path: file_path.clone(),
667 error: format!(
668 "notify watcher construction failed: {e}; falling back to polling"
669 ),
670 timestamp: SystemTime::now(),
671 });
672 None
673 }
674 };
675
676 // Reload worker — consumes events from the notify callback,
677 // debounces, and re-parses on change.
678 let target_file = file_path.clone();
679 let handlers_for_worker = Arc::clone(&handlers);
680 let current_for_worker = Arc::clone(¤t);
681 let stop_for_worker = Arc::clone(&stop);
682 let mut last_modified_seen = initial_modified;
683
684 let handle = thread::spawn(move || {
685 while !stop_for_worker.load(Ordering::Relaxed) {
686 // Block up to `poll_interval` for the next event so
687 // the stop flag is observed promptly even when the
688 // file is quiet.
689 let first = match rx.recv_timeout(poll_interval) {
690 Ok(ev) => Some(ev),
691 Err(mpsc::RecvTimeoutError::Timeout) => None,
692 Err(mpsc::RecvTimeoutError::Disconnected) => break,
693 };
694
695 // If we got an event, drain the channel for the
696 // debounce window so the burst from a single save
697 // collapses to one reload.
698 let mut relevant = false;
699 if let Some(ev) = first {
700 relevant |= event_targets_path(&ev, &target_file);
701
702 let deadline = std::time::Instant::now() + debounce;
703 loop {
704 let remaining =
705 deadline.saturating_duration_since(std::time::Instant::now());
706 if remaining.is_zero() {
707 break;
708 }
709 match rx.recv_timeout(remaining) {
710 Ok(ev) => relevant |= event_targets_path(&ev, &target_file),
711 Err(_) => break,
712 }
713 }
714 } else if !polling_fallback {
715 continue;
716 }
717
718 // Path resolution: did the target file actually change?
719 let metadata = std::fs::metadata(&target_file);
720 match metadata {
721 Ok(meta) => {
722 let modified = meta.modified().ok();
723 let is_newer = match modified {
724 Some(m) => m > last_modified_seen,
725 None => true,
726 };
727 if !relevant && !is_newer {
728 continue;
729 }
730
731 handlers_for_worker.dispatch(&ConfigChangeEvent::FileModified {
732 path: target_file.clone(),
733 timestamp: SystemTime::now(),
734 });
735
736 match Config::from_file(&target_file) {
737 Ok(new_config) => {
738 if let Ok(mut cfg) = current_for_worker.write() {
739 *cfg = new_config;
740 if let Some(m) = modified {
741 last_modified_seen = m;
742 }
743 handlers_for_worker.dispatch(&ConfigChangeEvent::Reloaded {
744 path: target_file.clone(),
745 timestamp: SystemTime::now(),
746 });
747 }
748 }
749 Err(e) => {
750 handlers_for_worker.dispatch(&ConfigChangeEvent::ReloadFailed {
751 path: target_file.clone(),
752 error: e.to_string(),
753 timestamp: SystemTime::now(),
754 });
755 }
756 }
757 }
758 Err(_) => {
759 // File missing — likely deleted between
760 // events. Emit FileDeleted but keep the
761 // last-known-good config in place.
762 handlers_for_worker.dispatch(&ConfigChangeEvent::FileDeleted {
763 path: target_file.clone(),
764 timestamp: SystemTime::now(),
765 });
766 }
767 }
768 }
769 });
770
771 HotReloadHandle {
772 handle: Some(handle),
773 stop,
774 handlers: self.handlers,
775 _bridges: self.bridges,
776 _watcher: watcher,
777 }
778 }
779}
780
781/// Helper: does the `notify::Event` reference our watched file?
782///
783/// When watching a directory non-recursively, every event carries the
784/// list of paths it applies to. Filtering on the exact file path keeps
785/// us from reacting to unrelated sibling files in the same directory.
786#[cfg(feature = "hot-reload")]
787fn event_targets_path(event: ¬ify::Event, target: &Path) -> bool {
788 use notify::EventKind;
789 if !matches!(
790 event.kind,
791 EventKind::Modify(_) | EventKind::Create(_) | EventKind::Remove(_) | EventKind::Any
792 ) {
793 return false;
794 }
795 // Canonical-form comparison helps with macOS symlink/realpath
796 // shenanigans. Fall back to direct equality when canonicalize
797 // can't resolve (e.g. file was just deleted).
798 let target_canon = std::fs::canonicalize(target).ok();
799 event.paths.iter().any(|p| {
800 if p == target {
801 return true;
802 }
803 if let (Some(tc), Ok(pc)) = (&target_canon, std::fs::canonicalize(p)) {
804 return *tc == pc;
805 }
806 false
807 })
808}
809
810/// Handle for controlling the hot-reload background thread.
811///
812/// Returned by [`HotReloadConfig::start_watching`]. Dropping the
813/// handle (or calling [`HotReloadHandle::stop`]) signals the worker
814/// to exit and tears down the kernel-level watch registration.
815/// Holding the handle keeps the watcher alive.
816///
817/// New handlers can be registered after `start_watching` via
818/// [`HotReloadHandle::on_change`] — the handler list is shared
819/// between the original `HotReloadConfig` and the spawned worker
820/// thread.
821pub struct HotReloadHandle {
822 handle: Option<thread::JoinHandle<()>>,
823 stop: Arc<AtomicBool>,
824 /// Lock-free handler list shared with the worker thread.
825 /// Carried here so that `on_change` continues to work after
826 /// the original `HotReloadConfig` has been consumed by
827 /// `start_watching`.
828 handlers: Arc<HandlerList>,
829 /// Bridge subscriptions kept alive for the lifetime of the
830 /// watcher. The deprecated `with_change_notifications` path
831 /// installed these; dropping the handle drops them, which
832 /// unregisters the bridge handlers.
833 _bridges: Vec<Subscription>,
834 /// Watcher kept alive for the duration of the watch. Dropping
835 /// the watcher tears down the kernel registration. Only carried
836 /// when the `hot-reload` feature is on.
837 #[cfg(feature = "hot-reload")]
838 _watcher: Option<notify::RecommendedWatcher>,
839}
840
841impl HotReloadHandle {
842 /// Register a change handler after `start_watching` has been
843 /// called.
844 ///
845 /// Semantics match [`HotReloadConfig::on_change`]. Useful when
846 /// the consumer of the handle is a different component from
847 /// whoever called `start_watching` — pass the handle around and
848 /// let each component install its own handler.
849 pub fn on_change<F>(&self, handler: F) -> Subscription
850 where
851 F: Fn(&ConfigChangeEvent) + Send + Sync + 'static,
852 {
853 let id = self.handlers.register(Arc::new(handler));
854 Subscription {
855 list: Arc::downgrade(&self.handlers),
856 id,
857 }
858 }
859
860 /// Stop the background watching thread.
861 ///
862 /// # Errors
863 ///
864 /// Returns an error if the background thread panicked.
865 pub fn stop(mut self) -> Result<()> {
866 self.stop.store(true, Ordering::Relaxed);
867 if let Some(handle) = self.handle.take() {
868 handle
869 .join()
870 .map_err(|_| Error::concurrency("Failed to join background thread".to_string()))?;
871 }
872 Ok(())
873 }
874}
875
876impl Drop for HotReloadHandle {
877 fn drop(&mut self) {
878 self.stop.store(true, Ordering::Relaxed);
879 if let Some(handle) = self.handle.take() {
880 let _ = handle.join();
881 }
882 }
883}
884
885#[cfg(test)]
886mod tests {
887 use super::*;
888 use std::fs::File;
889 use std::io::Write;
890 use std::sync::atomic::AtomicUsize;
891 use tempfile::TempDir;
892
893 /// Helper: write a CONF body to `path` and `fsync` it so the
894 /// kernel surfaces the modification event before we proceed.
895 fn write_conf(path: &Path, body: &str) {
896 let mut f = File::create(path).unwrap();
897 f.write_all(body.as_bytes()).unwrap();
898 f.flush().unwrap();
899 f.sync_all().unwrap();
900 }
901
902 #[test]
903 fn test_hot_reload_basic() {
904 let temp_dir = TempDir::new().unwrap();
905 let config_path = temp_dir.path().join("test.conf");
906 write_conf(&config_path, "key=value1\n");
907
908 let mut hot_config = HotReloadConfig::from_file(&config_path).unwrap();
909 {
910 let config = hot_config.config();
911 let config_read = config.read().unwrap();
912 assert_eq!(
913 config_read.get("key").unwrap().as_string().unwrap(),
914 "value1"
915 );
916 }
917
918 // Sleep past filesystem mtime resolution before re-writing.
919 thread::sleep(Duration::from_millis(10));
920 write_conf(&config_path, "key=value2\n");
921
922 let reloaded = hot_config.reload().unwrap();
923 assert!(reloaded);
924
925 {
926 let config = hot_config.config();
927 let config_read = config.read().unwrap();
928 assert_eq!(
929 config_read.get("key").unwrap().as_string().unwrap(),
930 "value2"
931 );
932 }
933 }
934
935 #[test]
936 #[allow(deprecated)]
937 fn test_hot_reload_notifications_deprecated_bridge() {
938 // Tests that the deprecated `with_change_notifications` bridge
939 // still produces events through the new dispatch path.
940 let temp_dir = TempDir::new().unwrap();
941 let config_path = temp_dir.path().join("test.conf");
942 write_conf(&config_path, "key=value1\n");
943
944 let (mut hot_config, receiver) = HotReloadConfig::from_file(&config_path)
945 .unwrap()
946 .with_change_notifications();
947
948 thread::sleep(Duration::from_millis(10));
949 write_conf(&config_path, "key=value2\n");
950 hot_config.reload().unwrap();
951
952 let event = receiver.try_recv().unwrap();
953 match event {
954 ConfigChangeEvent::Reloaded { path, .. } => assert_eq!(path, config_path),
955 _ => panic!("Expected Reloaded event"),
956 }
957 }
958
959 #[test]
960 fn test_on_change_single_handler() {
961 let temp_dir = TempDir::new().unwrap();
962 let config_path = temp_dir.path().join("test.conf");
963 write_conf(&config_path, "key=value1\n");
964
965 let mut hot = HotReloadConfig::from_file(&config_path).unwrap();
966 let counter = Arc::new(AtomicUsize::new(0));
967 let c = Arc::clone(&counter);
968 let _sub = hot.on_change(move |event| {
969 if matches!(event, ConfigChangeEvent::Reloaded { .. }) {
970 c.fetch_add(1, Ordering::Relaxed);
971 }
972 });
973
974 thread::sleep(Duration::from_millis(10));
975 write_conf(&config_path, "key=value2\n");
976 hot.reload().unwrap();
977
978 assert_eq!(counter.load(Ordering::Relaxed), 1);
979 }
980
981 #[test]
982 fn test_on_change_multiple_handlers_fire_in_order() {
983 let temp_dir = TempDir::new().unwrap();
984 let config_path = temp_dir.path().join("test.conf");
985 write_conf(&config_path, "key=value1\n");
986
987 let mut hot = HotReloadConfig::from_file(&config_path).unwrap();
988 let order: Arc<std::sync::Mutex<Vec<u8>>> = Arc::new(std::sync::Mutex::new(Vec::new()));
989
990 let o1 = Arc::clone(&order);
991 let _s1 = hot.on_change(move |_e| o1.lock().unwrap().push(1));
992 let o2 = Arc::clone(&order);
993 let _s2 = hot.on_change(move |_e| o2.lock().unwrap().push(2));
994 let o3 = Arc::clone(&order);
995 let _s3 = hot.on_change(move |_e| o3.lock().unwrap().push(3));
996
997 thread::sleep(Duration::from_millis(10));
998 write_conf(&config_path, "key=value2\n");
999 hot.reload().unwrap();
1000
1001 // Three handlers see the Reloaded event in registration order.
1002 // (Each `reload` produces exactly one Reloaded event.)
1003 let final_order = order.lock().unwrap().clone();
1004 assert_eq!(final_order, vec![1u8, 2, 3]);
1005 }
1006
1007 #[test]
1008 fn test_on_change_drop_unregisters() {
1009 let temp_dir = TempDir::new().unwrap();
1010 let config_path = temp_dir.path().join("test.conf");
1011 write_conf(&config_path, "key=value1\n");
1012
1013 let mut hot = HotReloadConfig::from_file(&config_path).unwrap();
1014 let counter = Arc::new(AtomicUsize::new(0));
1015 let c = Arc::clone(&counter);
1016 let sub = hot.on_change(move |_e| {
1017 c.fetch_add(1, Ordering::Relaxed);
1018 });
1019
1020 // First reload: handler fires.
1021 thread::sleep(Duration::from_millis(10));
1022 write_conf(&config_path, "key=value2\n");
1023 hot.reload().unwrap();
1024 assert_eq!(counter.load(Ordering::Relaxed), 1);
1025
1026 // Drop the subscription — handler is unregistered.
1027 drop(sub);
1028
1029 // Second reload: handler does NOT fire.
1030 thread::sleep(Duration::from_millis(10));
1031 write_conf(&config_path, "key=value3\n");
1032 hot.reload().unwrap();
1033 assert_eq!(counter.load(Ordering::Relaxed), 1);
1034 }
1035
1036 #[test]
1037 fn test_on_change_panic_isolation() {
1038 // A handler that panics must NOT prevent subsequent handlers
1039 // from running and must NOT poison the watcher thread.
1040 let temp_dir = TempDir::new().unwrap();
1041 let config_path = temp_dir.path().join("test.conf");
1042 write_conf(&config_path, "key=value1\n");
1043
1044 let mut hot = HotReloadConfig::from_file(&config_path).unwrap();
1045 let after_panic = Arc::new(AtomicUsize::new(0));
1046
1047 let _s_panic = hot.on_change(|_e| {
1048 panic!("handler-side panic; should be swallowed");
1049 });
1050 let after = Arc::clone(&after_panic);
1051 let _s_after = hot.on_change(move |_e| {
1052 after.fetch_add(1, Ordering::Relaxed);
1053 });
1054
1055 thread::sleep(Duration::from_millis(10));
1056 write_conf(&config_path, "key=value2\n");
1057 hot.reload().unwrap();
1058
1059 // The second handler ran despite the first panicking.
1060 assert_eq!(after_panic.load(Ordering::Relaxed), 1);
1061 }
1062
1063 #[test]
1064 fn test_on_change_forget_keeps_handler_alive() {
1065 let temp_dir = TempDir::new().unwrap();
1066 let config_path = temp_dir.path().join("test.conf");
1067 write_conf(&config_path, "key=value1\n");
1068
1069 let mut hot = HotReloadConfig::from_file(&config_path).unwrap();
1070 let counter = Arc::new(AtomicUsize::new(0));
1071 let c = Arc::clone(&counter);
1072
1073 // forget() — handler is now process-lifetime (or, more
1074 // precisely, lifetime of the HotReloadConfig's HandlerList).
1075 hot.on_change(move |_e| {
1076 c.fetch_add(1, Ordering::Relaxed);
1077 })
1078 .forget();
1079
1080 thread::sleep(Duration::from_millis(10));
1081 write_conf(&config_path, "key=value2\n");
1082 hot.reload().unwrap();
1083 assert_eq!(counter.load(Ordering::Relaxed), 1);
1084
1085 thread::sleep(Duration::from_millis(10));
1086 write_conf(&config_path, "key=value3\n");
1087 hot.reload().unwrap();
1088 assert_eq!(counter.load(Ordering::Relaxed), 2);
1089 }
1090
1091 #[test]
1092 fn test_handle_on_change_after_start_watching() {
1093 // Verify that `HotReloadHandle::on_change` works post-
1094 // start_watching — handlers registered via the handle see
1095 // events the same as handlers registered before.
1096 let temp_dir = TempDir::new().unwrap();
1097 let config_path = temp_dir.path().join("test.conf");
1098 write_conf(&config_path, "key=value1\n");
1099
1100 let hot = HotReloadConfig::from_file(&config_path)
1101 .unwrap()
1102 .with_poll_interval(Duration::from_millis(50))
1103 .with_debounce(Duration::from_millis(25));
1104
1105 let handle = hot.start_watching();
1106
1107 let counter = Arc::new(AtomicUsize::new(0));
1108 let c = Arc::clone(&counter);
1109 let _sub = handle.on_change(move |_e| {
1110 c.fetch_add(1, Ordering::Relaxed);
1111 });
1112
1113 thread::sleep(Duration::from_millis(150));
1114 write_conf(&config_path, "key=value2\n");
1115 thread::sleep(Duration::from_millis(500));
1116
1117 assert!(
1118 counter.load(Ordering::Relaxed) >= 1,
1119 "handle.on_change handler never fired"
1120 );
1121
1122 handle.stop().unwrap();
1123 }
1124
1125 #[test]
1126 fn test_automatic_watching() {
1127 let temp_dir = TempDir::new().unwrap();
1128 let config_path = temp_dir.path().join("test.conf");
1129 write_conf(&config_path, "key=value1\n");
1130
1131 let counter = Arc::new(AtomicUsize::new(0));
1132 let hot = HotReloadConfig::from_file(&config_path)
1133 .unwrap()
1134 .with_poll_interval(Duration::from_millis(50))
1135 .with_debounce(Duration::from_millis(25));
1136
1137 let c = Arc::clone(&counter);
1138 let _sub = hot.on_change(move |event| {
1139 if matches!(event, ConfigChangeEvent::Reloaded { .. }) {
1140 c.fetch_add(1, Ordering::Relaxed);
1141 }
1142 });
1143
1144 let config_ref = hot.config();
1145 let handle = hot.start_watching();
1146
1147 thread::sleep(Duration::from_millis(100));
1148 write_conf(&config_path, "key=value2\n");
1149 thread::sleep(Duration::from_millis(500));
1150
1151 {
1152 let config_read = config_ref.read().unwrap();
1153 assert_eq!(
1154 config_read.get("key").unwrap().as_string().unwrap(),
1155 "value2"
1156 );
1157 }
1158 assert!(
1159 counter.load(Ordering::Relaxed) >= 1,
1160 "expected at least one Reloaded event"
1161 );
1162
1163 handle.stop().unwrap();
1164 }
1165}