prefer 0.4.1

A lightweight library for managing application configurations with support for multiple file formats
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
//! Database configuration loader.
//!
//! Provides a simplified trait (`ConfigLoader`) for loading configuration from
//! databases, and a `DbLoader` adapter that bridges it to the `Loader` trait.
//!
//! Configuration data can be provided in two forms:
//!
//! - **Raw** — a format string (e.g., stored JSON/TOML/YAML) that gets
//!   parsed using the appropriate formatter from the provided list.
//! - **Columnar** — structured key-value pairs from database columns,
//!   converted directly to `ConfigValue`.
//!
//! # Example
//!
//! ```no_run
//! use prefer::loader::db::{DbLoader, ConfigLoader, ConfigEntry};
//! use prefer::registry::RegisteredLoader;
//! use async_trait::async_trait;
//!
//! struct MyDbLoader;
//!
//! #[async_trait]
//! impl ConfigLoader for MyDbLoader {
//!     fn scheme(&self) -> &str {
//!         "mydb"
//!     }
//!
//!     async fn load_config(&self, identifier: &str) -> prefer::Result<ConfigEntry> {
//!         Ok(ConfigEntry::Raw {
//!             format: "json".to_string(),
//!             content: r#"{"key": "value"}"#.to_string(),
//!         })
//!     }
//!
//!     fn name(&self) -> &str {
//!         "my_database"
//!     }
//! }
//!
//! static MY_LOADER: DbLoader<MyDbLoader> = DbLoader::new(MyDbLoader);
//! inventory::submit! { RegisteredLoader(&MY_LOADER) }
//!
//! #[tokio::main]
//! async fn main() -> prefer::Result<()> {
//!     let config = prefer::load("mydb://settings").await?;
//!     let value: String = config.get("key")?;
//!     Ok(())
//! }
//! ```

use crate::error::{Error, Result};
use crate::formatter::Formatter;
use crate::loader::{LoadResult, Loader};
use crate::value::ConfigValue;
use async_trait::async_trait;
use std::collections::{BTreeMap, HashMap};

/// A single value from a database column.
#[derive(Debug, Clone, PartialEq)]
pub enum ColumnValue {
    Null,
    Bool(bool),
    Integer(i64),
    Float(f64),
    String(String),
}

/// A configuration entry loaded from a database.
///
/// Supports two storage strategies:
///
/// - `Raw` — the database stores serialized config (JSON, TOML, YAML, etc.)
///   in a text column. The format hint tells the loader which formatter to use.
/// - `Columnar` — the database stores config values across table columns.
///   The key-value pairs are converted directly to `ConfigValue`.
#[derive(Debug, Clone)]
pub enum ConfigEntry {
    Raw { format: String, content: String },
    Columnar(BTreeMap<String, ColumnValue>),
}

/// Trait for loading configuration from a database.
///
/// Implement this trait for your specific database backend. The `scheme()`
/// method declares what URL scheme this loader handles, and `load_config()`
/// fetches the configuration for a given identifier.
#[async_trait]
pub trait ConfigLoader: Send + Sync + 'static {
    /// The URL scheme this loader handles (e.g., "postgres", "sqlite").
    fn scheme(&self) -> &str;

    /// Load configuration content for the given identifier.
    ///
    /// The identifier is the full URL string (e.g., "postgres://localhost/myapp").
    async fn load_config(&self, identifier: &str) -> Result<ConfigEntry>;

    /// Human-readable name for error messages.
    fn name(&self) -> &str;
}

/// A `Loader` that delegates to a `ConfigLoader` implementation.
///
/// Wraps any `ConfigLoader` and adapts it to the `Loader` trait,
/// routing identifiers by URL scheme and returning parsed configuration
/// data.
pub struct DbLoader<L: ConfigLoader>(pub L);

impl<L: ConfigLoader> DbLoader<L> {
    pub const fn new(loader: L) -> Self {
        Self(loader)
    }
}

#[async_trait]
impl<L: ConfigLoader> Loader for DbLoader<L> {
    fn provides(&self, identifier: &str) -> bool {
        let prefix = format!("{}://", self.0.scheme());
        identifier.starts_with(&prefix)
    }

