Skip to main content

schedr_config/
sources.rs

1//! Where configuration comes from: the file, `SCHEDR_CONFIG__*` environment variables, the
2//! short aliases, and command-line flags (see archive/PROJECT.md, Configuration).
3//!
4//! Every source is a `figment` provider whose metadata names the exact origin of a value
5//! (the file, `SCHEDR_CONFIG__OPS__PORT`, `SCHEDR_DAG_PATH`, `--ops-port`), so error messages
6//! say where a bad value came from.
7
8use std::collections::BTreeMap;
9use std::path::{Path, PathBuf};
10
11use figment::value::{Dict, Map, Value};
12use figment::{Error, Metadata, Profile, Provider, Source};
13
14#[cfg(test)]
15mod tests;
16
17/// The prefix of environment variables that mirror the configuration file.
18pub const ENV_PREFIX: &str = "SCHEDR_CONFIG__";
19
20/// The environment variable naming the configuration file.
21pub const CONFIG_FILE_ENV: &str = "SCHEDR_CONFIG_FILE";
22
23/// The configuration file read when neither `--config` nor `SCHEDR_CONFIG_FILE` names one.
24pub const DEFAULT_CONFIG_FILE: &str = "/etc/schedr/config.toml";
25
26/// Short aliases: environment variable → configuration key.
27pub const ALIASES: [(&str, &str); 2] = [
28    ("SCHEDR_DAG_PATH", "dags.path"),
29    ("SCHEDR_SCRIPT_PATH", "scripts.path"),
30];
31
32/// Which configuration file to read.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum ConfigFile {
35    /// Named by `--config` or `SCHEDR_CONFIG_FILE`: it must exist.
36    Explicit(PathBuf),
37    /// The default location: read if it exists, otherwise defaults and environment only.
38    Default(PathBuf),
39}
40
41impl ConfigFile {
42    /// The file's path.
43    #[must_use]
44    pub fn path(&self) -> &Path {
45        match self {
46            Self::Explicit(p) | Self::Default(p) => p,
47        }
48    }
49
50    /// Whether a missing file is an error.
51    #[must_use]
52    pub const fn is_required(&self) -> bool {
53        matches!(self, Self::Explicit(_))
54    }
55}
56
57/// Chooses the configuration file: the `--config` flag, then `SCHEDR_CONFIG_FILE`, then
58/// [`DEFAULT_CONFIG_FILE`].
59#[must_use]
60pub fn config_file(flag: Option<&Path>, env: &BTreeMap<String, String>) -> ConfigFile {
61    match (flag, env.get(CONFIG_FILE_ENV)) {
62        (Some(path), _) => ConfigFile::Explicit(path.to_owned()),
63        (None, Some(path)) if !path.is_empty() => ConfigFile::Explicit(path.into()),
64        _ => ConfigFile::Default(DEFAULT_CONFIG_FILE.into()),
65    }
66}
67
68/// The configuration file's contents, with its path for messages.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub struct FileSource<'a> {
71    /// Where the contents were read from.
72    pub path: &'a Path,
73    /// The TOML text.
74    pub contents: &'a str,
75}
76
77/// A configuration value given on the command line, e.g. `--ops-port 9100`.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct Override {
80    /// The configuration key, dotted (`ops.port`).
81    pub key: String,
82    /// The value.
83    pub value: OverrideValue,
84    /// The flag it came from, for messages (`--ops-port`).
85    pub flag: String,
86}
87
88/// What a command-line flag gives.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub enum OverrideValue {
91    /// Text parsed like an environment variable's (`9100` a number).
92    Text(String),
93    /// A list of strings taken as they are, e.g. a repeated `--dag-path` (paths may hold `:`).
94    List(Vec<String>),
95}
96
97impl From<&str> for OverrideValue {
98    fn from(text: &str) -> Self {
99        Self::Text(text.to_owned())
100    }
101}
102
103/// Why an environment variable can't be used as configuration.
104#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
105pub enum SourceError {
106    /// A `SCHEDR_CONFIG__` variable with an empty key part (`SCHEDR_CONFIG__DAGS____PATH`).
107    #[error("environment variable `{0}` is not a configuration key (empty part between `__`)")]
108    InvalidEnvKey(String),
109    /// An alias and the full key are both set.
110    #[error("`{alias}` and `{var}` set the same key `{key}`; set only one")]
111    AliasConflict {
112        /// The alias, e.g. `SCHEDR_DAG_PATH`.
113        alias: &'static str,
114        /// The full variable, e.g. `SCHEDR_CONFIG__DAGS__PATH`.
115        var: String,
116        /// The key both set.
117        key: &'static str,
118    },
119}
120
121/// The configuration key of a `SCHEDR_CONFIG__` variable (`SCHEDR_CONFIG__DAGS__POLL_INTERVAL`
122/// → `dags.poll_interval`), or `None` for other variables.
123///
124/// # Errors
125///
126/// Returns [`SourceError::InvalidEnvKey`] if the key has an empty part.
127pub fn env_key(var: &str) -> Result<Option<String>, SourceError> {
128    let Some(rest) = var.strip_prefix(ENV_PREFIX) else {
129        return Ok(None);
130    };
131    let parts: Vec<String> = rest.split("__").map(str::to_ascii_lowercase).collect();
132    if parts.iter().any(String::is_empty) {
133        return Err(SourceError::InvalidEnvKey(var.to_owned()));
134    }
135    Ok(Some(parts.join(".")))
136}
137
138/// One value from the environment or the command line.
139#[derive(Debug, Clone, PartialEq, Eq)]
140struct Entry {
141    key: String,
142    value: OverrideValue,
143    origin: String,
144}
145
146/// A provider of key/value entries, each with its own origin for messages.
147#[derive(Debug, Clone)]
148pub(crate) struct Entries {
149    name: &'static str,
150    entries: Vec<Entry>,
151}
152
153impl Provider for Entries {
154    fn metadata(&self) -> Metadata {
155        let origins: BTreeMap<String, String> = self
156            .entries
157            .iter()
158            .map(|e| (e.key.clone(), e.origin.clone()))
159            .collect();
160        Metadata::named(self.name).interpolater(move |_: &Profile, keys: &[&str]| {
161            let key = keys.join(".");
162            origins.get(&key).cloned().unwrap_or(key)
163        })
164    }
165
166    fn data(&self) -> Result<Map<Profile, Dict>, Error> {
167        let mut dict = Dict::new();
168        for entry in &self.entries {
169            // A secret is its text as given: parsed, `PASSWORD=000123` would be the integer
170            // 123 (B201).
171            let last = entry.key.rsplit('.').next().unwrap_or_default();
172            let secret = last == "password" || last == "token";
173            let value: Value = match &entry.value {
174                OverrideValue::List(items) => Value::from(items.clone()),
175                OverrideValue::Text(text) if secret => Value::from(text.clone()),
176                OverrideValue::Text(text) => {
177                    text.parse().expect("parsing a figment value never fails")
178                }
179            };
180            if let Some(nested) = figment::util::nest(&entry.key, value).into_dict() {
181                dict = merge(dict, nested);
182            }
183        }
184        Ok(Profile::Default.collect(dict))
185    }
186}
187
188/// Deep-merges `b` into `a` (`b` wins).
189fn merge(mut a: Dict, b: Dict) -> Dict {
190    for (key, value) in b {
191        let merged = match (a.remove(&key), value) {
192            (Some(Value::Dict(_, old)), Value::Dict(tag, new)) => Value::Dict(tag, merge(old, new)),
193            (_, new) => new,
194        };
195        a.insert(key, merged);
196    }
197    a
198}
199
200/// The provider for `SCHEDR_CONFIG__*` variables and the short aliases.
201///
202/// # Errors
203///
204/// Returns a [`SourceError`] for a malformed `SCHEDR_CONFIG__` variable, or when an alias and
205/// its full variable are both set.
206pub(crate) fn env_provider(env: &BTreeMap<String, String>) -> Result<Entries, SourceError> {
207    let mut entries = Vec::new();
208    for (var, value) in env {
209        if let Some(key) = env_key(var)? {
210            entries.push(Entry {
211                key,
212                value: OverrideValue::Text(value.clone()),
213                origin: var.clone(),
214            });
215        }
216    }
217    for (alias, key) in ALIASES {
218        if let Some(value) = env.get(alias) {
219            if let Some(full) = entries.iter().find(|e| e.key == key) {
220                return Err(SourceError::AliasConflict {
221                    alias,
222                    var: full.origin.clone(),
223                    key,
224                });
225            }
226            entries.push(Entry {
227                key: key.to_owned(),
228                value: OverrideValue::Text(value.clone()),
229                origin: alias.to_owned(),
230            });
231        }
232    }
233    Ok(Entries {
234        name: "environment variable",
235        entries,
236    })
237}
238
239/// The provider for command-line overrides.
240pub(crate) fn override_provider(overrides: &[Override]) -> Entries {
241    let entries = overrides
242        .iter()
243        .map(|o| Entry {
244            key: o.key.clone(),
245            value: o.value.clone(),
246            origin: o.flag.clone(),
247        })
248        .collect();
249    Entries {
250        name: "command-line flag",
251        entries,
252    }
253}
254
255/// The metadata of the configuration file, naming its path in messages.
256pub(crate) fn file_metadata(path: &Path) -> Metadata {
257    Metadata::from("configuration file", Source::File(path.to_owned()))
258}