pub struct HotReloadConfig { /* private fields */ }Expand description
Hot-reloadable configuration container.
Construct with HotReloadConfig::from_file, then either drive
reloads manually with HotReloadConfig::reload or hand off to a
background watcher with HotReloadConfig::start_watching.
Every reload applies the same checks before the new configuration replaces the current one (since v1.4.0):
- the file must not change while it is read, and the watcher waits for its size and modification time to settle first;
- a file that holds no values does not replace a configuration that
does, unless
HotReloadConfig::allow_empty_reloadis set; - the
HotReloadConfig::with_validatorcheck, and the validation rules set on the current configuration (featurevalidation), must pass; - read-only mode, the defaults table and the validation rules carry over to the new configuration.
A refused reload keeps the current configuration and dispatches
ConfigChangeEvent::ReloadFailed. Handlers run after the new
configuration is in place and the lock is released, so a handler may
read the configuration.
Writers should still replace the file atomically (write a temporary
file, then rename it over the target, as Config::save_to_file does):
a writer that pauses for longer than the debounce window in the middle
of an in-place rewrite can leave a partial file that parses.
Configurable knobs (all consuming-builder style, intended for fluent construction):
HotReloadConfig::on_change— register a change handler (v1.0.0+; the recommended notification API).HotReloadConfig::with_change_notifications— receiveConfigChangeEvents on anmpscchannel (deprecated since v1.0.0; kept as a bridge for backwards compatibility).HotReloadConfig::with_debounce— adjust the debounce window (default 100 ms).HotReloadConfig::with_poll_interval— set the polling interval. Used directly when thehot-reloadfeature is off; used as the watchdog interval when the feature is on.HotReloadConfig::with_polling_fallback— opt into a parallel polling watchdog in addition to the event-driven watcher, for environments where the kernel watcher is known unreliable.HotReloadConfig::with_validatorandHotReloadConfig::allow_empty_reload: reload checks (v1.4.0+).
Implementations§
Source§impl HotReloadConfig
impl HotReloadConfig
Sourcepub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self>
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self>
Create a new hot-reloadable configuration from a file.
Loads with the default LoadOptions, as Config::from_file
does.
§Errors
Returns an error if the file cannot be read, parsed, or stat’d for its modification time.
Sourcepub fn from_file_strict<P: AsRef<Path>>(path: P) -> Result<Self>
pub fn from_file_strict<P: AsRef<Path>>(path: P) -> Result<Self>
Create a hot-reloadable configuration that reads NOML strictly
(no include, no env()), on the first load and on every reload.
Since v1.4.0.
§Errors
Sourcepub fn from_file_with<P: AsRef<Path>>(
path: P,
options: LoadOptions,
) -> Result<Self>
pub fn from_file_with<P: AsRef<Path>>( path: P, options: LoadOptions, ) -> Result<Self>
Create a hot-reloadable configuration that loads the file with
options, on the first load and on every reload.
Since v1.4.0.
§Errors
Sourcepub fn with_poll_interval(self, interval: Duration) -> Self
pub fn with_poll_interval(self, interval: Duration) -> Self
Set the polling interval for file change detection.
When the hot-reload feature is enabled (the default in v0.9.6+),
the primary watcher is event-driven and this interval is only
consulted as the watchdog cadence if with_polling_fallback
has been called.
When the hot-reload feature is disabled, this is the actual
polling cadence of the background thread.
Intervals below 10 ms are raised to 10 ms (since v1.4.0; a zero interval used to spin a core).
Sourcepub fn with_debounce(self, debounce: Duration) -> Self
pub fn with_debounce(self, debounce: Duration) -> Self
Override the debounce window applied to clustered file-change events.
Editors that save via “write-to-tmp + atomic-rename” generate multiple kernel events for a single user save. The debounce collapses any burst within this window to a single reload. Default: 100 ms.
Sourcepub fn with_polling_fallback(self) -> Self
pub fn with_polling_fallback(self) -> Self
Opt into running a polling watchdog in addition to the event-driven watcher.
Network filesystems (SMB, NFS), some container overlay
filesystems, and a handful of edge-case kernel configurations
drop or delay events that notify would normally surface.
Enabling the polling fallback re-derives changes from periodic
stat(2) calls on the watched path, at the
HotReloadConfig::with_poll_interval cadence.
Has no effect (and costs nothing) when the hot-reload Cargo
feature is disabled — the watcher is already polling in that
configuration.
Sourcepub fn allow_empty_reload(self) -> Self
pub fn allow_empty_reload(self) -> Self
Let a reload whose file holds no values replace a configuration that has values.
Off by default (since v1.4.0): a file that is truncated and then rewritten in place is empty for a moment, and reading it then would swap in an empty configuration, so every read would fall back to its default.
Sourcepub fn with_validator<F>(self, validator: F) -> Self
pub fn with_validator<F>(self, validator: F) -> Self
Check every reloaded configuration before it goes live.
The check runs on the newly loaded configuration. When it returns
an error, the current configuration is kept and
ConfigChangeEvent::ReloadFailed carries the error’s text. It
does not run on the first load.
Since v1.4.0.
§Example
use config_lib::hot_reload::HotReloadConfig;
use config_lib::Error;
let hot = HotReloadConfig::from_file("app.conf")?.with_validator(|config| {
if config.contains_key("server.port") {
Ok(())
} else {
Err(Error::validation("server.port is required"))
}
});
let _handle = hot.start_watching();Sourcepub fn on_change<F>(&self, handler: F) -> Subscription
pub fn on_change<F>(&self, handler: F) -> Subscription
Register a change handler. Recommended notification API (v1.0.0+).
The handler is invoked inline on the reloader thread every
time a ConfigChangeEvent is produced — typically a few
milliseconds after the underlying filesystem event, plus the
debounce window. Dispatch overhead is a single atomic pointer
load (~5 ns) plus the handler’s own cost; multiple handlers
are called in registration order with no per-handler channel
allocation.
Handlers run with no lock held: on
ConfigChangeEvent::Reloaded the new configuration is already in
place, and the handler may read it through
HotReloadConfig::config. (Before v1.4.0 the background watcher
dispatched while it still held the write lock, so a handler that
read the configuration deadlocked every reader.)
Returns a Subscription whose Drop unregisters the
handler. Bind to a let _sub = ... if you want the handler
to live for the surrounding scope, or call
Subscription::forget to detach the drop hook.
§Panics
If the handler itself panics, the panic is caught via
catch_unwind and discarded — other handlers continue to
receive the event and the reloader thread is not torn down.
Handler authors should avoid panicking, but a buggy handler
won’t take down the whole library.
§Example
use config_lib::hot_reload::{HotReloadConfig, ConfigChangeEvent};
let hot = HotReloadConfig::from_file("app.conf")?;
let shared = hot.config();
let _sub = hot.on_change(move |event: &ConfigChangeEvent| {
if let ConfigChangeEvent::Reloaded { .. } = event {
let port: u16 = shared.read().map(|c| c.get_or("port", 8080)).unwrap_or(8080);
println!("port is now {port}");
}
});
let _handle = hot.start_watching();
// ... `_sub` and `_handle` are alive for the rest of the scopeSourcepub fn with_change_notifications(self) -> (Self, Receiver<ConfigChangeEvent>)
👎Deprecated since 1.0.0: use on_change for lock-free dispatch; this method continues to work but pays an mpsc allocation per event
pub fn with_change_notifications(self) -> (Self, Receiver<ConfigChangeEvent>)
use on_change for lock-free dispatch; this method continues to work but pays an mpsc allocation per event
Enable channel-based change notifications. Deprecated since
v1.0.0 — prefer HotReloadConfig::on_change.
Internally bridges to the same lock-free handler list as
on_change by registering a closure that forwards events
to an mpsc::Sender. The bridge subscription is held by
self so the channel keeps receiving events for the
lifetime of the watcher.
The bridge pays one extra mpsc::Sender::send per event
(~100–200 ns) on top of the lock-free dispatch cost — the
inverse of why on_change exists. Existing code using
Receiver<ConfigChangeEvent> continues to work unchanged.
Sourcepub fn config(&self) -> Arc<RwLock<Config>> ⓘ
pub fn config(&self) -> Arc<RwLock<Config>> ⓘ
Get a thread-safe reference to the current configuration.
Sourcepub fn snapshot(&self) -> Result<Config>
pub fn snapshot(&self) -> Result<Config>
Get a freshly-reparsed snapshot of the configuration file as it exists on disk right now.
This is distinct from reading the current Arc<RwLock<Config>>
— it bypasses the watcher and re-reads the file. Useful for
“what would I see if I reloaded now” inspection.
§Errors
Returns an error if the file cannot be read or parsed.
Sourcepub fn reload(&mut self) -> Result<bool>
pub fn reload(&mut self) -> Result<bool>
Manually trigger a reload check.
Re-stats the file, and re-parses it if its modification time is
newer or its size differs from the last load. Dispatches a
ConfigChangeEvent::Reloaded or
ConfigChangeEvent::ReloadFailed notification through the
handler list, after the new configuration is in place.
The new configuration goes through the checks listed on
HotReloadConfig; when one refuses it, the current configuration
is kept and the error is returned.
Returns Ok(true) if a reload was performed, Ok(false) if
the file was unchanged since the last check.
§Errors
Returns an error if the file cannot be stat’d, read, or parsed, if it changed while it was read, or if a reload check refused it.
Sourcepub fn start_watching(self) -> HotReloadHandle
pub fn start_watching(self) -> HotReloadHandle
Start automatic hot reloading in a background thread.
With the hot-reload Cargo feature enabled (the default in
v0.9.6+), the background worker registers a
notify::RecommendedWatcher on the file’s parent directory
and reacts to kernel events. Otherwise it falls back to a
poll_interval-cadence polling thread (the v0.9.5 behavior).
If the event watcher cannot be started, or stops, the worker
dispatches ConfigChangeEvent::ReloadFailed and polls the file
instead (since v1.4.0; before, it stopped reloading).
Sourcepub fn last_modified(&self) -> SystemTime
pub fn last_modified(&self) -> SystemTime
Get the last modification time.