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
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
//! Component lifecycle management.
//!
//! Provides the `Lifecycle` trait for components that manage
//! background resources and the `LifecycleRegistry` for ordered
//! startup/shutdown sequencing.
//!
//! # Feature-gated async/sync
//!
//! When any async feature is enabled (remote, config-bus, encryption, watch),
//! the async version (using `async_trait`) is used. Otherwise, a sync
//! # Design (ADR-041)
//!
//! - `start()` is idempotent
//! - `stop()` must flush all pending persistent operations
//! - FIFO start / LIFO stop order

use crate::error::{ConfigConfigError, ConfigError, ConfigResult};

#[cfg(any(
    feature = "remote",
    feature = "config-bus",
    feature = "encryption",
    feature = "watch"
))]
mod async_impl {
    use super::*;
    use async_trait::async_trait;
    use std::sync::Arc;

    #[async_trait]
    pub trait Lifecycle: Send + Sync {
        async fn start(&self) -> Result<(), ConfigConfigError> {
            Ok(())
        }
        async fn stop(&self) -> ConfigResult<()> {
            Ok(())
        }
    }

    pub(crate) struct LifecycleRegistry {
        components: Vec<(String, Arc<dyn Lifecycle>)>,
    }

    impl LifecycleRegistry {
        pub(crate) fn new() -> Self {
            Self {
                components: Vec::new(),
            }
        }
        pub(crate) fn register(&mut self, name: impl Into<String>, component: Arc<dyn Lifecycle>) {
            self.components.push((name.into(), component));
        }
        #[allow(dead_code)]
        pub(crate) async fn start_all(&self) -> Result<(), ConfigConfigError> {
            for (name, c) in &self.components {
                c.start()
                    .await
                    .map_err(|e| ConfigConfigError::InvalidValue {
                        field: "lifecycle".into(),
                        expected_type: "operational".into(),
                        message: format!("{} failed: {}", name, e),
                    })?;
            }
            Ok(())
        }
        #[allow(dead_code)]
        pub(crate) async fn stop_all(&self) -> ConfigResult<()> {
            // Per ADR-041: stop() must flush all pending persistent operations,
            // so we MUST call stop() on every component even if some fail.
            // Collect all errors and aggregate them (Rule 12: Fail Loud).
            let mut errors: Vec<(String, ConfigError)> = Vec::new();
            for (name, c) in self.components.iter().rev() {
                if let Err(e) = c.stop().await {
                    errors.push((name.clone(), e));
                }
            }
            if errors.is_empty() {
                Ok(())
            } else {
                let detail = errors
                    .iter()
                    .map(|(name, e)| format!("  - {}: {}", name, e))
                    .collect::<Vec<_>>()
                    .join("\n");
                Err(ConfigError::InvalidValue {
                    key: "lifecycle".into(),
                    expected_type: "operational".into(),
                    message: format!(
                        "stop_all failed for {} component(s):\n{}",
                        errors.len(),
                        detail
                    ),
                })
            }
        }
        #[allow(dead_code)]
        pub(crate) fn is_empty(&self) -> bool {
            self.components.is_empty()
        }
        #[allow(dead_code)]
        pub(crate) fn len(&self) -> usize {
            self.components.len()
        }
    }
}

#[cfg(not(any(
    feature = "remote",
    feature = "config-bus",
    feature = "encryption",
    feature = "watch"
)))]
mod sync_impl {
    use super::*;

    pub trait Lifecycle: Send + Sync {
        fn start(&self) -> Result<(), ConfigConfigError> {
            Ok(())
        }
        fn stop(&self) -> ConfigResult<()> {
            Ok(())
        }
    }

    pub(crate) struct LifecycleRegistry {
        components: Vec<(String, Box<dyn Lifecycle>)>,
    }

