hyperi-rustlib 2.5.4

Opinionated Rust framework for high-throughput data pipelines at PB scale. Auto-wiring config, logging, metrics, tracing, health, and graceful shutdown — built from many years of production infrastructure experience.
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
// Project:   hyperi-rustlib
// File:      src/config/reloader.rs
// Purpose:   Universal config hot-reload with SIGHUP, periodic, and file polling
// Language:  Rust
//
// License:   FSL-1.1-ALv2
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Universal configuration reloader for DFE components.
//!
//! `ConfigReloader<T>` provides three reload triggers, any combination of
//! which can be enabled simultaneously:
//!
//! 1. **SIGHUP** (Unix only) — standard daemon reload signal
//! 2. **Periodic timer** — reload every N seconds
//! 3. **File polling** — detect config file changes via mtime comparison
//!
//! The reloader calls a user-supplied `reload_fn` to load config and a
//! `validate_fn` to validate before applying. On success it updates the
//! `SharedConfig<T>` which notifies all subscribers.
//!
//! ## Usage
//!
//! ```rust,no_run
//! use std::path::PathBuf;
//! use std::time::Duration;
//! use hyperi_rustlib::config::reloader::{ConfigReloader, ReloaderConfig};
//! use hyperi_rustlib::config::shared::SharedConfig;
//!
//! #[derive(Clone, Debug, Default)]
//! struct AppConfig {
//!     pub workers: usize,
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     let config = AppConfig { workers: 4 };
//!     let shared = SharedConfig::new(config);
//!
//!     let reloader_config = ReloaderConfig {
//!         config_path: Some(PathBuf::from("config.yaml")),
//!         poll_interval: Duration::from_secs(5),
//!         periodic_interval: Duration::ZERO,  // disabled
//!         debounce: Duration::from_millis(500),
//!         enable_sighup: true,
//!     };
//!
//!     let reloader = ConfigReloader::new(
//!         reloader_config,
//!         shared.clone(),
//!         || {
//!             // Your config loading logic here
//!             Ok(AppConfig { workers: 8 })
//!         },
//!         |cfg| {
//!             // Your validation logic here
//!             if cfg.workers == 0 {
//!                 return Err("workers must be > 0".into());
//!             }
//!             Ok(())
//!         },
//!     );
//!
//!     let _handle = reloader.start();
//!     // ... run your application ...
//! }
//! ```
//!
//! ## Migration from Component-Specific Implementations
//!
//! ### From dfe-loader's `ConfigWatcher` (file polling)
//!
//! ```text
//! // Before:
//! let watcher = ConfigWatcher::new(WatcherConfig {
//!     config_path, poll_interval, debounce, enabled: true,
//! }, shared)?;
//! let _handle = watcher.start();
//!
//! // After:
//! let reloader = ConfigReloader::new(
//!     ReloaderConfig {
//!         config_path: Some(config_path),
//!         poll_interval,
//!         debounce,
//!         enable_sighup: true,      // bonus: also reload on SIGHUP
//!         periodic_interval: Duration::ZERO,
//!     },
//!     shared,
//!     || Config::load(path),        // your reload function
//!     |c| c.validate(),             // your validate function
//! );
//! let _handle = reloader.start();
//! ```
//!
//! ### From dfe-receiver's `config_reload_task` (SIGHUP + periodic)
//!
//! ```text
//! // Before (inline in main.rs):
//! tokio::spawn(config_reload_task(state, reload_secs));
//!
//! // After:
//! let reloader = ConfigReloader::new(
//!     ReloaderConfig {
//!         periodic_interval: Duration::from_secs(reload_secs),
//!         enable_sighup: true,
//!         config_path: None,         // no file watching
//!         ..Default::default()
//!     },
//!     shared,
//!     || Config::load(path),
//!     |c| c.validate(),
//! );
//! let _handle = reloader.start();
//! ```
//!
//! ### From dfe-archiver (not yet wired)
//!
//! The archiver has `SharedConfig` and `reload_config()` ready but not
//! connected. Use `ConfigReloader` to complete the integration:
//!
//! ```text
//! let reloader = ConfigReloader::new(
//!     ReloaderConfig {
//!         config_path: config.config_path.as_ref().map(PathBuf::from),
//!         periodic_interval: Duration::from_secs(config.config_reload_secs),
//!         enable_sighup: true,
//!         ..Default::default()
//!     },
//!     shared,
//!     || load_config(config_path),
//!     |c| validate_config(c),
//! );
//! let _handle = reloader.start();
//! ```

