capy-core 0.4.0

Typed configuration, application context, and errors for the Capy web framework.
Documentation
use crate::{AppError, Result};
use figment::{
    providers::{Env, Format, Serialized, Toml},
    Figment,
};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, path::Path};

/// Application and database settings, resolved before startup.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct AppConfig {
    /// HTTP server settings.
    pub app: AppSettings,
    /// Database connection settings.
    pub database: DatabaseSettings,
    /// Listener overrides and bounded graceful shutdown (`SERVER_*`).
    pub server: ServerSettings,
    /// Request and readiness bounds (`HTTP_*`).
    pub http: HttpSettings,
}

/// Listener settings. Unspecified host/port retain legacy `APP_HOST`/`APP_PORT`.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct ServerSettings {
    /// Explicit listener interface or hostname; overrides `app.host`.
    pub host: Option<String>,
    /// Explicit listener port; overrides `app.port`.
    pub port: Option<u16>,
    /// Maximum graceful drain time in seconds (1..=3600).
    pub shutdown_timeout_seconds: u64,
}

impl Default for ServerSettings {
    fn default() -> Self {
        Self {
            host: None,
            port: None,
            shutdown_timeout_seconds: 10,
        }
    }
}

/// Small HTTP policy surface, expressed in seconds and bytes to avoid ambiguous units.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct HttpSettings {
    /// Deadline until response headers (0 disables it, otherwise at most 86400).
    pub request_timeout_seconds: u64,
    /// Independent readiness database probe timeout (1..=30 seconds).
    pub readiness_timeout_seconds: u64,
    /// Default body limit in bytes (1..=1073741824); native route overrides remain possible.
    pub max_body_bytes: usize,
    /// Enable negotiated gzip response compression with Tower's default predicate.
    pub compression: bool,
}

impl Default for HttpSettings {
    fn default() -> Self {
        Self {
            request_timeout_seconds: 30,
            readiness_timeout_seconds: 2,
            max_body_bytes: 2 * 1024 * 1024,
            compression: true,
        }
    }
}

/// HTTP server and logging settings. Environment variables use `APP_`.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct AppSettings {
    /// Display name of this application.
    pub name: String,
    /// `development`, `test`, or `production`.
    pub environment: String,
    /// Interface or hostname to bind.
    pub host: String,
    /// TCP port to bind (zero allows the OS to choose).
    pub port: u16,
}

impl Default for AppSettings {
    fn default() -> Self {
        Self {
            name: "Capy".into(),
            environment: "development".into(),
            host: "127.0.0.1".into(),
            port: 8000,
        }
    }
}

/// SeaORM connection settings. Environment variables use `DATABASE_`.
#[derive(Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct DatabaseSettings {
    /// PostgreSQL or SQLite connection URL. Debug output redacts this value.
    pub url: String,
    /// Maximum pool size; SQLite in-memory databases always use one connection.
    pub max_connections: u32,
    /// Maximum time to initialize the connection pool, in seconds.
    pub connect_timeout_seconds: u64,
    /// Minimum idle connections; cannot exceed the configured maximum.
    pub min_connections: u32,
    /// Maximum wait for an available connection, in seconds.
    pub acquire_timeout_seconds: u64,
    /// Maximum idle lifetime in seconds (1..=86400).
    pub idle_timeout_seconds: u64,
}

impl std::fmt::Debug for DatabaseSettings {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DatabaseSettings")
            .field("url", &"[redacted]")
            .field("max_connections", &self.max_connections)
            .field("connect_timeout_seconds", &self.connect_timeout_seconds)
            .field("min_connections", &self.min_connections)
            .field("acquire_timeout_seconds", &self.acquire_timeout_seconds)
            .field("idle_timeout_seconds", &self.idle_timeout_seconds)
            .finish()
    }
}

impl Default for DatabaseSettings {
    fn default() -> Self {
        Self {
            url: String::new(),
            max_connections: 10,
            connect_timeout_seconds: 10,
            min_connections: 0,
            acquire_timeout_seconds: 10,
            idle_timeout_seconds: 600,
        }
    }
}

impl AppConfig {
    /// Load from the current project directory.
    pub fn load() -> Result<Self> {
        Self::load_from(".")
    }

