tier 0.1.11

Rust configuration library for layered TOML, env, and CLI settings
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
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
use std::collections::BTreeMap;
#[cfg(feature = "watch")]
use std::path::Path;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(feature = "watch")]
use std::sync::mpsc::RecvTimeoutError;
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex, RwLock};
use std::thread::{self, JoinHandle};
#[cfg(feature = "watch")]
use std::time::Instant;
use std::time::{Duration, SystemTime};

#[cfg(feature = "watch")]
use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use serde_json::Value;

use crate::report::collect_diff_paths;
use crate::{ConfigError, ConfigReport, LoadedConfig};

type LoaderFn<T> = dyn Fn() -> Result<LoadedConfig<T>, ConfigError> + Send + Sync + 'static;

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
/// Policy applied when a background watcher encounters a reload failure.
pub enum ReloadFailurePolicy {
    /// Keep the last good configuration and continue watching for future changes.
    #[default]
    KeepLastGood,
    /// Keep the last good configuration and stop the background watcher.
    StopWatcher,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
/// Options controlling watcher-side reload behavior.
pub struct ReloadOptions {
    /// Behavior applied after a failed reload.
    pub on_error: ReloadFailurePolicy,
    /// Whether to emit success events even when the effective configuration did not change.
    pub emit_unchanged: bool,
}

impl Default for ReloadOptions {
    fn default() -> Self {
        Self {
            on_error: ReloadFailurePolicy::KeepLastGood,
            emit_unchanged: false,
        }
    }
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
/// A single redacted configuration change observed during reload.
pub struct ConfigChange {
    /// Dot-delimited path that changed.
    pub path: String,
    /// Previous redacted value, when present.
    pub before: Option<Value>,
    /// New redacted value, when present.
    pub after: Option<Value>,
    /// Whether either side of the change was redacted.
    pub redacted: bool,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
/// Structured summary of a successful reload attempt.
pub struct ReloadSummary {
    /// Whether the effective redacted configuration changed.
    pub had_changes: bool,
    /// Changed paths in normalized order.
    pub changed_paths: Vec<String>,
    /// Structured per-path change details.
    pub changes: Vec<ConfigChange>,
}

impl ReloadSummary {
    /// Returns `true` when the reload was a no-op.
    #[must_use]
    pub fn is_noop(&self) -> bool {
        !self.had_changes
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
/// Structured details about a rejected reload attempt.
pub struct ReloadFailure {
    /// Human-readable error message.
    pub error: String,
    /// Whether the previous configuration snapshot was preserved.
    pub last_good_retained: bool,
    /// Whether the watcher that observed the error stopped after the failure.
    pub watcher_stopped: bool,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
/// Structured event emitted after each successful or rejected reload attempt.
pub enum ReloadEvent {
    /// A reload was applied successfully.
    Applied(ReloadSummary),
    /// A reload failed and the previous configuration was kept.
    Rejected(ReloadFailure),
}

/// Thread-safe holder for the active configuration and reload logic.
///
/// `ReloadHandle<T>` keeps the most recent successful [`LoadedConfig`] in
/// memory and reuses the same loader closure for subsequent reloads. Failed
/// reloads never replace the active configuration, which makes it suitable for
/// long-running services.
///
/// # Examples
///
/// ```no_run
/// use serde::{Deserialize, Serialize};
/// use tier::{ConfigLoader, ReloadHandle};
///
/// #[derive(Debug, Clone, Serialize, Deserialize)]
/// struct AppConfig {
///     port: u16,
/// }
///
/// impl Default for AppConfig {
///     fn default() -> Self {
///         Self { port: 3000 }
///     }
/// }
///
/// let handle = ReloadHandle::new(|| ConfigLoader::new(AppConfig::default()).load())?;
/// let snapshot = handle.snapshot();
/// assert_eq!(snapshot.port, 3000);
/// # Ok::<(), tier::ConfigError>(())
/// ```
pub struct ReloadHandle<T> {
    state: Arc<RwLock<LoadedConfig<T>>>,
    loader: Arc<LoaderFn<T>>,
    last_error: Arc<Mutex<Option<String>>>,
    subscribers: Arc<Mutex<Vec<Sender<ReloadEvent>>>>,
}

impl<T> Clone for ReloadHandle<T> {
    fn clone(&self) -> Self {
        Self {
            state: Arc::clone(&self.state),
            loader: Arc::clone(&self.loader),
            last_error: Arc::clone(&self.last_error),
            subscribers: Arc::clone(&self.subscribers),
        }
    }
}

impl<T> ReloadHandle<T>
where
    T: Send + Sync + 'static,
{
    /// Creates a reload handle from a loader closure and performs the initial load.
    pub fn new<F>(loader: F) -> Result<Self, ConfigError>
    where
        F: Fn() -> Result<LoadedConfig<T>, ConfigError> + Send + Sync + 'static,
    {
        let initial = loader()?;
        Ok(Self {
            state: Arc::new(RwLock::new(initial)),
            loader: Arc::new(loader),
            last_error: Arc::new(Mutex::new(None)),
            subscribers: Arc::new(Mutex::new(Vec::new())),
        })
    }

    /// Attempts to reload configuration, preserving the previous state on failure.
    pub fn reload(&self) -> Result<(), ConfigError> {
        self.reload_with_options(&ReloadOptions {
            emit_unchanged: true,
            ..ReloadOptions::default()
        })
        .map(|_| ())
    }

    /// Attempts to reload configuration and returns a structured diff summary.
    pub fn reload_detailed(&self) -> Result<ReloadSummary, ConfigError> {
        self.reload_with_options(&ReloadOptions {
            emit_unchanged: true,
            ..ReloadOptions::default()
        })
    }

    /// Returns the most recent reload error, if any.
    #[must_use]
    pub fn last_error(&self) -> Option<String> {
        mutex_lock(&self.last_error).clone()
    }

    /// Subscribes to future reload events.
    pub fn subscribe(&self) -> Receiver<ReloadEvent> {
        let (tx, rx) = mpsc::channel();
        mutex_lock(&self.subscribers).push(tx);
        rx
    }

    /// Starts a polling watcher that reloads when any watched file changes.
    pub fn start_polling<I, P>(&self, paths: I, interval: Duration) -> PollingWatcher
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.start_polling_with_options(paths, interval, ReloadOptions::default())
    }

    /// Starts a polling watcher with explicit reload behavior options.
    pub fn start_polling_with_options<I, P>(
        &self,
        paths: I,
        interval: Duration,
        options: ReloadOptions,
    ) -> PollingWatcher
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        PollingWatcher::spawn(
            self.clone(),
            paths.into_iter().map(Into::into).collect(),
            interval,
            options,
        )
    }

    #[cfg(feature = "watch")]
    /// Starts a native filesystem watcher with event debouncing.
    ///
    /// File paths are watched through their parent directories so atomic
    /// replace-and-rename writes still trigger a reload.
    pub fn start_native<I, P>(
        &self,
        paths: I,
        debounce: Duration,
    ) -> Result<NativeWatcher, ConfigError>
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.start_native_with_options(paths, debounce, ReloadOptions::default())
    }

