capy-core 0.10.0

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

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

/// JSON wire envelope for Capy's standardized errors. It never carries native causes.
#[derive(Clone, Debug, Serialize, schemars::JsonSchema)]
pub struct ApiErrorResponse {
    /// Stable application policy code, present only for intentional listener rejection.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,
    /// Safe public message.
    pub message: String,
    /// Field validation errors, present only for validation failures.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[schemars(with = "ValidationErrors")]
    pub errors: Option<ValidationErrors>,
}

/// 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,
    /// The process-local abuse limit has been reached.
    #[error("Too many requests; try again later")]
    TooManyRequests,
    /// Internal password admission timed out, filled its bounded queue, or closed.
    /// Distinct from client abuse (429) and the HTTP request deadline (504).
    #[error("Service temporarily unavailable")]
    AuthCapacity,
    /// No trustworthy network identity is available for required IP throttling.
    #[error("Service temporarily unavailable")]
    ClientIdentityUnavailable,
    /// A transactional lifecycle participant failed; the owner must roll back.
    #[error("Internal server error")]
    Lifecycle,
    /// A deliberately public application rejection from a transactional listener.
    #[error("{0}")]
    Rejected(#[from] crate::EventRejection),
    /// 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 {
    /// Normalize native JSON rejections without reflecting payloads or parse internals.
    pub fn from_json_rejection(error: axum::extract::rejection::JsonRejection) -> Self {
        match error.status() {
            StatusCode::PAYLOAD_TOO_LARGE => Self::PayloadTooLarge,
            StatusCode::UNSUPPORTED_MEDIA_TYPE => Self::UnsupportedMediaType,
            StatusCode::UNPROCESSABLE_ENTITY => Self::Validation(
                [(
                    "body".into(),
                    vec!["The JSON body has missing or invalid fields.".into()],
                )]
                .into(),
            ),
            _ => Self::BadRequest("Malformed JSON body".into()),
        }
    }

    /// Broad diagnostic category, safe to log without driver messages or input data.
    pub fn kind(&self) -> &'static str {
        match self {
            Self::Lifecycle => "lifecycle",
            Self::Rejected(_) => "application_rejection",
            Self::AuthCapacity => "auth_capacity",
            Self::ClientIdentityUnavailable => "client_identity",
            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::Rejected(problem) => problem.status(),
            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,
            Self::TooManyRequests => StatusCode::TOO_MANY_REQUESTS,
            Self::AuthCapacity | Self::ClientIdentityUnavailable => StatusCode::SERVICE_UNAVAILABLE,
            _ => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let status = self.status();
        let body = if let Self::Rejected(problem) = &self {
            ApiErrorResponse {
                code: Some(problem.code().into()),
                message: problem.to_string(),
                errors: match problem {
                    crate::EventRejection::Validation { errors, .. } => Some(errors.clone()),
                    _ => None,
                },
            }
        } else if let Self::Validation(errors) = &self {
            ApiErrorResponse {
                code: None,
                message: "Validation failed".into(),
                errors: Some(errors.clone()),
            }
        } else if status.is_server_error() {
            ApiErrorResponse {
                code: None,
                message: if status == StatusCode::SERVICE_UNAVAILABLE {
                    "Service temporarily unavailable"
                } else {
                    "Internal server error"
                }
                .into(),
                errors: None,
            }
        } else {
            ApiErrorResponse {
                code: None,
                message: self.to_string(),
                errors: None,
            }
        };
        let mut response = (status, Json(body)).into_response();
        response.extensions_mut().insert(ErrorKind(self.kind()));
        response
    }
}