1use std::fmt;
23use std::path::Path;
24
25use serde::de::DeserializeOwned;
26use toml::{Table, Value};
27
28use crate::error::{Error, Result};
29
30const ENV_PREFIX: &str = "GLACIER__";
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34pub enum Env {
35 Development,
36 Test,
37 Production,
38}
39
40impl Env {
41 pub fn current() -> Env {
48 match std::env::var("GLACIER_ENV") {
49 Err(_) => Env::Development,
50 Ok(value) => value.parse().unwrap_or_else(|_| {
51 panic!("GLACIER_ENV=`{value}` is not one of development, test, production")
52 }),
53 }
54 }
55
56 pub fn as_str(self) -> &'static str {
57 match self {
58 Env::Development => "development",
59 Env::Test => "test",
60 Env::Production => "production",
61 }
62 }
63
64 pub fn is_development(self) -> bool {
65 self == Env::Development
66 }
67
68 pub fn is_production(self) -> bool {
69 self == Env::Production
70 }
71}
72
73impl std::str::FromStr for Env {
74 type Err = ();
75
76 fn from_str(s: &str) -> std::result::Result<Self, ()> {
77 match s {
78 "development" | "dev" => Ok(Env::Development),
79 "test" => Ok(Env::Test),
80 "production" | "prod" => Ok(Env::Production),
81 _ => Err(()),
82 }
83 }
84}
85
86impl fmt::Display for Env {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 f.write_str(self.as_str())
89 }
90}
91
92#[derive(Debug, Clone)]
94pub struct Config {
95 env: Env,
96 table: Table,
97}
98
99static CURRENT: std::sync::RwLock<Option<Config>> = std::sync::RwLock::new(None);
100
101pub fn app_name() -> String {
104 Config::current().map_or_else(|_| "Glacier app".to_owned(), |config| config.app_name())
105}
106
107impl Config {
108 pub fn current() -> Result<Config> {
116 CURRENT
117 .read()
118 .unwrap_or_else(|e| e.into_inner())
119 .clone()
120 .ok_or_else(|| {
121 crate::Error::internal("the app's config isn't loaded yet (App::config)")
122 })
123 }
124
125 pub fn make_current(&self) {
127 *CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(self.clone());
128 }
129
130 pub fn load() -> Result<Self> {
132 Self::load_from("config", Env::current())
133 }
134
135 pub fn load_from(dir: impl AsRef<Path>, env: Env) -> Result<Self> {
136 let mut table = Table::new();
137 for name in ["default", env.as_str()] {
138 let path = dir.as_ref().join(format!("{name}.toml"));
139 let source = match std::fs::read_to_string(&path) {
140 Ok(source) => source,
141 Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
142 Err(err) => return Err(err.into()),
143 };
144 merge_toml(&mut table, &source, &path.display().to_string())?;
145 }
146 apply_env_overrides(&mut table, std::env::vars());
147 Ok(Self { env, table })
148 }
149
150 pub fn load_embedded(files: &[(&str, &str)]) -> Result<Self> {
155 Self::load_embedded_as(files, Env::current())
156 }
157
158 pub fn load_embedded_as(files: &[(&str, &str)], env: Env) -> Result<Self> {
160 let mut table = Table::new();
161 for name in ["default", env.as_str()] {
162 if let Some((_, source)) = files.iter().find(|(file, _)| *file == name) {
163 merge_toml(&mut table, source, &format!("config/{name}.toml"))?;
164 }
165 }
166 apply_env_overrides(&mut table, std::env::vars());
167 Ok(Self { env, table })
168 }
169
170 pub fn from_toml(env: Env, source: &str) -> Result<Self> {
173 let table = toml::from_str(source).map_err(|e| Error::internal(e.to_string()))?;
174 Ok(Self { env, table })
175 }
176
177 pub fn env(&self) -> Env {
178 self.env
179 }
180
181 pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<T> {
183 self.get_opt(key)?
184 .ok_or_else(|| Error::internal(format!("missing config key `{key}`")))
185 }
186
187 pub fn get_opt<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
189 let Some(value) = lookup(&self.table, key) else {
190 return Ok(None);
191 };
192 value.clone().try_into().map(Some).or_else(|e| {
193 match value {
197 Value::Integer(_) | Value::Float(_) | Value::Boolean(_) => {
198 Value::String(value.to_string()).try_into().map(Some)
199 }
200 _ => Err(e.clone()),
201 }
202 .map_err(|_| Error::internal(format!("config key `{key}`: {e}")))
203 })
204 }
205
206 pub fn secret(&self, key: &str, env_var: &str) -> Result<Option<String>> {
219 let configured = self
220 .get_opt::<String>(key)?
221 .filter(|value| !value.is_empty());
222 if configured.is_some() || self.env == Env::Test {
223 return Ok(configured);
224 }
225 Ok(std::env::var(env_var)
226 .ok()
227 .filter(|value| !value.is_empty()))
228 }
229
230 pub fn deserialize<T: DeserializeOwned>(&self) -> Result<T> {
232 Value::Table(self.table.clone())
233 .try_into()
234 .map_err(|e| Error::internal(format!("config: {e}")))
235 }
236
237 pub fn url(&self) -> Result<String> {
246 if let Some(url) = self.get_opt::<String>("url")? {
247 return Ok(url.trim_end_matches('/').to_owned());
248 }
249 if self.env() == Env::Production {
250 return Err(Error::internal(
251 "set `url` in the config (GLACIER__URL), the app's public address, for absolute links",
252 ));
253 }
254 let addr = self
255 .addr()?
256 .replace("0.0.0.0", "localhost")
257 .replace("127.0.0.1", "localhost");
258 Ok(format!("http://{addr}"))
259 }
260
261 pub fn app_name(&self) -> String {
263 self.get_opt::<String>("name")
264 .ok()
265 .flatten()
266 .unwrap_or_else(|| "Glacier app".to_owned())
267 }
268
269 pub fn addr(&self) -> Result<String> {
271 let host: String = self
272 .get_opt("server.host")?
273 .unwrap_or_else(|| "127.0.0.1".into());
274 let port: u16 = self.get_opt("server.port")?.unwrap_or(4000);
275 Ok(format!("{host}:{port}"))
276 }
277}
278
279fn merge_toml(table: &mut Table, source: &str, name: &str) -> Result<()> {
280 let parsed: Table =
281 toml::from_str(source).map_err(|e| Error::internal(format!("{name}: {e}")))?;
282 merge(table, parsed);
283 Ok(())
284}
285
286fn lookup<'t>(table: &'t Table, key: &str) -> Option<&'t Value> {
287 let mut parts = key.split('.');
288 let mut value = table.get(parts.next()?)?;
289 for part in parts {
290 value = value.as_table()?.get(part)?;
291 }
292 Some(value)
293}
294
295fn merge(base: &mut Table, overlay: Table) {
297 for (key, value) in overlay {
298 match (base.get_mut(&key), value) {
299 (Some(Value::Table(existing)), Value::Table(incoming)) => merge(existing, incoming),
300 (_, value) => {
301 base.insert(key, value);
302 }
303 }
304 }
305}
306
307fn apply_env_overrides(table: &mut Table, vars: impl Iterator<Item = (String, String)>) {
308 let vars: Vec<(String, String)> = vars.collect();
309 let port = vars
312 .iter()
313 .find(|(name, _)| name == "PORT")
314 .map(|(_, raw)| (format!("{ENV_PREFIX}SERVER__PORT"), raw.clone()));
315 for (name, raw) in port.into_iter().chain(vars) {
316 let Some(path) = name.strip_prefix(ENV_PREFIX) else {
317 continue;
318 };
319 let keys: Vec<String> = path.split("__").map(str::to_lowercase).collect();
320 if keys.iter().any(String::is_empty) {
321 continue;
322 }
323
324 let mut current = &mut *table;
325 for key in &keys[..keys.len() - 1] {
326 let entry = current
327 .entry(key.clone())
328 .or_insert_with(|| Value::Table(Table::new()));
329 if !entry.is_table() {
330 *entry = Value::Table(Table::new());
331 }
332 current = entry.as_table_mut().expect("just ensured a table");
333 }
334 current.insert(keys[keys.len() - 1].clone(), parse_env_value(&raw));
335 }
336}
337
338fn parse_env_value(raw: &str) -> Value {
341 if let Ok(i) = raw.parse::<i64>() {
342 Value::Integer(i)
343 } else if let Ok(f) = raw.parse::<f64>() {
344 Value::Float(f)
345 } else if let Ok(b) = raw.parse::<bool>() {
346 Value::Boolean(b)
347 } else {
348 Value::String(raw.to_owned())
349 }
350}
351
352#[cfg(test)]
353mod tests {
354 #[test]
355 fn the_apps_url_is_configured_never_guessed() {
356 let config = Config::from_toml(Env::Development, "[server]\nport = 4100\n").unwrap();
357 assert_eq!(config.url().unwrap(), "http://localhost:4100");
358 let config =
359 Config::from_toml(Env::Production, "url = \"https://shop.example/\"\n").unwrap();
360 assert_eq!(config.url().unwrap(), "https://shop.example");
361 let config = Config::from_toml(Env::Production, "").unwrap();
362 assert!(config.url().is_err(), "production says where it lives");
363 }
364
365 use super::*;
366
367 #[test]
368 fn merges_files_and_env() {
369 let dir = std::env::temp_dir().join(format!("glacier-config-{}", std::process::id()));
370 std::fs::create_dir_all(&dir).unwrap();
371 std::fs::write(
372 dir.join("default.toml"),
373 "[server]\nport = 4000\nhost = \"0.0.0.0\"\n[db]\npool = 5\n",
374 )
375 .unwrap();
376 std::fs::write(dir.join("production.toml"), "[server]\nport = 80\n").unwrap();
377
378 let config = Config::load_from(&dir, Env::Production).unwrap();
379 assert_eq!(config.addr().unwrap(), "0.0.0.0:80");
380 assert_eq!(config.get::<u32>("db.pool").unwrap(), 5);
381 assert!(config.get_opt::<String>("nope.nothing").unwrap().is_none());
382 assert!(config.get::<bool>("db.pool").is_err());
383
384 let dev = Config::load_from(&dir, Env::Development).unwrap();
385 assert_eq!(dev.addr().unwrap(), "0.0.0.0:4000");
386 std::fs::remove_dir_all(dir).unwrap();
387 }
388
389 #[test]
390 fn env_vars_override_nested_keys() {
391 let mut table: Table = toml::from_str("[server]\nport = 4000\nhost = \"x\"").unwrap();
392 apply_env_overrides(
393 &mut table,
394 [
395 ("GLACIER__SERVER__PORT".into(), "8080".into()),
396 ("GLACIER__SECRET_KEY_BASE".into(), "abc".into()),
397 ("GLACIER__FEATURES__SIGNUP".into(), "true".into()),
398 ("OTHER".into(), "ignored".into()),
399 ]
400 .into_iter(),
401 );
402 let config = Config {
403 env: Env::Test,
404 table,
405 };
406 assert_eq!(config.get::<u16>("server.port").unwrap(), 8080);
407 assert_eq!(config.get::<String>("server.host").unwrap(), "x");
408 assert_eq!(config.get::<String>("secret_key_base").unwrap(), "abc");
409 assert!(config.get::<bool>("features.signup").unwrap());
410 assert_eq!(
412 config
413 .secret("secret_key_base", "GLACIER_TEST_UNSET")
414 .unwrap()
415 .as_deref(),
416 Some("abc")
417 );
418 assert_eq!(
419 config.secret("missing.key", "GLACIER_TEST_UNSET").unwrap(),
420 None
421 );
422 assert_eq!(config.get::<String>("server.port").unwrap(), "8080");
424 assert_eq!(config.get::<String>("features.signup").unwrap(), "true");
425 }
426
427 #[test]
428 fn loads_embedded_files_for_the_environment() {
429 let files = [
430 ("default", "[server]\nport = 4000\nhost = \"127.0.0.1\""),
431 ("production", "[server]\nhost = \"0.0.0.0\""),
432 ("development", "[server]\nport = 3000"),
433 ];
434 let prod = Config::load_embedded_as(&files, Env::Production).unwrap();
435 assert_eq!(prod.get::<String>("server.host").unwrap(), "0.0.0.0");
436 assert_eq!(prod.get::<u16>("server.port").unwrap(), 4000);
437 let test = Config::load_embedded_as(&files, Env::Test).unwrap();
438 assert_eq!(test.get::<String>("server.host").unwrap(), "127.0.0.1");
439 let err = Config::load_embedded_as(&[("default", "port = ")], Env::Test).unwrap_err();
440 assert!(err.to_string().contains("config/default.toml"), "{err}");
441 }
442
443 #[test]
444 fn port_from_the_platform() {
445 let port = |vars: &[(&str, &str)]| {
446 let mut table: Table = toml::from_str("[server]\nport = 4000").unwrap();
447 apply_env_overrides(
448 &mut table,
449 vars.iter().map(|(k, v)| (k.to_string(), v.to_string())),
450 );
451 Config {
452 env: Env::Production,
453 table,
454 }
455 .get::<u16>("server.port")
456 .unwrap()
457 };
458 assert_eq!(port(&[]), 4000);
459 assert_eq!(
460 port(&[("PORT", "8080")]),
461 8080,
462 "PORT beats the config files"
463 );
464 assert_eq!(
465 port(&[("GLACIER__SERVER__PORT", "9000"), ("PORT", "8080")]),
466 9000,
467 "the GLACIER__ variable beats PORT, in any order"
468 );
469 }
470
471 #[test]
472 fn deserializes_into_app_structs() {
473 #[derive(serde::Deserialize)]
474 struct AppConfig {
475 mailer: Mailer,
476 }
477 #[derive(serde::Deserialize)]
478 struct Mailer {
479 from: String,
480 }
481
482 let config = Config::from_toml(Env::Test, "[mailer]\nfrom = \"hi@example.com\"").unwrap();
483 let app: AppConfig = config.deserialize().unwrap();
484 assert_eq!(app.mailer.from, "hi@example.com");
485 }
486
487 #[test]
488 fn parses_env_names() {
489 assert_eq!("prod".parse::<Env>(), Ok(Env::Production));
490 assert_eq!("development".parse::<Env>(), Ok(Env::Development));
491 assert!("producton".parse::<Env>().is_err());
492 }
493}