    impl LifecycleRegistry {
        pub(crate) fn new() -> Self {
            Self {
                components: Vec::new(),
            }
        }
        pub(crate) fn register(&mut self, name: impl Into<String>, component: Box<dyn Lifecycle>) {
            self.components.push((name.into(), component));
        }
        #[allow(dead_code)]
        pub(crate) fn start_all(&self) -> Result<(), ConfigConfigError> {
            for (name, c) in &self.components {
                c.start().map_err(|e| ConfigConfigError::InvalidValue {
                    field: "lifecycle".into(),
                    expected_type: "operational".into(),
                    message: format!("{} failed: {}", name, e),
                })?;
            }
            Ok(())
        }
        #[allow(dead_code)]
        pub(crate) fn stop_all(&self) -> ConfigResult<()> {
            // Per ADR-041: stop() must flush all pending persistent operations,
            // so we MUST call stop() on every component even if some fail.
            // Collect all errors and aggregate them (Rule 12: Fail Loud).
            let mut errors: Vec<(String, ConfigError)> = Vec::new();
            for (name, c) in self.components.iter().rev() {
                if let Err(e) = c.stop() {
                    errors.push((name.clone(), e));
                }
            }
            if errors.is_empty() {
                Ok(())
            } else {
                let detail = errors
                    .iter()
                    .map(|(name, e)| format!("  - {}: {}", name, e))
                    .collect::<Vec<_>>()
                    .join("\n");
                Err(ConfigError::InvalidValue {
                    key: "lifecycle".into(),
                    expected_type: "operational".into(),
                    message: format!(
                        "stop_all failed for {} component(s):\n{}",
                        errors.len(),
                        detail
                    ),
                })
            }
        }
        #[allow(dead_code)]
        pub(crate) fn is_empty(&self) -> bool {
            self.components.is_empty()
        }
        pub(crate) fn len(&self) -> usize {
            self.components.len()
        }
    }
}

#[cfg(any(
    feature = "remote",
    feature = "config-bus",
    feature = "encryption",
    feature = "watch"
))]
pub use async_impl::Lifecycle;
#[cfg(any(
    feature = "remote",
    feature = "config-bus",
    feature = "encryption",
    feature = "watch"
))]
pub(crate) use async_impl::LifecycleRegistry;
#[cfg(not(any(
    feature = "remote",
    feature = "config-bus",
    feature = "encryption",
    feature = "watch"
)))]
pub use sync_impl::Lifecycle;
#[cfg(not(any(
    feature = "remote",
    feature = "config-bus",
    feature = "encryption",
    feature = "watch"
)))]
#[allow(unused_imports)] // LifecycleRegistry re-exported for API completeness
pub(crate) use sync_impl::LifecycleRegistry;

#[cfg(test)]
mod tests {
    use crate::error::ConfigConfigError;

    struct TestComponent {
        started: std::sync::atomic::AtomicBool,
        stopped: std::sync::atomic::AtomicBool,
    }

    impl TestComponent {
        fn new() -> Self {
            Self {
                started: std::sync::atomic::AtomicBool::new(false),
                stopped: std::sync::atomic::AtomicBool::new(false),
            }
        }
    }

