Skip to main content

aurelin_framework/
configuration.rs

1//! Application environment loading without process-wide mutation.
2
3use std::{collections::HashMap, env, io, path::Path};
4
5use config::{Config, ConfigError, Environment};
6use serde::Deserialize;
7use thiserror::Error;
8
9/// Configuration could not be loaded. Values are deliberately not included in
10/// dotenv parse diagnostics because environment files may contain credentials.
11#[derive(Debug, Error)]
12pub enum ConfigurationError {
13    #[error("could not read the application environment file")]
14    Read(#[source] io::Error),
15    #[error("invalid application environment syntax at character {0}")]
16    Syntax(usize),
17    #[error("could not parse the application environment")]
18    Environment,
19    #[error("invalid server configuration: {0}")]
20    Server(#[from] ConfigError),
21}
22
23/// A snapshot of `.env` plus external variables, with external variables taking
24/// precedence. Missing environment files are allowed, as in Laravel.
25///
26/// An externally supplied `APP_ENV` selects `.env.APP_ENV` when that file exists.
27/// No process environment is changed, including when called in an async app.
28pub fn environment(base_path: &Path) -> Result<HashMap<String, String>, ConfigurationError> {
29    environment_from(base_path, env::vars().collect())
30}
31
32/// Loads an environment snapshot from dotenv files and explicit external
33/// values. This is useful for hosts that source environment values somewhere
34/// other than the current process.
35pub fn environment_from(
36    base_path: &Path,
37    external: HashMap<String, String>,
38) -> Result<HashMap<String, String>, ConfigurationError> {
39    let mut path = base_path.join(".env");
40    if let Some(name) = external.get("APP_ENV") {
41        let candidate = base_path.join(format!(".env.{name}"));
42        match candidate.try_exists() {
43            Ok(true) => path = candidate,
44            Ok(false) => {}
45            Err(error) => return Err(ConfigurationError::Read(error)),
46        }
47    }
48
49    let mut values = HashMap::new();
50    match dotenvy::from_path_iter(&path) {
51        Ok(entries) => {
52            for entry in entries {
53                let (key, value) = entry.map_err(environment_error)?;
54                values.entry(key).or_insert(value);
55            }
56        }
57        Err(dotenvy::Error::Io(error)) if error.kind() == io::ErrorKind::NotFound => {}
58        Err(error) => return Err(environment_error(error)),
59    }
60    values.extend(external);
61    Ok(values)
62}
63
64fn environment_error(error: dotenvy::Error) -> ConfigurationError {
65    match error {
66        dotenvy::Error::Io(error) => ConfigurationError::Read(error),
67        dotenvy::Error::LineParse(_, position) => ConfigurationError::Syntax(position),
68        _ => ConfigurationError::Environment,
69    }
70}
71
72/// HTTP listener settings. Defaults follow Laravel 13's development server.
73#[derive(Debug, Deserialize)]
74pub struct ServerConfig {
75    pub host: String,
76    pub port: u16,
77}
78
79impl ServerConfig {
80    /// Reads `SERVER_HOST` and `SERVER_PORT`, defaulting to `127.0.0.1:8000`.
81    pub fn from_environment(values: HashMap<String, String>) -> Result<Self, ConfigurationError> {
82        Ok(Config::builder()
83            .set_default("host", "127.0.0.1")?
84            .set_default("port", 8000)?
85            .add_source(Environment::with_prefix("SERVER").source(Some(values)))
86            .build()?
87            .try_deserialize()?)
88    }
89}