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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Configuration Hot Reloading System
//!
//! Enterprise-grade hot reloading with:
//! - File watching for automatic updates
//! - Arc swapping for zero-downtime updates
//! - Change notifications and callbacks
//! - Thread-safe concurrent access
//! - Graceful error handling and fallback
use crate::config::Config;
use crate::error::{Error, Result};
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, RwLock};
use std::thread;
use std::time::{Duration, SystemTime};
/// Configuration change event types
#[derive(Debug, Clone)]
pub enum ConfigChangeEvent {
/// Configuration successfully reloaded
Reloaded {
/// Path to the configuration file that was reloaded
path: PathBuf,
/// Timestamp when the reload completed
timestamp: SystemTime,
},
/// Configuration reload failed
ReloadFailed {
/// Path to the configuration file that failed to reload
path: PathBuf,
/// Error message describing what went wrong
error: String,
/// Timestamp when the error occurred
timestamp: SystemTime,
},
/// Configuration file was modified
FileModified {
/// Path to the configuration file that was modified
path: PathBuf,
/// Timestamp when the modification was detected
timestamp: SystemTime,
},
/// Configuration file was deleted
FileDeleted {
/// Path to the configuration file that was deleted
path: PathBuf,
/// Timestamp when the deletion was detected
timestamp: SystemTime,
},
}
/// Hot-reloadable configuration container
pub struct HotReloadConfig {
/// Current configuration (thread-safe)
current: Arc<RwLock<Config>>,
/// File path being watched
file_path: PathBuf,
/// Last known modification time
last_modified: SystemTime,
/// Event sender for notifications
event_sender: Option<Sender<ConfigChangeEvent>>,
/// Polling interval for file changes
poll_interval: Duration,
}
impl HotReloadConfig {
/// Create a new hot-reloadable configuration from a file
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
let path = path.as_ref().to_path_buf();
let config = Config::from_file(&path)?;
let last_modified = std::fs::metadata(&path)
.map_err(|e| Error::io(path.display().to_string(), e))?
.modified()
.map_err(|e| Error::io(path.display().to_string(), e))?;
Ok(Self {
current: Arc::new(RwLock::new(config)),
file_path: path,
last_modified,
event_sender: None,
poll_interval: Duration::from_millis(1000), // Default 1 second polling
})
}
/// Set the polling interval for file change detection
pub fn with_poll_interval(mut self, interval: Duration) -> Self {
self.poll_interval = interval;
self
}
/// Enable change notifications
pub fn with_change_notifications(mut self) -> (Self, Receiver<ConfigChangeEvent>) {
let (sender, receiver) = mpsc::channel();
self.event_sender = Some(sender);
(self, receiver)
}
/// Get a thread-safe reference to the current configuration
pub fn config(&self) -> Arc<RwLock<Config>> {
Arc::clone(&self.current)
}
/// Get a read-only snapshot of the current configuration
pub fn snapshot(&self) -> Result<Config> {
let _config = self
.current
.read()
.map_err(|_| Error::concurrency("Failed to acquire read lock".to_string()))?;
// Create a deep copy of the config
// Since Config doesn't implement Clone, we'll serialize and deserialize
let _content = std::fs::read_to_string(&self.file_path)
.map_err(|e| Error::io(self.file_path.display().to_string(), e))?;
Config::from_file(&self.file_path)
}
/// Manually trigger a reload
pub fn reload(&mut self) -> Result<bool> {
let metadata = std::fs::metadata(&self.file_path)
.map_err(|e| Error::io(self.file_path.display().to_string(), e))?;
let modified = metadata
.modified()
.map_err(|e| Error::io(self.file_path.display().to_string(), e))?;
if modified <= self.last_modified {
return Ok(false); // No changes
}
match Config::from_file(&self.file_path) {
Ok(new_config) => {
// Atomic swap of configuration
{
let mut config = self.current.write().map_err(|_| {
Error::concurrency("Failed to acquire write lock".to_string())
})?;
*config = new_config;
}
self.last_modified = modified;
// Send notification if enabled
if let Some(ref sender) = self.event_sender {
let _ = sender.send(ConfigChangeEvent::Reloaded {
path: self.file_path.clone(),
timestamp: SystemTime::now(),
});
}
Ok(true)
}
Err(e) => {
// Send error notification if enabled
if let Some(ref sender) = self.event_sender {
let _ = sender.send(ConfigChangeEvent::ReloadFailed {
path: self.file_path.clone(),
error: e.to_string(),
timestamp: SystemTime::now(),
});
}
Err(e)
}
}
}
/// Start automatic hot reloading in a background thread
pub fn start_watching(self) -> HotReloadHandle {
let (stop_sender, stop_receiver) = mpsc::channel();
let config_clone = Arc::clone(&self.current);
let file_path = self.file_path.clone();
let event_sender = self.event_sender.clone();
let poll_interval = self.poll_interval;
let mut last_modified = self.last_modified;
let handle = thread::spawn(move || {
loop {
// Check for stop signal
if stop_receiver.try_recv().is_ok() {
break;
}
// Check for file changes
if let Ok(metadata) = std::fs::metadata(&file_path) {
if let Ok(modified) = metadata.modified() {
if modified > last_modified {
// File was modified, send notification
if let Some(ref sender) = event_sender {
let _ = sender.send(ConfigChangeEvent::FileModified {
path: file_path.clone(),
timestamp: SystemTime::now(),
});
}
// Attempt to reload
match Config::from_file(&file_path) {
Ok(new_config) => {
// Atomic swap
if let Ok(mut config) = config_clone.write() {
*config = new_config;
last_modified = modified;
// Send success notification
if let Some(ref sender) = event_sender {
let _ = sender.send(ConfigChangeEvent::Reloaded {
path: file_path.clone(),
timestamp: SystemTime::now(),
});
}
}
}
Err(e) => {
// Send error notification
if let Some(ref sender) = event_sender {
let _ = sender.send(ConfigChangeEvent::ReloadFailed {
path: file_path.clone(),
error: e.to_string(),
timestamp: SystemTime::now(),
});
}
}
}
}
}
}
thread::sleep(poll_interval);
}
});
HotReloadHandle {
handle: Some(handle),
stop_sender,
}
}
/// Get the file path being watched
pub fn file_path(&self) -> &Path {
&self.file_path
}
/// Get the last modification time
pub fn last_modified(&self) -> SystemTime {
self.last_modified
}
}
/// Handle for controlling hot reload background thread
pub struct HotReloadHandle {
handle: Option<thread::JoinHandle<()>>,
stop_sender: Sender<()>,
}
impl HotReloadHandle {
/// Stop the background watching thread
pub fn stop(mut self) -> Result<()> {
if self.stop_sender.send(()).is_err() {
return Err(Error::concurrency("Failed to send stop signal".to_string()));
}
if let Some(handle) = self.handle.take() {
handle
.join()
.map_err(|_| Error::concurrency("Failed to join background thread".to_string()))?;
}
Ok(())
}
}
impl Drop for HotReloadHandle {
fn drop(&mut self) {
let _ = self.stop_sender.send(());
if let Some(handle) = self.handle.take() {
let _ = handle.join();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use std::io::Write;
use tempfile::TempDir;
#[test]
fn test_hot_reload_basic() {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("test.conf");
// Create initial config file
let mut file = File::create(&config_path).unwrap();
writeln!(file, "key=value1").unwrap();
file.flush().unwrap();
drop(file);
// Create hot reload config
let mut hot_config = HotReloadConfig::from_file(&config_path).unwrap();
// Read initial value
{
let config = hot_config.config();
let config_read = config.read().unwrap();
assert_eq!(
config_read.get("key").unwrap().as_string().unwrap(),
"value1"
);
}
// Wait a bit to ensure different modification time
thread::sleep(Duration::from_millis(10));
// Update config file
let mut file = File::create(&config_path).unwrap();
writeln!(file, "key=value2").unwrap();
file.flush().unwrap();
drop(file);
// Manual reload
let reloaded = hot_config.reload().unwrap();
assert!(reloaded);
// Verify new value
{
let config = hot_config.config();
let config_read = config.read().unwrap();
assert_eq!(
config_read.get("key").unwrap().as_string().unwrap(),
"value2"
);
}
}
#[test]
fn test_hot_reload_notifications() {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("test.conf");
// Create initial config file
let mut file = File::create(&config_path).unwrap();
writeln!(file, "key=value1").unwrap();
file.flush().unwrap();
drop(file);
// Create hot reload config with notifications
let (mut hot_config, receiver) = HotReloadConfig::from_file(&config_path)
.unwrap()
.with_change_notifications();
// Wait a bit
thread::sleep(Duration::from_millis(10));
// Update config file
let mut file = File::create(&config_path).unwrap();
writeln!(file, "key=value2").unwrap();
file.flush().unwrap();
drop(file);
// Manual reload should trigger notification
hot_config.reload().unwrap();
// Check for notification
let event = receiver.try_recv().unwrap();
match event {
ConfigChangeEvent::Reloaded { path, .. } => {
assert_eq!(path, config_path);
}
_ => panic!("Expected Reloaded event"),
}
}
#[test]
fn test_automatic_watching() {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("test.conf");
// Create initial config file
let mut file = File::create(&config_path).unwrap();
writeln!(file, "key=value1").unwrap();
file.flush().unwrap();
drop(file);
// Create hot reload config with fast polling
let (hot_config, receiver) = HotReloadConfig::from_file(&config_path)
.unwrap()
.with_poll_interval(Duration::from_millis(50))
.with_change_notifications();
let config_ref = hot_config.config();
let handle = hot_config.start_watching();
// Wait a bit
thread::sleep(Duration::from_millis(100));
// Update config file
let mut file = File::create(&config_path).unwrap();
writeln!(file, "key=value2").unwrap();
file.flush().unwrap();
drop(file);
// Wait for automatic reload
thread::sleep(Duration::from_millis(200));
// Check that config was updated
{
let config_read = config_ref.read().unwrap();
assert_eq!(
config_read.get("key").unwrap().as_string().unwrap(),
"value2"
);
}
// Check for notifications
let mut received_events = Vec::new();
while let Ok(event) = receiver.try_recv() {
received_events.push(event);
}
assert!(!received_events.is_empty());
// Should have received at least a Reloaded event
let has_reloaded = received_events
.iter()
.any(|event| matches!(event, ConfigChangeEvent::Reloaded { .. }));
assert!(has_reloaded);
// Stop watching
handle.stop().unwrap();
}
}