cfgmatic-source 2.2.0

Configuration sources (file, env, remote) 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
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
//! 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,ignore
//! use cfgmatic_source::application::SourceCoordinator;
//! use cfgmatic_source::infrastructure::{FileSource, EnvSource};
//!
//! let coordinator = SourceCoordinator::builder()
//!     .add_source(file_source, 10)
//!     .add_source(env_source, 20)
//!     .build();
//!
//! let result = coordinator.load()?;
//! println!("Loaded from {} sources", result.loaded_count());
//! ```

use std::collections::BTreeMap;

use serde::de::DeserializeOwned;

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

/// Result of loading configuration from multiple sources.
#[derive(Debug, Clone)]
pub struct LoadResult {
    /// Merged configuration content.
    pub content: ParsedContent,

    /// Number of sources that were successfully loaded.
    pub loaded_count: usize,

    /// Names of sources that were loaded.
    pub loaded_sources: Vec<String>,

    /// Names of sources that failed (if not fail-fast).
    pub failed_sources: Vec<(String, String)>,

    /// Total processing time in milliseconds.
    pub processing_time_ms: u64,
}

impl LoadResult {
    /// Create a new load result.
    #[must_use]
    pub fn new(content: ParsedContent) -> Self {
        Self {
            content,
            loaded_count: 0,
            loaded_sources: Vec::new(),
            failed_sources: Vec::new(),
            processing_time_ms: 0,
        }
    }

    /// Get the merged configuration content.
    #[must_use]
    pub fn content(&self) -> &ParsedContent {
        &self.content
    }

    /// Get the number of successfully loaded sources.
    #[must_use]
    pub fn loaded_count(&self) -> usize {
        self.loaded_count
    }

    /// Check if any sources failed.
    #[must_use]
    pub fn has_failures(&self) -> bool {
        !self.failed_sources.is_empty()
    }

    /// Convert to a specific type.
    ///
    /// # Errors
    ///
    /// Returns an error if deserialization fails.
    pub fn to_type<T: DeserializeOwned>(&self) -> Result<T> {
        self.content.to_type()
    }
}

/// A boxed source with its priority.
type BoxedSource = Box<dyn Source>;

/// Entry in the source registry.
struct SourceEntry {
    source: BoxedSource,
    priority: i32,
    order: usize,
}

impl std::fmt::Debug for SourceEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SourceEntry")
            .field("priority", &self.priority)
            .field("order", &self.order)
            .field("display_name", &self.source.display_name())
            .finish()
    }
}

/// Service for coordinating multiple configuration sources.
///
/// The SourceCoordinator manages multiple sources, loads them according
/// to their priorities, and merges the results.
pub struct SourceCoordinator {
    /// Registered sources with their priorities.
    sources: Vec<SourceEntry>,

    /// Loading options.
    options: LoadOptions,

    /// Cache for loaded content.
    cache: BTreeMap<String, ParsedContent>,

    /// Whether caching is enabled.
    cache_enabled: bool,
}

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 fn source_count(&self) -> usize {
        self.sources.len()
    }

    /// Check if there are any sources registered.
    #[must_use]
    pub 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();
    }

    /// Load configuration from all sources.
    ///
    /// Sources are loaded in priority order (highest first) and merged.
    ///
    /// # Errors
    ///
    /// Returns an error if a required source fails and fail_fast is enabled.
    pub fn load(&mut self) -> Result<LoadResult> {
        let start = std::time::Instant::now();

        // Sort sources by priority (descending)
        let mut sorted_sources: Vec<_> = self.sources.iter().collect();
        sorted_sources.sort_by(|a, b| {
            b.priority
                .cmp(&a.priority)
                .then_with(|| a.order.cmp(&b.order))
        });

        let mut contents = Vec::new();
        let mut loaded_sources = Vec::new();
        let mut failed_sources = Vec::new();
        let mut loaded_count = 0;

        for entry in sorted_sources {
            let name = entry.source.display_name();

            // Check cache first
            if self.cache_enabled {
                if let Some(cached) = self.cache.get(&name) {
                    contents.push(cached.clone());
                    loaded_sources.push(name.clone());
                    loaded_count += 1;
                    continue;
                }
            }

            // Load from source
            match self.load_source(&*entry.source) {
                Ok(content) => {
                    if self.cache_enabled {
                        self.cache.insert(name.clone(), content.clone());
                    }
                    contents.push(content);
                    loaded_sources.push(name.clone());
                    loaded_count += 1;
                }
                Err(e) => {
                    if entry.source.is_optional() && self.options.ignore_optional_missing {
                        continue;
                    }
                    if self.options.fail_fast {
                        return Err(e);
                    }
                    failed_sources.push((name, e.to_string()));
                }
            }
        }

        // Check if all sources failed
        if contents.is_empty() && !failed_sources.is_empty() {
            let error_messages: Vec<String> = failed_sources
                .iter()
                .map(|(name, e)| format!("{}: {}", name, e))
                .collect();
            return Err(SourceError::custom(&error_messages.join(", ")));
        }

        // Merge contents
        let merged = self.merge_contents(contents);

        Ok(LoadResult {
            content: merged,
            loaded_count,
            loaded_sources,
            failed_sources,
            processing_time_ms: start.elapsed().as_millis() as u64,
        })
    }

    /// Load from a single source.
    fn load_source(&self, source: &dyn Source) -> Result<ParsedContent> {
        source.validate()?;
        let raw = source.load_raw()?;

        // Try to detect format
        let format = source.detect_format();
        if let Some(fmt) = format {
            let content = raw.as_str()?;
            return fmt.parse(content.as_ref());
        }

        // Try to detect from content
        let content = raw.as_str()?;
        if let Some(fmt) = crate::domain::Format::from_content(content.as_ref()) {
            return fmt.parse(content.as_ref());
        }

        Err(SourceError::unsupported("cannot detect format"))
    }

    /// Merge multiple contents according to the merge strategy.
    fn merge_contents(&self, contents: Vec<ParsedContent>) -> ParsedContent {
        if contents.is_empty() {
            return ParsedContent::Null;
        }

        let strategy = self.options.merge_strategy;

        contents
            .into_iter()
            .reduce(|acc, content| match strategy {
                MergeStrategy::Replace => content,
                MergeStrategy::Deep | MergeStrategy::Shallow | MergeStrategy::Strict => {
                    acc.merge(&content)
                }
            })
            .unwrap_or(ParsedContent::Null)
    }

    /// 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> {
        let result = self.load()?;
        result.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()
    }
}

