servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! Parse a single environment snapshot without echoing potentially secret values.

use super::{AppConfig, ConfigError};
use crate::Role;
use std::time::Duration;

impl AppConfig {
    /// Load `SERVLET_*` variables over defaults and validate for [`Role::All`].
    /// See [`Self::from_env_for_role`] for other roles and loading behavior.
    pub fn from_env() -> Result<Self, ConfigError> {
        Self::from_env_for_role(Role::All)
    }

    /// Load `SERVLET_*` variables over defaults and validate for the selected role.
    ///
    /// Unknown keys and invalid values are rejected. No dotenv discovery or
    /// environment mutation occurs.
    pub fn from_env_for_role(role: Role) -> Result<Self, ConfigError> {
        let config = Self::load_environment()?;
        config.validate_for_role(role)?;
        Ok(config)
    }

    pub(crate) fn load_environment() -> Result<Self, ConfigError> {
        let mut values = Vec::new();
        for (key, value) in std::env::vars_os() {
            if key.to_string_lossy().starts_with("SERVLET_") {
                let key = key
                    .into_string()
                    .map_err(|_| ConfigError::Environment("non-UTF-8 key".into()))?;
                let value = value
                    .into_string()
                    .map_err(|_| ConfigError::Environment(key.clone()))?;
                values.push((key, value));
            }
        }
        Self::parse_pairs(values)
    }

    /// Load a supplied environment snapshot and validate for [`Role::All`].
    /// See [`Self::from_env_pairs_for_role`] for other roles and value formats.
    pub fn from_env_pairs<I, K, V>(values: I) -> Result<Self, ConfigError>
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        Self::from_env_pairs_for_role(values, Role::All)
    }

    /// Load a supplied environment snapshot and validate for the selected role.
    ///
    /// Durations are positive integer milliseconds (`100ms`) or seconds (`30s`).
    pub fn from_env_pairs_for_role<I, K, V>(values: I, role: Role) -> Result<Self, ConfigError>
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let config = Self::parse_pairs(values)?;
        config.validate_for_role(role)?;
        Ok(config)
    }

    fn parse_pairs<I, K, V>(values: I) -> Result<Self, ConfigError>
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let mut config = Self::default();
        for (key, value) in values {
            let (key, value) = (key.as_ref(), value.as_ref());
            if !key.starts_with("SERVLET_") {
                continue;
            }
            config
                .assign(key, value)
                .ok_or_else(|| ConfigError::Environment(key.to_owned()))?;
        }
        Ok(config)
    }
    fn assign(&mut self, key: &str, value: &str) -> Option<()> {
        match key {
            "SERVLET_BIND" => self.bind = value.parse().ok()?,
            "SERVLET_ADMIN_BIND" => {
                self.admin_bind = if value == "off" {
                    None
                } else {
                    Some(value.parse().ok()?)
                }
            }
            "SERVLET_ALLOW_REMOTE_ADMIN" => self.allow_remote_admin = value.parse().ok()?,
            "SERVLET_REQUEST_BODY_LIMIT" => self.request_body_limit = value.parse().ok()?,
            "SERVLET_MAX_IN_FLIGHT" => self.max_in_flight = value.parse().ok()?,
            "SERVLET_MAX_CONNECTIONS" => self.max_connections = value.parse().ok()?,
            "SERVLET_HEADER_TIMEOUT" => self.header_timeout = duration(value)?,
            "SERVLET_BODY_IDLE_TIMEOUT" => self.body_idle_timeout = duration(value)?,
            "SERVLET_REQUEST_TIMEOUT" => self.request_timeout = duration(value)?,
            "SERVLET_STARTUP_TIMEOUT" => self.startup_timeout = duration(value)?,
            "SERVLET_SHUTDOWN_TIMEOUT" => self.shutdown_timeout = duration(value)?,
            "SERVLET_CLEANUP_RESERVE" => self.cleanup_reserve = duration(value)?,
            _ => return None,
        }
        Some(())
    }
}
fn duration(value: &str) -> Option<Duration> {
    if let Some(millis) = value.strip_suffix("ms") {
        Some(Duration::from_millis(millis.parse().ok()?))
    } else {
        Some(Duration::from_secs(value.strip_suffix('s')?.parse().ok()?))
    }
}

#[cfg(test)]
#[path = "environment_test.rs"]
mod environment_test;