glacier-web 0.1.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Configuration and environments.
//!
//! `Config::load()` merges, in increasing priority:
//!
//! 1. `config/default.toml`
//! 2. `config/<env>.toml` (`development`, `test` or `production`)
//! 3. environment variables: `GLACIER__SERVER__PORT=8080` sets `server.port`.
//!    `PORT`, which hosting platforms set, also sets it (the `GLACIER__`
//!    variable wins if both are set).
//!
//! Keys Glacier itself reads:
//!
//! | key | default | |
//! | --- | --- | --- |
//! | `server.host` | `127.0.0.1` | |
//! | `server.port` | `4000` | or `PORT` |
//! | `server.max_body_size` | 2 MiB | bytes |
//! | `secret_key_base` | random per boot | at least 32 bytes; signs and encrypts cookies. Required in production. |

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__";

/// The environment the app runs in, from `GLACIER_ENV`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Env {
    Development,
    Test,
    Production,
}

impl Env {
    /// Reads `GLACIER_ENV`, defaulting to development when unset.
    ///
    /// # Panics
    ///
    /// On an unrecognized value. A typo like `producton` must not silently
    /// boot in development mode with debug pages switched on.
    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())
    }
}

/// Merged configuration for one environment.
#[derive(Debug, Clone)]
pub struct Config {
    env: Env,
    table: Table,
}

impl Config {
    /// Loads `./config` for the current environment.
    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 })
    }

    /// Like [`Config::load`], from files compiled into the binary:
    /// `(name, contents)` pairs such as `("production", "…")`, as
    /// `glacier::config!()` passes them in release builds. Environment
    /// variables still override them.
    pub fn load_embedded(files: &[(&str, &str)]) -> Result<Self> {
        Self::load_embedded_as(files, Env::current())
    }

    /// [`Config::load_embedded`] for a given environment.
    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 })
    }

    /// Builds a config from a TOML string, without touching the filesystem
    /// or environment. Handy in tests.
    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
    }

    /// Reads a dotted key such as `"database.pool_size"`.
    pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<T> {
        self.get_opt(key)?
            .ok_or_else(|| Error::internal(format!("missing config key `{key}`")))
    }

    /// Like `get`, but a missing key is `Ok(None)`.
    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)
            .map_err(|e| Error::internal(format!("config key `{key}`: {e}")))
    }

    /// Deserializes the whole config into an app-defined struct.
    pub fn deserialize<T: DeserializeOwned>(&self) -> Result<T> {
        Value::Table(self.table.clone())
            .try_into()
            .map_err(|e| Error::internal(format!("config: {e}")))
    }

    /// `server.host:server.port`, defaulting to `127.0.0.1:4000`.
    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)
}

/// Deep-merges `overlay` into `base`; tables merge, everything else replaces.
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();
    // `PORT`, as hosting platforms set it, is `server.port`; applied first,
    // so `GLACIER__SERVER__PORT` still wins.
    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));
    }
}

/// Env values are typed loosely: integers, floats and booleans are
/// recognized, everything else is a string.
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 {
    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::<String>("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());
    }

    #[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());
    }
}