capy-core 0.3.0

Typed configuration, application context, and errors for the Capy web framework.
Documentation
use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde_json::json;
use std::collections::BTreeMap;

/// Field names (including dotted nested paths) mapped to validation messages.
pub type ValidationErrors = BTreeMap<String, Vec<String>>;

/// The result type used by application handlers and startup.
pub type Result<T = ()> = std::result::Result<T, AppError>;

/// Errors with predictable HTTP statuses and safe public messages.
#[derive(thiserror::Error)]
pub enum AppError {
    /// The resource does not exist.
    #[error("Resource not found")]
    NotFound,
    /// Authentication is required.
    #[error("Unauthenticated")]
    Unauthorized,
    /// The operation is forbidden.
    #[error("Forbidden")]
    Forbidden,
    /// Field validation failed.
    #[error("Validation failed")]
    Validation(ValidationErrors),
    /// A conflict message safe to send to clients.
    #[error("{0}")]
    Conflict(String),
    /// A malformed request message safe to send to clients.
    #[error("{0}")]
    BadRequest(String),
    /// The payload exceeds Axum's body limit.
    #[error("Request body too large")]
    PayloadTooLarge,
    /// JSON requires an appropriate content type.
    #[error("Content-Type must be application/json")]
    UnsupportedMediaType,
    /// No handler accepts this request method.
    #[error("Method not allowed")]
    MethodNotAllowed,
    /// A native database error; its details are never returned over HTTP.
    #[error("Database operation failed")]
    Database(#[from] sea_orm::DbErr),
    /// Database initialization failed; the native cause is retained for inspection.
    /// Display/Debug use a safe category rather than driver text or connection URLs.
    #[error("Failed to connect to database: {}. Check DATABASE_URL and database availability.", connection_cause(.0))]
    DatabaseConnection(#[source] sea_orm::DbErr),
    /// An internal error; its details are never returned over HTTP.
    #[error("Internal server error")]
    Internal(#[from] anyhow::Error),
    /// A safe, actionable startup diagnostic.
    #[error("{0}")]
    Configuration(String),
    /// An operating system error during startup.
    #[error("Could not start the HTTP server. Check APP_HOST, APP_PORT, and port availability.")]
    Io(#[from] std::io::Error),
}

// Rust's main prints Debug on failure. Keep that output safe as well.
impl std::fmt::Debug for AppError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(self, f)
    }
}

/// Safe error category carried on an HTTP response for request diagnostics.
#[derive(Clone, Copy, Debug)]
pub struct ErrorKind(pub &'static str);

fn connection_cause(error: &sea_orm::DbErr) -> &'static str {
    use sea_orm::{ConnAcquireErr, DbErr, RuntimeErr, SqlxError};
    match error {
        DbErr::ConnectionAcquire(ConnAcquireErr::Timeout) => "connection pool timed out",
        DbErr::ConnectionAcquire(ConnAcquireErr::ConnectionClosed) => "connection pool closed",
        DbErr::Conn(RuntimeErr::SqlxError(error)) => match error {
            SqlxError::Io(e) => match e.kind() {
                std::io::ErrorKind::ConnectionRefused => "connection refused",
                std::io::ErrorKind::TimedOut => "connection timed out",
                std::io::ErrorKind::PermissionDenied => "permission denied",
                _ => "network or filesystem I/O failure",
            },
            SqlxError::Tls(_) => "TLS negotiation failed",
            SqlxError::Configuration(_) => "invalid connection options",
            SqlxError::Database(_) => "database rejected the connection",
            SqlxError::PoolTimedOut => "connection pool timed out",
            _ => "driver connection failure",
        },
        _ => "driver connection failure",
    }
}

impl AppError {
    /// Broad diagnostic category, safe to log without driver messages or input data.
    pub fn kind(&self) -> &'static str {
        match self {
            Self::Database(_) | Self::DatabaseConnection(_) => "database",
            Self::Internal(_) => "internal",
            Self::Configuration(_) => "configuration",
            Self::Io(_) => "io",
            Self::Validation(_) => "validation",
            _ => "request",
        }
    }

    /// The public HTTP status associated with this error.
    pub fn status(&self) -> StatusCode {
        match self {
            Self::NotFound => StatusCode::NOT_FOUND,
            Self::Unauthorized => StatusCode::UNAUTHORIZED,
            Self::Forbidden => StatusCode::FORBIDDEN,
            Self::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY,
            Self::Conflict(_) => StatusCode::CONFLICT,
            Self::BadRequest(_) => StatusCode::BAD_REQUEST,
            Self::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
            Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
            Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
            _ => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let status = self.status();
        let body = if let Self::Validation(errors) = &self {
            json!({ "message": "Validation failed", "errors": errors })
        } else if status.is_server_error() {
            json!({ "message": "Internal server error" })
        } else {
            json!({ "message": self.to_string() })
        };
        let mut response = (status, Json(body)).into_response();
        response.extensions_mut().insert(ErrorKind(self.kind()));
        response
    }
}