cfgmatic-source 5.0.1

Configuration sources (file, env, memory) for cfgmatic framework
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
//! Source coordinator for managing multiple configuration sources.
//!
//! This module provides the [`SourceCoordinator`] service which coordinates
//! multiple configuration sources with priorities and merge strategies.
//!
//! # Example
//!
//! ```rust,no_run
//! use cfgmatic_source::application::SourceCoordinator;
//! use cfgmatic_source::infrastructure::MemorySource;
//!
//! let mut coordinator = SourceCoordinator::builder()
//!     .add_source(MemorySource::builder().set("host", "localhost").build(), 10)
//!     .add_source(MemorySource::builder().set("port", "8080").build(), 20)
//!     .build();
//!
//! let result = coordinator.load()?;
//! assert_eq!(result.loaded_count(), 2);
//! # Ok::<(), cfgmatic_source::SourceError>(())
//! ```

mod builder;
mod entry;
mod loading;
mod result;

use std::collections::BTreeMap;

use super::support::{elapsed_millis_u64, to_tracked_layer};
pub use builder::SourceCoordinatorBuilder;
use entry::SourceEntry;
use loading::LayerCollection;
pub use result::{LoadReport, LoadResult, SourceLayer};
use serde::de::DeserializeOwned;

use crate::config::LoadOptions;
use crate::domain::{ParsedContent, Result, Source, SourceError};

/// Service for coordinating multiple configuration sources.
///
/// The `SourceCoordinator` manages multiple sources, loads them according
/// to their priorities, and merges the results.
#[derive(Default)]
pub struct SourceCoordinator {
    /// Registered sources with their priorities.
    pub(super) sources: Vec<SourceEntry>,

    /// Loading options.
    pub(super) options: LoadOptions,

    /// Cache for loaded content.
    pub(super) cache: BTreeMap<String, ParsedContent>,
}

impl SourceCoordinator {
    /// Create a new empty coordinator.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a builder for constructing a `SourceCoordinator`.
    #[must_use]
    pub fn builder() -> SourceCoordinatorBuilder {
        SourceCoordinatorBuilder::new()
    }

    /// Add a source with a priority.
    ///
    /// Higher priority sources override lower priority ones.
    pub fn add_source<S: Source + 'static>(&mut self, source: S, priority: i32) -> &mut Self {
        let entry = SourceEntry {
            source: Box::new(source),
            priority,
            order: self.sources.len(),
        };
        self.sources.push(entry);
        self
    }

    /// Get the number of registered sources.
    #[must_use]
    pub const fn source_count(&self) -> usize {
        self.sources.len()
    }

    /// Check if there are any sources registered.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.sources.is_empty()
    }

    /// Clear all sources.
    pub fn clear(&mut self) {
        self.sources.clear();
        self.cache.clear();
    }

    /// Clear the cache.
    pub fn clear_cache(&mut self) {
        self.cache.clear();
    }

    /// Collect parsed layers from all registered sources.
    ///
    /// Layers are returned in merge application order.
    ///
    /// # Errors
    ///
    /// Returns an error if a required source fails and `fail_fast` is enabled.
    pub fn collect_layers(&mut self) -> Result<Vec<SourceLayer>> {
        loading::collect_loaded_layers(&self.sources, &self.options, &mut self.cache)
            .map(|collection| collection.layers)
    }

    /// Load configuration from all sources and return the canonical report.
    ///
    /// # Errors
    ///
    /// Returns an error if a required source fails and `fail_fast` is enabled.
    pub fn load_report(&mut self) -> Result<LoadReport> {
        let start = std::time::Instant::now();
        let LayerCollection {
            layers,
            loaded_sources,
            failed_sources,
            loaded_count,
        } = loading::collect_loaded_layers(&self.sources, &self.options, &mut self.cache)?;

        if layers.is_empty() && !failed_sources.is_empty() {
            let error_messages: Vec<String> = failed_sources
                .iter()
                .map(|(name, error)| format!("{name}: {error}"))
                .collect();
            return Err(SourceError::custom(&error_messages.join(", ")));
        }

        let tracked_layers: Vec<_> = layers.iter().map(to_tracked_layer).collect::<Result<_>>()?;
        let merge_report = cfgmatic_merge::merge_layers_with_report(
            &tracked_layers,
            &super::support::merge_options(self.options.merge_strategy),
        )
        .map_err(|error| SourceError::custom(&error.to_string()))?;
        let merged = ParsedContent::from_json(merge_report.merged.clone());

        Ok(LoadReport {
            layers,
            merged,
            merge_report,
            loaded_count,
            loaded_sources,
            failed_sources,
            processing_time_ms: elapsed_millis_u64(start),
        })
    }

    /// Load configuration from all sources.
    ///
    /// This is a lightweight compatibility wrapper over [`Self::load_report`].
    ///
    /// # Errors
    ///
    /// Returns an error if loading fails.
    pub fn load(&mut self) -> Result<LoadResult> {
        self.load_report().map(LoadReport::into_load_result)
    }

    /// Load and convert to a specific type.
    ///
    /// # Errors
    ///
    /// Returns an error if loading or deserialization fails.
    pub fn load_as<T: DeserializeOwned>(&mut self) -> Result<T> {
        self.load_report()?.to_type()
    }

    /// Reload all sources, clearing the cache.
    ///
    /// # Errors
    ///
    /// Returns an error if loading fails.
    pub fn reload(&mut self) -> Result<LoadResult> {
        self.clear_cache();
        self.load()
    }

    /// Reload all sources and return the canonical report.
    ///
    /// # Errors
    ///
    /// Returns an error if loading fails.
    pub fn reload_report(&mut self) -> Result<LoadReport> {
        self.clear_cache();
        self.load_report()
    }
}