    // Lifecycle is imported from the active impl (sync or async depending on features)
    #[cfg(any(
        feature = "remote",
        feature = "config-bus",
        feature = "encryption",
        feature = "watch"
    ))]
    mod async_tests {
        use super::*;
        use crate::Lifecycle;

        struct AsyncComponent(TestComponent);

        #[async_trait::async_trait]
        impl crate::Lifecycle for AsyncComponent {
            async fn start(&self) -> Result<(), ConfigConfigError> {
                self.0
                    .started
                    .store(true, std::sync::atomic::Ordering::Release);
                Ok(())
            }
            async fn stop(&self) -> crate::ConfigResult<()> {
                self.0
                    .stopped
                    .store(true, std::sync::atomic::Ordering::Release);
                Ok(())
            }
        }

        #[tokio::test]
        async fn test_component_lifecycle_start_stop() {
            let comp = AsyncComponent(TestComponent::new());
            assert!(!comp.0.started.load(std::sync::atomic::Ordering::Acquire));
            comp.start().await.unwrap();
            assert!(comp.0.started.load(std::sync::atomic::Ordering::Acquire));
            comp.stop().await.unwrap();
            assert!(comp.0.stopped.load(std::sync::atomic::Ordering::Acquire));
        }

        #[tokio::test]
        async fn test_lifecycle_default_impl() {
            struct NoopComponent;
            #[async_trait::async_trait]
            impl crate::Lifecycle for NoopComponent {}

            let comp = NoopComponent;
            assert!(comp.start().await.is_ok());
            assert!(comp.stop().await.is_ok());
        }

        #[tokio::test]
        async fn test_registry_start_all_stop_all() {
            use super::super::async_impl::LifecycleRegistry;
            use std::sync::Arc;

            let mut reg = LifecycleRegistry::new();
            let c1 = Arc::new(AsyncComponent(TestComponent::new()));
            let c2 = Arc::new(AsyncComponent(TestComponent::new()));

            reg.register("comp1", c1.clone());
            reg.register("comp2", c2.clone());

            reg.start_all().await.unwrap();
            assert!(c1.0.started.load(std::sync::atomic::Ordering::Acquire));
            assert!(c2.0.started.load(std::sync::atomic::Ordering::Acquire));

            reg.stop_all().await.unwrap();
            assert!(c1.0.stopped.load(std::sync::atomic::Ordering::Acquire));
            assert!(c2.0.stopped.load(std::sync::atomic::Ordering::Acquire));
        }

        #[tokio::test]
        async fn test_registry_stop_reverse_order() {
            use super::super::async_impl::LifecycleRegistry;
            use std::sync::Arc;

            let order: Vec<&str> = Vec::new();
            let order = std::sync::Arc::new(std::sync::Mutex::new(order));

            struct OrderedComp {
                name: &'static str,
                order: Arc<std::sync::Mutex<Vec<&'static str>>>,
            }
            #[async_trait::async_trait]
            impl crate::Lifecycle for OrderedComp {
                async fn stop(&self) -> crate::ConfigResult<()> {
                    self.order.lock().unwrap().push(self.name);
                    Ok(())
                }
            }

            let mut reg = LifecycleRegistry::new();
            let c1 = Arc::new(OrderedComp {
                name: "a",
                order: order.clone(),
            });
            let c2 = Arc::new(OrderedComp {
                name: "b",
                order: order.clone(),
            });
            let c3 = Arc::new(OrderedComp {
                name: "c",
                order: order.clone(),
            });

            reg.register("c", c3);
            reg.register("b", c2);
            reg.register("a", c1);

            reg.start_all().await.unwrap();
            reg.stop_all().await.unwrap();
            let stopped_order = order.lock().unwrap().clone();
            assert_eq!(
                stopped_order,
                vec!["a", "b", "c"],
                "should stop in reverse registration order"
            );
        }

        #[tokio::test]
        async fn test_registry_empty() {
            use super::super::async_impl::LifecycleRegistry;
            let reg = LifecycleRegistry::new();
            assert!(reg.is_empty());
            reg.start_all().await.unwrap();
            reg.stop_all().await.unwrap();
        }

        /// Regression test for C-13: stop_all previously swallowed stop() errors
        /// via `let _ = c.1.stop().await;`. Verifies that:
        /// 1. stop_all returns Err when any component's stop() fails
        /// 2. ALL components are still stopped (no short-circuit), per ADR-041
        /// 3. The aggregated error message lists every failed component (Rule 12)
        #[tokio::test]
        async fn test_stop_all_aggregates_errors_and_stops_all() {
            use super::super::async_impl::LifecycleRegistry;
            use std::sync::Arc;

            struct FailingStop {
                name: &'static str,
                stopped: std::sync::atomic::AtomicBool,
                fail: bool,
            }
            #[async_trait::async_trait]
            impl crate::Lifecycle for FailingStop {
                async fn stop(&self) -> crate::ConfigResult<()> {
                    self.stopped
                        .store(true, std::sync::atomic::Ordering::Release);
                    if self.fail {
                        Err(crate::error::ConfigError::InvalidValue {
                            key: self.name.into(),
                            expected_type: "operational".into(),
                            message: format!("{} failed to flush", self.name),
                        })
                    } else {
                        Ok(())
                    }
                }
            }

            let mut reg = LifecycleRegistry::new();
            // Register 3 components: ok, fail, fail — reverse stop order will be fail, fail, ok
            let c_ok = Arc::new(FailingStop {
                name: "ok",
                stopped: std::sync::atomic::AtomicBool::new(false),
                fail: false,
            });
            let c_fail1 = Arc::new(FailingStop {
                name: "fail1",
                stopped: std::sync::atomic::AtomicBool::new(false),
                fail: true,
            });
            let c_fail2 = Arc::new(FailingStop {
                name: "fail2",
                stopped: std::sync::atomic::AtomicBool::new(false),
                fail: true,
            });
            reg.register("ok", c_ok.clone());
            reg.register("fail1", c_fail1.clone());
            reg.register("fail2", c_fail2.clone());

            let result = reg.stop_all().await;

            // Must return Err (Rule 12: Fail Loud)
            let err = result.expect_err("stop_all must return Err when components fail");

            // Error message must surface BOTH failures (not just the first)
            let msg = err.to_string();
            assert!(
                msg.contains("fail1"),
                "aggregated error must mention fail1; got: {}",
                msg
            );
            assert!(
                msg.contains("fail2"),
                "aggregated error must mention fail2; got: {}",
                msg
            );
            assert!(
                msg.contains("2 component(s)"),
                "error must report failure count; got: {}",
                msg
            );

            // ALL components must have been stopped despite failures (ADR-041)
            assert!(
                c_ok.stopped.load(std::sync::atomic::Ordering::Acquire),
                "ok component must still be stopped"
            );
            assert!(
                c_fail1.stopped.load(std::sync::atomic::Ordering::Acquire),
                "fail1 component must still be stopped"
            );
            assert!(
                c_fail2.stopped.load(std::sync::atomic::Ordering::Acquire),
                "fail2 component must still be stopped"
            );
        }
    }

    #[cfg(not(any(
        feature = "remote",
        feature = "config-bus",
        feature = "encryption",
        feature = "watch"
    )))]
    mod sync_tests {
        use super::*;
        // Bring the `Lifecycle` trait into scope so its `start()`/`stop()`
        // methods are callable on `SyncComponent` (which `impl`s the trait via
        // the fully-qualified `crate::Lifecycle` path). Without this import the
        // compiler reports E0599 "method not found" under default features.
        use crate::Lifecycle;

        struct SyncComponent(TestComponent);

        impl crate::Lifecycle for SyncComponent {
            fn start(&self) -> Result<(), ConfigConfigError> {
                self.0
                    .started
                    .store(true, std::sync::atomic::Ordering::Release);
                Ok(())
            }
            fn stop(&self) -> crate::ConfigResult<()> {
                self.0
                    .stopped
                    .store(true, std::sync::atomic::Ordering::Release);
                Ok(())
            }
        }

        #[test]
        fn test_component_lifecycle_start_stop() {
            let comp = SyncComponent(TestComponent::new());
            assert!(!comp.0.started.load(std::sync::atomic::Ordering::Acquire));
            comp.start().unwrap();
            assert!(comp.0.started.load(std::sync::atomic::Ordering::Acquire));
            comp.stop().unwrap();
            assert!(comp.0.stopped.load(std::sync::atomic::Ordering::Acquire));
        }

        #[test]
        fn test_registry_start_all_stop_all() {
            use crate::impl_::lifecycle::sync_impl::LifecycleRegistry;
            let mut reg = LifecycleRegistry::new();
            let c1 = Box::new(SyncComponent(TestComponent::new()));
            let c2 = Box::new(SyncComponent(TestComponent::new()));

            reg.register("comp1", c1);
            reg.register("comp2", c2);

            assert!(!reg.is_empty());
            reg.start_all().unwrap();
            reg.stop_all().unwrap();
        }

        /// Regression test for C-13 (sync variant): stop_all previously swallowed
        /// stop() errors via `let _ = c.1.stop();`. Verifies that:
        /// 1. stop_all returns Err when any component's stop() fails
        /// 2. ALL components are still stopped (no short-circuit), per ADR-041
        /// 3. The aggregated error message lists every failed component (Rule 12)
        #[test]
        fn test_stop_all_aggregates_errors_and_stops_all() {
            use crate::impl_::lifecycle::sync_impl::LifecycleRegistry;

            struct FailingStop {
                name: &'static str,
                stopped: std::sync::atomic::AtomicBool,
                fail: bool,
            }
            impl crate::Lifecycle for FailingStop {
                fn stop(&self) -> crate::ConfigResult<()> {
                    self.stopped
                        .store(true, std::sync::atomic::Ordering::Release);
                    if self.fail {
                        Err(crate::error::ConfigError::InvalidValue {
                            key: self.name.into(),
                            expected_type: "operational".into(),
                            message: format!("{} failed to flush", self.name),
                        })
                    } else {
                        Ok(())
                    }
                }
            }

            let mut reg = LifecycleRegistry::new();
            let c_ok = Box::new(FailingStop {
                name: "ok",
                stopped: std::sync::atomic::AtomicBool::new(false),
                fail: false,
            });
            let c_fail1 = Box::new(FailingStop {
                name: "fail1",
                stopped: std::sync::atomic::AtomicBool::new(false),
                fail: true,
            });
            let c_fail2 = Box::new(FailingStop {
                name: "fail2",
                stopped: std::sync::atomic::AtomicBool::new(false),
                fail: true,
            });
            reg.register("ok", c_ok);
            reg.register("fail1", c_fail1);
            reg.register("fail2", c_fail2);

            let result = reg.stop_all();

            let err = result.expect_err("stop_all must return Err when components fail");
            let msg = err.to_string();
            assert!(
                msg.contains("fail1"),
                "aggregated error must mention fail1; got: {}",
                msg
            );
            assert!(
                msg.contains("fail2"),
                "aggregated error must mention fail2; got: {}",
                msg
            );
            assert!(
                msg.contains("2 component(s)"),
                "error must report failure count; got: {}",
                msg
            );
        }
    }
}