    /// Starts a native filesystem watcher with explicit reload behavior options.
    #[cfg(feature = "watch")]
    pub fn start_native_with_options<I, P>(
        &self,
        paths: I,
        debounce: Duration,
        options: ReloadOptions,
    ) -> Result<NativeWatcher, ConfigError>
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        NativeWatcher::spawn(
            self.clone(),
            paths.into_iter().map(Into::into).collect(),
            debounce,
            options,
        )
    }

    fn reload_with_options(&self, options: &ReloadOptions) -> Result<ReloadSummary, ConfigError> {
        let before_report = read_lock(&self.state).report().clone();
        let before_raw = before_report.final_value().clone();
        let before_redacted = before_report.redacted_value();

        match (self.loader)() {
            Ok(next) => {
                let after_raw = next.report().final_value().clone();
                let after_redacted = next.report().redacted_value();
                let summary = build_reload_summary(
                    &before_raw,
                    &after_raw,
                    &before_redacted,
                    &after_redacted,
                );
                *write_lock(&self.state) = next;
                *mutex_lock(&self.last_error) = None;
                if options.emit_unchanged || summary.had_changes {
                    self.emit_event(ReloadEvent::Applied(summary.clone()));
                }
                Ok(summary)
            }
            Err(error) => {
                self.record_error_message(error.to_string());
                self.emit_event(ReloadEvent::Rejected(ReloadFailure {
                    error: error.to_string(),
                    last_good_retained: true,
                    watcher_stopped: matches!(options.on_error, ReloadFailurePolicy::StopWatcher),
                }));
                Err(error)
            }
        }
    }
}

impl<T> ReloadHandle<T>
where
    T: Clone + Send + Sync + 'static,
{
    /// Returns a full snapshot of the current loaded configuration and report.
    #[must_use]
    pub fn snapshot(&self) -> LoadedConfig<T> {
        read_lock(&self.state).clone()
    }

    /// Returns a cloned copy of the current configuration value.
    #[must_use]
    pub fn config(&self) -> T {
        read_lock(&self.state).config().clone()
    }

    /// Returns a cloned copy of the current configuration report.
    #[must_use]
    pub fn report(&self) -> ConfigReport {
        read_lock(&self.state).report().clone()
    }
}

impl<T> ReloadHandle<T> {
    fn record_error_message(&self, message: String) {
        *mutex_lock(&self.last_error) = Some(message);
    }

