spicex 0.1.1

A complete configuration solution for Rust applications, inspired by Viper
Documentation
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
//! File system watching utilities for configuration files.

use crate::error::{ConfigError, ConfigResult};
use notify::{Event, RecommendedWatcher, RecursiveMode, Watcher};
use std::path::{Path, PathBuf};
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
use std::time::Duration;

/// Type alias for configuration change callback functions.
pub type ConfigChangeCallback = Box<dyn Fn() + Send + Sync>;

/// Manages file system watching for configuration files.
pub struct FileWatcher {
    _watcher: RecommendedWatcher,
    receiver: mpsc::Receiver<notify::Result<Event>>,
    watched_files: Vec<PathBuf>,
    callbacks: Arc<Mutex<Vec<ConfigChangeCallback>>>,
    is_watching: bool,
}

impl FileWatcher {
    /// Creates a new file watcher for the specified path.
    pub fn new<P: AsRef<Path>>(path: P) -> ConfigResult<Self> {
        let (sender, receiver) = mpsc::channel();

        let mut watcher = notify::recommended_watcher(sender)
            .map_err(|e| ConfigError::FileWatch(e.to_string()))?;

        let path_buf = path.as_ref().to_path_buf();
        watcher
            .watch(&path_buf, RecursiveMode::NonRecursive)
            .map_err(|e| ConfigError::FileWatch(e.to_string()))?;

        Ok(Self {
            _watcher: watcher,
            receiver,
            watched_files: vec![path_buf],
            callbacks: Arc::new(Mutex::new(Vec::new())),
            is_watching: false,
        })
    }

    /// Creates a new file watcher without watching any files initially.
    pub fn new_empty() -> ConfigResult<Self> {
        let (sender, receiver) = mpsc::channel();

        let watcher = notify::recommended_watcher(sender)
            .map_err(|e| ConfigError::FileWatch(e.to_string()))?;

        Ok(Self {
            _watcher: watcher,
            receiver,
            watched_files: Vec::new(),
            callbacks: Arc::new(Mutex::new(Vec::new())),
            is_watching: false,
        })
    }

    /// Adds a file to be watched.
    pub fn watch_file<P: AsRef<Path>>(&mut self, path: P) -> ConfigResult<()> {
        let path_buf = path.as_ref().to_path_buf();

        // Only watch if the file exists
        if !path_buf.exists() {
            return Err(ConfigError::FileWatch(format!(
                "Cannot watch non-existent file: {}",
                path_buf.display()
            )));
        }

        self._watcher
            .watch(&path_buf, RecursiveMode::NonRecursive)
            .map_err(|e| ConfigError::FileWatch(e.to_string()))?;

        self.watched_files.push(path_buf);
        Ok(())
    }

    /// Removes a file from being watched.
    pub fn unwatch_file<P: AsRef<Path>>(&mut self, path: P) -> ConfigResult<()> {
        let path_buf = path.as_ref().to_path_buf();

        self._watcher
            .unwatch(&path_buf)
            .map_err(|e| ConfigError::FileWatch(e.to_string()))?;

        self.watched_files.retain(|p| p != &path_buf);
        Ok(())
    }

    /// Gets the list of currently watched files.
    pub fn watched_files(&self) -> &[PathBuf] {
        &self.watched_files
    }

    /// Registers a callback to be called when configuration changes are detected.
    pub fn on_config_change<F>(&self, callback: F) -> ConfigResult<()>
    where
        F: Fn() + Send + Sync + 'static,
    {
        let mut callbacks = self.callbacks.lock().map_err(|e| {
            ConfigError::FileWatch(format!("Failed to acquire callback lock: {e}"))
        })?;

        callbacks.push(Box::new(callback));
        Ok(())
    }

