Skip to main content

capy_core/
error.rs

1use axum::{
2    http::StatusCode,
3    response::{IntoResponse, Response},
4    Json,
5};
6use serde::Serialize;
7use std::collections::BTreeMap;
8
9/// Field names (including dotted nested paths) mapped to validation messages.
10pub type ValidationErrors = BTreeMap<String, Vec<String>>;
11
12/// JSON wire envelope for Capy's standardized errors. It never carries native causes.
13#[derive(Clone, Debug, Serialize, schemars::JsonSchema)]
14pub struct ApiErrorResponse {
15    /// Stable application policy code, present only for intentional listener rejection.
16    #[serde(skip_serializing_if = "Option::is_none")]
17    pub code: Option<String>,
18    /// Safe public message.
19    pub message: String,
20    /// Field validation errors, present only for validation failures.
21    #[serde(skip_serializing_if = "Option::is_none")]
22    #[schemars(with = "ValidationErrors")]
23    pub errors: Option<ValidationErrors>,
24}
25
26/// The result type used by application handlers and startup.
27pub type Result<T = ()> = std::result::Result<T, AppError>;
28
29/// Errors with predictable HTTP statuses and safe public messages.
30#[derive(thiserror::Error)]
31pub enum AppError {
32    /// The resource does not exist.
33    #[error("Resource not found")]
34    NotFound,
35    /// Authentication is required.
36    #[error("Unauthenticated")]
37    Unauthorized,
38    /// The operation is forbidden.
39    #[error("Forbidden")]
40    Forbidden,
41    /// Field validation failed.
42    #[error("Validation failed")]
43    Validation(ValidationErrors),
44    /// A conflict message safe to send to clients.
45    #[error("{0}")]
46    Conflict(String),
47    /// A malformed request message safe to send to clients.
48    #[error("{0}")]
49    BadRequest(String),
50    /// The payload exceeds Axum's body limit.
51    #[error("Request body too large")]
52    PayloadTooLarge,
53    /// JSON requires an appropriate content type.
54    #[error("Content-Type must be application/json")]
55    UnsupportedMediaType,
56    /// No handler accepts this request method.
57    #[error("Method not allowed")]
58    MethodNotAllowed,
59    /// The process-local abuse limit has been reached.
60    #[error("Too many requests; try again later")]
61    TooManyRequests,
62    /// Internal password admission timed out, filled its bounded queue, or closed.
63    /// Distinct from client abuse (429) and the HTTP request deadline (504).
64    #[error("Service temporarily unavailable")]
65    AuthCapacity,
66    /// No trustworthy network identity is available for required IP throttling.
67    #[error("Service temporarily unavailable")]
68    ClientIdentityUnavailable,
69    /// A transactional lifecycle participant failed; the owner must roll back.
70    #[error("Internal server error")]
71    Lifecycle,
72    /// A deliberately public application rejection from a transactional listener.
73    #[error("{0}")]
74    Rejected(#[from] crate::EventRejection),
75    /// A native database error; its details are never returned over HTTP.
76    #[error("Database operation failed")]
77    Database(#[from] sea_orm::DbErr),
78    /// Database initialization failed; the native cause is retained for inspection.
79    /// Display/Debug use a safe category rather than driver text or connection URLs.
80    #[error("Failed to connect to database: {}. Check DATABASE_URL and database availability.", connection_cause(.0))]
81    DatabaseConnection(#[source] sea_orm::DbErr),
82    /// An internal error; its details are never returned over HTTP.
83    #[error("Internal server error")]
84    Internal(#[from] anyhow::Error),
85    /// A safe, actionable startup diagnostic.
86    #[error("{0}")]
87    Configuration(String),
88    /// An operating system error during startup.
89    #[error("Could not start the HTTP server. Check APP_HOST, APP_PORT, and port availability.")]
90    Io(#[from] std::io::Error),
91}
92
93// Rust's main prints Debug on failure. Keep that output safe as well.
94impl std::fmt::Debug for AppError {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        std::fmt::Display::fmt(self, f)
97    }
98}
99
100/// Safe error category carried on an HTTP response for request diagnostics.
101#[derive(Clone, Copy, Debug)]
102pub struct ErrorKind(pub &'static str);
103
104fn connection_cause(error: &sea_orm::DbErr) -> &'static str {
105    use sea_orm::{ConnAcquireErr, DbErr, RuntimeErr, SqlxError};
106    match error {
107        DbErr::ConnectionAcquire(ConnAcquireErr::Timeout) => "connection pool timed out",
108        DbErr::ConnectionAcquire(ConnAcquireErr::ConnectionClosed) => "connection pool closed",
109        DbErr::Conn(RuntimeErr::SqlxError(error)) => match error {
110            SqlxError::Io(e) => match e.kind() {
111                std::io::ErrorKind::ConnectionRefused => "connection refused",
112                std::io::ErrorKind::TimedOut => "connection timed out",
113                std::io::ErrorKind::PermissionDenied => "permission denied",
114                _ => "network or filesystem I/O failure",
115            },
116            SqlxError::Tls(_) => "TLS negotiation failed",
117            SqlxError::Configuration(_) => "invalid connection options",
118            SqlxError::Database(_) => "database rejected the connection",
119            SqlxError::PoolTimedOut => "connection pool timed out",
120            _ => "driver connection failure",
121        },
122        _ => "driver connection failure",
123    }
124}
125
126impl AppError {
127    /// Normalize native JSON rejections without reflecting payloads or parse internals.
128    pub fn from_json_rejection(error: axum::extract::rejection::JsonRejection) -> Self {
129        match error.status() {
130            StatusCode::PAYLOAD_TOO_LARGE => Self::PayloadTooLarge,
131            StatusCode::UNSUPPORTED_MEDIA_TYPE => Self::UnsupportedMediaType,
132            StatusCode::UNPROCESSABLE_ENTITY => Self::Validation(
133                [(
134                    "body".into(),
135                    vec!["The JSON body has missing or invalid fields.".into()],
136                )]
137                .into(),
138            ),
139            _ => Self::BadRequest("Malformed JSON body".into()),
140        }
141    }
142
143    /// Broad diagnostic category, safe to log without driver messages or input data.
144    pub fn kind(&self) -> &'static str {
145        match self {
146            Self::Lifecycle => "lifecycle",
147            Self::Rejected(_) => "application_rejection",
148            Self::AuthCapacity => "auth_capacity",
149            Self::ClientIdentityUnavailable => "client_identity",
150            Self::Database(_) | Self::DatabaseConnection(_) => "database",
151            Self::Internal(_) => "internal",
152            Self::Configuration(_) => "configuration",
153            Self::Io(_) => "io",
154            Self::Validation(_) => "validation",
155            _ => "request",
156        }
157    }
158
159    /// The public HTTP status associated with this error.
160    pub fn status(&self) -> StatusCode {
161        match self {
162            Self::Rejected(problem) => problem.status(),
163            Self::NotFound => StatusCode::NOT_FOUND,
164            Self::Unauthorized => StatusCode::UNAUTHORIZED,
165            Self::Forbidden => StatusCode::FORBIDDEN,
166            Self::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY,
167            Self::Conflict(_) => StatusCode::CONFLICT,
168            Self::BadRequest(_) => StatusCode::BAD_REQUEST,
169            Self::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
170            Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
171            Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
172            Self::TooManyRequests => StatusCode::TOO_MANY_REQUESTS,
173            Self::AuthCapacity | Self::ClientIdentityUnavailable => StatusCode::SERVICE_UNAVAILABLE,
174            _ => StatusCode::INTERNAL_SERVER_ERROR,
175        }
176    }
177}
178
179impl IntoResponse for AppError {
180    fn into_response(self) -> Response {
181        let status = self.status();
182        let body = if let Self::Rejected(problem) = &self {
183            ApiErrorResponse {
184                code: Some(problem.code().into()),
185                message: problem.to_string(),
186                errors: match problem {
187                    crate::EventRejection::Validation { errors, .. } => Some(errors.clone()),
188                    _ => None,
189                },
190            }
191        } else if let Self::Validation(errors) = &self {
192            ApiErrorResponse {
193                code: None,
194                message: "Validation failed".into(),
195                errors: Some(errors.clone()),
196            }
197        } else if status.is_server_error() {
198            ApiErrorResponse {
199                code: None,
200                message: if status == StatusCode::SERVICE_UNAVAILABLE {
201                    "Service temporarily unavailable"
202                } else {
203                    "Internal server error"
204                }
205                .into(),
206                errors: None,
207            }
208        } else {
209            ApiErrorResponse {
210                code: None,
211                message: self.to_string(),
212                errors: None,
213            }
214        };
215        let mut response = (status, Json(body)).into_response();
216        response.extensions_mut().insert(ErrorKind(self.kind()));
217        response
218    }
219}