    fn emit_event(&self, event: ReloadEvent) {
        let mut subscribers = mutex_lock(&self.subscribers);
        subscribers.retain(|subscriber| subscriber.send(event.clone()).is_ok());
    }
}

/// Handle for a background polling watcher.
pub struct PollingWatcher {
    stop: Arc<AtomicBool>,
    join: Option<JoinHandle<()>>,
}

impl PollingWatcher {
    fn spawn<T>(
        handle: ReloadHandle<T>,
        paths: Vec<PathBuf>,
        interval: Duration,
        options: ReloadOptions,
    ) -> Self
    where
        T: Send + Sync + 'static,
    {
        let stop = Arc::new(AtomicBool::new(false));
        let join_stop = Arc::clone(&stop);
        let join = thread::spawn(move || {
            let mut seen = collect_mtimes(&paths);
            while !join_stop.load(Ordering::Relaxed) {
                thread::sleep(interval);
                let current = collect_mtimes(&paths);
                if current != seen {
                    let reload_result = handle.reload_with_options(&options);
                    seen = current;
                    if reload_result.is_err()
                        && matches!(options.on_error, ReloadFailurePolicy::StopWatcher)
                    {
                        return;
                    }
                }
            }
        });

        Self {
            stop,
            join: Some(join),
        }
    }

    /// Stops the watcher and joins the background thread.
    pub fn stop(mut self) {
        self.shutdown();
    }

    fn shutdown(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
        if let Some(join) = self.join.take() {
            let _ = join.join();
        }
    }
}

impl Drop for PollingWatcher {
    fn drop(&mut self) {
        self.shutdown();
    }
}

#[cfg(feature = "watch")]
enum WatchMessage {
    Event(notify::Result<Event>),
    Stop,
}

#[cfg(feature = "watch")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WatchTargetKind {
    File,
    Directory,
}

#[cfg(feature = "watch")]
#[derive(Debug, Clone)]
struct WatchTarget {
    path: PathBuf,
    kind: WatchTargetKind,
    watch_root: PathBuf,
    recursive: bool,
}

#[cfg(feature = "watch")]
impl WatchTarget {
    fn matches_event_path(&self, path: &Path) -> bool {
        match self.kind {
            WatchTargetKind::File => path == self.path,
            WatchTargetKind::Directory => path == self.path || path.starts_with(&self.path),
        }
    }
}

#[cfg(feature = "watch")]
#[derive(Debug, Clone)]
struct WatchRegistration {
    root: PathBuf,
    recursive: bool,
}

#[cfg(feature = "watch")]
/// Handle for a background native filesystem watcher.
pub struct NativeWatcher {
    watcher: Option<RecommendedWatcher>,
    stop: Option<Sender<WatchMessage>>,
    join: Option<JoinHandle<()>>,
}

#[cfg(feature = "watch")]
impl NativeWatcher {
    fn spawn<T>(
        handle: ReloadHandle<T>,
        paths: Vec<PathBuf>,
        debounce: Duration,
        options: ReloadOptions,
    ) -> Result<Self, ConfigError>
    where
        T: Send + Sync + 'static,
    {
        let targets = prepare_watch_targets(paths)?;
        if targets.is_empty() {
            return Err(ConfigError::Watch {
                message: "at least one path must be watched".to_owned(),
            });
        }

        let registrations = collect_watch_registrations(&targets);
        let (tx, rx) = mpsc::channel();
        let callback_tx = tx.clone();
        let mut watcher = notify::recommended_watcher(move |event| {
            let _ = callback_tx.send(WatchMessage::Event(event));
        })
        .map_err(map_watch_error)?;

        for registration in &registrations {
            let mode = if registration.recursive {
                RecursiveMode::Recursive
            } else {
                RecursiveMode::NonRecursive
            };
            watcher
                .watch(&registration.root, mode)
                .map_err(map_watch_error)?;
        }

        let join =
            thread::spawn(move || run_native_watch_loop(handle, targets, rx, debounce, options));

        Ok(Self {
            watcher: Some(watcher),
            stop: Some(tx),
            join: Some(join),
        })
    }

