hexcfg 1.1.4

A hexagonal architecture configuration loading crate with multi-source support
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
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Default configuration service implementation.
//!
//! This module provides the default implementation of the `ConfigurationService`
//! trait, which aggregates multiple configuration sources and provides a unified
//! interface for accessing configuration values.

use crate::domain::{ConfigError, ConfigKey, ConfigValue, ConfigurationService, Result};
use crate::ports::{ConfigSource, ConfigWatcher};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

/// Default implementation of the configuration service.
///
/// This service manages multiple configuration sources and queries them in priority
/// order to resolve configuration values. Sources with higher priority values are
/// queried first, and the first value found is returned.
///
/// # Examples
///
/// ```rust
/// use hexcfg::prelude::*;
/// use hexcfg::service::DefaultConfigService;
///
/// # fn main() -> Result<()> {
/// // Create a service with environment variables
/// let service = DefaultConfigService::builder()
///     .with_env_vars()
///     .build()?;
///
/// // Or use the default configuration (env + yaml if available)
/// let service = DefaultConfigService::with_defaults("myapp", "com.example")?;
/// # Ok(())
/// # }
/// ```
pub struct DefaultConfigService {
    /// List of configuration sources, maintained in priority order (highest first)
    sources: Vec<Box<dyn ConfigSource>>,
    /// Cache for configuration values
    cache: Arc<RwLock<HashMap<String, ConfigValue>>>,
    /// List of registered watchers
    watchers: Vec<Box<dyn ConfigWatcher>>,
}

impl DefaultConfigService {
    /// Creates a new empty configuration service.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hexcfg::service::DefaultConfigService;
    ///
    /// let service = DefaultConfigService::new();
    /// ```
    pub fn new() -> Self {
        Self {
            sources: Vec::new(),
            cache: Arc::new(RwLock::new(HashMap::new())),
            watchers: Vec::new(),
        }
    }

    /// Creates a new configuration service builder.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hexcfg::service::DefaultConfigService;
    ///
    /// # fn main() -> hexcfg::domain::Result<()> {
    /// let service = DefaultConfigService::builder()
    ///     .with_env_vars()
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn builder() -> ConfigurationServiceBuilder {
        ConfigurationServiceBuilder::new()
    }

    /// Creates a configuration service with default sources.
    ///
    /// This includes environment variables and a YAML file from the default
    /// OS-appropriate location. If the YAML file doesn't exist, only environment
    /// variables will be used.
    ///
    /// # Arguments
    ///
    /// * `app_name` - The application name
    /// * `qualifier` - The organization/qualifier (e.g., "com.example")
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use hexcfg::service::DefaultConfigService;
    ///
    /// # fn main() -> hexcfg::domain::Result<()> {
    /// let service = DefaultConfigService::with_defaults("myapp", "com.example")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_defaults(app_name: &str, qualifier: &str) -> Result<Self> {
        let mut builder = Self::builder();

        // Always add environment variables
        #[cfg(feature = "env")]
        {
            builder = builder.with_env_vars();
        }

        // Try to add YAML file from default location
        #[cfg(feature = "yaml")]
        {
            use crate::adapters::YamlFileAdapter;
            if let Ok(adapter) = YamlFileAdapter::from_default_location(app_name, qualifier) {
                builder = builder.with_source(Box::new(adapter));
            }
        }

        builder.build()
    }

    /// Adds a configuration source to the service.
    ///
    /// Sources are automatically sorted by priority after being added.
    pub fn add_source(&mut self, source: Box<dyn ConfigSource>) {
        self.sources.push(source);
        self.sort_sources();
        self.invalidate_cache();
    }

    /// Sorts sources by priority (highest first).
    fn sort_sources(&mut self) {
        self.sources
            .sort_by_key(|b| std::cmp::Reverse(b.priority()));
    }

    /// Invalidates the cache.
    fn invalidate_cache(&self) {
        if let Ok(mut cache) = self.cache.write() {
            cache.clear();
        }
    }

    /// Queries all sources for a configuration value, respecting priority order.
    fn query_sources(&self, key: &ConfigKey) -> Result<Option<ConfigValue>> {
        for source in &self.sources {
            match source.get(key) {
                Ok(Some(value)) => return Ok(Some(value)),
                Ok(None) => continue,
                Err(e) => {
                    // Log the error but continue to next source
                    tracing::debug!(
                        "Error querying source '{}' for key '{}': {}",
                        source.name(),
                        key,
                        e
                    );
                    continue;
                }
            }
        }
        Ok(None)
    }
}

