use std::fmt;
use std::path::Path;
use serde::de::DeserializeOwned;
use toml::{Table, Value};
use crate::error::{Error, Result};
const ENV_PREFIX: &str = "GLACIER__";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Env {
Development,
Test,
Production,
}
impl Env {
pub fn current() -> Env {
match std::env::var("GLACIER_ENV") {
Err(_) => Env::Development,
Ok(value) => value.parse().unwrap_or_else(|_| {
panic!("GLACIER_ENV=`{value}` is not one of development, test, production")
}),
}
}
pub fn as_str(self) -> &'static str {
match self {
Env::Development => "development",
Env::Test => "test",
Env::Production => "production",
}
}
pub fn is_development(self) -> bool {
self == Env::Development
}
pub fn is_production(self) -> bool {
self == Env::Production
}
}
impl std::str::FromStr for Env {
type Err = ();
fn from_str(s: &str) -> std::result::Result<Self, ()> {
match s {
"development" | "dev" => Ok(Env::Development),
"test" => Ok(Env::Test),
"production" | "prod" => Ok(Env::Production),
_ => Err(()),
}
}
}
impl fmt::Display for Env {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone)]
pub struct Config {
env: Env,
table: Table,
}
static CURRENT: std::sync::RwLock<Option<Config>> = std::sync::RwLock::new(None);
pub fn app_name() -> String {
Config::current().map_or_else(|_| "Glacier app".to_owned(), |config| config.app_name())
}
impl Config {
pub fn current() -> Result<Config> {
CURRENT
.read()
.unwrap_or_else(|e| e.into_inner())
.clone()
.ok_or_else(|| {
crate::Error::internal("the app's config isn't loaded yet (App::config)")
})
}
pub fn make_current(&self) {
*CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(self.clone());
}
pub fn load() -> Result<Self> {
Self::load_from("config", Env::current())
}
pub fn load_from(dir: impl AsRef<Path>, env: Env) -> Result<Self> {
let mut table = Table::new();
for name in ["default", env.as_str()] {
let path = dir.as_ref().join(format!("{name}.toml"));
let source = match std::fs::read_to_string(&path) {
Ok(source) => source,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
Err(err) => return Err(err.into()),
};
merge_toml(&mut table, &source, &path.display().to_string())?;
}
apply_env_overrides(&mut table, std::env::vars());
Ok(Self { env, table })
}
pub fn load_embedded(files: &[(&str, &str)]) -> Result<Self> {
Self::load_embedded_as(files, Env::current())
}
pub fn load_embedded_as(files: &[(&str, &str)], env: Env) -> Result<Self> {
let mut table = Table::new();
for name in ["default", env.as_str()] {
if let Some((_, source)) = files.iter().find(|(file, _)| *file == name) {
merge_toml(&mut table, source, &format!("config/{name}.toml"))?;
}
}
apply_env_overrides(&mut table, std::env::vars());
Ok(Self { env, table })
}
pub fn from_toml(env: Env, source: &str) -> Result<Self> {
let table = toml::from_str(source).map_err(|e| Error::internal(e.to_string()))?;
Ok(Self { env, table })
}
pub fn env(&self) -> Env {
self.env
}
pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<T> {
self.get_opt(key)?
.ok_or_else(|| Error::internal(format!("missing config key `{key}`")))
}
pub fn get_opt<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
let Some(value) = lookup(&self.table, key) else {
return Ok(None);
};
value.clone().try_into().map(Some).or_else(|e| {
match value {
Value::Integer(_) | Value::Float(_) | Value::Boolean(_) => {
Value::String(value.to_string()).try_into().map(Some)
}
_ => Err(e.clone()),
}
.map_err(|_| Error::internal(format!("config key `{key}`: {e}")))
})
}
pub fn secret(&self, key: &str, env_var: &str) -> Result<Option<String>> {
let configured = self
.get_opt::<String>(key)?
.filter(|value| !value.is_empty());
if configured.is_some() || self.env == Env::Test {
return Ok(configured);
}
Ok(std::env::var(env_var)
.ok()
.filter(|value| !value.is_empty()))
}
pub fn deserialize<T: DeserializeOwned>(&self) -> Result<T> {
Value::Table(self.table.clone())
.try_into()
.map_err(|e| Error::internal(format!("config: {e}")))
}
pub fn url(&self) -> Result<String> {
if let Some(url) = self.get_opt::<String>("url")? {
return Ok(url.trim_end_matches('/').to_owned());
}
if self.env() == Env::Production {
return Err(Error::internal(
"set `url` in the config (GLACIER__URL), the app's public address, for absolute links",
));
}
let addr = self
.addr()?
.replace("0.0.0.0", "localhost")
.replace("127.0.0.1", "localhost");
Ok(format!("http://{addr}"))
}
pub fn app_name(&self) -> String {
self.get_opt::<String>("name")
.ok()
.flatten()
.unwrap_or_else(|| "Glacier app".to_owned())
}
pub fn addr(&self) -> Result<String> {
let host: String = self
.get_opt("server.host")?
.unwrap_or_else(|| "127.0.0.1".into());
let port: u16 = self.get_opt("server.port")?.unwrap_or(4000);
Ok(format!("{host}:{port}"))
}
}
fn merge_toml(table: &mut Table, source: &str, name: &str) -> Result<()> {
let parsed: Table =
toml::from_str(source).map_err(|e| Error::internal(format!("{name}: {e}")))?;
merge(table, parsed);
Ok(())
}
fn lookup<'t>(table: &'t Table, key: &str) -> Option<&'t Value> {
let mut parts = key.split('.');
let mut value = table.get(parts.next()?)?;
for part in parts {
value = value.as_table()?.get(part)?;
}
Some(value)
}
fn merge(base: &mut Table, overlay: Table) {
for (key, value) in overlay {
match (base.get_mut(&key), value) {
(Some(Value::Table(existing)), Value::Table(incoming)) => merge(existing, incoming),
(_, value) => {
base.insert(key, value);
}
}
}
}
fn apply_env_overrides(table: &mut Table, vars: impl Iterator<Item = (String, String)>) {
let vars: Vec<(String, String)> = vars.collect();
let port = vars
.iter()
.find(|(name, _)| name == "PORT")
.map(|(_, raw)| (format!("{ENV_PREFIX}SERVER__PORT"), raw.clone()));
for (name, raw) in port.into_iter().chain(vars) {
let Some(path) = name.strip_prefix(ENV_PREFIX) else {
continue;
};
let keys: Vec<String> = path.split("__").map(str::to_lowercase).collect();
if keys.iter().any(String::is_empty) {
continue;
}
let mut current = &mut *table;
for key in &keys[..keys.len() - 1] {
let entry = current
.entry(key.clone())
.or_insert_with(|| Value::Table(Table::new()));
if !entry.is_table() {
*entry = Value::Table(Table::new());
}
current = entry.as_table_mut().expect("just ensured a table");
}
current.insert(keys[keys.len() - 1].clone(), parse_env_value(&raw));
}
}
fn parse_env_value(raw: &str) -> Value {
if let Ok(i) = raw.parse::<i64>() {
Value::Integer(i)
} else if let Ok(f) = raw.parse::<f64>() {
Value::Float(f)
} else if let Ok(b) = raw.parse::<bool>() {
Value::Boolean(b)
} else {
Value::String(raw.to_owned())
}
}
#[cfg(test)]
mod tests {
#[test]
fn the_apps_url_is_configured_never_guessed() {
let config = Config::from_toml(Env::Development, "[server]\nport = 4100\n").unwrap();
assert_eq!(config.url().unwrap(), "http://localhost:4100");
let config =
Config::from_toml(Env::Production, "url = \"https://shop.example/\"\n").unwrap();
assert_eq!(config.url().unwrap(), "https://shop.example");
let config = Config::from_toml(Env::Production, "").unwrap();
assert!(config.url().is_err(), "production says where it lives");
}
use super::*;
#[test]
fn merges_files_and_env() {
let dir = std::env::temp_dir().join(format!("glacier-config-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("default.toml"),
"[server]\nport = 4000\nhost = \"0.0.0.0\"\n[db]\npool = 5\n",
)
.unwrap();
std::fs::write(dir.join("production.toml"), "[server]\nport = 80\n").unwrap();
let config = Config::load_from(&dir, Env::Production).unwrap();
assert_eq!(config.addr().unwrap(), "0.0.0.0:80");
assert_eq!(config.get::<u32>("db.pool").unwrap(), 5);
assert!(config.get_opt::<String>("nope.nothing").unwrap().is_none());
assert!(config.get::<bool>("db.pool").is_err());
let dev = Config::load_from(&dir, Env::Development).unwrap();
assert_eq!(dev.addr().unwrap(), "0.0.0.0:4000");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn env_vars_override_nested_keys() {
let mut table: Table = toml::from_str("[server]\nport = 4000\nhost = \"x\"").unwrap();
apply_env_overrides(
&mut table,
[
("GLACIER__SERVER__PORT".into(), "8080".into()),
("GLACIER__SECRET_KEY_BASE".into(), "abc".into()),
("GLACIER__FEATURES__SIGNUP".into(), "true".into()),
("OTHER".into(), "ignored".into()),
]
.into_iter(),
);
let config = Config {
env: Env::Test,
table,
};
assert_eq!(config.get::<u16>("server.port").unwrap(), 8080);
assert_eq!(config.get::<String>("server.host").unwrap(), "x");
assert_eq!(config.get::<String>("secret_key_base").unwrap(), "abc");
assert!(config.get::<bool>("features.signup").unwrap());
assert_eq!(
config
.secret("secret_key_base", "GLACIER_TEST_UNSET")
.unwrap()
.as_deref(),
Some("abc")
);
assert_eq!(
config.secret("missing.key", "GLACIER_TEST_UNSET").unwrap(),
None
);
assert_eq!(config.get::<String>("server.port").unwrap(), "8080");
assert_eq!(config.get::<String>("features.signup").unwrap(), "true");
}
#[test]
fn loads_embedded_files_for_the_environment() {
let files = [
("default", "[server]\nport = 4000\nhost = \"127.0.0.1\""),
("production", "[server]\nhost = \"0.0.0.0\""),
("development", "[server]\nport = 3000"),
];
let prod = Config::load_embedded_as(&files, Env::Production).unwrap();
assert_eq!(prod.get::<String>("server.host").unwrap(), "0.0.0.0");
assert_eq!(prod.get::<u16>("server.port").unwrap(), 4000);
let test = Config::load_embedded_as(&files, Env::Test).unwrap();
assert_eq!(test.get::<String>("server.host").unwrap(), "127.0.0.1");
let err = Config::load_embedded_as(&[("default", "port = ")], Env::Test).unwrap_err();
assert!(err.to_string().contains("config/default.toml"), "{err}");
}
#[test]
fn port_from_the_platform() {
let port = |vars: &[(&str, &str)]| {
let mut table: Table = toml::from_str("[server]\nport = 4000").unwrap();
apply_env_overrides(
&mut table,
vars.iter().map(|(k, v)| (k.to_string(), v.to_string())),
);
Config {
env: Env::Production,
table,
}
.get::<u16>("server.port")
.unwrap()
};
assert_eq!(port(&[]), 4000);
assert_eq!(
port(&[("PORT", "8080")]),
8080,
"PORT beats the config files"
);
assert_eq!(
port(&[("GLACIER__SERVER__PORT", "9000"), ("PORT", "8080")]),
9000,
"the GLACIER__ variable beats PORT, in any order"
);
}
#[test]
fn deserializes_into_app_structs() {
#[derive(serde::Deserialize)]
struct AppConfig {
mailer: Mailer,
}
#[derive(serde::Deserialize)]
struct Mailer {
from: String,
}
let config = Config::from_toml(Env::Test, "[mailer]\nfrom = \"hi@example.com\"").unwrap();
let app: AppConfig = config.deserialize().unwrap();
assert_eq!(app.mailer.from, "hi@example.com");
}
#[test]
fn parses_env_names() {
assert_eq!("prod".parse::<Env>(), Ok(Env::Production));
assert_eq!("development".parse::<Env>(), Ok(Env::Development));
assert!("producton".parse::<Env>().is_err());
}
}