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. The
20//! write lock is held only for the swap and the checks on it, never
21//! while handlers run.
22//! - **Reload checks** (v1.4.0+): a file that changes while it is read, or
23//! that holds no values, does not replace the current configuration;
24//! a caller's validator and the configuration's validation rules must
25//! pass; read-only mode, defaults and rules carry over.
26//! - **Lock-free in-process notification dispatch** (v1.0.0+). Register
27//! handlers via `HotReloadConfig::on_change` / `HotReloadHandle::on_change`;
28//! the reloader thread invokes every registered handler inline with
29//! no channel allocation and no cross-thread wakeup, after the new
30//! configuration is in place and with no lock held, so a handler can
31//! read the configuration. Backed by
32//! `ArcSwap<Vec<Handler>>` — snapshot reads cost a single atomic
33//! pointer load (~5 ns) regardless of how many handlers are
34//! registered. See `docs/PERFORMANCE.md` for measured numbers.
35//! - **Panic isolation.** Each handler invocation is wrapped in
36//! `catch_unwind` so one bad handler can't take down the watcher
37//! or other handlers.
38//! - **Polling fallback** (always available, used as the default when
39//! the `hot-reload` feature is disabled, or available as an opt-in
40//! on top of event-driven watching for environments where the kernel
41//! APIs are known-broken — network filesystems, some container
42//! layers).
43
44use crate::config::Config;
45use crate::error::{Error, Result};
46use crate::load::LoadOptions;
47use arc_swap::ArcSwap;
48use std::panic::{catch_unwind, AssertUnwindSafe};
49use std::path::{Path, PathBuf};
50use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
51use std::sync::mpsc::{self, Receiver};
52use std::sync::{Arc, RwLock, Weak};
53use std::thread;
54use std::time::{Duration, SystemTime};
55
56/// Configuration change event types.
57///
58/// **Stability:** `ConfigChangeEvent` is `#[non_exhaustive]` so the
59/// v1.x SemVer contract can add new variants (e.g. `Renamed`,
60/// `PermissionDenied`) in MINOR releases without breaking user code.
61/// Callers must use a wildcard arm when pattern-matching.
62#[derive(Debug, Clone)]
63#[non_exhaustive]
64pub enum ConfigChangeEvent {
65 /// Configuration successfully reloaded
66 Reloaded {
67 /// Path to the configuration file that was reloaded
68 path: PathBuf,
69 /// Timestamp when the reload completed
70 timestamp: SystemTime,
71 },
72 /// Configuration reload failed
73 ReloadFailed {
74 /// Path to the configuration file that failed to reload
75 path: PathBuf,
76 /// Error message describing what went wrong
77 error: String,
78 /// Timestamp when the error occurred
79 timestamp: SystemTime,
80 },
81 /// Configuration file was modified
82 FileModified {
83 /// Path to the configuration file that was modified
84 path: PathBuf,
85 /// Timestamp when the modification was detected
86 timestamp: SystemTime,
87 },
88 /// Configuration file was deleted
89 FileDeleted {
90 /// Path to the configuration file that was deleted
91 path: PathBuf,
92 /// Timestamp when the deletion was detected
93 timestamp: SystemTime,
94 },
95}
96
97/// Default debounce window applied to file-change events before
98/// triggering a reload. Sized to cover the editor "save via atomic
99/// rename" pattern (where a single save fires multiple kernel events
100/// within ~10–50 ms).
101const DEFAULT_DEBOUNCE: Duration = Duration::from_millis(100);
102
103// =========================================================================
104// HandlerList — lock-free in-process notification dispatch (v1.0.0+)
105// =========================================================================
106
107/// Boxed handler closure. `Arc` so that an iteration snapshot can
108/// outlive registration / unregistration of the same handler without
109/// invalidating the in-flight call.
110type Handler = Arc<dyn Fn(&ConfigChangeEvent) + Send + Sync + 'static>;
111
112/// Lock-free handler list backing [`HotReloadConfig::on_change`].
113///
114/// Reads (the dispatch path on the reloader thread) take a snapshot
115/// of the current handler vector via one `ArcSwap::load` — a single
116/// relaxed atomic pointer load. Writes (register / unregister)
117/// allocate a new vector, copy the old contents minus/plus one
118/// handler, and atomic-swap the pointer (`rcu`-style update). Writes
119/// never block reads.
120///
121/// The handler list is shared between [`HotReloadConfig`] and its
122/// spawned worker thread via `Arc<HandlerList>`, so handlers can be
123/// registered before *or* after [`HotReloadConfig::start_watching`]
124/// — see [`HotReloadHandle::on_change`].
125pub(crate) struct HandlerList {
126 handlers: ArcSwap<Vec<(u64, Handler)>>,
127 next_id: AtomicU64,
128}
129
130impl HandlerList {
131 fn new() -> Self {
132 Self {
133 handlers: ArcSwap::from_pointee(Vec::new()),
134 next_id: AtomicU64::new(0),
135 }
136 }
137
138 /// Dispatch an event to every registered handler.
139 ///
140 /// Each handler is invoked inline on the calling thread. Panic
141 /// isolation: a handler that panics is caught via `catch_unwind`
142 /// so subsequent handlers still run and the reloader thread is
143 /// not torn down.
144 fn dispatch(&self, event: &ConfigChangeEvent) {
145 // Single atomic pointer load — the dispatch hot path.
146 let snapshot = self.handlers.load();
147 for (_id, handler) in snapshot.iter() {
148 // Clone the Arc<dyn Fn> so the handler stays alive even
149 // if it's concurrently unregistered during this loop
150 // iteration. Refcount bump, no allocation.
151 let h = Arc::clone(handler);
152 // REPS-AUDIT: handlers are user-supplied; one panicking
153 // handler must not break the watcher or other handlers.
154 // `catch_unwind` swallows the panic and we discard the
155 // payload (handlers are best-effort observers).
156 let _ = catch_unwind(AssertUnwindSafe(move || {
157 h(event);
158 }));
159 }
160 }
161
162 /// Register a new handler, returning its assigned id.
163 fn register(&self, handler: Handler) -> u64 {
164 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
165 self.handlers.rcu(|current| {
166 let mut next = Vec::with_capacity(current.len() + 1);
167 next.extend(current.iter().cloned());
168 next.push((id, Arc::clone(&handler)));
169 next
170 });
171 id
172 }
173
174 /// Remove the handler with the given id, if present. Idempotent.
175 fn unregister(&self, id: u64) {
176 self.handlers.rcu(|current| {
177 current
178 .iter()
179 .filter(|(other_id, _)| *other_id != id)
180 .cloned()
181 .collect::<Vec<_>>()
182 });
183 }
184}
185
186/// RAII handle for a registered change-notification handler.
187///
188/// Returned by [`HotReloadConfig::on_change`] /
189/// [`HotReloadHandle::on_change`]. Drop the `Subscription` to
190/// unregister the handler. The watcher itself outlives any individual
191/// subscription — multiple subscriptions can come and go without
192/// touching the underlying [`HotReloadConfig`].
193///
194/// # Example
195///
196/// ```rust,no_run
197/// use config_lib::hot_reload::{HotReloadConfig, ConfigChangeEvent};
198///
199/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
200/// let hot = HotReloadConfig::from_file("app.conf")?;
201/// let _subscription = hot.on_change(|event: &ConfigChangeEvent| {
202/// println!("config changed: {event:?}");
203/// });
204/// // Drop `_subscription` (e.g. at end of scope) to unregister.
205/// # Ok(())
206/// # }
207/// ```
208#[must_use = "dropping the Subscription immediately unregisters the handler; bind to a name (`let _sub = ...`) or call `.forget()` to keep the handler alive"]
209pub struct Subscription {
210 list: Weak<HandlerList>,
211 id: u64,
212}
213
214impl Subscription {
215 /// Detach the subscription from its drop-based unregistration
216 /// hook. The handler stays registered for the lifetime of the
217 /// underlying watcher (until the [`HotReloadConfig`] or
218 /// [`HotReloadHandle`] that produced it is dropped).
219 ///
220 /// Useful for global / process-lifetime handlers where the
221 /// caller has no convenient owning scope to hold the
222 /// `Subscription`.
223 pub fn forget(mut self) {
224 // Clear the weak reference so Drop becomes a no-op.
225 self.list = Weak::new();
226 }
227}
228
229impl Drop for Subscription {
230 fn drop(&mut self) {
231 if let Some(list) = self.list.upgrade() {
232 list.unregister(self.id);
233 }
234 }
235}
236
237impl std::fmt::Debug for Subscription {
238 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239 f.debug_struct("Subscription")
240 .field("id", &self.id)
241 .field("alive", &(self.list.strong_count() > 0))
242 .finish()
243 }
244}
245
246// =========================================================================
247// Reloading: load, check, swap, then notify
248// =========================================================================
249
250/// A caller's check, run on every reloaded configuration before it goes
251/// live. See [`HotReloadConfig::with_validator`].
252type Validator = Arc<dyn Fn(&Config) -> Result<()> + Send + Sync + 'static>;
253
254/// Shortest polling interval. `recv_timeout(0)` returns at once, so a zero
255/// interval used to spin a core.
256const MIN_POLL_INTERVAL: Duration = Duration::from_millis(10);
257
258/// Most size checks made while waiting for a write to finish
259const MAX_SETTLE_CHECKS: u32 = 50;
260
261/// Size and modification time of the watched file
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
263struct Stamp {
264 len: u64,
265 modified: Option<SystemTime>,
266}
267
268fn stamp(path: &Path) -> std::io::Result<Stamp> {
269 let meta = std::fs::metadata(path)?;
270 Ok(Stamp {
271 len: meta.len(),
272 modified: meta.modified().ok(),
273 })
274}
275
276/// Why a reload did not happen
277enum ReloadError {
278 /// The file changed while it was read: a write is still going on
279 Unsettled,
280 /// The file could not be loaded, or the result was refused
281 Failed(Error),
282}
283
284/// Everything a reload needs. Shared by [`HotReloadConfig::reload`] and the
285/// background workers, so both apply the same checks.
286#[derive(Clone)]
287struct Reloader {
288 current: Arc<RwLock<Config>>,
289 file_path: PathBuf,
290 handlers: Arc<HandlerList>,
291 load: LoadOptions,
292 allow_empty: bool,
293 validator: Option<Validator>,
294}
295
296impl Reloader {
297 fn io_error(&self, e: std::io::Error) -> ReloadError {
298 ReloadError::Failed(Error::io(self.file_path.display().to_string(), e))
299 }
300
301 /// Load the file, check the result, and swap it in.
302 ///
303 /// The new configuration is refused, and the current one kept, when the
304 /// file changed while it was read, when it holds no values but the
305 /// current configuration does (unless empty reloads are allowed), when
306 /// the caller's validator refuses it, or when the validation rules set
307 /// on the current configuration find a critical error. Read-only mode,
308 /// the defaults table and the validation rules carry over.
309 ///
310 /// The write lock is held only for the checks that need the current
311 /// configuration and the swap; nothing is dispatched under it.
312 fn reload(&self) -> std::result::Result<Stamp, ReloadError> {
313 let before = stamp(&self.file_path).map_err(|e| self.io_error(e))?;
314 let mut next =
315 Config::from_file_with(&self.file_path, &self.load).map_err(ReloadError::Failed)?;
316 let after = stamp(&self.file_path).map_err(|e| self.io_error(e))?;
317 if before != after {
318 return Err(ReloadError::Unsettled);
319 }
320 if let Some(validator) = &self.validator {
321 validator(&next).map_err(ReloadError::Failed)?;
322 }
323
324 let mut current = self
325 .current
326 .write()
327 .map_err(|_| ReloadError::Failed(Error::concurrency("configuration lock poisoned")))?;
328 if !self.allow_empty && next.is_empty() && !current.is_empty() {
329 return Err(ReloadError::Failed(Error::validation(
330 "the file holds no values, so the current configuration is kept \
331 (a file read while it was being written looks like this; see \
332 HotReloadConfig::allow_empty_reload)",
333 )));
334 }
335 next.inherit_runtime_state(&mut current);
336 #[cfg(feature = "validation")]
337 {
338 match next.validate_critical_only() {
339 Ok(errors) if errors.is_empty() => {}
340 Ok(errors) => {
341 next.return_validation_rules(&mut current);
342 return Err(ReloadError::Failed(Error::validation(format!(
343 "the new configuration fails {} critical validation check(s), \
344 so the current configuration is kept",
345 errors.len()
346 ))));
347 }
348 Err(e) => {
349 next.return_validation_rules(&mut current);
350 return Err(ReloadError::Failed(e));
351 }
352 }
353 }
354 *current = next;
355 drop(current);
356 Ok(after)
357 }
358
359 fn dispatch(&self, event: ConfigChangeEvent) {
360 self.handlers.dispatch(&event);
361 }
362
363 fn failed(&self, error: &Error) {
364 self.dispatch(ConfigChangeEvent::ReloadFailed {
365 path: self.file_path.clone(),
366 error: error.to_string(),
367 timestamp: SystemTime::now(),
368 });
369 }
370
371 /// Reload and notify the handlers, after the lock is released. Returns
372 /// the stamp to compare later changes against: the loaded file's on
373 /// success, the refused file's on failure (so it is not retried until
374 /// it changes again), and `last` when a write was still going on.
375 fn reload_and_notify(&self, last: Option<Stamp>) -> Option<Stamp> {
376 match self.reload() {
377 Ok(loaded) => {
378 self.dispatch(ConfigChangeEvent::Reloaded {
379 path: self.file_path.clone(),
380 timestamp: SystemTime::now(),
381 });
382 Some(loaded)
383 }
384 Err(ReloadError::Unsettled) => last,
385 Err(ReloadError::Failed(e)) => {
386 self.failed(&e);
387 stamp(&self.file_path).ok().or(last)
388 }
389 }
390 }
391
392 /// Wait until the file's size and modification time stop changing, so
393 /// a write in progress is not read half-way. Checks every `settle`, at
394 /// most [`MAX_SETTLE_CHECKS`] times.
395 fn wait_until_settled(&self, settle: Duration, stop: &AtomicBool) {
396 let mut last = stamp(&self.file_path).ok();
397 for _ in 0..MAX_SETTLE_CHECKS {
398 thread::sleep(settle);
399 if stop.load(Ordering::Relaxed) {
400 return;
401 }
402 let now = stamp(&self.file_path).ok();
403 if now == last {
404 return;
405 }
406 last = now;
407 }
408 }
409
410 /// Poll the file every `interval` until `stop` is set
411 fn poll_loop(
412 &self,
413 stop: &AtomicBool,
414 interval: Duration,
415 settle: Duration,
416 mut last: Option<Stamp>,
417 ) {
418 let mut deleted = false;
419 while !stop.load(Ordering::Relaxed) {
420 match stamp(&self.file_path) {
421 Ok(now) => {
422 deleted = false;
423 if Some(now) != last {
424 self.dispatch(ConfigChangeEvent::FileModified {
425 path: self.file_path.clone(),
426 timestamp: SystemTime::now(),
427 });
428 self.wait_until_settled(settle, stop);
429 last = self.reload_and_notify(last);
430 }
431 }
432 Err(_) => {
433 if !deleted {
434 deleted = true;
435 self.dispatch(ConfigChangeEvent::FileDeleted {
436 path: self.file_path.clone(),
437 timestamp: SystemTime::now(),
438 });
439 }
440 }
441 }
442 thread::sleep(interval);
443 }
444 }
445}
446
447// =========================================================================
448// HotReloadConfig
449// =========================================================================
450
451/// Hot-reloadable configuration container.
452///
453/// Construct with [`HotReloadConfig::from_file`], then either drive
454/// reloads manually with [`HotReloadConfig::reload`] or hand off to a
455/// background watcher with [`HotReloadConfig::start_watching`].
456///
457/// Every reload applies the same checks before the new configuration
458/// replaces the current one (since v1.4.0):
459///
460/// - the file must not change while it is read, and the watcher waits for
461/// its size and modification time to settle first;
462/// - a file that holds no values does not replace a configuration that
463/// does, unless [`HotReloadConfig::allow_empty_reload`] is set;
464/// - the [`HotReloadConfig::with_validator`] check, and the validation
465/// rules set on the current configuration (feature `validation`), must
466/// pass;
467/// - read-only mode, the defaults table and the validation rules carry
468/// over to the new configuration.
469///
470/// A refused reload keeps the current configuration and dispatches
471/// [`ConfigChangeEvent::ReloadFailed`]. Handlers run after the new
472/// configuration is in place and the lock is released, so a handler may
473/// read the configuration.
474///
475/// Writers should still replace the file atomically (write a temporary
476/// file, then rename it over the target, as [`Config::save_to_file`] does):
477/// a writer that pauses for longer than the debounce window in the middle
478/// of an in-place rewrite can leave a partial file that parses.
479///
480/// Configurable knobs (all consuming-builder style, intended for
481/// fluent construction):
482///
483/// - [`HotReloadConfig::on_change`] — register a change handler
484/// (v1.0.0+; the recommended notification API).
485/// - [`HotReloadConfig::with_change_notifications`] — receive
486/// [`ConfigChangeEvent`]s on an `mpsc` channel (deprecated since
487/// v1.0.0; kept as a bridge for backwards compatibility).
488/// - [`HotReloadConfig::with_debounce`] — adjust the debounce window
489/// (default 100 ms).
490/// - [`HotReloadConfig::with_poll_interval`] — set the polling
491/// interval. Used directly when the `hot-reload` feature is off;
492/// used as the watchdog interval when the feature is on.
493/// - [`HotReloadConfig::with_polling_fallback`] — opt into a
494/// parallel polling watchdog *in addition to* the event-driven
495/// watcher, for environments where the kernel watcher is known
496/// unreliable.
497/// - [`HotReloadConfig::with_validator`] and
498/// [`HotReloadConfig::allow_empty_reload`]: reload checks (v1.4.0+).
499pub struct HotReloadConfig {
500 /// Current configuration (thread-safe)
501 current: Arc<RwLock<Config>>,
502 /// File path being watched
503 file_path: PathBuf,
504 /// Last known modification time
505 last_modified: SystemTime,
506 /// Size of the file when it was last loaded
507 last_len: Option<u64>,
508 /// Lock-free handler list. Shared with the worker thread via
509 /// `Arc<HandlerList>` once `start_watching` is called.
510 handlers: Arc<HandlerList>,
511 /// Bridge subscriptions kept alive by the deprecated
512 /// `with_change_notifications` API. Each entry registers a
513 /// closure that forwards events to the corresponding
514 /// `mpsc::Sender`; dropping the subscription stops the
515 /// forwarding. Stored here so the bridge lives at least as
516 /// long as the `HotReloadConfig` itself, and is moved into the
517 /// [`HotReloadHandle`] when `start_watching` consumes self.
518 bridges: Vec<Subscription>,
519 /// Polling interval — used as primary cadence when the
520 /// `hot-reload` feature is off, or as the watchdog interval when
521 /// the feature is on and `polling_fallback_enabled` is set.
522 poll_interval: Duration,
523 /// Debounce window applied to clustered file-change events.
524 debounce: Duration,
525 /// Whether to run the polling watchdog *in addition to* the
526 /// event-driven watcher. Useful on network filesystems.
527 polling_fallback_enabled: bool,
528 /// Options every reload loads the file with
529 load: LoadOptions,
530 /// Whether an empty file may replace a non-empty configuration
531 allow_empty: bool,
532 /// Caller's check on every reloaded configuration
533 validator: Option<Validator>,
534}
535
536impl HotReloadConfig {
537 /// Create a new hot-reloadable configuration from a file.
538 ///
539 /// Loads with the default [`LoadOptions`], as [`Config::from_file`]
540 /// does.
541 ///
542 /// # Errors
543 ///
544 /// Returns an error if the file cannot be read, parsed, or stat'd
545 /// for its modification time.
546 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
547 Self::from_file_with(path, LoadOptions::default())
548 }
549
550 /// Create a hot-reloadable configuration that reads NOML strictly
551 /// (no `include`, no `env()`), on the first load and on every reload.
552 ///
553 /// Since v1.4.0.
554 ///
555 /// # Errors
556 ///
557 /// As [`HotReloadConfig::from_file`].
558 pub fn from_file_strict<P: AsRef<Path>>(path: P) -> Result<Self> {
559 Self::from_file_with(path, LoadOptions::strict_defaults())
560 }
561
562 /// Create a hot-reloadable configuration that loads the file with
563 /// `options`, on the first load and on every reload.
564 ///
565 /// Since v1.4.0.
566 ///
567 /// # Errors
568 ///
569 /// As [`HotReloadConfig::from_file`].
570 pub fn from_file_with<P: AsRef<Path>>(path: P, options: LoadOptions) -> Result<Self> {
571 let path = path.as_ref().to_path_buf();
572 let config = Config::from_file_with(&path, &options)?;
573
574 let metadata =
575 std::fs::metadata(&path).map_err(|e| Error::io(path.display().to_string(), e))?;
576 let last_modified = metadata
577 .modified()
578 .map_err(|e| Error::io(path.display().to_string(), e))?;
579
580 Ok(Self {
581 current: Arc::new(RwLock::new(config)),
582 file_path: path,
583 last_modified,
584 last_len: Some(metadata.len()),
585 handlers: Arc::new(HandlerList::new()),
586 bridges: Vec::new(),
587 poll_interval: Duration::from_secs(1),
588 debounce: DEFAULT_DEBOUNCE,
589 polling_fallback_enabled: false,
590 load: options,
591 allow_empty: false,
592 validator: None,
593 })
594 }
595
596 /// Set the polling interval for file change detection.
597 ///
598 /// When the `hot-reload` feature is enabled (the default in v0.9.6+),
599 /// the primary watcher is event-driven and this interval is only
600 /// consulted as the watchdog cadence if `with_polling_fallback`
601 /// has been called.
602 ///
603 /// When the `hot-reload` feature is disabled, this is the actual
604 /// polling cadence of the background thread.
605 ///
606 /// Intervals below 10 ms are raised to 10 ms (since v1.4.0; a zero
607 /// interval used to spin a core).
608 pub fn with_poll_interval(mut self, interval: Duration) -> Self {
609 self.poll_interval = interval.max(MIN_POLL_INTERVAL);
610 self
611 }
612
613 /// Override the debounce window applied to clustered file-change
614 /// events.
615 ///
616 /// Editors that save via "write-to-tmp + atomic-rename" generate
617 /// multiple kernel events for a single user save. The debounce
618 /// collapses any burst within this window to a single reload.
619 /// Default: 100 ms.
620 pub fn with_debounce(mut self, debounce: Duration) -> Self {
621 self.debounce = debounce;
622 self
623 }
624
625 /// Opt into running a polling watchdog *in addition to* the
626 /// event-driven watcher.
627 ///
628 /// Network filesystems (SMB, NFS), some container overlay
629 /// filesystems, and a handful of edge-case kernel configurations
630 /// drop or delay events that `notify` would normally surface.
631 /// Enabling the polling fallback re-derives changes from periodic
632 /// `stat(2)` calls on the watched path, at the
633 /// [`HotReloadConfig::with_poll_interval`] cadence.
634 ///
635 /// Has no effect (and costs nothing) when the `hot-reload` Cargo
636 /// feature is disabled — the watcher is already polling in that
637 /// configuration.
638 pub fn with_polling_fallback(mut self) -> Self {
639 self.polling_fallback_enabled = true;
640 self
641 }
642
643 /// Let a reload whose file holds no values replace a configuration
644 /// that has values.
645 ///
646 /// Off by default (since v1.4.0): a file that is truncated and then
647 /// rewritten in place is empty for a moment, and reading it then would
648 /// swap in an empty configuration, so every read would fall back to
649 /// its default.
650 pub fn allow_empty_reload(mut self) -> Self {
651 self.allow_empty = true;
652 self
653 }
654
655 /// Check every reloaded configuration before it goes live.
656 ///
657 /// The check runs on the newly loaded configuration. When it returns
658 /// an error, the current configuration is kept and
659 /// [`ConfigChangeEvent::ReloadFailed`] carries the error's text. It
660 /// does not run on the first load.
661 ///
662 /// Since v1.4.0.
663 ///
664 /// # Example
665 ///
666 /// ```rust,no_run
667 /// use config_lib::hot_reload::HotReloadConfig;
668 /// use config_lib::Error;
669 ///
670 /// # fn main() -> Result<(), Error> {
671 /// let hot = HotReloadConfig::from_file("app.conf")?.with_validator(|config| {
672 /// if config.contains_key("server.port") {
673 /// Ok(())
674 /// } else {
675 /// Err(Error::validation("server.port is required"))
676 /// }
677 /// });
678 /// let _handle = hot.start_watching();
679 /// # Ok(())
680 /// # }
681 /// ```
682 pub fn with_validator<F>(mut self, validator: F) -> Self
683 where
684 F: Fn(&Config) -> Result<()> + Send + Sync + 'static,
685 {
686 self.validator = Some(Arc::new(validator));
687 self
688 }
689
690 /// Register a change handler. **Recommended notification API**
691 /// (v1.0.0+).
692 ///
693 /// The handler is invoked inline on the reloader thread every
694 /// time a [`ConfigChangeEvent`] is produced — typically a few
695 /// milliseconds after the underlying filesystem event, plus the
696 /// debounce window. Dispatch overhead is a single atomic pointer
697 /// load (~5 ns) plus the handler's own cost; multiple handlers
698 /// are called in registration order with no per-handler channel
699 /// allocation.
700 ///
701 /// Handlers run with no lock held: on
702 /// [`ConfigChangeEvent::Reloaded`] the new configuration is already in
703 /// place, and the handler may read it through
704 /// [`HotReloadConfig::config`]. (Before v1.4.0 the background watcher
705 /// dispatched while it still held the write lock, so a handler that
706 /// read the configuration deadlocked every reader.)
707 ///
708 /// Returns a [`Subscription`] whose `Drop` unregisters the
709 /// handler. Bind to a `let _sub = ...` if you want the handler
710 /// to live for the surrounding scope, or call
711 /// [`Subscription::forget`] to detach the drop hook.
712 ///
713 /// # Panics
714 ///
715 /// If the handler itself panics, the panic is caught via
716 /// `catch_unwind` and discarded — other handlers continue to
717 /// receive the event and the reloader thread is not torn down.
718 /// Handler authors should avoid panicking, but a buggy handler
719 /// won't take down the whole library.
720 ///
721 /// # Example
722 ///
723 /// ```rust,no_run
724 /// use config_lib::hot_reload::{HotReloadConfig, ConfigChangeEvent};
725 ///
726 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
727 /// let hot = HotReloadConfig::from_file("app.conf")?;
728 /// let shared = hot.config();
729 /// let _sub = hot.on_change(move |event: &ConfigChangeEvent| {
730 /// if let ConfigChangeEvent::Reloaded { .. } = event {
731 /// let port: u16 = shared.read().map(|c| c.get_or("port", 8080)).unwrap_or(8080);
732 /// println!("port is now {port}");
733 /// }
734 /// });
735 /// let _handle = hot.start_watching();
736 /// // ... `_sub` and `_handle` are alive for the rest of the scope
737 /// # Ok(())
738 /// # }
739 /// ```
740 pub fn on_change<F>(&self, handler: F) -> Subscription
741 where
742 F: Fn(&ConfigChangeEvent) + Send + Sync + 'static,
743 {
744 let id = self.handlers.register(Arc::new(handler));
745 Subscription {
746 list: Arc::downgrade(&self.handlers),
747 id,
748 }
749 }
750
751 /// Enable channel-based change notifications. **Deprecated since
752 /// v1.0.0** — prefer [`HotReloadConfig::on_change`].
753 ///
754 /// Internally bridges to the same lock-free handler list as
755 /// `on_change` by registering a closure that forwards events
756 /// to an `mpsc::Sender`. The bridge subscription is held by
757 /// `self` so the channel keeps receiving events for the
758 /// lifetime of the watcher.
759 ///
760 /// The bridge pays one extra `mpsc::Sender::send` per event
761 /// (~100–200 ns) on top of the lock-free dispatch cost — the
762 /// inverse of why `on_change` exists. Existing code using
763 /// `Receiver<ConfigChangeEvent>` continues to work unchanged.
764 #[deprecated(
765 since = "1.0.0",
766 note = "use `on_change` for lock-free dispatch; this method continues to work but pays an mpsc allocation per event"
767 )]
768 pub fn with_change_notifications(mut self) -> (Self, Receiver<ConfigChangeEvent>) {
769 let (tx, rx) = mpsc::channel();
770 let bridge = self.on_change(move |event| {
771 let _ = tx.send(event.clone());
772 });
773 self.bridges.push(bridge);
774 (self, rx)
775 }
776
777 /// Get a thread-safe reference to the current configuration.
778 pub fn config(&self) -> Arc<RwLock<Config>> {
779 Arc::clone(&self.current)
780 }
781
782 /// Get a freshly-reparsed snapshot of the configuration file as
783 /// it exists on disk *right now*.
784 ///
785 /// This is distinct from reading the current `Arc<RwLock<Config>>`
786 /// — it bypasses the watcher and re-reads the file. Useful for
787 /// "what would I see if I reloaded now" inspection.
788 ///
789 /// # Errors
790 ///
791 /// Returns an error if the file cannot be read or parsed.
792 pub fn snapshot(&self) -> Result<Config> {
793 Config::from_file_with(&self.file_path, &self.load)
794 }
795
796 fn reloader(&self) -> Reloader {
797 Reloader {
798 current: Arc::clone(&self.current),
799 file_path: self.file_path.clone(),
800 handlers: Arc::clone(&self.handlers),
801 load: self.load.clone(),
802 allow_empty: self.allow_empty,
803 validator: self.validator.clone(),
804 }
805 }
806
807 /// Wait between size checks for a write to settle: half the debounce
808 /// window, between 10 ms and 100 ms
809 fn settle_time(&self) -> Duration {
810 (self.debounce / 2).clamp(MIN_POLL_INTERVAL, DEFAULT_DEBOUNCE)
811 }
812
813 /// Manually trigger a reload check.
814 ///
815 /// Re-stats the file, and re-parses it if its modification time is
816 /// newer or its size differs from the last load. Dispatches a
817 /// [`ConfigChangeEvent::Reloaded`] or
818 /// [`ConfigChangeEvent::ReloadFailed`] notification through the
819 /// handler list, after the new configuration is in place.
820 ///
821 /// The new configuration goes through the checks listed on
822 /// [`HotReloadConfig`]; when one refuses it, the current configuration
823 /// is kept and the error is returned.
824 ///
825 /// Returns `Ok(true)` if a reload was performed, `Ok(false)` if
826 /// the file was unchanged since the last check.
827 ///
828 /// # Errors
829 ///
830 /// Returns an error if the file cannot be stat'd, read, or parsed, if
831 /// it changed while it was read, or if a reload check refused it.
832 pub fn reload(&mut self) -> Result<bool> {
833 let now = stamp(&self.file_path)
834 .map_err(|e| Error::io(self.file_path.display().to_string(), e))?;
835 let newer = now.modified.map_or(true, |m| m > self.last_modified);
836 if !newer && Some(now.len) == self.last_len {
837 return Ok(false);
838 }
839
840 let reloader = self.reloader();
841 match reloader.reload() {
842 Ok(loaded) => {
843 if let Some(m) = loaded.modified {
844 self.last_modified = m;
845 }
846 self.last_len = Some(loaded.len);
847 reloader.dispatch(ConfigChangeEvent::Reloaded {
848 path: self.file_path.clone(),
849 timestamp: SystemTime::now(),
850 });
851 Ok(true)
852 }
853 Err(ReloadError::Unsettled) => {
854 let e = Error::general("the file changed while it was read; try again");
855 reloader.failed(&e);
856 Err(e)
857 }
858 Err(ReloadError::Failed(e)) => {
859 reloader.failed(&e);
860 Err(e)
861 }
862 }
863 }
864
865 /// Start automatic hot reloading in a background thread.
866 ///
867 /// With the `hot-reload` Cargo feature enabled (the default in
868 /// v0.9.6+), the background worker registers a
869 /// `notify::RecommendedWatcher` on the file's parent directory
870 /// and reacts to kernel events. Otherwise it falls back to a
871 /// `poll_interval`-cadence polling thread (the v0.9.5 behavior).
872 ///
873 /// If the event watcher cannot be started, or stops, the worker
874 /// dispatches [`ConfigChangeEvent::ReloadFailed`] and polls the file
875 /// instead (since v1.4.0; before, it stopped reloading).
876 pub fn start_watching(self) -> HotReloadHandle {
877 #[cfg(feature = "hot-reload")]
878 {
879 self.start_watching_event_driven()
880 }
881 #[cfg(not(feature = "hot-reload"))]
882 {
883 self.start_watching_polling()
884 }
885 }
886
887 /// Get the file path being watched.
888 pub fn file_path(&self) -> &Path {
889 &self.file_path
890 }
891
892 /// Get the last modification time.
893 pub fn last_modified(&self) -> SystemTime {
894 self.last_modified
895 }
896
897 fn initial_stamp(&self) -> Option<Stamp> {
898 Some(Stamp {
899 len: self.last_len?,
900 modified: Some(self.last_modified),
901 })
902 }
903
904 // -----------------------------------------------------------------
905 // Polling watcher — used as the primary watcher when the
906 // `hot-reload` Cargo feature is disabled, and when the event-driven
907 // watcher cannot start or stops.
908 // -----------------------------------------------------------------
909
910 #[cfg(not(feature = "hot-reload"))]
911 fn start_watching_polling(self) -> HotReloadHandle {
912 let stop = Arc::new(AtomicBool::new(false));
913 let stop_clone = Arc::clone(&stop);
914 let reloader = self.reloader();
915 let poll_interval = self.poll_interval;
916 let settle = self.settle_time();
917 let initial = self.initial_stamp();
918
919 let handle = thread::spawn(move || {
920 reloader.poll_loop(&stop_clone, poll_interval, settle, initial);
921 });
922
923 HotReloadHandle {
924 handle: Some(handle),
925 stop,
926 handlers: self.handlers,
927 _bridges: self.bridges,
928 }
929 }
930
931 // -----------------------------------------------------------------
932 // Event-driven watcher — gated on the `hot-reload` feature.
933 // -----------------------------------------------------------------
934
935 #[cfg(feature = "hot-reload")]
936 fn start_watching_event_driven(self) -> HotReloadHandle {
937 use notify::{Event, RecursiveMode, Watcher};
938
939 let stop = Arc::new(AtomicBool::new(false));
940 let reloader = self.reloader();
941 let file_path = self.file_path.clone();
942 let debounce = self.debounce;
943 let settle = self.settle_time();
944 let poll_interval = self.poll_interval;
945 let polling_fallback = self.polling_fallback_enabled;
946 let initial = self.initial_stamp();
947
948 // Channel from the notify callback to the reload worker.
949 // This `mpsc` is purely internal — between the notify
950 // callback (which runs on `notify`'s own thread) and our
951 // worker thread. It is NOT the user-facing notification
952 // channel; that path is via `HandlerList::dispatch`.
953 let (tx, rx) = mpsc::channel::<Event>();
954
955 // Build the watcher. We watch the *parent* directory (not the
956 // file itself) so that atomic-rename saves — where the file's
957 // inode is replaced — still surface as events on our target.
958 let watcher_dir = match file_path.parent() {
959 Some(dir) if !dir.as_os_str().is_empty() => dir.to_path_buf(),
960 _ => PathBuf::from("."),
961 };
962
963 let watcher_result = notify::RecommendedWatcher::new(
964 move |res: notify::Result<Event>| {
965 if let Ok(event) = res {
966 let _ = tx.send(event);
967 }
968 },
969 notify::Config::default(),
970 )
971 .and_then(|mut w| {
972 w.watch(&watcher_dir, RecursiveMode::NonRecursive)?;
973 Ok(w)
974 });
975
976 let watcher = match watcher_result {
977 Ok(w) => Some(w),
978 Err(e) => {
979 // The platform event API is unavailable (watch limit
980 // reached, permissions, an unsupported filesystem). The
981 // worker polls instead.
982 reloader.failed(&Error::general(format!(
983 "the file watcher could not start ({e}); polling every {} ms instead",
984 poll_interval.as_millis()
985 )));
986 None
987 }
988 };
989 let watching = watcher.is_some();
990
991 // Reload worker — consumes events from the notify callback,
992 // debounces, and re-parses on change.
993 let target_file = file_path;
994 let stop_for_worker = Arc::clone(&stop);
995
996 let handle = thread::spawn(move || {
997 let mut last = initial;
998 if !watching {
999 reloader.poll_loop(&stop_for_worker, poll_interval, settle, last);
1000 return;
1001 }
1002 let mut deleted = false;
1003 while !stop_for_worker.load(Ordering::Relaxed) {
1004 // Block up to `poll_interval` for the next event so
1005 // the stop flag is observed promptly even when the
1006 // file is quiet.
1007 let first = match rx.recv_timeout(poll_interval) {
1008 Ok(ev) => Some(ev),
1009 Err(mpsc::RecvTimeoutError::Timeout) => None,
1010 Err(mpsc::RecvTimeoutError::Disconnected) => {
1011 reloader.failed(&Error::general(format!(
1012 "the file watcher stopped; polling every {} ms instead",
1013 poll_interval.as_millis()
1014 )));
1015 reloader.poll_loop(&stop_for_worker, poll_interval, settle, last);
1016 return;
1017 }
1018 };
1019
1020 // If we got an event, drain the channel for the
1021 // debounce window so the burst from a single save
1022 // collapses to one reload.
1023 let mut relevant = false;
1024 if let Some(ev) = first {
1025 relevant |= event_targets_path(&ev, &target_file);
1026
1027 let deadline = std::time::Instant::now() + debounce;
1028 loop {
1029 let remaining =
1030 deadline.saturating_duration_since(std::time::Instant::now());
1031 if remaining.is_zero() {
1032 break;
1033 }
1034 match rx.recv_timeout(remaining) {
1035 Ok(ev) => relevant |= event_targets_path(&ev, &target_file),
1036 Err(_) => break,
1037 }
1038 }
1039 } else if !polling_fallback {
1040 continue;
1041 }
1042
1043 // Path resolution: did the target file actually change?
1044 match stamp(&target_file) {
1045 Ok(now) => {
1046 deleted = false;
1047 if !relevant && Some(now) == last {
1048 continue;
1049 }
1050
1051 reloader.dispatch(ConfigChangeEvent::FileModified {
1052 path: target_file.clone(),
1053 timestamp: SystemTime::now(),
1054 });
1055 reloader.wait_until_settled(settle, &stop_for_worker);
1056 last = reloader.reload_and_notify(last);
1057 }
1058 Err(_) => {
1059 // File missing — likely deleted between
1060 // events. Emit FileDeleted once but keep the
1061 // last-known-good config in place.
1062 if !deleted {
1063 deleted = true;
1064 reloader.dispatch(ConfigChangeEvent::FileDeleted {
1065 path: target_file.clone(),
1066 timestamp: SystemTime::now(),
1067 });
1068 }
1069 }
1070 }
1071 }
1072 });
1073
1074 HotReloadHandle {
1075 handle: Some(handle),
1076 stop,
1077 handlers: self.handlers,
1078 _bridges: self.bridges,
1079 _watcher: watcher,
1080 }
1081 }
1082}
1083
1084/// Helper: does the `notify::Event` reference our watched file?
1085///
1086/// When watching a directory non-recursively, every event carries the
1087/// list of paths it applies to. Filtering on the exact file path keeps
1088/// us from reacting to unrelated sibling files in the same directory.
1089#[cfg(feature = "hot-reload")]
1090fn event_targets_path(event: ¬ify::Event, target: &Path) -> bool {
1091 use notify::EventKind;
1092 if !matches!(
1093 event.kind,
1094 EventKind::Modify(_) | EventKind::Create(_) | EventKind::Remove(_) | EventKind::Any
1095 ) {
1096 return false;
1097 }
1098 // Canonical-form comparison helps with macOS symlink/realpath
1099 // shenanigans. Fall back to direct equality when canonicalize
1100 // can't resolve (e.g. file was just deleted).
1101 let target_canon = std::fs::canonicalize(target).ok();
1102 event.paths.iter().any(|p| {
1103 if p == target {
1104 return true;
1105 }
1106 if let (Some(tc), Ok(pc)) = (&target_canon, std::fs::canonicalize(p)) {
1107 return *tc == pc;
1108 }
1109 false
1110 })
1111}
1112
1113/// Handle for controlling the hot-reload background thread.
1114///
1115/// Returned by [`HotReloadConfig::start_watching`]. Dropping the
1116/// handle (or calling [`HotReloadHandle::stop`]) signals the worker
1117/// to exit and tears down the kernel-level watch registration.
1118/// Holding the handle keeps the watcher alive.
1119///
1120/// New handlers can be registered after `start_watching` via
1121/// [`HotReloadHandle::on_change`] — the handler list is shared
1122/// between the original `HotReloadConfig` and the spawned worker
1123/// thread.
1124pub struct HotReloadHandle {
1125 handle: Option<thread::JoinHandle<()>>,
1126 stop: Arc<AtomicBool>,
1127 /// Lock-free handler list shared with the worker thread.
1128 /// Carried here so that `on_change` continues to work after
1129 /// the original `HotReloadConfig` has been consumed by
1130 /// `start_watching`.
1131 handlers: Arc<HandlerList>,
1132 /// Bridge subscriptions kept alive for the lifetime of the
1133 /// watcher. The deprecated `with_change_notifications` path
1134 /// installed these; dropping the handle drops them, which
1135 /// unregisters the bridge handlers.
1136 _bridges: Vec<Subscription>,
1137 /// Watcher kept alive for the duration of the watch. Dropping
1138 /// the watcher tears down the kernel registration. Only carried
1139 /// when the `hot-reload` feature is on.
1140 #[cfg(feature = "hot-reload")]
1141 _watcher: Option<notify::RecommendedWatcher>,
1142}
1143
1144impl HotReloadHandle {
1145 /// Register a change handler after `start_watching` has been
1146 /// called.
1147 ///
1148 /// Semantics match [`HotReloadConfig::on_change`]. Useful when
1149 /// the consumer of the handle is a different component from
1150 /// whoever called `start_watching` — pass the handle around and
1151 /// let each component install its own handler.
1152 pub fn on_change<F>(&self, handler: F) -> Subscription
1153 where
1154 F: Fn(&ConfigChangeEvent) + Send + Sync + 'static,
1155 {
1156 let id = self.handlers.register(Arc::new(handler));
1157 Subscription {
1158 list: Arc::downgrade(&self.handlers),
1159 id,
1160 }
1161 }
1162
1163 /// Stop the background watching thread.
1164 ///
1165 /// # Errors
1166 ///
1167 /// Returns an error if the background thread panicked.
1168 pub fn stop(mut self) -> Result<()> {
1169 self.stop.store(true, Ordering::Relaxed);
1170 if let Some(handle) = self.handle.take() {
1171 handle
1172 .join()
1173 .map_err(|_| Error::concurrency("Failed to join background thread".to_string()))?;
1174 }
1175 Ok(())
1176 }
1177}
1178
1179impl Drop for HotReloadHandle {
1180 fn drop(&mut self) {
1181 self.stop.store(true, Ordering::Relaxed);
1182 if let Some(handle) = self.handle.take() {
1183 let _ = handle.join();
1184 }
1185 }
1186}
1187
1188#[cfg(test)]
1189mod tests {
1190 use super::*;
1191 use std::fs::File;
1192 use std::io::Write;
1193 use std::sync::atomic::AtomicUsize;
1194 use tempfile::TempDir;
1195
1196 /// Helper: write a CONF body to `path` and `fsync` it so the
1197 /// kernel surfaces the modification event before we proceed.
1198 fn write_conf(path: &Path, body: &str) {
1199 let mut f = File::create(path).unwrap();
1200 f.write_all(body.as_bytes()).unwrap();
1201 f.flush().unwrap();
1202 f.sync_all().unwrap();
1203 }
1204
1205 #[test]
1206 fn test_hot_reload_basic() {
1207 let temp_dir = TempDir::new().unwrap();
1208 let config_path = temp_dir.path().join("test.conf");
1209 write_conf(&config_path, "key=value1\n");
1210
1211 let mut hot_config = HotReloadConfig::from_file(&config_path).unwrap();
1212 {
1213 let config = hot_config.config();
1214 let config_read = config.read().unwrap();
1215 assert_eq!(
1216 config_read.get("key").unwrap().as_string().unwrap(),
1217 "value1"
1218 );
1219 }
1220
1221 // Sleep past filesystem mtime resolution before re-writing.
1222 thread::sleep(Duration::from_millis(10));
1223 write_conf(&config_path, "key=value2\n");
1224
1225 let reloaded = hot_config.reload().unwrap();
1226 assert!(reloaded);
1227
1228 {
1229 let config = hot_config.config();
1230 let config_read = config.read().unwrap();
1231 assert_eq!(
1232 config_read.get("key").unwrap().as_string().unwrap(),
1233 "value2"
1234 );
1235 }
1236 }
1237
1238 #[test]
1239 #[allow(deprecated)]
1240 fn test_hot_reload_notifications_deprecated_bridge() {
1241 // Tests that the deprecated `with_change_notifications` bridge
1242 // still produces events through the new dispatch path.
1243 let temp_dir = TempDir::new().unwrap();
1244 let config_path = temp_dir.path().join("test.conf");
1245 write_conf(&config_path, "key=value1\n");
1246
1247 let (mut hot_config, receiver) = HotReloadConfig::from_file(&config_path)
1248 .unwrap()
1249 .with_change_notifications();
1250
1251 thread::sleep(Duration::from_millis(10));
1252 write_conf(&config_path, "key=value2\n");
1253 hot_config.reload().unwrap();
1254
1255 let event = receiver.try_recv().unwrap();
1256 match event {
1257 ConfigChangeEvent::Reloaded { path, .. } => assert_eq!(path, config_path),
1258 _ => panic!("Expected Reloaded event"),
1259 }
1260 }
1261
1262 #[test]
1263 fn test_on_change_single_handler() {
1264 let temp_dir = TempDir::new().unwrap();
1265 let config_path = temp_dir.path().join("test.conf");
1266 write_conf(&config_path, "key=value1\n");
1267
1268 let mut hot = HotReloadConfig::from_file(&config_path).unwrap();
1269 let counter = Arc::new(AtomicUsize::new(0));
1270 let c = Arc::clone(&counter);
1271 let _sub = hot.on_change(move |event| {
1272 if matches!(event, ConfigChangeEvent::Reloaded { .. }) {
1273 c.fetch_add(1, Ordering::Relaxed);
1274 }
1275 });
1276
1277 thread::sleep(Duration::from_millis(10));
1278 write_conf(&config_path, "key=value2\n");
1279 hot.reload().unwrap();
1280
1281 assert_eq!(counter.load(Ordering::Relaxed), 1);
1282 }
1283
1284 #[test]
1285 fn test_on_change_multiple_handlers_fire_in_order() {
1286 let temp_dir = TempDir::new().unwrap();
1287 let config_path = temp_dir.path().join("test.conf");
1288 write_conf(&config_path, "key=value1\n");
1289
1290 let mut hot = HotReloadConfig::from_file(&config_path).unwrap();
1291 let order: Arc<std::sync::Mutex<Vec<u8>>> = Arc::new(std::sync::Mutex::new(Vec::new()));
1292
1293 let o1 = Arc::clone(&order);
1294 let _s1 = hot.on_change(move |_e| o1.lock().unwrap().push(1));
1295 let o2 = Arc::clone(&order);
1296 let _s2 = hot.on_change(move |_e| o2.lock().unwrap().push(2));
1297 let o3 = Arc::clone(&order);
1298 let _s3 = hot.on_change(move |_e| o3.lock().unwrap().push(3));
1299
1300 thread::sleep(Duration::from_millis(10));
1301 write_conf(&config_path, "key=value2\n");
1302 hot.reload().unwrap();
1303
1304 // Three handlers see the Reloaded event in registration order.
1305 // (Each `reload` produces exactly one Reloaded event.)
1306 let final_order = order.lock().unwrap().clone();
1307 assert_eq!(final_order, vec![1u8, 2, 3]);
1308 }
1309
1310 #[test]
1311 fn test_on_change_drop_unregisters() {
1312 let temp_dir = TempDir::new().unwrap();
1313 let config_path = temp_dir.path().join("test.conf");
1314 write_conf(&config_path, "key=value1\n");
1315
1316 let mut hot = HotReloadConfig::from_file(&config_path).unwrap();
1317 let counter = Arc::new(AtomicUsize::new(0));
1318 let c = Arc::clone(&counter);
1319 let sub = hot.on_change(move |_e| {
1320 c.fetch_add(1, Ordering::Relaxed);
1321 });
1322
1323 // First reload: handler fires.
1324 thread::sleep(Duration::from_millis(10));
1325 write_conf(&config_path, "key=value2\n");
1326 hot.reload().unwrap();
1327 assert_eq!(counter.load(Ordering::Relaxed), 1);
1328
1329 // Drop the subscription — handler is unregistered.
1330 drop(sub);
1331
1332 // Second reload: handler does NOT fire.
1333 thread::sleep(Duration::from_millis(10));
1334 write_conf(&config_path, "key=value3\n");
1335 hot.reload().unwrap();
1336 assert_eq!(counter.load(Ordering::Relaxed), 1);
1337 }
1338
1339 #[test]
1340 fn test_on_change_panic_isolation() {
1341 // A handler that panics must NOT prevent subsequent handlers
1342 // from running and must NOT poison the watcher thread.
1343 let temp_dir = TempDir::new().unwrap();
1344 let config_path = temp_dir.path().join("test.conf");
1345 write_conf(&config_path, "key=value1\n");
1346
1347 let mut hot = HotReloadConfig::from_file(&config_path).unwrap();
1348 let after_panic = Arc::new(AtomicUsize::new(0));
1349
1350 let _s_panic = hot.on_change(|_e| {
1351 panic!("handler-side panic; should be swallowed");
1352 });
1353 let after = Arc::clone(&after_panic);
1354 let _s_after = hot.on_change(move |_e| {
1355 after.fetch_add(1, Ordering::Relaxed);
1356 });
1357
1358 thread::sleep(Duration::from_millis(10));
1359 write_conf(&config_path, "key=value2\n");
1360 hot.reload().unwrap();
1361
1362 // The second handler ran despite the first panicking.
1363 assert_eq!(after_panic.load(Ordering::Relaxed), 1);
1364 }
1365
1366 #[test]
1367 fn test_on_change_forget_keeps_handler_alive() {
1368 let temp_dir = TempDir::new().unwrap();
1369 let config_path = temp_dir.path().join("test.conf");
1370 write_conf(&config_path, "key=value1\n");
1371
1372 let mut hot = HotReloadConfig::from_file(&config_path).unwrap();
1373 let counter = Arc::new(AtomicUsize::new(0));
1374 let c = Arc::clone(&counter);
1375
1376 // forget() — handler is now process-lifetime (or, more
1377 // precisely, lifetime of the HotReloadConfig's HandlerList).
1378 hot.on_change(move |_e| {
1379 c.fetch_add(1, Ordering::Relaxed);
1380 })
1381 .forget();
1382
1383 thread::sleep(Duration::from_millis(10));
1384 write_conf(&config_path, "key=value2\n");
1385 hot.reload().unwrap();
1386 assert_eq!(counter.load(Ordering::Relaxed), 1);
1387
1388 thread::sleep(Duration::from_millis(10));
1389 write_conf(&config_path, "key=value3\n");
1390 hot.reload().unwrap();
1391 assert_eq!(counter.load(Ordering::Relaxed), 2);
1392 }
1393
1394 #[test]
1395 fn test_handle_on_change_after_start_watching() {
1396 // Verify that `HotReloadHandle::on_change` works post-
1397 // start_watching — handlers registered via the handle see
1398 // events the same as handlers registered before.
1399 let temp_dir = TempDir::new().unwrap();
1400 let config_path = temp_dir.path().join("test.conf");
1401 write_conf(&config_path, "key=value1\n");
1402
1403 let hot = HotReloadConfig::from_file(&config_path)
1404 .unwrap()
1405 .with_poll_interval(Duration::from_millis(50))
1406 .with_debounce(Duration::from_millis(25));
1407
1408 let handle = hot.start_watching();
1409
1410 let counter = Arc::new(AtomicUsize::new(0));
1411 let c = Arc::clone(&counter);
1412 let _sub = handle.on_change(move |_e| {
1413 c.fetch_add(1, Ordering::Relaxed);
1414 });
1415
1416 thread::sleep(Duration::from_millis(150));
1417 write_conf(&config_path, "key=value2\n");
1418 thread::sleep(Duration::from_millis(500));
1419
1420 assert!(
1421 counter.load(Ordering::Relaxed) >= 1,
1422 "handle.on_change handler never fired"
1423 );
1424
1425 handle.stop().unwrap();
1426 }
1427
1428 #[test]
1429 fn test_automatic_watching() {
1430 let temp_dir = TempDir::new().unwrap();
1431 let config_path = temp_dir.path().join("test.conf");
1432 write_conf(&config_path, "key=value1\n");
1433
1434 let counter = Arc::new(AtomicUsize::new(0));
1435 let hot = HotReloadConfig::from_file(&config_path)
1436 .unwrap()
1437 .with_poll_interval(Duration::from_millis(50))
1438 .with_debounce(Duration::from_millis(25));
1439
1440 let c = Arc::clone(&counter);
1441 let _sub = hot.on_change(move |event| {
1442 if matches!(event, ConfigChangeEvent::Reloaded { .. }) {
1443 c.fetch_add(1, Ordering::Relaxed);
1444 }
1445 });
1446
1447 let config_ref = hot.config();
1448 let handle = hot.start_watching();
1449
1450 thread::sleep(Duration::from_millis(100));
1451 write_conf(&config_path, "key=value2\n");
1452 thread::sleep(Duration::from_millis(500));
1453
1454 {
1455 let config_read = config_ref.read().unwrap();
1456 assert_eq!(
1457 config_read.get("key").unwrap().as_string().unwrap(),
1458 "value2"
1459 );
1460 }
1461 assert!(
1462 counter.load(Ordering::Relaxed) >= 1,
1463 "expected at least one Reloaded event"
1464 );
1465
1466 handle.stop().unwrap();
1467 }
1468}