Skip to main content

dynamic_config/
bindings.rs

1//! Binding one field to one environment variable, by name.
2//!
3//! The [`env`](crate::LoadSpec::env_prefix) layer covers the case where the
4//! variable names are yours to choose: `APP_DB_POOL__MAX_SIZE` follows from the
5//! prefix, the key and the field. It does not cover the case where they are
6//! not.
7//!
8//! ```text
9//! PORT                 the platform picked it — Heroku, Cloud Run, Fly
10//! DATABASE_URL         a convention older than this program
11//! REDIS_URL            an add-on wrote it into the environment
12//! ```
13//!
14//! None of those can be renamed, and none of them fit a prefix. A binding says
15//! *this field comes from that variable*, and nothing else changes:
16//!
17//! ```rust,no_run
18//! # #[cfg(feature = "toml")] {
19//! # use serde::Deserialize;
20//! # #[dynamic_config::dynamic_config]
21//! # #[derive(Deserialize)] struct ServerConfig { port: u16 }
22//! ServerConfig::bind_env("port", "PORT")?;
23//!
24//! ServerConfig::builder("server")
25//!     .file("config.toml")
26//!     .env("APP_")
27//!     .init()?;
28//! # }
29//! # Ok::<(), dynamic_config::Error>(())
30//! ```
31//!
32//! # Where it sits
33//!
34//! ```text
35//! defaults < files < remote < APP_SERVER_* < bindings < flags < overrides
36//! ```
37//!
38//! Just above the prefixed environment layer, because a binding is the more
39//! specific statement: somebody named this variable on purpose, and the
40//! prefixed one is a convention.
41//!
42//! # Read at load time, not at binding time
43//!
44//! The variable is looked up during each `load()`, so a reload picks up a
45//! change to it. Binding a variable that is not set contributes nothing — it is
46//! not an error, because the whole point is that the platform may or may not
47//! have set it.
48
49use std::collections::BTreeMap;
50use std::sync::Mutex;
51
52use figment::value::{Dict, Value};
53use figment::{Metadata, Profile, Provider};
54
55use crate::error::Error;
56
57/// The environment variables bound to fields of one configuration type.
58///
59/// `EnvBindings::new()` is `const`, so this lives in a `static` — which is how
60/// `#[dynamic_config]` emits it.
61#[derive(Debug, Default)]
62pub struct EnvBindings {
63    /// Key path → variable name.
64    entries: Mutex<BTreeMap<String, String>>,
65}
66
67impl EnvBindings {
68    /// No bindings.
69    #[must_use]
70    pub const fn new() -> Self {
71        Self {
72            entries: Mutex::new(BTreeMap::new()),
73        }
74    }
75
76    /// Binds the field at `path` to the environment variable `variable`.
77    ///
78    /// Takes effect on the next `load()`. Binding the same path twice replaces
79    /// the first binding rather than layering it: two variables for one field
80    /// would have no defensible order between them.
81    ///
82    /// # Errors
83    ///
84    /// If `path` is empty or has an empty segment — `"a..b"` names nothing.
85    pub fn bind(&self, path: &str, variable: &str) -> Result<(), Error> {
86        crate::layer::check_path(path)?;
87
88        self.lock().insert(path.to_owned(), variable.to_owned());
89
90        Ok(())
91    }
92
93    /// Drops every binding.
94    pub fn clear(&self) {
95        self.lock().clear();
96    }
97
98    /// Whether anything is bound.
99    #[must_use]
100    pub fn is_empty(&self) -> bool {
101        self.lock().is_empty()
102    }
103
104    /// The variable bound to `path`, if any.
105    #[must_use]
106    pub fn variable(&self, path: &str) -> Option<String> {
107        self.lock().get(path).cloned()
108    }
109
110    /// One provider per binding, so a value can be traced to the variable that
111    /// supplied it rather than to "a binding" in general.
112    ///
113    /// figment attaches metadata per provider, not per key, so naming the
114    /// variable means one provider each. There are as many as the program made
115    /// bindings — a handful — and they are built once per load.
116    pub(crate) fn providers(&self, key: &str, allow_empty: bool) -> Vec<BindingProvider> {
117        self.lock()
118            .iter()
119            .map(|(path, variable)| BindingProvider {
120                path: path.clone(),
121                variable: variable.clone(),
122                key: key.to_owned(),
123                allow_empty,
124            })
125            .collect()
126    }
127
128    fn lock(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, String>> {
129        // Recovered rather than propagated, as everywhere else in the crate:
130        // the map has no invariant a panic could break.
131        self.entries
132            .lock()
133            .unwrap_or_else(std::sync::PoisonError::into_inner)
134    }
135}
136
137/// Prefixed onto the variable's name, so the loader can recognise this layer
138/// and report the variable rather than a category.
139pub(crate) const BINDING_PREFIX: &str = "the environment variable ";
140
141/// One binding: one path, one variable.
142pub(crate) struct BindingProvider {
143    path: String,
144    variable: String,
145    key: String,
146    allow_empty: bool,
147}
148
149impl Provider for BindingProvider {
150    fn metadata(&self) -> Metadata {
151        Metadata::named(format!("{BINDING_PREFIX}{}", self.variable))
152    }
153
154    fn data(&self) -> figment::Result<figment::value::Map<Profile, Dict>> {
155        let mut values = Dict::new();
156
157        if let Some(value) = resolve(&self.variable, self.allow_empty) {
158            crate::layer::insert_path(&mut values, &self.path, value);
159        }
160
161        let mut map = figment::value::Map::new();
162        map.insert(Profile::from(self.key.clone()), values);
163
164        Ok(map)
165    }
166}
167
168/// Reads one variable, or `None` if it does not usefully exist.
169fn resolve(variable: &str, allow_empty: bool) -> Option<Value> {
170    let text = std::env::var_os(variable)?;
171    let text = text.to_str()?;
172
173    // The same rule as the prefixed layer and `.env` files, `allow_empty_env`
174    // included: an unset value rendered into a deployment template leaves
175    // exactly `PORT=` (or a run of spaces), and letting that blank out a good
176    // value is a bad afternoon — unless the program asked for exactly that.
177    if text.trim().is_empty() && !allow_empty {
178        return None;
179    }
180
181    // Parsed the way the environment layer parses: `8080` is a number, `[1,2]`
182    // a list, and anything else a string.
183    Some(
184        text.parse::<Value>()
185            .unwrap_or_else(|_| Value::from(text.to_owned())),
186    )
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    #[test]
194    fn a_path_with_an_empty_segment_is_refused() {
195        let bindings = EnvBindings::new();
196
197        assert!(bindings.bind("pool..max", "X").is_err());
198        assert!(bindings.bind("", "X").is_err());
199        assert!(bindings.bind("pool.max", "X").is_ok());
200    }
201
202    #[test]
203    fn binding_the_same_path_twice_replaces_rather_than_layers() {
204        let bindings = EnvBindings::new();
205
206        bindings.bind("port", "OLD_PORT").unwrap();
207        bindings.bind("port", "PORT").unwrap();
208
209        assert_eq!(bindings.variable("port").as_deref(), Some("PORT"));
210    }
211
212    #[test]
213    fn clearing_removes_everything() {
214        let bindings = EnvBindings::new();
215
216        bindings.bind("port", "PORT").unwrap();
217        assert!(!bindings.is_empty());
218
219        bindings.clear();
220        assert!(bindings.is_empty());
221    }
222}