Skip to main content

luxid_core/
config.rs

1//! Application configuration.
2//!
3//! Two layers, in precedence order: the environment overrides `luxid.toml`.
4//! That is the 12-factor arrangement — the file holds what is true for everyone,
5//! the environment holds what is true for this deployment.
6//!
7//! Keys are dotted. A nested TOML table flattens to `database.strict_relations`,
8//! and the environment spelling of that key is `DATABASE_STRICT_RELATIONS`. The
9//! mapping is mechanical so nobody has to look it up.
10//!
11//! This is deliberately *not* where typed application settings belong. A struct
12//! of your own, bound as a singleton in `providers()`, is better in every way
13//! that matters — it is validated once at boot rather than on every read. Use
14//! `Config` to build that struct, not as a substitute for it.
15
16use std::collections::BTreeMap;
17use std::path::Path;
18use std::str::FromStr;
19use std::sync::Arc;
20
21use serde::de::DeserializeOwned;
22use serde_json::Value;
23
24use crate::error::{Error, Result};
25
26#[derive(Debug, Default)]
27struct Inner {
28    values: BTreeMap<String, String>,
29}
30
31/// A read-only view of the application's configuration. Cheap to clone.
32#[derive(Debug, Clone, Default)]
33pub struct Config {
34    inner: Arc<Inner>,
35}
36
37impl Config {
38    pub fn new() -> Self {
39        Self::default()
40    }
41
42    /// Build from explicit pairs. Chiefly useful in tests.
43    pub fn from_pairs<K, V>(pairs: impl IntoIterator<Item = (K, V)>) -> Self
44    where
45        K: Into<String>,
46        V: Into<String>,
47    {
48        let values = pairs
49            .into_iter()
50            .map(|(key, value)| (normalise(&key.into()), value.into()))
51            .collect();
52
53        Self {
54            inner: Arc::new(Inner { values }),
55        }
56    }
57
58    /// The process environment alone.
59    pub fn from_env() -> Self {
60        let mut values = BTreeMap::new();
61        overlay_env(&mut values);
62
63        Self {
64            inner: Arc::new(Inner { values }),
65        }
66    }
67
68    /// `luxid.toml` with the environment layered over it.
69    ///
70    /// A missing file is not an error: an application configured entirely by
71    /// environment is a perfectly ordinary one, and failing here would make the
72    /// file mandatory for no reason.
73    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
74        let mut values = BTreeMap::new();
75
76        if let Ok(text) = std::fs::read_to_string(path.as_ref()) {
77            let table: toml::Table = toml::from_str(&text).map_err(|err| {
78                Error::internal(format!("could not read {:?}: {err}", path.as_ref()))
79            })?;
80
81            flatten("", &toml::Value::Table(table), &mut values);
82        }
83
84        overlay_env(&mut values);
85
86        Ok(Self {
87            inner: Arc::new(Inner { values }),
88        })
89    }
90
91    pub fn has(&self, key: &str) -> bool {
92        self.inner.values.contains_key(&normalise(key))
93    }
94
95    pub fn keys(&self) -> impl Iterator<Item = &str> {
96        self.inner.values.keys().map(String::as_str)
97    }
98
99    pub fn is_empty(&self) -> bool {
100        self.inner.values.is_empty()
101    }
102
103    /// The raw string, if the key is set.
104    pub fn raw(&self, key: &str) -> Option<&str> {
105        self.inner.values.get(&normalise(key)).map(String::as_str)
106    }
107
108    /// A required value, decoded into `T`.
109    pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<T> {
110        match self.try_get(key)? {
111            Some(value) => Ok(value),
112            None => Err(Error::internal(format!(
113                "configuration key `{key}` is not set. Add it to luxid.toml, or set `{}`.",
114                environment_key(key)
115            ))),
116        }
117    }
118
119    /// An optional value, decoded into `T`.
120    pub fn try_get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
121        match self.raw(key) {
122            Some(raw) => decode(key, raw).map(Some),
123            None => Ok(None),
124        }
125    }
126
127    /// A value with a fallback. A *malformed* value still fails — silently
128    /// falling back would hide a typo in production.
129    pub fn get_or<T: DeserializeOwned>(&self, key: &str, default: T) -> Result<T> {
130        Ok(self.try_get(key)?.unwrap_or(default))
131    }
132
133    /// A value with a fallback, parsed with `FromStr` instead of serde.
134    pub fn parse_or<T: FromStr>(&self, key: &str, default: T) -> Result<T> {
135        match self.raw(key) {
136            Some(raw) => raw
137                .parse()
138                .map_err(|_| Error::internal(format!("`{key}` could not be read from `{raw}`"))),
139            None => Ok(default),
140        }
141    }
142}
143
144/// Configuration keys are case-insensitive and `_`/`.` are interchangeable, so
145/// `DATABASE_STRICT_RELATIONS` and `database.strict_relations` are one key.
146fn normalise(key: &str) -> String {
147    key.trim().to_ascii_lowercase().replace('_', ".")
148}
149
150/// The environment spelling of a dotted key, for error messages.
151fn environment_key(key: &str) -> String {
152    normalise(key).replace('.', "_").to_ascii_uppercase()
153}
154
155fn overlay_env(values: &mut BTreeMap<String, String>) {
156    for (key, value) in std::env::vars() {
157        values.insert(normalise(&key), value);
158    }
159}
160
161fn flatten(prefix: &str, value: &toml::Value, out: &mut BTreeMap<String, String>) {
162    match value {
163        toml::Value::Table(table) => {
164            for (key, nested) in table {
165                let path = if prefix.is_empty() {
166                    key.clone()
167                } else {
168                    format!("{prefix}.{key}")
169                };
170
171                flatten(&path, nested, out);
172            }
173        }
174        // Arrays are rendered as their TOML form rather than being flattened
175        // into indexed keys, which nobody would guess the spelling of.
176        toml::Value::Array(_) => {
177            out.insert(normalise(prefix), value.to_string());
178        }
179        toml::Value::String(text) => {
180            out.insert(normalise(prefix), text.clone());
181        }
182        other => {
183            out.insert(normalise(prefix), other.to_string());
184        }
185    }
186}
187
188/// The same decoding the request layer uses: try the raw text as JSON, which
189/// handles numbers and booleans, then fall back to treating it as a string.
190fn decode<T: DeserializeOwned>(key: &str, raw: &str) -> Result<T> {
191    if let Ok(value) = serde_json::from_str::<T>(raw) {
192        return Ok(value);
193    }
194
195    serde_json::from_value(Value::String(raw.to_owned()))
196        .map_err(|err| Error::internal(format!("`{key}` could not be read from `{raw}`: {err}")))
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    fn config() -> Config {
204        Config::from_pairs([
205            ("app.name", "blogapp"),
206            ("app.per_page", "20"),
207            ("database.strict_relations", "true"),
208        ])
209    }
210
211    #[test]
212    fn decodes_typed_values() {
213        let config = config();
214
215        assert_eq!(config.get::<String>("app.name").unwrap(), "blogapp");
216        assert_eq!(config.get::<u32>("app.per_page").unwrap(), 20);
217        assert!(config.get::<bool>("database.strict_relations").unwrap());
218    }
219
220    #[test]
221    fn dots_and_underscores_and_case_are_one_key() {
222        let config = config();
223
224        assert_eq!(config.get::<u32>("APP_PER_PAGE").unwrap(), 20);
225        assert_eq!(config.get::<u32>("app_per_page").unwrap(), 20);
226        assert_eq!(config.get::<u32>("App.Per.Page").unwrap(), 20);
227    }
228
229    #[test]
230    fn a_missing_required_key_names_its_environment_spelling() {
231        let err = config().get::<String>("mail.driver").unwrap_err();
232        let message = format!("{err}");
233
234        assert!(message.contains("`mail.driver` is not set"), "{message}");
235        assert!(message.contains("MAIL_DRIVER"), "{message}");
236    }
237
238    #[test]
239    fn optional_and_defaulted_reads() {
240        let config = config();
241
242        assert_eq!(config.try_get::<String>("mail.driver").unwrap(), None);
243        assert_eq!(config.get_or("app.per_page", 10).unwrap(), 20);
244        assert_eq!(config.get_or("mail.retries", 3).unwrap(), 3);
245    }
246
247    #[test]
248    fn a_malformed_value_fails_rather_than_falling_back() {
249        // Silently defaulting would hide a typo until someone wondered why the
250        // setting had no effect.
251        let config = Config::from_pairs([("app.per_page", "twenty")]);
252
253        assert!(config.get::<u32>("app.per_page").is_err());
254        assert!(config.get_or("app.per_page", 10).is_err());
255    }
256
257    #[test]
258    fn flattens_nested_tables_into_dotted_keys() {
259        let toml_text = r#"
260            [app]
261            name = "blogapp"
262
263            [database]
264            strict_relations = true
265            pool = 8
266        "#;
267
268        let table: toml::Table = toml::from_str(toml_text).expect("valid toml");
269        let mut values = BTreeMap::new();
270        flatten("", &toml::Value::Table(table), &mut values);
271
272        assert_eq!(values.get("app.name").map(String::as_str), Some("blogapp"));
273        assert_eq!(
274            values.get("database.strict.relations").map(String::as_str),
275            Some("true")
276        );
277        assert_eq!(values.get("database.pool").map(String::as_str), Some("8"));
278    }
279
280    #[test]
281    fn a_missing_file_is_not_an_error() {
282        let config = Config::load("does-not-exist.toml").expect("absence is fine");
283
284        // The environment still came through.
285        assert!(config.keys().count() > 0 || config.is_empty());
286    }
287
288    #[test]
289    fn the_environment_overrides_the_file() {
290        // SAFETY: single-threaded test, and the key is unique to it.
291        unsafe { std::env::set_var("LUXID_TEST_OVERRIDE_KEY", "from-env") };
292
293        let mut values = BTreeMap::new();
294        values.insert("luxid.test.override.key".to_owned(), "from-file".to_owned());
295        overlay_env(&mut values);
296
297        assert_eq!(
298            values.get("luxid.test.override.key").map(String::as_str),
299            Some("from-env")
300        );
301
302        unsafe { std::env::remove_var("LUXID_TEST_OVERRIDE_KEY") };
303    }
304}