    /// Stops the watcher and joins the background thread.
    pub fn stop(mut self) {
        self.shutdown();
    }

    fn shutdown(&mut self) {
        self.watcher.take();
        if let Some(stop) = self.stop.take() {
            let _ = stop.send(WatchMessage::Stop);
        }
        if let Some(join) = self.join.take() {
            let _ = join.join();
        }
    }
}

#[cfg(feature = "watch")]
impl Drop for NativeWatcher {
    fn drop(&mut self) {
        self.shutdown();
    }
}

#[cfg(feature = "watch")]
fn run_native_watch_loop<T>(
    handle: ReloadHandle<T>,
    targets: Vec<WatchTarget>,
    rx: Receiver<WatchMessage>,
    debounce: Duration,
    options: ReloadOptions,
) where
    T: Send + Sync + 'static,
{
    loop {
        let deadline = match rx.recv() {
            Ok(WatchMessage::Stop) | Err(_) => return,
            Ok(WatchMessage::Event(event)) => {
                match handle_watch_message(&handle, &targets, event, debounce) {
                    Some(deadline) => deadline,
                    None => continue,
                }
            }
        };

        let mut deadline = deadline;
        loop {
            let timeout = deadline.saturating_duration_since(Instant::now());
            match rx.recv_timeout(timeout) {
                Ok(WatchMessage::Stop) | Err(RecvTimeoutError::Disconnected) => return,
                Err(RecvTimeoutError::Timeout) => break,
                Ok(WatchMessage::Event(event)) => {
                    if let Some(next_deadline) =
                        handle_watch_message(&handle, &targets, event, debounce)
                    {
                        deadline = next_deadline;
                    }
                }
            }
        }

        if handle.reload_with_options(&options).is_err()
            && matches!(options.on_error, ReloadFailurePolicy::StopWatcher)
        {
            return;
        }
    }
}

#[cfg(feature = "watch")]
fn handle_watch_message<T>(
    handle: &ReloadHandle<T>,
    targets: &[WatchTarget],
    event: notify::Result<Event>,
    debounce: Duration,
) -> Option<Instant> {
    match event {
        Ok(event) if event_requires_reload(&event, targets) => Some(Instant::now() + debounce),
        Ok(_) => None,
        Err(error) => {
            handle.record_error_message(format!("watch error: {error}"));
            None
        }
    }
}

#[cfg(feature = "watch")]
fn event_requires_reload(event: &Event, targets: &[WatchTarget]) -> bool {
    if matches!(event.kind, EventKind::Access(_)) {
        return false;
    }

    if event.paths.is_empty() {
        return true;
    }

    event
        .paths
        .iter()
        .filter_map(|path| absolutize_event_path(path))
        .any(|path| {
            targets
                .iter()
                .any(|target| target.matches_event_path(&path))
        })
}

#[cfg(feature = "watch")]
fn prepare_watch_targets(paths: Vec<PathBuf>) -> Result<Vec<WatchTarget>, ConfigError> {
    let mut targets = Vec::new();
    for path in paths {
        let path = absolutize_path(&path)?;
        if path.exists() && path.is_dir() {
            targets.push(WatchTarget {
                watch_root: path.clone(),
                path,
                kind: WatchTargetKind::Directory,
                recursive: true,
            });
            continue;
        }

        let parent = path
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| path.clone());
        let (watch_root, recursive) = if parent.exists() {
            (parent, false)
        } else if let Some(root) = nearest_existing_ancestor(&parent) {
            (root, true)
        } else {
            (std::env::current_dir().map_err(map_watch_io_error)?, true)
        };

        targets.push(WatchTarget {
            path,
            kind: WatchTargetKind::File,
            watch_root,
            recursive,
        });
    }

    Ok(targets)
}

#[cfg(feature = "watch")]
fn collect_watch_registrations(targets: &[WatchTarget]) -> Vec<WatchRegistration> {
    let mut registrations = BTreeMap::<PathBuf, bool>::new();
    for target in targets {
        registrations
            .entry(target.watch_root.clone())
            .and_modify(|recursive| *recursive |= target.recursive)
            .or_insert(target.recursive);
    }

    registrations
        .into_iter()
        .map(|(root, recursive)| WatchRegistration { root, recursive })
        .collect()
}

#[cfg(feature = "watch")]
fn nearest_existing_ancestor(path: &Path) -> Option<PathBuf> {
    let mut current = Some(path);
    while let Some(candidate) = current {
        if candidate.exists() {
            return Some(candidate.to_path_buf());
        }
        current = candidate.parent();
    }
    None
}

