use std::collections::BTreeMap;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use nitr_core::RuntimeOpts;
use nitr_core::{Error, Result};
use nitr_std::Builtins;
mod database;
mod env;
mod sections;
mod validate;
pub use database::DatabaseConfig;
pub use sections::*;
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
pub listen: SocketAddr,
pub handler_script: PathBuf,
pub config_script: Option<PathBuf>,
pub database: Option<DatabaseConfig>,
pub workers: usize,
pub max_streams: Option<usize>,
pub dev_mode: bool,
pub std: StdConfig,
pub trust_request_id: bool,
pub limits: LimitsConfig,
pub rate_limit: RateLimitConfig,
pub fetch: FetchConfig,
pub shutdown: ShutdownConfig,
pub compression: CompressionConfig,
pub cors: CorsConfig,
pub headers: BTreeMap<String, String>,
pub tls: TlsConfig,
pub cache: CacheConfig,
#[serde(rename = "static")]
pub static_files: StaticConfig,
pub templating: TemplatingConfig,
pub multipart: MultipartConfig,
pub cookies: CookiesConfig,
pub testing: TestingConfig,
pub env: EnvConfig,
pub lua: LuaConfig,
pub health: HealthConfig,
#[serde(skip)]
pub static_dirs_optional: bool,
pub openapi: OpenApiConfig,
pub swagger: SwaggerConfig,
pub log: LogConfig,
pub pidfile: Option<PathBuf>,
}
impl Default for Config {
fn default() -> Self {
Self {
listen: SocketAddr::from(([127, 0, 0, 1], 3000)),
handler_script: PathBuf::from("scripts/handler.lua"),
config_script: None,
database: None,
workers: std::thread::available_parallelism().map_or(1, |n| n.get()),
max_streams: None,
dev_mode: false,
std: StdConfig::default(),
trust_request_id: false,
limits: LimitsConfig::default(),
rate_limit: RateLimitConfig::default(),
fetch: FetchConfig::default(),
shutdown: ShutdownConfig::default(),
compression: CompressionConfig::default(),
cors: CorsConfig::default(),
headers: BTreeMap::new(),
tls: TlsConfig::default(),
cache: CacheConfig::default(),
static_files: StaticConfig::default(),
templating: TemplatingConfig::default(),
multipart: MultipartConfig::default(),
cookies: CookiesConfig::default(),
testing: TestingConfig::default(),
env: EnvConfig::default(),
lua: LuaConfig::default(),
health: HealthConfig::default(),
static_dirs_optional: false,
openapi: OpenApiConfig::default(),
swagger: SwaggerConfig::default(),
log: LogConfig::default(),
pidfile: None,
}
}
}
impl Config {
pub(crate) fn readiness_delay(&self) -> std::time::Duration {
let probes_on_main = self.health.enabled && self.health.bind.is_none();
let secs = match self.shutdown.readiness_delay {
Some(secs) => secs,
None if probes_on_main && !self.dev_mode => 5,
None => 0,
};
std::time::Duration::from_secs(secs)
}
pub(crate) fn effective_max_streams(&self) -> usize {
self.max_streams
.unwrap_or_else(|| self.workers.max(1).saturating_sub(1).max(1))
}
pub fn from_file(path: &Path) -> Result<Self> {
let data = std::fs::read_to_string(path).map_err(|err| {
Error::Config(format!(
"failed to read the config file {}: {err}",
path.display()
))
})?;
if let Ok(doc) = toml::from_str::<toml::Value>(&data) {
check_moved_keys(&doc)?;
}
toml::from_str(&data).map_err(|err| {
Error::Config(format!(
"failed to parse the config file {}: {err}",
path.display()
))
})
}
pub fn env_options(&self) -> nitr_std::EnvOptions {
nitr_std::EnvOptions {
allow: self.env.allow.clone(),
mode: if self.dev_mode {
nitr_std::RunMode::Dev
} else {
nitr_std::RunMode::Run
},
}
}
pub fn cookie_insecure_warning(&self) -> Option<String> {
let auto_insecure = self.cookies.secure == CookieSecure::Auto && !self.tls.enabled;
(auto_insecure && !self.dev_mode).then(|| {
"a cookie was sent without the `Secure` attribute: [tls] enabled = false, and \
[cookies] secure = \"auto\" follows it. If TLS is terminated by a proxy in front \
of this process, set [cookies] secure = \"always\"; nothing here can detect that \
proxy."
.into()
})
}
pub fn cache_options(&self) -> nitr_std::CacheOptions {
nitr_std::CacheOptions {
max_entries: self.cache.max_entries.max(1),
max_bytes: self.cache.max_bytes,
default_ttl: self.cache.default_ttl,
}
}
pub fn builtins(&self) -> Result<Builtins> {
let Some(names) = &self.std.features else {
return Ok(Builtins::minimal());
};
let mut builtins = Builtins::empty();
for name in names {
let builtin = Builtins::from_config_name(name)
.ok_or_else(|| Error::Config(format!("unknown std feature `{name}`")))?;
if builtin == Builtins::TEMPLATE && self.templating.dir.is_none() {
return Err(Error::Config(
"std feature `template` is enabled but `[templating] dir` is not set".into(),
));
}
if builtin == Builtins::DATABASE && self.database.is_none() {
return Err(Error::Config(
"std feature `db` is enabled but `database` is not set".into(),
));
}
builtins |= builtin;
}
Ok(builtins)
}
pub(crate) fn package_dir(&self) -> &Path {
self.handler_script
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."))
}
pub fn runtime_opts(&self) -> Result<RuntimeOpts> {
let package_dir = self.package_dir().to_path_buf();
Ok(RuntimeOpts {
libs: self.lua.parse_stdlib()?,
memory_limit: self.lua.memory_limit,
dev_mode: self.dev_mode,
exec_timeout: match self.lua.exec_timeout_ms {
0 => None,
ms => Some(std::time::Duration::from_millis(ms)),
},
package_dir: Some(package_dir),
extra_package_dirs: Vec::new(),
})
}
}
fn check_moved_keys(doc: &toml::Value) -> Result {
let Some(table) = doc.as_table() else {
return Ok(());
};
if table.get("database").is_some_and(toml::Value::is_str) {
return Err(Error::Config(
"`database` is now a table: replace `database = \"app.db\"` with a \
`[database]` section containing `path = \"app.db\"`"
.into(),
));
}
if table.contains_key("tests_dir") {
return Err(Error::Config(
"`tests_dir` moved: replace it with a `[testing]` section \
containing `dir = \"...\"`"
.into(),
));
}
if table.contains_key("templates_dir") {
return Err(Error::Config(
"`templates_dir` moved: replace it with a `[templating]` section \
containing `dir = \"...\"`"
.into(),
));
}
Ok(())
}
#[cfg(test)]
mod tests;