1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
//! Configuration Hot-Reload Support
//!
//! Provides file watching and automatic reloading of configuration files
//! with validation and change notifications.
//!
//! # Features
//!
//! - File system watching with debouncing
//! - Automatic validation on reload
//! - Change callbacks for application updates
//! - Support for JSON, YAML, and TOML configs
//! - Thread-safe shared configuration state
//! - Graceful error handling (keeps old config on invalid changes)
//!
//! # Example
//!
//! ```rust,no_run
//! use mecha10_core::prelude::*;
//! use mecha10_core::config_watcher::ConfigWatcher;
//!
//! #[derive(Debug, Clone, Deserialize)]
//! struct MyConfig {
//! rate: f32,
//! enabled: bool,
//! }
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
//! // Create watcher with callback
//! let watcher = ConfigWatcher::new("config.yaml", |config: &MyConfig| {
//! println!("Config reloaded! Rate: {}", config.rate);
//! })?;
//!
//! // Get current config
//! let config = watcher.get();
//! println!("Initial rate: {}", config.rate);
//!
//! // Config automatically reloads when file changes
//! tokio::signal::ctrl_c().await?;
//! Ok(())
//! }
//! ```
use crate::{Mecha10Error, Result};
use anyhow::Context as _;
use notify::{Config, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher as NotifyWatcher};
use serde::de::DeserializeOwned;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;
use tokio::time::sleep;
use tracing::{debug, error, info, warn};
pub struct ConfigWatcher<T>
where
T: DeserializeOwned + Clone + Send + Sync + 'static,
{
config: Arc<RwLock<T>>,
path: PathBuf,
_watcher: RecommendedWatcher,
}
impl<T> ConfigWatcher<T>
where
T: DeserializeOwned + Clone + Send + Sync + 'static,
{
/// Create a new configuration watcher
///
/// # Arguments
///
/// * `path` - Path to configuration file
/// * `on_change` - Callback invoked when configuration changes
///
/// # Returns
///
/// A new `ConfigWatcher` instance
///
/// # Errors
///
/// Returns error if:
/// - File doesn't exist
/// - Initial configuration is invalid
/// - File watcher can't be created
///
/// # Example
///
/// ```rust,no_run
/// use mecha10_core::config_watcher::ConfigWatcher;
/// use mecha10_core::Result;
/// use serde::Deserialize;
///
/// #[derive(Debug, Clone, Deserialize)]
/// struct MyConfig {
/// rate: f32,
/// }
///
/// # fn main() -> Result<()> {
/// let watcher = ConfigWatcher::new("config.yaml", |config: &MyConfig| {
/// // Handle configuration change
/// println!("Config updated!");
/// })?;
/// # Ok(())
/// # }
/// ```
pub fn new<P, F>(path: P, on_change: F) -> Result<Self>
where
P: AsRef<Path>,
F: Fn(&T) + Send + Sync + 'static,
{
let path = path.as_ref().to_path_buf();
let initial_config = Self::load_config(&path)?;
let config = Arc::new(RwLock::new(initial_config));
let config_clone = Arc::clone(&config);
let path_clone = path.clone();
let on_change = Arc::new(on_change);
let (tx, mut rx) = tokio::sync::mpsc::channel(100);
let mut watcher = RecommendedWatcher::new(
move |res: notify::Result<Event>| {
if let Ok(event) = res {
if matches!(event.kind, EventKind::Modify(_) | EventKind::Create(_)) {
let _ = tx.blocking_send(event);
}
}
},
Config::default().with_poll_interval(Duration::from_millis(500)),
)
.map_err(|e| Mecha10Error::Configuration(format!("Failed to create file watcher: {}", e)))?;
watcher
.watch(&path, RecursiveMode::NonRecursive)
.map_err(|e| Mecha10Error::Configuration(format!("Failed to watch file {}: {}", path.display(), e)))?;
info!("Started watching config file: {}", path.display());
tokio::spawn(async move {
let mut last_reload = tokio::time::Instant::now();
while let Some(_event) = rx.recv().await {
if last_reload.elapsed() < Duration::from_secs(1) {
continue;
}
debug!("Config file changed, debouncing...");
sleep(Duration::from_millis(100)).await;
match Self::load_config(&path_clone) {
Ok(new_config) => {
info!("Successfully reloaded config from: {}", path_clone.display());
{
let mut config = config_clone.write().await;
*config = new_config.clone();
}
on_change(&new_config);
last_reload = tokio::time::Instant::now();
}
Err(e) => {
error!(
"Failed to reload config from {}: {}. Keeping old config.",
path_clone.display(),
e
);
warn!("Fix the configuration errors to apply changes.");
}
}
}
});
Ok(Self {
config,
path,
_watcher: watcher,
})
}
/// Get the current configuration
///
/// Returns a clone of the current configuration.
///
/// # Example
///
/// ```rust,no_run
/// use mecha10_core::config_watcher::ConfigWatcher;
/// use mecha10_core::Result;
/// use serde::Deserialize;
///
/// #[derive(Debug, Clone, Deserialize)]
/// struct MyConfig {
/// rate: f32,
/// }
///
/// # fn main() -> Result<()> {
/// let watcher = ConfigWatcher::new("config.yaml", |_config: &MyConfig| {})?;
/// let config = watcher.get();
/// println!("Current rate: {}", config.rate);
/// # Ok(())
/// # }
/// ```
pub fn get(&self) -> T {
let config = self.config.blocking_read();
config.clone()
}
/// Get the current configuration asynchronously
///
/// Returns a clone of the current configuration.
///
/// # Example
///
/// ```rust,no_run
/// use mecha10_core::config_watcher::ConfigWatcher;
/// use mecha10_core::Result;
/// use serde::Deserialize;
///
/// #[derive(Debug, Clone, Deserialize)]
/// struct MyConfig {
/// rate: f32,
/// }
///
/// # async fn example() -> Result<()> {
/// let watcher = ConfigWatcher::new("config.yaml", |_config: &MyConfig| {})?;
/// let config = watcher.get_async().await;
/// println!("Current rate: {}", config.rate);
/// # Ok(())
/// # }
/// ```
pub async fn get_async(&self) -> T {
let config = self.config.read().await;
config.clone()
}
/// Manually reload the configuration
///
/// Forces a reload of the configuration from disk.
///
/// # Returns
///
/// Ok(()) if reload succeeded, Err if loading or validation failed
///
/// # Example
///
/// ```rust,no_run
/// use mecha10_core::config_watcher::ConfigWatcher;
/// use mecha10_core::Result;
/// use serde::Deserialize;
///
/// #[derive(Debug, Clone, Deserialize)]
/// struct MyConfig {
/// rate: f32,
/// }
///
/// # async fn example() -> Result<()> {
/// let watcher = ConfigWatcher::new("config.yaml", |_config: &MyConfig| {})?;
/// watcher.reload().await?;
/// # Ok(())
/// # }
/// ```
pub async fn reload(&self) -> Result<()> {
let new_config = Self::load_config(&self.path)?;
let mut config = self.config.write().await;
*config = new_config;
info!("Manually reloaded config from: {}", self.path.display());
Ok(())
}
/// Get the path to the configuration file
pub fn path(&self) -> &Path {
&self.path
}
fn load_config(path: &Path) -> Result<T> {
use crate::config::load_config;
load_config(path)
.with_context(|| format!("Failed to load configuration from {}", path.display()))
.map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))
}
}
pub struct ValidatedConfigWatcher<T>
where
T: DeserializeOwned + Clone + Send + Sync + crate::config::Validate + 'static,
{
inner: ConfigWatcher<T>,
}
impl<T> ValidatedConfigWatcher<T>
where
T: DeserializeOwned + Clone + Send + Sync + crate::config::Validate + 'static,
{
/// Create a new validated configuration watcher
///
/// # Arguments
///
/// * `path` - Path to configuration file
/// * `on_change` - Callback invoked when configuration changes
///
/// # Returns
///
/// A new `ValidatedConfigWatcher` instance
///
/// # Errors
///
/// Returns error if initial configuration is invalid
pub fn new<P, F>(path: P, on_change: F) -> Result<Self>
where
P: AsRef<Path>,
F: Fn(&T) + Send + Sync + 'static,
{
let inner = ConfigWatcher::new(path, move |config: &T| {
if let Err(e) = config.validate() {
error!("Configuration validation failed: {}", e);
warn!("Keeping previous configuration.");
return;
}
on_change(config);
})?;
Ok(Self { inner })
}
/// Get the current configuration
pub fn get(&self) -> T {
self.inner.get()
}
/// Get the current configuration asynchronously
pub async fn get_async(&self) -> T {
self.inner.get_async().await
}
/// Manually reload and validate the configuration
pub async fn reload(&self) -> Result<()> {
self.inner.reload().await?;
self.inner.get().validate()?;
Ok(())
}
/// Get the path to the configuration file
pub fn path(&self) -> &Path {
self.inner.path()
}
}