#[cfg(feature = "watch")]
fn absolutize_path(path: &Path) -> Result<PathBuf, ConfigError> {
    if path.is_absolute() {
        Ok(path.to_path_buf())
    } else {
        Ok(std::env::current_dir()
            .map_err(map_watch_io_error)?
            .join(path))
    }
}

#[cfg(feature = "watch")]
fn absolutize_event_path(path: &Path) -> Option<PathBuf> {
    if path.is_absolute() {
        Some(path.to_path_buf())
    } else {
        std::env::current_dir().ok().map(|cwd| cwd.join(path))
    }
}

#[cfg(feature = "watch")]
fn map_watch_error(error: notify::Error) -> ConfigError {
    ConfigError::Watch {
        message: error.to_string(),
    }
}

#[cfg(feature = "watch")]
fn map_watch_io_error(error: std::io::Error) -> ConfigError {
    ConfigError::Watch {
        message: error.to_string(),
    }
}

fn collect_mtimes(paths: &[PathBuf]) -> BTreeMap<PathBuf, Option<SystemTime>> {
    let mut mtimes = BTreeMap::new();
    for path in paths {
        collect_mtimes_recursive(path, &mut mtimes);
    }
    mtimes
}

fn collect_mtimes_recursive(path: &PathBuf, mtimes: &mut BTreeMap<PathBuf, Option<SystemTime>>) {
    let metadata = std::fs::symlink_metadata(path).ok();
    let mtime = metadata
        .as_ref()
        .and_then(|metadata| metadata.modified().ok());
    mtimes.insert(path.clone(), mtime);

    let is_dir = metadata
        .as_ref()
        .is_some_and(|metadata| metadata.file_type().is_dir());
    if !is_dir {
        return;
    }

    let Ok(entries) = std::fs::read_dir(path) else {
        return;
    };

    for entry in entries.flatten() {
        collect_mtimes_recursive(&entry.path(), mtimes);
    }
}

fn read_lock<T>(lock: &RwLock<T>) -> std::sync::RwLockReadGuard<'_, T> {
    match lock.read() {
        Ok(guard) => guard,
        Err(poisoned) => poisoned.into_inner(),
    }
}

fn write_lock<T>(lock: &RwLock<T>) -> std::sync::RwLockWriteGuard<'_, T> {
    match lock.write() {
        Ok(guard) => guard,
        Err(poisoned) => poisoned.into_inner(),
    }
}

fn mutex_lock<T>(lock: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    match lock.lock() {
        Ok(guard) => guard,
        Err(poisoned) => poisoned.into_inner(),
    }
}

fn build_reload_summary(
    before_raw: &Value,
    after_raw: &Value,
    before_redacted: &Value,
    after_redacted: &Value,
) -> ReloadSummary {
    let mut changed_paths = Vec::new();
    collect_diff_paths(before_raw, after_raw, "", &mut changed_paths);
    changed_paths.sort();
    changed_paths.dedup();

    let changes = changed_paths
        .iter()
        .map(|path| {
            let before_value = redacted_value_at_path(before_redacted, path);
            let after_value = redacted_value_at_path(after_redacted, path);
            let redacted = before_value.as_ref().is_some_and(is_redacted_value)
                || after_value.as_ref().is_some_and(is_redacted_value);
            ConfigChange {
                path: path.clone(),
                before: before_value,
                after: after_value,
                redacted,
            }
        })
        .collect::<Vec<_>>();

    ReloadSummary {
        had_changes: before_raw != after_raw,
        changed_paths,
        changes,
    }
}

fn redacted_value_at_path(value: &Value, path: &str) -> Option<Value> {
    if path.is_empty() {
        return Some(value.clone());
    }

    let mut current = value;
    for segment in path.split('.') {
        match current {
            Value::String(text) if text == "***redacted***" => {
                return Some(Value::String(text.clone()));
            }
            Value::Object(map) => {
                current = map.get(segment)?;
            }
            Value::Array(values) => {
                let index = segment.parse::<usize>().ok()?;
                current = values.get(index)?;
            }
            _ => return None,
        }
    }

    Some(current.clone())
}

fn is_redacted_value(value: &Value) -> bool {
    match value {
        Value::String(text) => text == "***redacted***",
        Value::Array(values) => values.iter().any(is_redacted_value),
        Value::Object(map) => map.values().any(is_redacted_value),
        _ => false,
    }
}