impl Default for DefaultConfigService {
    fn default() -> Self {
        Self::new()
    }
}

impl ConfigurationService for DefaultConfigService {
    fn get(&self, key: &ConfigKey) -> Result<ConfigValue> {
        // Check cache first
        if let Ok(cache) = self.cache.read() {
            if let Some(value) = cache.get(key.as_str()) {
                return Ok(value.clone());
            }
        }

        // Query sources
        let value = self
            .query_sources(key)?
            .ok_or_else(|| ConfigError::ConfigKeyNotFound {
                key: key.as_str().to_string(),
            })?;

        // Update cache
        if let Ok(mut cache) = self.cache.write() {
            cache.insert(key.as_str().to_string(), value.clone());
        }

        Ok(value)
    }

    fn get_or_default(&self, key: &ConfigKey, default: &str) -> ConfigValue {
        self.get(key).unwrap_or_else(|_| ConfigValue::from(default))
    }

    fn has(&self, key: &ConfigKey) -> bool {
        self.get(key).is_ok()
    }

    fn reload(&mut self) -> Result<()> {
        // Reload all sources
        for source in &mut self.sources {
            if let Err(e) = source.reload() {
                tracing::warn!("Failed to reload source '{}': {}", source.name(), e);
            }
        }

        // Invalidate cache after reloading
        self.invalidate_cache();

        Ok(())
    }

    fn register_watcher(&mut self, watcher: Box<dyn ConfigWatcher>) -> Result<()> {
        self.watchers.push(watcher);
        Ok(())
    }
}

/// Builder for constructing a `DefaultConfigService`.
///
/// This builder provides a fluent interface for configuring and creating
/// a configuration service with multiple sources.
///
/// # Examples
///
/// ```rust
/// use hexcfg::service::ConfigurationServiceBuilder;
///
/// # fn main() -> hexcfg::domain::Result<()> {
/// let service = ConfigurationServiceBuilder::new()
///     .with_env_vars()
///     .build()?;
/// # Ok(())
/// # }
/// ```
pub struct ConfigurationServiceBuilder {
    sources: Vec<Box<dyn ConfigSource>>,
}

impl ConfigurationServiceBuilder {
    /// Creates a new builder.
    pub fn new() -> Self {
        Self {
            sources: Vec::new(),
        }
    }

    /// Adds a configuration source to the builder.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hexcfg::service::ConfigurationServiceBuilder;
    /// use hexcfg::adapters::EnvVarAdapter;
    ///
    /// # fn main() -> hexcfg::domain::Result<()> {
    /// let service = ConfigurationServiceBuilder::new()
    ///     .with_source(Box::new(EnvVarAdapter::new()))
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_source(mut self, source: Box<dyn ConfigSource>) -> Self {
        self.sources.push(source);
        self
    }

