confers 0.4.1

Production-ready Rust configuration library with zero boilerplate
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! Platform-level file debouncer using notify-debouncer-full.
//!
//! This module provides file system watching with platform-level debouncing,
//! wrapping the notify-debouncer-full crate for integration with confers.

#[cfg(feature = "watch")]
use crate::error::{ConfigError, ConfigResult};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;

/// Default recv timeout in milliseconds for polling the debouncer.
const DEFAULT_RECV_TIMEOUT_MS: u64 = 50;

/// File system watcher with debouncing.
///
/// This watcher monitors file changes and emits debounced events
/// to avoid triggering multiple reloads for a single file modification.
pub struct FsWatcher {
    /// Path being watched
    watch_path: Arc<PathBuf>,
    /// Receiver for debounced file events
    rx: Option<mpsc::Receiver<PathBuf>>,
    /// Sender for closing the channel
    tx: Option<mpsc::Sender<PathBuf>>,
    /// Handle to the watcher thread
    watcher_thread: Option<std::thread::JoinHandle<()>>,
    /// Running flag
    running: Arc<std::sync::atomic::AtomicBool>,
}

impl Drop for FsWatcher {
    fn drop(&mut self) {
        self.stop();
    }
}

impl FsWatcher {
    /// Create a new file system watcher.
    ///
    /// # Arguments
    ///
    /// * `path` - The file or directory to watch
    /// * `debounce_ms` - Debounce duration in milliseconds (default: 200ms)
    ///
    /// # Example
    ///
    /// ```rust
    /// async fn example() -> Result<(), Box<dyn std::error::Error>> {
    ///     use confers::watcher::FsWatcher;
    ///
    ///     let mut watcher = FsWatcher::new("./config.toml", 200).await?;
    ///
    ///     // Wait for file changes
    ///     while let Some(path) = watcher.recv().await {
    ///         println!("File changed: {:?}", path);
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn new(path: impl AsRef<Path>, debounce_ms: u64) -> ConfigResult<Self> {
        Self::with_recv_timeout(path, debounce_ms, DEFAULT_RECV_TIMEOUT_MS).await
    }

    /// Create a new file system watcher with custom recv timeout.
    ///
    /// # Arguments
    ///
    /// * `path` - The file or directory to watch
    /// * `debounce_ms` - Debounce duration in milliseconds
    /// * `recv_timeout_ms` - Recv timeout for polling debouncer events (default: 50ms)
    ///
    /// Lower values mean faster response but higher CPU usage.
    /// Higher values mean slower response but lower CPU usage.
    pub async fn with_recv_timeout(
        path: impl AsRef<Path>,
        debounce_ms: u64,
        recv_timeout_ms: u64,
    ) -> ConfigResult<Self> {
        let watch_path = Arc::new(path.as_ref().to_path_buf());

        // Verify the path exists
        if !watch_path.exists() {
            return Err(ConfigError::FileNotFound {
                filename: watch_path.as_ref().clone(),
                source: None,
            });
        }

        let (tx, rx) = mpsc::channel(100);
        let running = Arc::new(std::sync::atomic::AtomicBool::new(true));
        let path_clone = Arc::clone(&watch_path);
        let running_clone = Arc::clone(&running);
        let tx_for_thread = tx.clone();

        // Spawn the watcher in a dedicated thread (not tokio task)
        let watcher_thread = std::thread::spawn(move || {
            Self::run_watcher(
                &path_clone,
                debounce_ms,
                recv_timeout_ms,
                tx_for_thread,
                running_clone,
            );
        });

        Ok(Self {
            watch_path,
            rx: Some(rx),
            tx: Some(tx),
            watcher_thread: Some(watcher_thread),
            running,
        })
    }

    /// Receive the next file change event.
    ///
    /// Returns `Some(path)` when a file change is detected, `None` if the watcher is stopped.
    pub async fn recv(&mut self) -> Option<PathBuf> {
        if let Some(ref mut rx) = self.rx {
            rx.recv().await
        } else {
            None
        }
    }

    /// Get the path being watched.
    pub fn watch_path(&self) -> &Path {
        &self.watch_path
    }

    /// Stop the watcher.
    pub fn stop(&mut self) {
        if !self.running.load(std::sync::atomic::Ordering::SeqCst) {
            return;
        }

        self.running
            .store(false, std::sync::atomic::Ordering::SeqCst);

        // Drop the sender to close the channel, which will cause recv() to return None
        self.tx.take();

        // Wait for the watcher thread to finish
        if let Some(handle) = self.watcher_thread.take() {
            let _ = handle.join();
        }

        // Close the receiver
        self.rx.take();
    }

    /// Check if the watcher is running.
    pub fn is_running(&self) -> bool {
        self.running.load(std::sync::atomic::Ordering::SeqCst)
    }

