use std::collections::BTreeMap;
use std::fmt;
use std::path::{Component, Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::diagnostic::Diagnostic;
use crate::mode::RenderingMode;
pub const TOML_FILE: &str = "next-rust.toml";
pub const JSON_FILE: &str = "next-rust.json";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
#[serde(skip)]
pub root: PathBuf,
#[serde(skip)]
pub source: Option<PathBuf>,
pub app: AppConfig,
pub api: ApiConfig,
pub server: ServerConfig,
pub build: BuildConfig,
pub assets: AssetsConfig,
pub rendering: RenderingConfig,
pub images: ImagesConfig,
pub security: SecurityConfig,
pub env: EnvConfig,
pub dev: DevConfig,
pub logging: LoggingConfig,
pub redirects: Vec<RedirectRule>,
pub headers: Vec<HeaderRule>,
pub plugins: BTreeMap<String, serde_json::Value>,
}
impl Default for Config {
fn default() -> Self {
Self {
root: PathBuf::from("."),
source: None,
app: AppConfig::default(),
api: ApiConfig::default(),
server: ServerConfig::default(),
build: BuildConfig::default(),
assets: AssetsConfig::default(),
rendering: RenderingConfig::default(),
images: ImagesConfig::default(),
security: SecurityConfig::default(),
env: EnvConfig::default(),
dev: DevConfig::default(),
logging: LoggingConfig::default(),
redirects: Vec::new(),
headers: Vec::new(),
plugins: BTreeMap::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct AppConfig {
pub directory: PathBuf,
pub public: PathBuf,
pub base_path: String,
pub trailing_slash: bool,
pub lang: String,
pub html_precedence: HtmlPrecedence,
pub follow_symlinks: bool,
}
impl Default for AppConfig {
fn default() -> Self {
Self {
directory: PathBuf::from("app"),
public: PathBuf::from("public"),
base_path: String::new(),
trailing_slash: false,
lang: "en".into(),
html_precedence: HtmlPrecedence::Error,
follow_symlinks: true,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HtmlPrecedence {
#[default]
Error,
Rs,
Html,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ApiConfig {
pub directory: Option<PathBuf>,
pub prefix: String,
}
impl Default for ApiConfig {
fn default() -> Self {
Self { directory: None, prefix: "/api".into() }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ServerConfig {
pub host: String,
pub port: u16,
pub body_limit: usize,
pub header_timeout: u64,
pub request_timeout: u64,
pub shutdown_timeout: u64,
pub compression: bool,
pub http2: bool,
pub trust_proxy: bool,
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
host: "0.0.0.0".into(),
port: 3000,
body_limit: 2 * 1024 * 1024,
header_timeout: 10,
request_timeout: 60,
shutdown_timeout: 10,
compression: true,
http2: false,
trust_proxy: false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct BuildConfig {
pub output: PathBuf,
pub concurrency: usize,
pub optimize: Optimize,
pub panic: PanicStrategy,
}
impl Default for BuildConfig {
fn default() -> Self {
Self {
output: PathBuf::from(".next-rust"),
concurrency: 8,
optimize: Optimize::Size,
panic: PanicStrategy::Unwind,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Optimize {
#[default]
Size,
Speed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PanicStrategy {
#[default]
Unwind,
Abort,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct AssetsConfig {
pub optimize: bool,
pub public_max_age: u64,
}
impl Default for AssetsConfig {
fn default() -> Self {
Self { optimize: true, public_max_age: 0 }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct RenderingConfig {
pub default: RenderingMode,
pub streaming: bool,
pub revalidate: Option<u64>,
pub client_navigation: bool,
}
impl Default for RenderingConfig {
fn default() -> Self {
Self { default: RenderingMode::Auto, streaming: true, revalidate: None, client_navigation: true }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ImagesConfig {
pub sizes: Vec<u32>,
pub quality: u8,
pub max_age: u64,
}
impl Default for ImagesConfig {
fn default() -> Self {
Self { sizes: vec![640, 750, 828, 1080, 1200, 1920, 2048, 3840], quality: 75, max_age: 60 * 60 * 24 * 30 }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SecurityConfig {
pub headers: bool,
pub csp: Option<String>,
pub csrf: CsrfMode,
pub hsts_max_age: u64,
pub allowed_origins: Vec<String>,
}
impl Default for SecurityConfig {
fn default() -> Self {
Self { headers: true, csp: None, csrf: CsrfMode::Origin, hsts_max_age: 0, allowed_origins: Vec::new() }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CsrfMode {
#[default]
Origin,
Token,
Off,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct EnvConfig {
pub public_prefix: String,
}
impl Default for EnvConfig {
fn default() -> Self {
Self { public_prefix: "NEXT_RUST_PUBLIC_".into() }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct DevConfig {
pub poll_interval: u64,
pub overlay: bool,
pub watch: Vec<PathBuf>,
pub scaffold: bool,
}
impl Default for DevConfig {
fn default() -> Self {
Self { poll_interval: 250, overlay: true, watch: Vec::new(), scaffold: true }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct LoggingConfig {
pub format: LogFormat,
pub level: Option<String>,
pub requests: Option<bool>,
}
impl Default for LoggingConfig {
fn default() -> Self {
Self { format: LogFormat::Auto, level: None, requests: None }
}
}
impl LoggingConfig {
pub fn level(&self, env: crate::Environment) -> &str {
match &self.level {
Some(level) => level,
None if env.is_dev() => "info",
None => "error",
}
}
pub fn requests(&self, env: crate::Environment) -> bool {
self.requests.unwrap_or(env.is_dev())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LogFormat {
#[default]
Auto,
Pretty,
Json,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RedirectRule {
pub source: String,
pub destination: String,
#[serde(default)]
pub permanent: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HeaderRule {
pub source: String,
pub headers: BTreeMap<String, String>,
}
#[derive(Debug)]
pub enum ConfigError {
Io { path: PathBuf, error: std::io::Error },
Parse { path: PathBuf, message: String },
Ambiguous { dir: PathBuf },
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigError::Io { path, error } => write!(f, "could not read {}: {error}", path.display()),
ConfigError::Parse { path, message } => {
write!(f, "invalid configuration in {}:\n{message}", path.display())
}
ConfigError::Ambiguous { dir } => write!(
f,
"both {TOML_FILE} and {JSON_FILE} exist in {}; keep only one (TOML is preferred)",
dir.display()
),
}
}
}
impl std::error::Error for ConfigError {}
pub type TomlParser = fn(&str) -> Result<Config, String>;
impl Config {
pub fn discover(start: impl AsRef<Path>) -> Result<Self, ConfigError> {
Self::discover_with(start, Some(Self::from_toml_str))
}
pub fn discover_with(start: impl AsRef<Path>, toml: Option<TomlParser>) -> Result<Self, ConfigError> {
if let Ok(explicit) = std::env::var("NEXT_RUST_CONFIG") {
return Self::load_with(explicit, toml);
}
let start = absolutize(start.as_ref());
for dir in start.ancestors() {
let toml_file = dir.join(TOML_FILE);
let json = dir.join(JSON_FILE);
match (toml_file.is_file(), json.is_file()) {
(true, true) => return Err(ConfigError::Ambiguous { dir: dir.to_path_buf() }),
(true, false) => return Self::load_with(toml_file, toml),
(false, true) => return Self::load_with(json, toml),
_ => {}
}
if dir.join("Cargo.toml").is_file() && dir.join("app").is_dir() {
break;
}
}
let mut config = Config { root: start, ..Config::default() };
config.apply_env_overrides();
Ok(config)
}
pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
Self::load_with(path, Some(Self::from_toml_str))
}
pub fn load_with(path: impl AsRef<Path>, toml: Option<TomlParser>) -> Result<Self, ConfigError> {
let path = absolutize(path.as_ref());
let text = std::fs::read_to_string(&path).map_err(|error| ConfigError::Io { path: path.clone(), error })?;
let mut config = if path.extension().is_some_and(|e| e == "json") {
Self::from_json_str(&text)
} else {
match toml {
Some(parse) => parse(&text),
None => Err("this binary reads JSON configuration only (its configuration was embedded at build \
time); point NEXT_RUST_CONFIG at a .json file"
.to_owned()),
}
}
.map_err(|message| ConfigError::Parse { path: path.clone(), message })?;
config.root = path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."));
config.source = Some(path);
config.apply_env_overrides();
Ok(config)
}
pub fn from_toml_str(text: &str) -> Result<Self, String> {
toml::from_str(text).map_err(|e| e.to_string())
}
pub fn from_json_str(text: &str) -> Result<Self, String> {
serde_json::from_str(text).map_err(|e| e.to_string())
}
pub fn apply_env_overrides(&mut self) {
if let Some(port) = std::env::var("PORT").ok().and_then(|p| p.parse().ok()) {
self.server.port = port;
}
if let Ok(host) = std::env::var("HOST")
&& !host.is_empty()
{
self.server.host = host;
}
}
pub fn resolve(&self, path: impl AsRef<Path>) -> PathBuf {
let path = path.as_ref();
if path.is_absolute() { normalize(path) } else { normalize(&self.root.join(path)) }
}
pub fn app_dir(&self) -> PathBuf {
self.resolve(&self.app.directory)
}
pub fn public_dir(&self) -> PathBuf {
self.resolve(&self.app.public)
}
pub fn api_dir(&self) -> Option<PathBuf> {
self.api.directory.as_ref().map(|d| self.resolve(d))
}
pub fn output_dir(&self) -> PathBuf {
self.resolve(&self.build.output)
}
pub fn validate(&self) -> Vec<Diagnostic> {
let mut out = Vec::new();
let app = self.app_dir();
if !app.exists() {
out.push(
Diagnostic::error("NR0001", "App directory not found")
.location(&app)
.message(format!(
"The routing directory configured as `app.directory = {:?}`\nresolves to {}, which does not exist.",
self.app.directory,
app.display()
))
.help("create the directory or change `[app] directory` in next-rust.toml"),
);
} else if !app.is_dir() {
out.push(
Diagnostic::error("NR0002", "App directory is not a directory")
.location(&app)
.help("`[app] directory` must point to a directory"),
);
}
if let Some(api) = self.api_dir() {
if !api.is_dir() {
out.push(Diagnostic::error("NR0003", "API directory not found").location(api));
}
if !self.api.prefix.starts_with('/') {
out.push(
Diagnostic::error("NR0004", "API prefix must start with `/`")
.message(format!("found `api.prefix = {:?}`", self.api.prefix)),
);
}
}
if !self.app.base_path.is_empty() && (!self.app.base_path.starts_with('/') || self.app.base_path.ends_with('/'))
{
out.push(
Diagnostic::error("NR0005", "Invalid base path")
.message(format!("`app.base_path = {:?}`", self.app.base_path))
.help("use a leading slash and no trailing slash, e.g. `/docs`"),
);
}
for rule in &self.redirects {
if !rule.source.starts_with('/') {
out.push(
Diagnostic::error("NR0006", "Redirect source must start with `/`")
.message(format!("source = {:?}", rule.source)),
);
}
}
if let Some(level) = &self.logging.level
&& !matches!(level.as_str(), "error" | "warn" | "info" | "debug" | "trace")
{
out.push(
Diagnostic::warning("NR0007", "Unknown log level")
.message(format!("`logging.level = {level:?}`; falling back to `info`")),
);
}
out
}
pub fn socket_addr_string(&self) -> String {
if self.server.host.contains(':') {
format!("[{}]:{}", self.server.host, self.server.port)
} else {
format!("{}:{}", self.server.host, self.server.port)
}
}
}
fn absolutize(p: &Path) -> PathBuf {
if p.is_absolute() {
normalize(p)
} else {
normalize(&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")).join(p))
}
}
pub fn normalize(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for comp in path.components() {
match comp {
Component::CurDir => {}
Component::ParentDir => {
if !out.pop() {
out.push("..");
}
}
other => out.push(other.as_os_str()),
}
}
if out.as_os_str().is_empty() { PathBuf::from(".") } else { out }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_are_zero_config() {
let c = Config::from_toml_str("").unwrap();
assert_eq!(c.app.directory, PathBuf::from("app"));
assert_eq!(c.server.port, 3000);
assert_eq!(c.build.output, PathBuf::from(".next-rust"));
assert_eq!(c.rendering.default, RenderingMode::Auto);
}
#[test]
fn parses_sections() {
let c = Config::from_toml_str(
r#"
[app]
directory = "src/web"
[server]
port = 8080
[rendering]
default = "server"
[[redirects]]
source = "/old"
destination = "/new"
permanent = true
[plugins.analytics]
id = "x"
"#,
)
.unwrap();
assert_eq!(c.app.directory, PathBuf::from("src/web"));
assert_eq!(c.server.port, 8080);
assert_eq!(c.rendering.default, RenderingMode::Dynamic);
assert!(c.redirects[0].permanent);
assert_eq!(c.plugins["analytics"]["id"], "x");
}
#[test]
fn rejects_unknown_keys() {
let err = Config::from_toml_str("[app]\ndirectroy = \"x\"").unwrap_err();
assert!(err.contains("directroy"), "{err}");
}
#[test]
fn json_is_supported() {
let c = Config::from_json_str(r#"{"app":{"directory":"frontend"}}"#).unwrap();
assert_eq!(c.app.directory, PathBuf::from("frontend"));
}
#[test]
fn resolves_relative_to_root() {
let c = Config {
root: PathBuf::from("/work/repo/apps/site"),
app: AppConfig { directory: PathBuf::from("../shared/my-pages"), ..Default::default() },
..Default::default()
};
assert_eq!(c.app_dir(), PathBuf::from("/work/repo/apps/shared/my-pages"));
let c = Config {
root: PathBuf::from("/work"),
app: AppConfig { directory: PathBuf::from("/abs/pages/./x/.."), ..Default::default() },
..Default::default()
};
assert_eq!(c.app_dir(), PathBuf::from("/abs/pages"));
}
#[test]
fn discovery_walks_up() {
let base = std::env::temp_dir().join(format!("nr-config-{}", std::process::id()));
let nested = base.join("a/b");
std::fs::create_dir_all(&nested).unwrap();
std::fs::write(base.join(TOML_FILE), "[app]\ndirectory = \"website/routes\"\n").unwrap();
let c = Config::discover(&nested).unwrap();
assert_eq!(c.root, base);
assert_eq!(c.app_dir(), base.join("website/routes"));
let diags = c.validate();
assert_eq!(diags[0].code, "NR0001");
std::fs::write(base.join(JSON_FILE), "{}").unwrap();
assert!(matches!(Config::discover(&nested), Err(ConfigError::Ambiguous { .. })));
std::fs::remove_dir_all(&base).unwrap();
}
}