impl std::fmt::Debug for SourceCoordinator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SourceCoordinator")
            .field("source_count", &self.sources.len())
            .field("options", &self.options)
            .field("cache_entries", &self.cache.len())
            .finish()
    }
}

#[cfg(feature = "async")]
#[allow(clippy::wildcard_imports, clippy::unused_async)]
mod async_impl {
    use super::*;

    impl SourceCoordinator {
        /// Load configuration from all sources asynchronously.
        ///
        /// # Errors
        ///
        /// Returns an error if a required source fails and `fail_fast` is enabled.
        pub async fn load_async(&mut self) -> Result<LoadResult> {
            self.load()
        }

        /// Load configuration asynchronously and return a report.
        ///
        /// # Errors
        ///
        /// Returns an error if loading fails.
        pub async fn load_report_async(&mut self) -> Result<LoadReport> {
            self.load_report()
        }
    }
}

#[cfg(test)]
#[allow(clippy::wildcard_imports, clippy::unused_async, dead_code)]
mod tests {
    use std::fs;

    use super::*;
    use crate::config::MergeStrategy;
    use crate::domain::{Format, RawContent, SourceKind, SourceMetadata};
    #[cfg(feature = "file")]
    use crate::infrastructure::FileSource;
    #[cfg(feature = "file")]
    use tempfile::tempdir;

    struct TestSource {
        content: String,
        format: Format,
        optional: bool,
        name: String,
    }

    impl TestSource {
        fn new(name: &str, content: &str, format: Format) -> Self {
            Self {
                name: name.to_string(),
                content: content.to_string(),
                format,
                optional: false,
            }
        }

        fn with_optional(mut self, optional: bool) -> Self {
            self.optional = optional;
            self
        }
    }

    impl Source for TestSource {
        fn kind(&self) -> SourceKind {
            SourceKind::Memory
        }

        fn metadata(&self) -> SourceMetadata {
            SourceMetadata::new(&self.name)
        }

        fn load_raw(&self) -> Result<RawContent> {
            Ok(RawContent::from_string(&self.content))
        }

        fn detect_format(&self) -> Option<Format> {
            if self.format == Format::Unknown {
                None
            } else {
                Some(self.format)
            }
        }

        fn is_optional(&self) -> bool {
            self.optional
        }
    }

    #[test]
    fn test_load_result_new() {
        let result = LoadResult::new(ParsedContent::Null);
        assert!(result.content().is_null());
        assert_eq!(result.loaded_count(), 0);
        assert!(!result.has_failures());
    }

    #[test]
    fn test_source_coordinator_new() {
        let coordinator = SourceCoordinator::new();
        assert!(coordinator.is_empty());
        assert_eq!(coordinator.source_count(), 0);
    }

    #[test]
    fn test_source_coordinator_builder() {
        let coordinator = SourceCoordinator::builder()
            .merge_strategy(MergeStrategy::Deep)
            .fail_fast(false)
            .cache_enabled(false)
            .build();

        assert_eq!(coordinator.source_count(), 0);
        assert!(!coordinator.options.is_cache_enabled());
    }