    async fn load(&self, identifier: &str, formatters: &[&dyn Formatter]) -> Result<LoadResult> {
        let entry = self.0.load_config(identifier).await?;

        let data = match entry {
            ConfigEntry::Raw { format, content } => {
                let fmt = formatters
                    .iter()
                    .find(|f| f.extensions().contains(&format.as_str()))
                    .ok_or_else(|| Error::NoFormatterFound(format))?;
                fmt.deserialize(&content)?
            }
            ConfigEntry::Columnar(values) => columnar_to_config_value(values),
        };

        Ok(LoadResult {
            source: identifier.to_string(),
            data,
        })
    }

    fn name(&self) -> &str {
        self.0.name()
    }
}

fn column_to_config_value(value: ColumnValue) -> ConfigValue {
    match value {
        ColumnValue::Null => ConfigValue::Null,
        ColumnValue::Bool(b) => ConfigValue::Bool(b),
        ColumnValue::Integer(i) => ConfigValue::Integer(i),
        ColumnValue::Float(f) => ConfigValue::Float(f),
        ColumnValue::String(s) => ConfigValue::String(s),
    }
}

fn columnar_to_config_value(values: BTreeMap<String, ColumnValue>) -> ConfigValue {
    let map: HashMap<String, ConfigValue> = values
        .into_iter()
        .map(|(k, v)| (k, column_to_config_value(v)))
        .collect();
    ConfigValue::Object(map)
}

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

    struct TestLoader;

    #[async_trait]
    impl ConfigLoader for TestLoader {
        fn scheme(&self) -> &str {
            "testdb"
        }

        async fn load_config(&self, _identifier: &str) -> Result<ConfigEntry> {
            Ok(ConfigEntry::Raw {
                format: "json".to_string(),
                content: r#"{"key": "value", "num": 42}"#.to_string(),
            })
        }

        fn name(&self) -> &str {
            "test"
        }
    }

    struct EchoLoader;

    #[async_trait]
    impl ConfigLoader for EchoLoader {
        fn scheme(&self) -> &str {
            "echo"
        }

        async fn load_config(&self, identifier: &str) -> Result<ConfigEntry> {
            let mut values = BTreeMap::new();
            values.insert(
                "received".to_string(),
                ColumnValue::String(identifier.to_string()),
            );
            Ok(ConfigEntry::Columnar(values))
        }

        fn name(&self) -> &str {
            "echo"
        }
    }

    struct ColumnarLoader;

    #[async_trait]
    impl ConfigLoader for ColumnarLoader {
        fn scheme(&self) -> &str {
            "coldb"
        }

        async fn load_config(&self, _identifier: &str) -> Result<ConfigEntry> {
            let mut values = BTreeMap::new();
            values.insert("host".to_string(), ColumnValue::String("localhost".into()));
            values.insert("port".to_string(), ColumnValue::Integer(5432));
            values.insert("debug".to_string(), ColumnValue::Bool(true));
            values.insert("timeout".to_string(), ColumnValue::Float(30.5));
            values.insert("retired".to_string(), ColumnValue::Null);
            Ok(ConfigEntry::Columnar(values))
        }

        fn name(&self) -> &str {
            "columnar"
        }
    }

    struct FailingLoader;

    #[async_trait]
    impl ConfigLoader for FailingLoader {
        fn scheme(&self) -> &str {
            "faildb"
        }

        async fn load_config(&self, identifier: &str) -> Result<ConfigEntry> {
            Err(Error::SourceError {
                source_name: "faildb".to_string(),
                source: format!("connection failed for {}", identifier).into(),
            })
        }

        fn name(&self) -> &str {
            "failing"
        }
    }

    #[test]
    fn test_provides_matching_scheme() {
        let loader = DbLoader::new(TestLoader);
        assert!(loader.provides("testdb://some/path"));
        assert!(loader.provides("testdb://localhost/config"));
    }

    #[test]
    fn test_provides_rejects_other_schemes() {
        let loader = DbLoader::new(TestLoader);
        assert!(!loader.provides("postgres://localhost/db"));
        assert!(!loader.provides("file:///etc/config.toml"));
        assert!(!loader.provides("settings"));
    }

    #[test]
    fn test_provides_rejects_partial_scheme() {
        let loader = DbLoader::new(TestLoader);
        assert!(!loader.provides("testdb"));
        assert!(!loader.provides("testdb:/missing-slash"));
    }

    #[tokio::test]
    async fn test_load_raw_parses_with_formatter() {
        let formatters = registry::collect_formatters();
        let loader = DbLoader::new(TestLoader);
        let result = loader.load("testdb://settings", &formatters).await.unwrap();

        assert_eq!(result.source, "testdb://settings");
        assert_eq!(result.data.get("key").unwrap().as_str(), Some("value"));
        assert_eq!(result.data.get("num").unwrap().as_i64(), Some(42));
    }

    #[tokio::test]
    async fn test_identifier_passed_to_config_loader() {
        let formatters = registry::collect_formatters();
        let loader = DbLoader::new(EchoLoader);
        let result = loader
            .load("echo://my/specific/path", &formatters)
            .await
            .unwrap();

        assert_eq!(result.source, "echo://my/specific/path");
        assert_eq!(
            result.data.get("received").unwrap().as_str(),
            Some("echo://my/specific/path")
        );
    }

    #[tokio::test]
    async fn test_load_columnar_converts_directly() {
        let formatters = registry::collect_formatters();
        let loader = DbLoader::new(ColumnarLoader);
        let result = loader.load("coldb://settings", &formatters).await.unwrap();

        assert_eq!(result.source, "coldb://settings");
        assert_eq!(result.data.get("host").unwrap().as_str(), Some("localhost"));
        assert_eq!(result.data.get("port").unwrap().as_i64(), Some(5432));
        assert_eq!(result.data.get("debug").unwrap().as_bool(), Some(true));
        assert_eq!(result.data.get("timeout").unwrap().as_f64(), Some(30.5));
        assert!(matches!(
            result.data.get("retired").unwrap(),
            &ConfigValue::Null
        ));
    }

    #[tokio::test]
    async fn test_load_columnar_empty_map() {
        struct EmptyColumnarLoader;

        #[async_trait]
        impl ConfigLoader for EmptyColumnarLoader {
            fn scheme(&self) -> &str {
                "emptydb"
            }
            async fn load_config(&self, _id: &str) -> Result<ConfigEntry> {
                Ok(ConfigEntry::Columnar(BTreeMap::new()))
            }
            fn name(&self) -> &str {
                "empty"
            }
        }

        let formatters = registry::collect_formatters();
        let loader = DbLoader::new(EmptyColumnarLoader);
        let result = loader.load("emptydb://x", &formatters).await.unwrap();

        assert!(result.data.as_object().unwrap().is_empty());
    }

    #[tokio::test]
    async fn test_load_error_propagation() {
        let formatters = registry::collect_formatters();
        let loader = DbLoader::new(FailingLoader);
        let result = loader.load("faildb://settings", &formatters).await;

        match result {
            Err(Error::SourceError { source_name, .. }) => {
                assert_eq!(source_name, "faildb");
            }
            Err(other) => panic!("expected SourceError, got {:?}", other),
            Ok(_) => panic!("expected error, got Ok"),
        }
    }

    #[tokio::test]
    async fn test_load_raw_unknown_format_errors() {
        struct UnknownFormatLoader;

        #[async_trait]
        impl ConfigLoader for UnknownFormatLoader {
            fn scheme(&self) -> &str {
                "unkfmt"
            }
            async fn load_config(&self, _id: &str) -> Result<ConfigEntry> {
                Ok(ConfigEntry::Raw {
                    format: "bson".to_string(),
                    content: "{}".to_string(),
                })
            }
            fn name(&self) -> &str {
                "unknown-format"
            }
        }

        let formatters = registry::collect_formatters();
        let loader = DbLoader::new(UnknownFormatLoader);
        let result = loader.load("unkfmt://x", &formatters).await;

        assert!(matches!(result, Err(Error::NoFormatterFound(_))));
    }

    #[test]
    fn test_name_delegates() {
        let loader = DbLoader::new(TestLoader);
        assert_eq!(loader.name(), "test");
    }

    #[test]
    fn test_column_to_config_value() {
        assert_eq!(column_to_config_value(ColumnValue::Null), ConfigValue::Null);
        assert_eq!(
            column_to_config_value(ColumnValue::Bool(true)),
            ConfigValue::Bool(true)
        );
        assert_eq!(
            column_to_config_value(ColumnValue::Integer(42)),
            ConfigValue::Integer(42)
        );
        assert_eq!(
            column_to_config_value(ColumnValue::Float(1.5)),
            ConfigValue::Float(1.5)
        );
        assert_eq!(
            column_to_config_value(ColumnValue::String("hello".into())),
            ConfigValue::String("hello".into())
        );
    }
}