    /// Starts watching for file changes in a background thread.
    /// This method spawns a background thread that monitors for file changes
    /// and calls registered callbacks when changes are detected.
    pub fn start_watching(&mut self) -> ConfigResult<()> {
        if self.is_watching {
            return Ok(()); // Already watching
        }

        let callbacks = Arc::clone(&self.callbacks);
        let (_stop_sender, stop_receiver) = mpsc::channel::<()>();

        // We need to create a new receiver since we can't clone the existing one
        let (event_sender, event_receiver) = mpsc::channel();

        // Replace the watcher with a new one that uses our new sender
        let mut new_watcher = notify::recommended_watcher(event_sender)
            .map_err(|e| ConfigError::FileWatch(e.to_string()))?;

        // Re-watch all previously watched files
        for path in &self.watched_files {
            new_watcher
                .watch(path, RecursiveMode::NonRecursive)
                .map_err(|e| ConfigError::FileWatch(e.to_string()))?;
        }

        self._watcher = new_watcher;
        self.is_watching = true;

        // Spawn background thread for watching
        thread::spawn(move || {
            loop {
                // Check if we should stop
                if stop_receiver.try_recv().is_ok() {
                    break;
                }

                // Check for file system events
                match event_receiver.recv_timeout(Duration::from_millis(100)) {
                    Ok(Ok(_event)) => {
                        // File change detected, call all callbacks
                        if let Ok(callbacks_guard) = callbacks.lock() {
                            for callback in callbacks_guard.iter() {
                                callback();
                            }
                        }
                    }
                    Ok(Err(_)) => {
                        // Error in file watching, but continue
                        continue;
                    }
                    Err(mpsc::RecvTimeoutError::Timeout) => {
                        // No events, continue
                        continue;
                    }
                    Err(mpsc::RecvTimeoutError::Disconnected) => {
                        // Channel disconnected, stop watching
                        break;
                    }
                }
            }
        });

        Ok(())
    }

    /// Stops watching for file changes.
    pub fn stop_watching(&mut self) {
        self.is_watching = false;
        // Note: In a full implementation, we'd send a stop signal to the background thread
        // For now, the thread will detect disconnection and stop
    }

    /// Returns whether the watcher is currently active.
    pub fn is_watching(&self) -> bool {
        self.is_watching
    }

    /// Triggers all registered callbacks manually (for testing purposes).
    #[cfg(test)]
    pub fn trigger_callbacks_for_test(&self) {
        if let Ok(callbacks_guard) = self.callbacks.lock() {
            for callback in callbacks_guard.iter() {
                callback();
            }
        }
    }

    /// Checks for file system events with a timeout.
    /// This method is primarily for testing and manual polling.
    /// For automatic reloading, use start_watching() instead.
    pub fn check_for_changes(&self, timeout: Duration) -> ConfigResult<bool> {
        match self.receiver.recv_timeout(timeout) {
            Ok(Ok(_event)) => {
                // Call callbacks when changes are detected
                if let Ok(callbacks_guard) = self.callbacks.lock() {
                    for callback in callbacks_guard.iter() {
                        callback();
                    }
                }
                Ok(true)
            }
            Ok(Err(e)) => Err(ConfigError::FileWatch(e.to_string())),
            Err(mpsc::RecvTimeoutError::Timeout) => Ok(false),
            Err(mpsc::RecvTimeoutError::Disconnected) => {
                Err(ConfigError::FileWatch("Watcher disconnected".to_string()))
            }
        }
    }

    /// Blocks until a file change is detected.
    /// This method is primarily for testing and manual polling.
    /// For automatic reloading, use start_watching() instead.
    pub fn wait_for_change(&self) -> ConfigResult<()> {
        match self.receiver.recv() {
            Ok(Ok(_event)) => {
                // Call callbacks when changes are detected
                if let Ok(callbacks_guard) = self.callbacks.lock() {
                    for callback in callbacks_guard.iter() {
                        callback();
                    }
                }
                Ok(())
            }
            Ok(Err(e)) => Err(ConfigError::FileWatch(e.to_string())),
            Err(_) => Err(ConfigError::FileWatch("Watcher disconnected".to_string())),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::sync::{Arc, Mutex};
    use std::time::Duration;
    use tempfile::TempDir;

    #[test]
    fn test_file_watcher_creation() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.json");
        fs::write(&config_path, "{}").unwrap();

        let watcher = FileWatcher::new(&config_path);
        assert!(watcher.is_ok());

        let watcher = watcher.unwrap();
        assert_eq!(watcher.watched_files().len(), 1);
        assert_eq!(watcher.watched_files()[0], config_path);
    }

    #[test]
    fn test_empty_file_watcher() {
        let watcher = FileWatcher::new_empty();
        assert!(watcher.is_ok());

        let watcher = watcher.unwrap();
        assert_eq!(watcher.watched_files().len(), 0);
        assert!(!watcher.is_watching());
    }

    #[test]
    fn test_watch_multiple_files() {
        let temp_dir = TempDir::new().unwrap();
        let config1 = temp_dir.path().join("config1.json");
        let config2 = temp_dir.path().join("config2.yaml");

        fs::write(&config1, "{}").unwrap();
        fs::write(&config2, "key: value").unwrap();

        let mut watcher = FileWatcher::new_empty().unwrap();

        assert!(watcher.watch_file(&config1).is_ok());
        assert!(watcher.watch_file(&config2).is_ok());

        assert_eq!(watcher.watched_files().len(), 2);
    }

    #[test]
    fn test_watch_nonexistent_file() {
        let mut watcher = FileWatcher::new_empty().unwrap();
        let nonexistent = PathBuf::from("/nonexistent/file.json");

        let result = watcher.watch_file(&nonexistent);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Cannot watch non-existent file"));
    }

    #[test]
    fn test_callback_registration() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.json");
        fs::write(&config_path, "{}").unwrap();

        let watcher = FileWatcher::new(&config_path).unwrap();

        let callback_called = Arc::new(Mutex::new(false));
        let callback_called_clone = Arc::clone(&callback_called);

        let result = watcher.on_config_change(move || {
            *callback_called_clone.lock().unwrap() = true;
        });

        assert!(result.is_ok());
    }

