1use 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
17pub const ENV_PREFIX: &str = "SCHEDR_CONFIG__";
19
20pub const CONFIG_FILE_ENV: &str = "SCHEDR_CONFIG_FILE";
22
23pub const DEFAULT_CONFIG_FILE: &str = "/etc/schedr/config.toml";
25
26pub const ALIASES: [(&str, &str); 2] = [
28 ("SCHEDR_DAG_PATH", "dags.path"),
29 ("SCHEDR_SCRIPT_PATH", "scripts.path"),
30];
31
32#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum ConfigFile {
35 Explicit(PathBuf),
37 Default(PathBuf),
39}
40
41impl ConfigFile {
42 #[must_use]
44 pub fn path(&self) -> &Path {
45 match self {
46 Self::Explicit(p) | Self::Default(p) => p,
47 }
48 }
49
50 #[must_use]
52 pub const fn is_required(&self) -> bool {
53 matches!(self, Self::Explicit(_))
54 }
55}
56
57#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub struct FileSource<'a> {
71 pub path: &'a Path,
73 pub contents: &'a str,
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct Override {
80 pub key: String,
82 pub value: OverrideValue,
84 pub flag: String,
86}
87
88#[derive(Debug, Clone, PartialEq, Eq)]
90pub enum OverrideValue {
91 Text(String),
93 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#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
105pub enum SourceError {
106 #[error("environment variable `{0}` is not a configuration key (empty part between `__`)")]
108 InvalidEnvKey(String),
109 #[error("`{alias}` and `{var}` set the same key `{key}`; set only one")]
111 AliasConflict {
112 alias: &'static str,
114 var: String,
116 key: &'static str,
118 },
119}
120
121pub 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#[derive(Debug, Clone, PartialEq, Eq)]
140struct Entry {
141 key: String,
142 value: OverrideValue,
143 origin: String,
144}
145
146#[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 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
188fn 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
200pub(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
239pub(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
255pub(crate) fn file_metadata(path: &Path) -> Metadata {
257 Metadata::from("configuration file", Source::File(path.to_owned()))
258}