    /// Internal watcher function that runs in a dedicated thread.
    fn run_watcher(
        path: &Path,
        debounce_ms: u64,
        recv_timeout_ms: u64,
        tx: mpsc::Sender<PathBuf>,
        running: Arc<std::sync::atomic::AtomicBool>,
    ) {
        use notify_debouncer_full::{
            new_debouncer, notify::EventKind, notify::RecursiveMode, DebounceEventResult,
        };

        // Create a bridge channel for the debouncer callback
        let (bridge_tx, bridge_rx) = std::sync::mpsc::channel::<DebounceEventResult>();

        // Create the debouncer
        let mut debouncer =
            match new_debouncer(Duration::from_millis(debounce_ms), None, move |result| {
                let _ = bridge_tx.send(result);
            }) {
                Ok(d) => d,
                Err(_e) => {
                    // Failed to create debouncer - return silently
                    return;
                }
            };

        // Start watching
        if let Err(_e) = debouncer.watch(path, RecursiveMode::Recursive) {
            // Failed to watch - return silently
            return;
        }

        let recv_timeout = Duration::from_millis(recv_timeout_ms);

        // Process events
        while running.load(std::sync::atomic::Ordering::SeqCst) {
            match bridge_rx.recv_timeout(recv_timeout) {
                Ok(result) => {
                    if let Ok(events) = result {
                        for event in events {
                            match event.kind {
                                EventKind::Create(_)
                                | EventKind::Modify(_)
                                | EventKind::Remove(_) => {
                                    // Forward all file-system events. The is_file() check
                                    // was removed because it drops deletion events (the
                                    // path no longer exists) and can race with creation
                                    // events on some platforms. Callers decide what to
                                    // do with the event.
                                    for event_path in &event.paths {
                                        match tx.try_send(event_path.clone()) {
                                            Ok(_) => {}
                                            Err(mpsc::error::TrySendError::Full(_)) => {}
                                            Err(mpsc::error::TrySendError::Closed(_)) => {
                                                running.store(
                                                    false,
                                                    std::sync::atomic::Ordering::SeqCst,
                                                );
                                                return;
                                            }
                                        }
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                }
                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                    // Bridge channel disconnected - exit gracefully
                    break;
                }
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                    // Continue
                }
            }
        }

        // Explicitly stop the debouncer
        drop(debouncer);
    }
}

/// Multi-file watcher that watches multiple paths.
///
/// This is useful when watching multiple configuration files.
pub struct MultiFsWatcher {
    /// Paths being watched
    watch_paths: Arc<HashSet<PathBuf>>,
    /// Receiver for debounced file events
    rx: Option<mpsc::Receiver<PathBuf>>,
    /// Sender for closing the channel
    tx: Option<mpsc::Sender<PathBuf>>,
    /// Handle to the watcher thread
    watcher_thread: Option<std::thread::JoinHandle<()>>,
    /// Running flag
    running: Arc<std::sync::atomic::AtomicBool>,
}

impl Drop for MultiFsWatcher {
    fn drop(&mut self) {
        self.stop();
    }
}

impl MultiFsWatcher {
    /// Create a new multi-file system watcher.
    ///
    /// # Arguments
    ///
    /// * `paths` - Iterator of files or directories to watch
    /// * `debounce_ms` - Debounce duration in milliseconds (default: 200ms)
    ///
    /// # Example
    ///
    /// ```rust
    /// async fn example() -> Result<(), Box<dyn std::error::Error>> {
    ///     use confers::watcher::MultiFsWatcher;
    ///
    ///     let paths = vec!["./config.toml", "./config.prod.toml"];
    ///     let mut watcher = MultiFsWatcher::new(paths, 200).await?;
    ///
    ///     while let Some(path) = watcher.recv().await {
    ///         println!("File changed: {:?}", path);
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn new(
        paths: impl IntoIterator<Item = impl AsRef<Path>>,
        debounce_ms: u64,
    ) -> ConfigResult<Self> {
        Self::with_recv_timeout(paths, debounce_ms, DEFAULT_RECV_TIMEOUT_MS).await
    }

    /// Create a new multi-file system watcher with custom recv timeout.
    ///
    /// # Arguments
    ///
    /// * `paths` - Iterator of files or directories to watch
    /// * `debounce_ms` - Debounce duration in milliseconds
    /// * `recv_timeout_ms` - Recv timeout for polling debouncer events (default: 50ms)
    ///
    /// Lower values mean faster response but higher CPU usage.
    /// Higher values mean slower response but lower CPU usage.
    pub async fn with_recv_timeout(
        paths: impl IntoIterator<Item = impl AsRef<Path>>,
        debounce_ms: u64,
        recv_timeout_ms: u64,
    ) -> ConfigResult<Self> {
        let watch_paths: HashSet<PathBuf> = paths
            .into_iter()
            .map(|p| p.as_ref().to_path_buf())
            .collect();

        if watch_paths.is_empty() {
            return Err(ConfigError::InvalidValue {
                key: "paths".to_string(),
                expected_type: "non-empty path list".to_string(),
                message: "At least one path must be provided".to_string(),
            });
        }

        // Verify all paths exist
        for path in &watch_paths {
            if !path.exists() {
                return Err(ConfigError::FileNotFound {
                    filename: path.clone(),
                    source: None,
                });
            }
        }

        let (tx, rx) = mpsc::channel(100);
        let running = Arc::new(std::sync::atomic::AtomicBool::new(true));
        let paths_arc = Arc::new(watch_paths);
        let running_clone = Arc::clone(&running);
        let paths_for_thread = Arc::clone(&paths_arc);
        let tx_for_thread = tx.clone();

        // Spawn the watcher in a dedicated thread (not tokio task)
        let watcher_thread = std::thread::spawn(move || {
            Self::run_watcher(
                &paths_for_thread,
                debounce_ms,
                recv_timeout_ms,
                tx_for_thread,
                running_clone,
            );
        });

        Ok(Self {
            watch_paths: paths_arc,
            rx: Some(rx),
            tx: Some(tx),
            watcher_thread: Some(watcher_thread),
            running,
        })
    }

    /// Receive the next file change event.
    ///
    /// Returns `Some(path)` when a file change is detected, `None` if the watcher is stopped.
    pub async fn recv(&mut self) -> Option<PathBuf> {
        if let Some(ref mut rx) = self.rx {
            rx.recv().await
        } else {
            None
        }
    }

    /// Get all paths being watched.
    pub fn watch_paths(&self) -> &HashSet<PathBuf> {
        &self.watch_paths
    }

    /// Stop the watcher.
    pub fn stop(&mut self) {
        if !self.running.load(std::sync::atomic::Ordering::SeqCst) {
            return;
        }

        self.running
            .store(false, std::sync::atomic::Ordering::SeqCst);

        // Drop the sender to close the channel, which will cause recv() to return None
        self.tx.take();

        // Wait for the watcher thread to finish
        if let Some(handle) = self.watcher_thread.take() {
            let _ = handle.join();
        }

        // Close the receiver
        self.rx.take();
    }

    /// Check if the watcher is running.
    pub fn is_running(&self) -> bool {
        self.running.load(std::sync::atomic::Ordering::SeqCst)
    }

    /// Internal watcher function that runs in a dedicated thread.
    fn run_watcher(
        paths: &HashSet<PathBuf>,
        debounce_ms: u64,
        recv_timeout_ms: u64,
        tx: mpsc::Sender<PathBuf>,
        running: Arc<std::sync::atomic::AtomicBool>,
    ) {
        use notify_debouncer_full::{
            new_debouncer, notify::EventKind, notify::RecursiveMode, DebounceEventResult,
        };

        // Create a bridge channel for the debouncer callback
        let (bridge_tx, bridge_rx) = std::sync::mpsc::channel::<DebounceEventResult>();

        // Create the debouncer
        let mut debouncer =
            match new_debouncer(Duration::from_millis(debounce_ms), None, move |result| {
                let _ = bridge_tx.send(result);
            }) {
                Ok(d) => d,
                Err(_e) => {
                    // Failed to create debouncer - return silently
                    return;
                }
            };

        // Watch all paths
        for path in paths {
            if path.is_dir() {
                let _ = debouncer.watch(path.as_path(), RecursiveMode::Recursive);
            } else if path.is_file() {
                if let Some(parent) = path.parent() {
                    let _ = debouncer.watch(parent, RecursiveMode::Recursive);
                }
            }
        }

        let recv_timeout = Duration::from_millis(recv_timeout_ms);

        // Process events
        while running.load(std::sync::atomic::Ordering::SeqCst) {
            match bridge_rx.recv_timeout(recv_timeout) {
                Ok(result) => {
                    if let Ok(events) = result {
                        for event in events {
                            match event.kind {
                                EventKind::Create(_) | EventKind::Modify(_) => {
                                    for event_path in &event.paths {
                                        if event_path.is_file() && paths.contains(event_path) {
                                            match tx.try_send(event_path.clone()) {
                                                Ok(_) => {}
                                                Err(mpsc::error::TrySendError::Full(_)) => {}
                                                Err(mpsc::error::TrySendError::Closed(_)) => {
                                                    running.store(
                                                        false,
                                                        std::sync::atomic::Ordering::SeqCst,
                                                    );
                                                    return;
                                                }
                                            }
                                        }
                                    }
                                }
                                EventKind::Remove(_) => {
                                    // For Remove, the path no longer exists so
                                    // is_file() returns false. Check only
                                    // paths.contains() to forward deletions.
                                    for event_path in &event.paths {
                                        if paths.contains(event_path) {
                                            match tx.try_send(event_path.clone()) {
                                                Ok(_) => {}
                                                Err(mpsc::error::TrySendError::Full(_)) => {}
                                                Err(mpsc::error::TrySendError::Closed(_)) => {
                                                    running.store(
                                                        false,
                                                        std::sync::atomic::Ordering::SeqCst,
                                                    );
                                                    return;
                                                }
                                            }
                                        }
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                }
                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                    // Bridge channel disconnected - exit gracefully
                    break;
                }
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                    // Continue
                }
            }
        }

        // Explicitly stop the debouncer
        drop(debouncer);
    }
}