    #[test]
    fn test_unwatch_file() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.json");
        fs::write(&config_path, "{}").unwrap();

        let mut watcher = FileWatcher::new(&config_path).unwrap();
        assert_eq!(watcher.watched_files().len(), 1);

        assert!(watcher.unwatch_file(&config_path).is_ok());
        assert_eq!(watcher.watched_files().len(), 0);
    }

    #[test]
    fn test_file_change_detection() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.json");
        fs::write(&config_path, r#"{"key": "value1"}"#).unwrap();

        let watcher = FileWatcher::new(&config_path).unwrap();

        // Modify the file
        std::thread::spawn({
            let config_path = config_path.clone();
            move || {
                std::thread::sleep(Duration::from_millis(50));
                fs::write(&config_path, r#"{"key": "value2"}"#).unwrap();
            }
        });

        // Check for changes with a reasonable timeout
        let result = watcher.check_for_changes(Duration::from_millis(200));
        assert!(result.is_ok());
        // Note: The actual change detection depends on the file system and timing
    }

    #[test]
    fn test_multiple_callbacks() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.json");
        fs::write(&config_path, "{}").unwrap();

        let watcher = FileWatcher::new(&config_path).unwrap();

        let callback1_called = Arc::new(Mutex::new(false));
        let callback2_called = Arc::new(Mutex::new(false));

        let callback1_called_clone = Arc::clone(&callback1_called);
        let callback2_called_clone = Arc::clone(&callback2_called);

        // Register multiple callbacks
        watcher
            .on_config_change(move || {
                *callback1_called_clone.lock().unwrap() = true;
            })
            .unwrap();

        watcher
            .on_config_change(move || {
                *callback2_called_clone.lock().unwrap() = true;
            })
            .unwrap();

        // Simulate a file change by calling callbacks directly
        // In a real scenario, this would be triggered by file system events
        if let Ok(callbacks_guard) = watcher.callbacks.lock() {
            for callback in callbacks_guard.iter() {
                callback();
            }
        }

        // Both callbacks should have been called
        assert!(*callback1_called.lock().unwrap());
        assert!(*callback2_called.lock().unwrap());
    }

    #[test]
    fn test_start_stop_watching() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.json");
        fs::write(&config_path, "{}").unwrap();

        let mut watcher = FileWatcher::new(&config_path).unwrap();
        assert!(!watcher.is_watching());

        // Start watching
        watcher.start_watching().unwrap();
        assert!(watcher.is_watching());

        // Stop watching
        watcher.stop_watching();
        assert!(!watcher.is_watching());
    }

    #[test]
    fn test_callback_error_handling() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.json");
        fs::write(&config_path, "{}").unwrap();

        let watcher = FileWatcher::new(&config_path).unwrap();

        // Register a callback that might panic (but shouldn't crash the system)
        let result = watcher.on_config_change(|| {
            // This callback doesn't panic, but tests the error handling path
        });

        assert!(result.is_ok());
    }
}