    /// Adds environment variables as a configuration source.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hexcfg::service::ConfigurationServiceBuilder;
    ///
    /// # fn main() -> hexcfg::domain::Result<()> {
    /// let service = ConfigurationServiceBuilder::new()
    ///     .with_env_vars()
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "env")]
    pub fn with_env_vars(self) -> Self {
        use crate::adapters::EnvVarAdapter;
        self.with_source(Box::new(EnvVarAdapter::new().lowercase_keys(true)))
    }

    /// Adds environment variables with a prefix as a configuration source.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hexcfg::service::ConfigurationServiceBuilder;
    ///
    /// # fn main() -> hexcfg::domain::Result<()> {
    /// let service = ConfigurationServiceBuilder::new()
    ///     .with_env_prefix("MYAPP_")
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "env")]
    pub fn with_env_prefix(self, prefix: impl Into<String>) -> Self {
        use crate::adapters::EnvVarAdapter;
        self.with_source(Box::new(
            EnvVarAdapter::with_prefix(prefix).lowercase_keys(true),
        ))
    }

    /// Adds command-line arguments as a configuration source.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hexcfg::service::ConfigurationServiceBuilder;
    ///
    /// # fn main() -> hexcfg::domain::Result<()> {
    /// let args = vec!["--key", "value"];
    /// let service = ConfigurationServiceBuilder::new()
    ///     .with_cli_args(args)
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "cli")]
    pub fn with_cli_args<S: AsRef<str>>(self, args: Vec<S>) -> Self {
        use crate::adapters::CommandLineAdapter;
        self.with_source(Box::new(CommandLineAdapter::from_args(args)))
    }

    /// Adds a YAML file as a configuration source.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use hexcfg::service::ConfigurationServiceBuilder;
    ///
    /// # fn main() -> hexcfg::domain::Result<()> {
    /// let service = ConfigurationServiceBuilder::new()
    ///     .with_yaml_file("/etc/myapp/config.yaml")?
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "yaml")]
    pub fn with_yaml_file(self, path: impl AsRef<std::path::Path>) -> Result<Self> {
        use crate::adapters::YamlFileAdapter;
        let adapter = YamlFileAdapter::from_file(path)?;
        Ok(self.with_source(Box::new(adapter)))
    }

    /// Adds etcd as a configuration source.
    ///
    /// # Arguments
    ///
    /// * `endpoints` - List of etcd endpoints (e.g., `vec!["localhost:2379"]`)
    /// * `prefix` - Optional key prefix for namespacing
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use hexcfg::service::ConfigurationServiceBuilder;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> hexcfg::domain::Result<()> {
    /// let service = ConfigurationServiceBuilder::new()
    ///     .with_etcd(vec!["localhost:2379"], Some("myapp/")).await?
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "etcd")]
    pub async fn with_etcd<S: AsRef<str>>(
        self,
        endpoints: Vec<S>,
        prefix: Option<&str>,
    ) -> Result<Self> {
        use crate::adapters::EtcdAdapter;
        let adapter = EtcdAdapter::new(endpoints, prefix).await?;
        Ok(self.with_source(Box::new(adapter)))
    }

    /// Adds etcd as a configuration source with custom priority.
    ///
    /// # Arguments
    ///
    /// * `endpoints` - List of etcd endpoints
    /// * `prefix` - Optional key prefix for namespacing
    /// * `priority` - Priority for this source (higher values override lower values)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use hexcfg::service::ConfigurationServiceBuilder;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> hexcfg::domain::Result<()> {
    /// let service = ConfigurationServiceBuilder::new()
    ///     .with_etcd_priority(vec!["localhost:2379"], Some("myapp/"), 2).await?
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "etcd")]
    pub async fn with_etcd_priority<S: AsRef<str>>(
        self,
        endpoints: Vec<S>,
        prefix: Option<&str>,
        priority: u8,
    ) -> Result<Self> {
        use crate::adapters::EtcdAdapter;
        let adapter = EtcdAdapter::with_priority(endpoints, prefix, priority).await?;
        Ok(self.with_source(Box::new(adapter)))
    }

    /// Adds Redis as a configuration source.
    ///
    /// # Arguments
    ///
    /// * `url` - Redis connection URL (e.g., `"redis://localhost:6379"`)
    /// * `namespace` - Key prefix (for StringKeys mode) or hash key name (for Hash mode)
    /// * `storage_mode` - Whether to use string keys or hash storage
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use hexcfg::service::ConfigurationServiceBuilder;
    /// use hexcfg::adapters::RedisStorageMode;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> hexcfg::domain::Result<()> {
    /// let service = ConfigurationServiceBuilder::new()
    ///     .with_redis("redis://localhost:6379", "myapp:", RedisStorageMode::StringKeys).await?
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "redis")]
    pub async fn with_redis(
        self,
        url: &str,
        namespace: &str,
        storage_mode: crate::adapters::RedisStorageMode,
    ) -> Result<Self> {
        use crate::adapters::RedisAdapter;
        let adapter = RedisAdapter::new(url, namespace, storage_mode).await?;
        Ok(self.with_source(Box::new(adapter)))
    }

    /// Adds Redis as a configuration source with custom priority.
    ///
    /// # Arguments
    ///
    /// * `url` - Redis connection URL
    /// * `namespace` - Key prefix or hash key name
    /// * `storage_mode` - Whether to use string keys or hash storage
    /// * `priority` - Priority for this source (higher values override lower values)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use hexcfg::service::ConfigurationServiceBuilder;
    /// use hexcfg::adapters::RedisStorageMode;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> hexcfg::domain::Result<()> {
    /// let service = ConfigurationServiceBuilder::new()
    ///     .with_redis_priority(
    ///         "redis://localhost:6379",
    ///         "myapp:",
    ///         RedisStorageMode::Hash,
    ///         2
    ///     ).await?
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "redis")]
    pub async fn with_redis_priority(
        self,
        url: &str,
        namespace: &str,
        storage_mode: crate::adapters::RedisStorageMode,
        priority: u8,
    ) -> Result<Self> {
        use crate::adapters::RedisAdapter;
        let adapter = RedisAdapter::with_priority(url, namespace, storage_mode, priority).await?;
        Ok(self.with_source(Box::new(adapter)))
    }

    /// Builds the configuration service.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hexcfg::service::ConfigurationServiceBuilder;
    ///
    /// # fn main() -> hexcfg::domain::Result<()> {
    /// let service = ConfigurationServiceBuilder::new()
    ///     .with_env_vars()
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn build(self) -> Result<DefaultConfigService> {
        let mut service = DefaultConfigService::new();

        for source in self.sources {
            service.add_source(source);
        }

        Ok(service)
    }
}