    /// Resolve defaults < TOML files < `.env` < process environment.
    /// Reading `.env` never mutates the process environment.
    pub fn load_from(root: impl AsRef<Path>) -> Result<Self> {
        let root = root.as_ref();
        let mut app_env = BTreeMap::new();
        let mut db_env = BTreeMap::new();
        let mut server_env = BTreeMap::new();
        let mut http_env = BTreeMap::new();
        match dotenvy::from_path_iter(root.join(".env")) {
            Ok(entries) => {
                for entry in entries {
                    let (key, value) = entry.map_err(|_| {
                        AppError::Configuration("Could not parse .env. Check its syntax.".into())
                    })?;
                    let value = serde_json::from_str::<serde_json::Value>(&value)
                        .unwrap_or(serde_json::Value::String(value));
                    if let Some(key) = key.strip_prefix("APP_") {
                        app_env.insert(key.to_lowercase(), value);
                    } else if let Some(key) = key.strip_prefix("DATABASE_") {
                        db_env.insert(key.to_lowercase(), value);
                    } else if let Some(key) = key.strip_prefix("SERVER_") {
                        server_env.insert(key.to_lowercase(), value);
                    } else if let Some(key) = key.strip_prefix("HTTP_") {
                        http_env.insert(key.to_lowercase(), value);
                    }
                }
            }
            Err(dotenvy::Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(_) => return Err(AppError::Configuration("Could not read .env.".into())),
        }
        let app = Figment::from(Serialized::defaults(AppSettings::default()))
            .merge(Toml::file(root.join("config/app.toml")))
            .merge(Serialized::defaults(app_env))
            .merge(Env::prefixed("APP_"))
            .extract()
            .map_err(|_| {
                AppError::Configuration(
                    "Invalid application settings. Check config/app.toml and APP_* variables."
                        .into(),
                )
            })?;
        let database = Figment::from(Serialized::defaults(DatabaseSettings::default()))
            .merge(Toml::file(root.join("config/database.toml")))
            .merge(Serialized::defaults(db_env))
            .merge(Env::prefixed("DATABASE_"))
            .extract()
            .map_err(|_| AppError::Configuration(
                "Invalid database settings. Check config/database.toml and DATABASE_* variables.".into(),
            ))?;
        let server = Figment::from(Serialized::defaults(ServerSettings::default()))
            .merge(Toml::file(root.join("config/server.toml")))
            .merge(Serialized::defaults(server_env))
            .merge(Env::prefixed("SERVER_"))
            .extract()
            .map_err(|_| AppError::Configuration(
                "Invalid server settings. Check config/server.toml and SERVER_* variables; ports must be 0..=65535 and deadlines integer seconds.".into()))?;
        let http = Figment::from(Serialized::defaults(HttpSettings::default()))
            .merge(Toml::file(root.join("config/http.toml")))
            .merge(Serialized::defaults(http_env))
            .merge(Env::prefixed("HTTP_"))
            .extract()
            .map_err(|_| AppError::Configuration(
                "Invalid HTTP settings. Check config/http.toml and HTTP_* variables; deadlines use integer seconds and body limits use integer bytes.".into()))?;
        let config = Self {
            app,
            database,
            server,
            http,
        };
        config.validate()?;
        Ok(config)
    }

    /// Validate manually constructed configuration as well as loaded settings.
    pub fn validate(&self) -> Result<()> {
        if self.app.name.trim().is_empty() || self.app.host.trim().is_empty() {
            return Err(AppError::Configuration(
                "APP_NAME and APP_HOST cannot be empty.".into(),
            ));
        }
        if !matches!(
            self.app.environment.as_str(),
            "development" | "test" | "production"
        ) {
            return Err(AppError::Configuration(
                "APP_ENVIRONMENT must be development, test, or production.".into(),
            ));
        }
        if self.host().trim().is_empty() || self.host().chars().any(char::is_whitespace) {
            return Err(AppError::Configuration(
                "SERVER_HOST must be a hostname or IP address without whitespace.".into(),
            ));
        }
        if self.app.environment == "production" && self.port() == 0 {
            return Err(AppError::Configuration(
                "The production server port must be 1..=65535.".into(),
            ));
        }
        if !(1..=3600).contains(&self.server.shutdown_timeout_seconds) {
            return Err(AppError::Configuration(
                "SERVER_SHUTDOWN_TIMEOUT_SECONDS must be 1..=3600.".into(),
            ));
        }
        if self.http.request_timeout_seconds > 86400 {
            return Err(AppError::Configuration("HTTP_REQUEST_TIMEOUT_SECONDS must be 0..=86400 (0 intentionally disables the deadline).".into()));
        }
        if !(1..=30).contains(&self.http.readiness_timeout_seconds) {
            return Err(AppError::Configuration(
                "HTTP_READINESS_TIMEOUT_SECONDS must be 1..=30.".into(),
            ));
        }
        if !(1..=1024 * 1024 * 1024).contains(&self.http.max_body_bytes) {
            return Err(AppError::Configuration(
                "HTTP_MAX_BODY_BYTES must be 1..=1073741824.".into(),
            ));
        }
        self.database.validate()
    }

    /// Effective listener host, including explicit server overrides.
    pub fn host(&self) -> &str {
        self.server.host.as_deref().unwrap_or(&self.app.host)
    }

    /// Effective listener port, including explicit server overrides.
    pub fn port(&self) -> u16 {
        self.server.port.unwrap_or(self.app.port)
    }
}

impl DatabaseSettings {
    /// Validate supported backends and pool limits without exposing credentials.
    pub fn validate(&self) -> Result<()> {
        if self.url.trim().is_empty() {
            return Err(AppError::Configuration(
                "Database configuration error: DATABASE_URL is missing.".into(),
            ));
        }
        if !(self.url.starts_with("postgres://")
            || self.url.starts_with("postgresql://")
            || self.url.starts_with("sqlite:"))
        {
            return Err(AppError::Configuration(
                "DATABASE_URL must use PostgreSQL or SQLite.".into(),
            ));
        }
        if self.max_connections == 0
            || self.max_connections > 10_000
            || self.min_connections > self.max_connections
            || !(1..=3600).contains(&self.connect_timeout_seconds)
            || !(1..=3600).contains(&self.acquire_timeout_seconds)
            || !(1..=86400).contains(&self.idle_timeout_seconds)
        {
            return Err(AppError::Configuration(
                "Invalid database pool: max_connections must be 1..=10000, min_connections <= max_connections, connect/acquire timeouts 1..=3600 seconds, idle timeout 1..=86400 seconds.".into(),
            ));
        }
        Ok(())
    }
}