use super::{AppConfig, ConfigError};
use std::time::Duration;
impl AppConfig {
pub fn from_env() -> Result<Self, ConfigError> {
let config = Self::load_environment()?;
config.validate()?;
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)
}
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>,
{
let config = Self::parse_pairs(values)?;
config.validate()?;
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;