glacier-web 0.3.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! 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).or_else(|e| {
            // An environment variable that looks like a number or a
            // boolean (`GLACIER__MAIL__SMTP__PASSWORD=12345`) is read as
            // one; where text is wanted, it's still text.
            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}")))
        })
    }

    /// A secret, such as an API key: the config's `key` (which an
    /// environment variable overrides as usual: `stripe.api_key` from
    /// `GLACIER__STRIPE__API_KEY`), or else the service's own variable,
    /// `env_var` (`STRIPE_API_KEY`), as other tools set it. `None` when
    /// neither is set; an empty value counts as unset.
    ///
    /// Tests read only the config (and `GLACIER__…` variables): a real key
    /// left in a developer's shell never reaches them.
    ///
    /// ```ignore
    /// let key = config.secret("stripe.api_key", "STRIPE_API_KEY")?;
    /// ```
    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()))
    }

    /// 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::<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());
        // A secret from the config, or the service's own variable.
        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
        );
        // Text that looks like a number is still text where text is wanted.
        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());
    }
}