impl Default for ConfigurationServiceBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ports::ConfigSource;

    // Mock source for testing
    struct MockSource {
        name: String,
        priority: u8,
        values: HashMap<String, String>,
    }

    impl MockSource {
        fn new(name: &str, priority: u8) -> Self {
            Self {
                name: name.to_string(),
                priority,
                values: HashMap::new(),
            }
        }

        fn with_value(mut self, key: &str, value: &str) -> Self {
            self.values.insert(key.to_string(), value.to_string());
            self
        }
    }

    impl ConfigSource for MockSource {
        fn name(&self) -> &str {
            &self.name
        }

        fn priority(&self) -> u8 {
            self.priority
        }

        fn get(&self, key: &ConfigKey) -> Result<Option<ConfigValue>> {
            Ok(self
                .values
                .get(key.as_str())
                .map(|v| ConfigValue::from(v.as_str())))
        }

        fn all_keys(&self) -> Result<Vec<ConfigKey>> {
            Ok(self
                .values
                .keys()
                .map(|k| ConfigKey::from(k.as_str()))
                .collect())
        }

        fn reload(&mut self) -> Result<()> {
            Ok(())
        }
    }

    #[test]
    fn test_default_service_new() {
        let service = DefaultConfigService::new();
        assert_eq!(service.sources.len(), 0);
    }

    #[test]
    fn test_default_service_add_source() {
        let mut service = DefaultConfigService::new();
        let source = Box::new(MockSource::new("test", 1));

        service.add_source(source);
        assert_eq!(service.sources.len(), 1);
    }

    #[test]
    fn test_default_service_priority_order() {
        let mut service = DefaultConfigService::new();

        // Add sources in reverse priority order
        service.add_source(Box::new(MockSource::new("low", 1)));
        service.add_source(Box::new(MockSource::new("high", 3)));
        service.add_source(Box::new(MockSource::new("medium", 2)));

        // Verify they're sorted by priority (highest first)
        assert_eq!(service.sources[0].name(), "high");
        assert_eq!(service.sources[1].name(), "medium");
        assert_eq!(service.sources[2].name(), "low");
    }

    #[test]
    fn test_default_service_get_from_single_source() {
        let mut service = DefaultConfigService::new();
        let source = MockSource::new("test", 1).with_value("key", "value");

        service.add_source(Box::new(source));

        let key = ConfigKey::from("key");
        let value = service.get(&key).unwrap();
        assert_eq!(value.as_str(), "value");
    }

    #[test]
    fn test_default_service_get_precedence() {
        let mut service = DefaultConfigService::new();

        // Add sources with different priorities and values for the same key
        service.add_source(Box::new(
            MockSource::new("low", 1).with_value("key", "low_value"),
        ));
        service.add_source(Box::new(
            MockSource::new("high", 3).with_value("key", "high_value"),
        ));
        service.add_source(Box::new(
            MockSource::new("medium", 2).with_value("key", "medium_value"),
        ));

        let key = ConfigKey::from("key");
        let value = service.get(&key).unwrap();

        // Should get value from highest priority source
        assert_eq!(value.as_str(), "high_value");
    }

    #[test]
    fn test_default_service_get_missing_key() {
        let mut service = DefaultConfigService::new();
        service.add_source(Box::new(
            MockSource::new("test", 1).with_value("key", "value"),
        ));

        let key = ConfigKey::from("nonexistent");
        let result = service.get(&key);

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ConfigError::ConfigKeyNotFound { .. }
        ));
    }

    #[test]
    fn test_default_service_get_or_default() {
        let mut service = DefaultConfigService::new();
        service.add_source(Box::new(
            MockSource::new("test", 1).with_value("key", "value"),
        ));

        let key = ConfigKey::from("nonexistent");
        let value = service.get_or_default(&key, "default_value");

        assert_eq!(value.as_str(), "default_value");
    }

    #[test]
    fn test_default_service_has() {
        let mut service = DefaultConfigService::new();
        service.add_source(Box::new(
            MockSource::new("test", 1).with_value("key", "value"),
        ));

        assert!(service.has(&ConfigKey::from("key")));
        assert!(!service.has(&ConfigKey::from("nonexistent")));
    }

    #[test]
    fn test_default_service_cache() {
        let mut service = DefaultConfigService::new();
        service.add_source(Box::new(
            MockSource::new("test", 1).with_value("key", "value"),
        ));

        let key = ConfigKey::from("key");

        // First call should populate cache
        let value1 = service.get(&key).unwrap();

        // Second call should use cache
        let value2 = service.get(&key).unwrap();

        assert_eq!(value1.as_str(), value2.as_str());
    }

    #[test]
    fn test_default_service_reload() {
        let mut service = DefaultConfigService::new();
        service.add_source(Box::new(
            MockSource::new("test", 1).with_value("key", "value"),
        ));

        assert!(service.reload().is_ok());
    }

    #[test]
    fn test_builder_new() {
        let builder = ConfigurationServiceBuilder::new();
        assert_eq!(builder.sources.len(), 0);
    }

    #[test]
    fn test_builder_with_source() {
        let source = Box::new(MockSource::new("test", 1));
        let builder = ConfigurationServiceBuilder::new().with_source(source);

        assert_eq!(builder.sources.len(), 1);
    }

    #[test]
    fn test_builder_build() {
        let service = ConfigurationServiceBuilder::new()
            .with_source(Box::new(MockSource::new("test", 1)))
            .build()
            .unwrap();

        assert_eq!(service.sources.len(), 1);
    }

    #[test]
    #[cfg(feature = "env")]
    fn test_builder_with_env_vars() {
        let service = ConfigurationServiceBuilder::new()
            .with_env_vars()
            .build()
            .unwrap();

        assert_eq!(service.sources.len(), 1);
        assert_eq!(service.sources[0].name(), "env");
    }

    #[test]
    fn test_builder_default() {
        let builder = ConfigurationServiceBuilder::default();
        assert_eq!(builder.sources.len(), 0);
    }

    #[test]
    fn test_service_default() {
        let service = DefaultConfigService::default();
        assert_eq!(service.sources.len(), 0);
    }
}