impl Default for SourceCoordinator {
    fn default() -> Self {
        Self {
            sources: Vec::new(),
            options: LoadOptions::default(),
            cache: BTreeMap::new(),
            cache_enabled: true,
        }
    }
}

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_enabled", &self.cache_enabled)
            .finish()
    }
}

/// Builder for [`SourceCoordinator`].
#[derive(Default)]
pub struct SourceCoordinatorBuilder {
    sources: Vec<SourceEntry>,
    options: Option<LoadOptions>,
    cache_enabled: Option<bool>,
}

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

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

    /// Set the load options.
    #[must_use]
    pub fn options(mut self, options: LoadOptions) -> Self {
        self.options = Some(options);
        self
    }

    /// Set the merge strategy.
    #[must_use]
    pub fn merge_strategy(mut self, strategy: MergeStrategy) -> Self {
        let mut options = self.options.unwrap_or_default();
        options.merge_strategy = strategy;
        self.options = Some(options);
        self
    }

    /// Set whether to fail fast on errors.
    #[must_use]
    pub fn fail_fast(mut self, fail_fast: bool) -> Self {
        let mut options = self.options.unwrap_or_default();
        options.fail_fast = fail_fast;
        self.options = Some(options);
        self
    }

    /// Set whether to enable caching.
    #[must_use]
    pub fn cache_enabled(mut self, enabled: bool) -> Self {
        self.cache_enabled = Some(enabled);
        self
    }

    /// Build the SourceCoordinator.
    #[must_use]
    pub fn build(self) -> SourceCoordinator {
        SourceCoordinator {
            sources: self.sources,
            options: self.options.unwrap_or_default(),
            cache: BTreeMap::new(),
            cache_enabled: self.cache_enabled.unwrap_or(true),
        }
    }
}

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

#[cfg(feature = "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> {
            // Async implementation would use tokio::spawn for parallel loading
            // This is a placeholder that delegates to sync version
            self.load()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::{Format, RawContent, SourceKind, SourceMetadata};

    /// Test source implementation.
    struct TestSource {
        content: String,
        format: Format,
        optional: bool,
        name: String,
        priority_val: i32,
    }

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

        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.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_priority() {
        // Higher priority should override lower priority values
        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();
        // Higher priority source is applied last, so it wins
        assert_eq!(result.content().get("key").unwrap().as_str(), Some("high"));
    }

    #[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();

        // Should succeed because optional source failure is ignored
        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();

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

        // Second load should use cache
        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();
        // Cache should be cleared
        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();

        // First load
        coordinator.load().unwrap();

        // Reload should clear cache and reload
        let result = coordinator.reload().unwrap();
        assert_eq!(result.loaded_count(), 1);
    }

    #[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();

        // Loading empty coordinator should return Null
        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 mut obj = std::collections::BTreeMap::new();
        obj.insert(
            "key".to_string(),
            ParsedContent::String("value".to_string()),
        );
        let content = ParsedContent::Object(obj);

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