use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};

use tokio::task::JoinHandle;
use tracing::{debug, error, info, warn};

use super::shared::SharedConfig;

/// Boxed error type for reload/validate callbacks.
type BoxError = Box<dyn std::error::Error + Send + Sync>;

/// Configuration for the reloader.
#[derive(Debug, Clone)]
pub struct ReloaderConfig {
    /// Path to config file to watch for changes (None = no file watching).
    pub config_path: Option<PathBuf>,

    /// File polling interval. Only used when `config_path` is Some.
    /// Default: 5 seconds.
    pub poll_interval: Duration,

    /// Periodic reload interval. Set to `Duration::ZERO` to disable.
    /// Default: disabled.
    pub periodic_interval: Duration,

    /// Minimum time between reloads (debounce).
    /// Default: 500ms.
    pub debounce: Duration,

    /// Enable SIGHUP reload trigger (Unix only, ignored on other platforms).
    /// Default: true.
    pub enable_sighup: bool,
}

impl Default for ReloaderConfig {
    fn default() -> Self {
        Self {
            config_path: None,
            poll_interval: Duration::from_secs(5),
            periodic_interval: Duration::ZERO,
            debounce: Duration::from_millis(500),
            enable_sighup: true,
        }
    }
}

/// Universal configuration reloader.
///
/// Supports three reload triggers (any combination):
/// - **SIGHUP** (Unix) — `enable_sighup: true`
/// - **Periodic timer** — `periodic_interval > 0`
/// - **File polling** — `config_path: Some(path)`
///
/// On each trigger, calls `reload_fn` to load new config, `validate_fn` to
/// validate, then updates the `SharedConfig<T>` if valid.
/// Callback invoked after a successful reload with the new config value.
type PostReloadHook<T> = Arc<dyn Fn(&T) + Send + Sync>;

pub struct ConfigReloader<T: Clone + Send + Sync + 'static> {
    config: ReloaderConfig,
    shared: SharedConfig<T>,
    reload_fn: Arc<dyn Fn() -> Result<T, BoxError> + Send + Sync>,
    validate_fn: Arc<dyn Fn(&T) -> Result<(), BoxError> + Send + Sync>,
    post_reload_hooks: Vec<PostReloadHook<T>>,
}