    #[test]
    fn test_source_coordinator_add_source() {
        let source = TestSource::new("test", r#"{"key": "value"}"#, Format::Json);
        let mut coordinator = SourceCoordinator::new();

        coordinator.add_source(source, 10);
        assert_eq!(coordinator.source_count(), 1);
    }

    #[test]
    fn test_source_coordinator_load_single() {
        let source = TestSource::new("test", r#"{"key": "value"}"#, Format::Json);
        let mut coordinator = SourceCoordinator::builder().add_source(source, 10).build();

        let result = coordinator.load().unwrap();
        assert!(result.content().is_object());
        assert_eq!(result.loaded_count(), 1);
        assert!(!result.has_failures());
    }

    #[test]
    fn test_source_coordinator_load_multiple() {
        let source1 = TestSource::new("low", r#"{"a": 1}"#, Format::Json);
        let source2 = TestSource::new("high", r#"{"b": 2}"#, Format::Json);

        let mut coordinator = SourceCoordinator::builder()
            .add_source(source1, 1)
            .add_source(source2, 10)
            .merge_strategy(MergeStrategy::Deep)
            .build();

        let result = coordinator.load().unwrap();
        assert!(result.content().get("a").is_some());
        assert!(result.content().get("b").is_some());
    }

    #[test]
    fn test_source_coordinator_collect_layers_orders_by_priority_then_registration() {
        let source1 = TestSource::new("later-low", r#"{"name": "low"}"#, Format::Json);
        let source2 = TestSource::new("high", r#"{"name": "high"}"#, Format::Json);
        let source3 = TestSource::new("later-high", r#"{"name": "later-high"}"#, Format::Json);

        let mut coordinator = SourceCoordinator::builder()
            .add_source(source1, 1)
            .add_source(source2, 10)
            .add_source(source3, 10)
            .build();

        let layers = coordinator.collect_layers().unwrap();

        assert_eq!(layers.len(), 3);
        assert_eq!(layers[0].registration_index, 0);
        assert_eq!(layers[1].registration_index, 1);
        assert_eq!(layers[2].registration_index, 2);
        assert_eq!(layers[0].priority, 1);
        assert_eq!(layers[1].priority, 10);
        assert_eq!(layers[2].priority, 10);
    }

    #[test]
    fn test_source_coordinator_collect_layers_skips_optional_missing_like_load_report() {
        let required = TestSource::new("required", r#"{"a": 1}"#, Format::Json);
        let optional = TestSource::new("optional", r"invalid", Format::Unknown).with_optional(true);

        let mut coordinator = SourceCoordinator::builder()
            .add_source(required, 1)
            .add_source(optional, 2)
            .fail_fast(false)
            .build();

        let layers = coordinator.collect_layers().unwrap();

        assert_eq!(layers.len(), 1);
        assert_eq!(layers[0].content.get("a").unwrap().as_integer(), Some(1));
    }

    #[test]
    fn test_source_coordinator_collect_layers_preserves_negative_priority() {
        let source1 = TestSource::new("low", r#"{"value": "low"}"#, Format::Json);
        let source2 = TestSource::new("default", r#"{"value": "mid"}"#, Format::Json);
        let source3 = TestSource::new("high", r#"{"value": "high"}"#, Format::Json);

        let mut coordinator = SourceCoordinator::builder()
            .add_source(source2, 0)
            .add_source(source3, 10)
            .add_source(source1, -10)
            .build();

        let layers = coordinator.collect_layers().unwrap();

        assert_eq!(
            layers
                .iter()
                .map(|layer| layer.priority)
                .collect::<Vec<_>>(),
            vec![-10, 0, 10]
        );
    }

    #[test]
    fn test_source_coordinator_priority() {
        let source1 = TestSource::new("low", r#"{"key": "low"}"#, Format::Json);
        let source2 = TestSource::new("high", r#"{"key": "high"}"#, Format::Json);

        let mut coordinator = SourceCoordinator::builder()
            .add_source(source1, 1)
            .add_source(source2, 10)
            .merge_strategy(MergeStrategy::Deep)
            .build();

        let result = coordinator.load().unwrap();
        assert_eq!(result.content().get("key").unwrap().as_str(), Some("high"));
    }

    #[test]
    fn test_source_coordinator_load_report_exposes_merge_details() {
        let source1 = TestSource::new("defaults", r#"{"server":{"port":8080}}"#, Format::Json);
        let source2 = TestSource::new("env", r#"{"server":{"port":9090}}"#, Format::Json);

        let mut coordinator = SourceCoordinator::builder()
            .add_source(source1, 1)
            .add_source(source2, 10)
            .merge_strategy(MergeStrategy::Deep)
            .build();

        let report = coordinator.load_report().unwrap();
        let explanation = report.merge_report.explain_path("/server/port").unwrap();

        assert_eq!(report.loaded_count, 2);
        assert_eq!(report.layers.len(), 2);
        assert_eq!(
            report
                .merged
                .get("server")
                .unwrap()
                .get("port")
                .unwrap()
                .as_integer(),
            Some(9090)
        );
        assert_eq!(explanation.winner.unwrap().source, "env");
    }

    #[test]
    fn test_source_coordinator_optional_source() {
        let required =
            TestSource::new("required", r#"{"a": 1}"#, Format::Json).with_optional(false);
        let optional = TestSource::new("optional", r"invalid", Format::Unknown).with_optional(true);

        let mut coordinator = SourceCoordinator::builder()
            .add_source(required, 1)
            .add_source(optional, 2)
            .build();

        let result = coordinator.load().unwrap();
        assert!(result.content().get("a").is_some());
    }

    #[test]
    fn test_source_coordinator_cache() {
        let source = TestSource::new("test", r#"{"key": "value"}"#, Format::Json);
        let mut coordinator = SourceCoordinator::builder()
            .add_source(source, 10)
            .cache_enabled(true)
            .build();

        let result1 = coordinator.load().unwrap();
        assert_eq!(result1.loaded_count(), 1);

        let result2 = coordinator.load().unwrap();
        assert_eq!(result2.loaded_count(), 1);
    }

    #[test]
    fn test_source_coordinator_clear_cache() {
        let source = TestSource::new("test", r#"{"key": "value"}"#, Format::Json);
        let mut coordinator = SourceCoordinator::builder()
            .add_source(source, 10)
            .cache_enabled(true)
            .build();

        coordinator.load().unwrap();
        coordinator.clear_cache();
        assert!(coordinator.cache.is_empty());
    }

    #[test]
    fn test_source_coordinator_reload() {
        let source = TestSource::new("test", r#"{"key": "value"}"#, Format::Json);
        let mut coordinator = SourceCoordinator::builder()
            .add_source(source, 10)
            .cache_enabled(true)
            .build();

        coordinator.load().unwrap();
        let result = coordinator.reload().unwrap();
        assert_eq!(result.loaded_count(), 1);
    }

    #[cfg(feature = "file")]
    #[test]
    fn test_source_coordinator_cache_uses_source_identity() {
        let temp_dir = tempdir().unwrap();
        let first = temp_dir.path().join("first.json");
        let second = temp_dir.path().join("second.json");

        fs::write(&first, r#"{"first": 1}"#).unwrap();
        fs::write(&second, r#"{"second": 2}"#).unwrap();

        let mut coordinator = SourceCoordinator::builder()
            .add_source(FileSource::new(&first), 1)
            .add_source(FileSource::new(&second), 2)
            .cache_enabled(true)
            .merge_strategy(MergeStrategy::Deep)
            .build();

        let result = coordinator.load().unwrap();

        assert_eq!(result.content().get("first").unwrap().as_integer(), Some(1));
        assert_eq!(
            result.content().get("second").unwrap().as_integer(),
            Some(2)
        );
    }

    #[test]
    fn test_source_coordinator_to_type() {
        use serde::Deserialize;

        #[derive(Debug, Deserialize, PartialEq)]
        struct Config {
            key: String,
        }

        let source = TestSource::new("test", r#"{"key": "value"}"#, Format::Json);
        let mut coordinator = SourceCoordinator::builder().add_source(source, 10).build();

        let config: Config = coordinator.load_as().unwrap();
        assert_eq!(config.key, "value");
    }

    #[test]
    fn test_source_coordinator_empty() {
        let mut coordinator = SourceCoordinator::new();
        let result = coordinator.load().unwrap();
        assert!(result.content().is_null());
    }

    #[test]
    fn test_source_coordinator_clear() {
        let source = TestSource::new("test", r#"{"key": "value"}"#, Format::Json);
        let mut coordinator = SourceCoordinator::builder().add_source(source, 10).build();

        assert_eq!(coordinator.source_count(), 1);

        coordinator.clear();
        assert!(coordinator.is_empty());
    }

    #[test]
    fn test_load_result_to_type() {
        use serde::Deserialize;

        #[derive(Debug, Deserialize, PartialEq)]
        struct Config {
            key: String,
        }

        let result = LoadResult {
            content: ParsedContent::Object(
                std::iter::once((
                    "key".to_string(),
                    ParsedContent::String("value".to_string()),
                ))
                .collect(),
            ),
            loaded_count: 1,
            loaded_sources: vec!["test".to_string()],
            failed_sources: Vec::new(),
            processing_time_ms: 0,
        };

        let config: Config = result.to_type().unwrap();
        assert_eq!(config.key, "value");
    }
}