use std::fmt;
use axum::{
Json,
http::{HeaderValue, StatusCode, header::CONTENT_TYPE},
response::{IntoResponse, Response},
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;
use crate::result::{ClassifyError, ErrorDescriptor, ErrorKind};
use super::{ProblemCode, ProblemType};
use crate::http::request_context::{RequestContext, RequestId};
pub const PROBLEM_JSON_MEDIA_TYPE: &str = "application/problem+json";
#[derive(Clone, Serialize)]
#[non_exhaustive]
pub struct ProblemDetails {
#[serde(rename = "type")]
type_uri: String,
title: String,
status: u16,
code: String,
detail: String,
#[serde(skip_serializing_if = "Option::is_none")]
instance: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
request_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
trace_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
details: Option<Value>,
}
impl ProblemDetails {
#[must_use]
pub fn type_uri(&self) -> &str {
&self.type_uri
}
#[must_use]
pub fn title(&self) -> &str {
&self.title
}
#[must_use]
pub const fn status(&self) -> u16 {
self.status
}
#[must_use]
pub fn code(&self) -> &str {
&self.code
}
#[must_use]
pub fn detail(&self) -> &str {
&self.detail
}
#[must_use]
pub fn instance(&self) -> Option<&str> {
self.instance.as_deref()
}
#[must_use]
pub fn request_id(&self) -> Option<&str> {
self.request_id.as_deref()
}
#[must_use]
pub fn trace_id(&self) -> Option<&str> {
self.trace_id.as_deref()
}
#[must_use]
pub const fn details(&self) -> Option<&Value> {
self.details.as_ref()
}
}
impl<'de> Deserialize<'de> for ProblemDetails {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
struct ProblemDetailsWire {
#[serde(rename = "type")]
type_uri: String,
title: String,
status: u16,
code: String,
detail: String,
instance: Option<String>,
request_id: Option<String>,
trace_id: Option<String>,
details: Option<Value>,
}
let wire = ProblemDetailsWire::deserialize(deserializer)?;
let status = StatusCode::from_u16(wire.status).map_err(serde::de::Error::custom)?;
if !is_problem_status(status) {
return Err(serde::de::Error::custom(
"problem status must be a 4xx or 5xx status code",
));
}
let type_uri = ProblemType::try_new(wire.type_uri)
.map_err(serde::de::Error::custom)?
.into_string();
let code = ProblemCode::try_new(wire.code)
.map_err(serde::de::Error::custom)?
.into_string();
let request_id = wire
.request_id
.map(RequestId::new)
.transpose()
.map_err(serde::de::Error::custom)?
.map(|request_id| request_id.to_string());
Ok(Self {
type_uri,
title: wire.title,
status: wire.status,
code,
detail: wire.detail,
instance: wire.instance,
request_id,
trace_id: wire.trace_id,
details: wire.details,
})
}
}
impl fmt::Debug for ProblemDetails {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ProblemDetails")
.field("status", &self.status)
.field("code", &self.code)
.field("request_id", &self.request_id)
.field("trace_id", &self.trace_id)
.field("type_uri", &"[REDACTED]")
.field("title", &"[REDACTED]")
.field("detail", &"[REDACTED]")
.field("instance", &self.instance.as_ref().map(|_| "[REDACTED]"))
.field("details", &self.details.as_ref().map(|_| "[REDACTED]"))
.finish()
}
}
#[derive(Clone)]
pub struct ApiProblem {
status: StatusCode,
body: Box<ProblemDetails>,
}
impl fmt::Debug for ApiProblem {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ApiProblem")
.field("status", &self.status)
.field("body", &self.body)
.finish()
}
}
pub trait IntoApiProblem {
fn into_api_problem(self) -> ApiProblem;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ErrorCategory {
Validation,
Authentication,
Authorization,
NotFound,
Conflict,
RateLimit,
Dependency,
Internal,
}
impl ErrorCategory {
#[must_use]
pub const fn status(self) -> StatusCode {
match self {
Self::Validation => StatusCode::BAD_REQUEST,
Self::Authentication => StatusCode::UNAUTHORIZED,
Self::Authorization => StatusCode::FORBIDDEN,
Self::NotFound => StatusCode::NOT_FOUND,
Self::Conflict => StatusCode::CONFLICT,
Self::RateLimit => StatusCode::TOO_MANY_REQUESTS,
Self::Dependency => StatusCode::SERVICE_UNAVAILABLE,
Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
impl From<ErrorKind> for ErrorCategory {
fn from(kind: ErrorKind) -> Self {
match kind {
ErrorKind::Validation => Self::Validation,
ErrorKind::Authentication => Self::Authentication,
ErrorKind::Authorization => Self::Authorization,
ErrorKind::NotFound => Self::NotFound,
ErrorKind::Conflict => Self::Conflict,
ErrorKind::RateLimit => Self::RateLimit,
ErrorKind::Timeout | ErrorKind::Dependency | ErrorKind::Unavailable => Self::Dependency,
ErrorKind::Internal => Self::Internal,
}
}
}
#[derive(Clone)]
pub struct PublicError {
category: ErrorCategory,
code: ProblemCode,
detail: String,
details: Option<Value>,
}
impl fmt::Debug for PublicError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PublicError")
.field("category", &self.category)
.field("code", &self.code)
.field("detail", &"[REDACTED]")
.field("details", &self.details.as_ref().map(|_| "[REDACTED]"))
.finish()
}
}
impl PublicError {
#[must_use]
pub fn new(category: ErrorCategory, code: ProblemCode, detail: impl Into<String>) -> Self {
Self {
category,
code,
detail: detail.into(),
details: None,
}
}
#[must_use]
pub fn validation(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::new(ErrorCategory::Validation, code, detail)
}
#[must_use]
pub fn dependency(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::new(ErrorCategory::Dependency, code, detail)
}
#[must_use]
pub fn internal(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::new(ErrorCategory::Internal, code, detail)
}
#[must_use]
pub fn from_descriptor(descriptor: ErrorDescriptor) -> Self {
Self::new(
ErrorCategory::from(descriptor.kind()),
ProblemCode::from_error_code(descriptor.code().clone()),
descriptor.public_message(),
)
}
#[must_use]
pub fn with_details(mut self, details: Value) -> Self {
self.details = Some(details);
self
}
#[must_use]
pub const fn category(&self) -> ErrorCategory {
self.category
}
#[must_use]
pub fn code(&self) -> &ProblemCode {
&self.code
}
#[must_use]
pub fn detail(&self) -> &str {
&self.detail
}
}
impl IntoApiProblem for PublicError {
fn into_api_problem(self) -> ApiProblem {
let mut problem =
ApiProblem::from_valid_status(self.category.status(), self.code, self.detail);
if let Some(details) = self.details {
problem = problem.with_details(details);
}
problem
}
}
impl From<PublicError> for ApiProblem {
fn from(error: PublicError) -> Self {
error.into_api_problem()
}
}
impl ApiProblem {
pub fn try_new(
status: StatusCode,
code: ProblemCode,
detail: impl Into<String>,
) -> Result<Self, ApiProblemStatusError> {
if !is_problem_status(status) {
return Err(ApiProblemStatusError::InvalidStatus {
status: status.as_u16(),
});
}
Ok(Self::from_valid_status(status, code, detail))
}
fn from_valid_status(status: StatusCode, code: ProblemCode, detail: impl Into<String>) -> Self {
Self {
status,
body: Box::new(ProblemDetails {
type_uri: ProblemType::about_blank().into_string(),
title: status.canonical_reason().unwrap_or("HTTP error").to_owned(),
detail: detail.into(),
status: status.as_u16(),
code: code.into_string(),
instance: None,
request_id: None,
trace_id: None,
details: None,
}),
}
}
#[must_use]
pub fn bad_request(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::BAD_REQUEST, code, detail)
}
#[must_use]
pub fn unauthorized(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::UNAUTHORIZED, code, detail)
}
#[must_use]
pub fn forbidden(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::FORBIDDEN, code, detail)
}
#[must_use]
pub fn not_found(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::NOT_FOUND, code, detail)
}
#[must_use]
pub fn service_unavailable(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::SERVICE_UNAVAILABLE, code, detail)
}
#[must_use]
pub fn conflict(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::CONFLICT, code, detail)
}
#[must_use]
pub fn unprocessable_entity(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::UNPROCESSABLE_ENTITY, code, detail)
}
#[must_use]
pub fn payload_too_large(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::PAYLOAD_TOO_LARGE, code, detail)
}
#[must_use]
pub fn too_many_requests(code: ProblemCode, detail: impl Into<String>) -> Self {
Self::from_valid_status(StatusCode::TOO_MANY_REQUESTS, code, detail)
}
#[must_use]
pub fn internal_error() -> Self {
Self::from_valid_status(
StatusCode::INTERNAL_SERVER_ERROR,
ProblemCode::INTERNAL_ERROR,
"internal server error",
)
}
#[must_use]
pub fn with_request_id(mut self, request_id: &RequestId) -> Self {
self.body.request_id = Some(request_id.to_string());
self
}
#[must_use]
pub fn with_trace_id(mut self, trace_id: impl Into<String>) -> Self {
let trace_id = trace_id.into();
if !trace_id.trim().is_empty() {
self.body.trace_id = Some(trace_id);
}
self
}
#[must_use]
pub fn with_request_context(mut self, context: &RequestContext) -> Self {
self.body.request_id = Some(context.request_id().to_string());
if let Some(trace_id) = context.trace_id() {
self.body.trace_id = Some(trace_id.to_owned());
}
self
}
#[must_use]
pub fn maybe_request_id(self, request_id: Option<&RequestId>) -> Self {
if let Some(request_id) = request_id {
self.with_request_id(request_id)
} else {
self
}
}
#[must_use]
pub fn with_type(mut self, type_uri: ProblemType) -> Self {
self.body.type_uri = type_uri.into_string();
self
}
#[must_use]
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.body.title = title.into();
self
}
#[must_use]
pub fn with_instance(mut self, instance: impl Into<String>) -> Self {
self.body.instance = Some(instance.into());
self
}
#[must_use]
pub fn with_details(mut self, details: Value) -> Self {
self.body.details = Some(details);
self
}
#[must_use]
pub const fn status(&self) -> StatusCode {
self.status
}
#[must_use]
pub fn body(&self) -> &ProblemDetails {
&self.body
}
#[must_use]
pub fn into_body(self) -> ProblemDetails {
*self.body
}
}
impl IntoApiProblem for ApiProblem {
fn into_api_problem(self) -> ApiProblem {
self
}
}
impl IntoResponse for ApiProblem {
fn into_response(self) -> Response {
let mut response = (self.status, Json(self.body)).into_response();
response.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_static(PROBLEM_JSON_MEDIA_TYPE),
);
response
}
}
impl std::fmt::Display for ApiProblem {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
formatter,
"HTTP problem {} ({})",
self.body.code,
self.status.as_u16()
)
}
}
impl std::error::Error for ApiProblem {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum ApiProblemStatusError {
#[error("problem status must be a 4xx or 5xx status code, got {status}")]
InvalidStatus {
#[doc = "The HTTP status code."]
status: u16,
},
}
impl ClassifyError for ApiProblemStatusError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal("api_problem_invalid_status")
}
}
fn is_problem_status(status: StatusCode) -> bool {
status.is_client_error() || status.is_server_error()
}