impl<T: Clone + Send + Sync + 'static> ConfigReloader<T> {
    /// Create a new config reloader.
    ///
    /// - `config`: Reload trigger configuration
    /// - `shared`: Shared config to update on successful reload
    /// - `reload_fn`: Called to load a fresh config (re-reads file + env)
    /// - `validate_fn`: Called to validate before applying (return Err to reject)
    pub fn new(
        config: ReloaderConfig,
        shared: SharedConfig<T>,
        reload_fn: impl Fn() -> Result<T, BoxError> + Send + Sync + 'static,
        validate_fn: impl Fn(&T) -> Result<(), BoxError> + Send + Sync + 'static,
    ) -> Self {
        Self {
            config,
            shared,
            reload_fn: Arc::new(reload_fn),
            validate_fn: Arc::new(validate_fn),
            post_reload_hooks: Vec::new(),
        }
    }

    /// Add a hook that runs after each successful reload.
    ///
    /// Use this to connect to the config registry:
    ///
    /// ```rust,no_run
    /// # use hyperi_rustlib::config::reloader::ConfigReloader;
    /// # use hyperi_rustlib::config::registry;
    /// // reloader.with_registry_update("my_app");
    /// ```
    #[must_use]
    pub fn with_post_reload_hook(mut self, hook: impl Fn(&T) + Send + Sync + 'static) -> Self {
        self.post_reload_hooks.push(Arc::new(hook));
        self
    }

    /// Connect to the config registry: after each successful reload,
    /// call `registry::update()` so listeners are notified and the
    /// registry reflects the new effective config.
    ///
    /// Requires `T: Serialize + Default`.
    #[must_use]
    pub fn with_registry_update(self, key: &str) -> Self
    where
        T: serde::Serialize + Default,
    {
        let key = key.to_string();
        self.with_post_reload_hook(move |config| {
            super::registry::update::<T>(&key, config);
        })
    }

    /// Start the reload loop in a background task.
    ///
    /// Returns a `JoinHandle` that can be used to abort the reloader.
    /// The task runs until cancelled or the process exits.
    pub fn start(self) -> JoinHandle<()> {
        let has_file = self.config.config_path.is_some();
        let has_periodic = self.config.periodic_interval > Duration::ZERO;
        let has_sighup = self.config.enable_sighup;

        info!(
            file_watch = has_file,
            periodic = has_periodic,
            sighup = has_sighup,
            "Config reloader started"
        );

        tokio::spawn(async move {
            self.run_loop().await;
        })
    }

    /// Main reload loop — waits for any trigger, then attempts reload.
    async fn run_loop(self) {
        #[cfg(feature = "shutdown")]
        let shutdown_token = crate::shutdown::token();

        // File polling state
        let mut last_modified: Option<SystemTime> =
            self.config.config_path.as_ref().and_then(|p| file_mtime(p));
        let mut last_reload = Instant::now();

        // Set up poll timer (for file watching)
        let mut poll_timer = self
            .config
            .config_path
            .as_ref()
            .map(|_| tokio::time::interval(self.config.poll_interval));

        // Set up periodic timer
        let mut periodic_timer = if self.config.periodic_interval > Duration::ZERO {
            Some(tokio::time::interval(self.config.periodic_interval))
        } else {
            None
        };

        // Set up SIGHUP handler
        #[cfg(unix)]
        let mut sighup = if self.config.enable_sighup {
            Some(
                tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())
                    .expect("failed to register SIGHUP handler"),
            )
        } else {
            None
        };

        loop {
            // Check for global shutdown before waiting for next trigger
            #[cfg(feature = "shutdown")]
            if shutdown_token.is_cancelled() {
                info!("Config reloader stopping (shutdown)");
                return;
            }

            let trigger_result = {
                #[cfg(feature = "shutdown")]
                {
                    tokio::select! {
                        trigger = self.wait_for_trigger(
                            &mut poll_timer,
                            &mut periodic_timer,
                            #[cfg(unix)]
                            &mut sighup,
                            &mut last_modified,
                        ) => Some(trigger),
                        () = shutdown_token.cancelled() => None,
                    }
                }
                #[cfg(not(feature = "shutdown"))]
                {
                    Some(
                        self.wait_for_trigger(
                            &mut poll_timer,
                            &mut periodic_timer,
                            #[cfg(unix)]
                            &mut sighup,
                            &mut last_modified,
                        )
                        .await,
                    )
                }
            };

            let Some(trigger) = trigger_result else {
                info!("Config reloader stopping (shutdown)");
                return;
            };

            // Debounce check
            if last_reload.elapsed() < self.config.debounce {
                debug!("Debouncing config reload");
                continue;
            }

            match trigger {
                ReloadTrigger::FileChanged => {
                    info!(
                        path = ?self.config.config_path,
                        "Config file changed, reloading"
                    );
                }
                ReloadTrigger::Periodic => {
                    info!("Periodic config reload triggered");
                }
                ReloadTrigger::Sighup => {
                    info!("SIGHUP received, reloading configuration");
                }
            }

            self.do_reload();
            last_reload = Instant::now();
        }
    }

    /// Wait for the next reload trigger.
    ///
    /// Returns which trigger fired. For file polling, also updates last_modified.
    async fn wait_for_trigger(
        &self,
        poll_timer: &mut Option<tokio::time::Interval>,
        periodic_timer: &mut Option<tokio::time::Interval>,
        #[cfg(unix)] sighup: &mut Option<tokio::signal::unix::Signal>,
        last_modified: &mut Option<SystemTime>,
    ) -> ReloadTrigger {
        loop {
            let trigger = self
                .select_trigger(
                    poll_timer,
                    periodic_timer,
                    #[cfg(unix)]
                    sighup,
                )
                .await;

            match trigger {
                ReloadTrigger::FileChanged => {
                    // Check if file actually changed (mtime comparison)
                    if let Some(ref path) = self.config.config_path {
                        let current_mtime = file_mtime(path);
                        let changed = match (&*last_modified, &current_mtime) {
                            (Some(last), Some(current)) => current > last,
                            (None, Some(_)) => true,
                            _ => false,
                        };
                        if changed {
                            *last_modified = current_mtime;
                            return ReloadTrigger::FileChanged;
                        }
                    }
                    // No actual change, loop back
                }
                other => return other,
            }
        }
    }

    /// Select on all enabled triggers, returning which one fired first.
    #[cfg(unix)]
    async fn select_trigger(
        &self,
        poll_timer: &mut Option<tokio::time::Interval>,
        periodic_timer: &mut Option<tokio::time::Interval>,
        sighup: &mut Option<tokio::signal::unix::Signal>,
    ) -> ReloadTrigger {
        tokio::select! {
            _ = async {
                match poll_timer.as_mut() {
                    Some(timer) => timer.tick().await,
                    None => std::future::pending().await,
                }
            } => ReloadTrigger::FileChanged,

            _ = async {
                match periodic_timer.as_mut() {
                    Some(timer) => timer.tick().await,
                    None => std::future::pending().await,
                }
            } => ReloadTrigger::Periodic,

            () = async {
                match sighup.as_mut() {
                    Some(sig) => { sig.recv().await; },
                    None => std::future::pending::<()>().await,
                }
            } => ReloadTrigger::Sighup,
        }
    }

    /// Select on all enabled triggers (non-Unix: no SIGHUP).
    #[cfg(not(unix))]
    async fn select_trigger(
        &self,
        poll_timer: &mut Option<tokio::time::Interval>,
        periodic_timer: &mut Option<tokio::time::Interval>,
    ) -> ReloadTrigger {
        tokio::select! {
            _ = async {
                match poll_timer.as_mut() {
                    Some(timer) => timer.tick().await,
                    None => std::future::pending().await,
                }
            } => ReloadTrigger::FileChanged,

            _ = async {
                match periodic_timer.as_mut() {
                    Some(timer) => timer.tick().await,
                    None => std::future::pending().await,
                }
            } => ReloadTrigger::Periodic,
        }
    }

    /// Attempt to reload config: load → validate → update shared.
    fn do_reload(&self) {
        match (self.reload_fn)() {
            Ok(new_config) => {
                if let Err(e) = (self.validate_fn)(&new_config) {
                    error!(error = %e, "Config reload validation failed, keeping current config");
                    #[cfg(feature = "metrics")]
                    metrics::counter!("config_reloads_total", "result" => "error").increment(1);
                    return;
                }

                let old_version = self.shared.version();
                self.shared.update(new_config.clone());
                let new_version = self.shared.version();

                // Run post-reload hooks (registry update, etc.)
                for hook in &self.post_reload_hooks {
                    hook(&new_config);
                }

                #[cfg(feature = "metrics")]
                metrics::counter!("config_reloads_total", "result" => "success").increment(1);

                info!(
                    old_version = old_version,
                    new_version = new_version,
                    "Configuration reloaded successfully"
                );
            }
            Err(e) => {
                warn!(error = %e, "Config reload failed, keeping current config");
                #[cfg(feature = "metrics")]
                metrics::counter!("config_reloads_total", "result" => "error").increment(1);
            }
        }
    }
}

