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