/// Which trigger caused a reload.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ReloadTrigger {
    FileChanged,
    Periodic,
    #[allow(dead_code)]
    Sighup,
}

/// Get the modification time of a file.
fn file_mtime(path: &PathBuf) -> Option<SystemTime> {
    std::fs::metadata(path).ok().and_then(|m| m.modified().ok())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::io::Write;
    use std::sync::atomic::{AtomicBool, Ordering};
    use tempfile::TempDir;

    #[derive(Clone, Debug, Default, PartialEq)]
    struct TestConfig {
        pub value: String,
    }

    #[test]
    fn test_reloader_config_defaults() {
        let config = ReloaderConfig::default();
        assert!(config.config_path.is_none());
        assert_eq!(config.poll_interval, Duration::from_secs(5));
        assert_eq!(config.periodic_interval, Duration::ZERO);
        assert_eq!(config.debounce, Duration::from_millis(500));
        assert!(config.enable_sighup);
    }

    #[tokio::test]
    async fn test_periodic_reload() {
        let shared = SharedConfig::new(TestConfig {
            value: "initial".into(),
        });
        let mut rx = shared.subscribe();

        let call_count = Arc::new(std::sync::atomic::AtomicU32::new(0));
        let call_count_clone = call_count.clone();

        let reloader = ConfigReloader::new(
            ReloaderConfig {
                periodic_interval: Duration::from_millis(50),
                debounce: Duration::from_millis(10),
                enable_sighup: false,
                ..Default::default()
            },
            shared.clone(),
            move || {
                call_count_clone.fetch_add(1, Ordering::Relaxed);
                Ok(TestConfig {
                    value: "reloaded".into(),
                })
            },
            |_| Ok(()),
        );

        let handle = reloader.start();

        // Wait for at least one reload
        let result = tokio::time::timeout(Duration::from_secs(2), rx.changed()).await;
        assert!(result.is_ok(), "Should receive reload notification");

        assert_eq!(shared.read().value, "reloaded");
        assert!(shared.version() >= 1);
        assert!(call_count.load(Ordering::Relaxed) >= 1);

        handle.abort();
    }

    #[tokio::test]
    async fn test_file_change_triggers_reload() {
        let dir = TempDir::new().unwrap();
        let config_path = dir.path().join("config.yaml");
        fs::write(&config_path, "initial content").unwrap();

        let shared = SharedConfig::new(TestConfig {
            value: "initial".into(),
        });
        let mut rx = shared.subscribe();

        let path_for_reload = config_path.clone();
        let reloader = ConfigReloader::new(
            ReloaderConfig {
                config_path: Some(config_path.clone()),
                poll_interval: Duration::from_millis(50),
                debounce: Duration::from_millis(10),
                enable_sighup: false,
                ..Default::default()
            },
            shared.clone(),
            move || {
                let content = fs::read_to_string(&path_for_reload).unwrap_or_default();
                Ok(TestConfig { value: content })
            },
            |_| Ok(()),
        );

        let handle = reloader.start();

        // Let the watcher start and record initial mtime
        tokio::time::sleep(Duration::from_millis(150)).await;

        // Modify the file
        {
            let mut file = fs::OpenOptions::new()
                .write(true)
                .truncate(true)
                .open(&config_path)
                .unwrap();
            file.write_all(b"updated content").unwrap();
            file.sync_all().unwrap();
        }

        // Wait for the reload
        let result = tokio::time::timeout(Duration::from_secs(2), rx.changed()).await;
        if result.is_ok() {
            assert_eq!(shared.read().value, "updated content");
        }

        handle.abort();
    }

    #[tokio::test]
    async fn test_validation_failure_preserves_config() {
        let shared = SharedConfig::new(TestConfig {
            value: "good".into(),
        });

        let should_fail = Arc::new(AtomicBool::new(true));
        let should_fail_clone = should_fail.clone();

        let reloader = ConfigReloader::new(
            ReloaderConfig {
                periodic_interval: Duration::from_millis(50),
                debounce: Duration::from_millis(10),
                enable_sighup: false,
                ..Default::default()
            },
            shared.clone(),
            || {
                Ok(TestConfig {
                    value: "bad".into(),
                })
            },
            move |_cfg| {
                if should_fail_clone.load(Ordering::Relaxed) {
                    Err("validation failed".into())
                } else {
                    Ok(())
                }
            },
        );

        let handle = reloader.start();

        // Let a few reload attempts happen (all should fail validation)
        tokio::time::sleep(Duration::from_millis(200)).await;

        // Config should still be the original
        assert_eq!(shared.read().value, "good");
        assert_eq!(shared.version(), 0);

        handle.abort();
    }

    #[tokio::test]
    async fn test_reload_fn_error_preserves_config() {
        let shared = SharedConfig::new(TestConfig {
            value: "good".into(),
        });

        let reloader = ConfigReloader::new(
            ReloaderConfig {
                periodic_interval: Duration::from_millis(50),
                debounce: Duration::from_millis(10),
                enable_sighup: false,
                ..Default::default()
            },
            shared.clone(),
            || Err("load failed".into()),
            |_| Ok(()),
        );

        let handle = reloader.start();

        // Let a few reload attempts happen
        tokio::time::sleep(Duration::from_millis(200)).await;

        // Config should still be the original
        assert_eq!(shared.read().value, "good");
        assert_eq!(shared.version(), 0);

        handle.abort();
    }

    #[test]
    fn test_file_mtime() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("test.txt");
        fs::write(&path, "content").unwrap();

        let mtime = file_mtime(&path);
        assert!(mtime.is_some());

        // Non-existent file
        let mtime = file_mtime(&PathBuf::from("/nonexistent/file.txt"));
        assert!(mtime.is_none());
    }
}