use std::fmt;
use axum::{
Json,
extract::rejection::JsonRejection,
http::{HeaderValue, StatusCode, header::CONTENT_TYPE},
response::{IntoResponse, Response},
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;
use crate::result::{ClassifyError, ErrorBoundaryPolicy, 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, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[non_exhaustive]
pub struct ProblemDetails {
#[serde(rename = "type")]
#[cfg_attr(feature = "openapi", schema(schema_with = schema::problem_type))]
type_uri: ProblemType,
title: String,
#[serde(
serialize_with = "serialize_problem_status",
deserialize_with = "deserialize_problem_status"
)]
#[cfg_attr(feature = "openapi", schema(value_type = u16, minimum = 400, maximum = 599))]
status: StatusCode,
#[cfg_attr(feature = "openapi", schema(schema_with = schema::problem_code))]
code: ProblemCode,
detail: String,
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "openapi", schema(nullable = false))]
instance: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "openapi", schema(schema_with = schema::request_id))]
request_id: Option<RequestId>,
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "openapi", schema(nullable = false))]
trace_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
details: Option<Value>,
}
#[cfg(feature = "openapi")]
mod schema {
use utoipa::{PartialSchema, openapi::schema::AllOfBuilder};
use super::{ProblemCode, ProblemType, RequestId};
pub(super) fn problem_type() -> AllOfBuilder {
AllOfBuilder::new()
.item(ProblemType::schema())
.description(Some("URI identifying the problem type."))
}
pub(super) fn problem_code() -> AllOfBuilder {
AllOfBuilder::new()
.item(ProblemCode::schema())
.description(Some("Stable machine-readable error code."))
}
pub(super) fn request_id() -> AllOfBuilder {
AllOfBuilder::new()
.item(RequestId::schema())
.description(Some("Request identifier used for log correlation."))
}
}
impl ProblemDetails {
#[must_use]
pub fn type_uri(&self) -> &str {
self.type_uri.as_str()
}
#[must_use]
pub fn title(&self) -> &str {
&self.title
}
#[must_use]
pub const fn status(&self) -> u16 {
self.status.as_u16()
}
#[must_use]
pub fn code(&self) -> &str {
self.code.as_str()
}
#[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_ref().map(RequestId::as_str)
}
#[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 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(Debug, Clone)]
pub struct ApiProblem {
body: Box<ProblemDetails>,
}
impl ApiProblem {
#[must_use]
pub fn from_error<E: ClassifyError + ?Sized>(error: &E, policy: ErrorBoundaryPolicy) -> Self {
Self::from_descriptor(policy.decide(error).into_descriptor())
}
#[must_use]
pub fn from_descriptor(descriptor: ErrorDescriptor) -> Self {
let status = match descriptor.kind() {
ErrorKind::Validation => StatusCode::BAD_REQUEST,
ErrorKind::Authentication => StatusCode::UNAUTHORIZED,
ErrorKind::Authorization => StatusCode::FORBIDDEN,
ErrorKind::NotFound => StatusCode::NOT_FOUND,
ErrorKind::Conflict => StatusCode::CONFLICT,
ErrorKind::RateLimit => StatusCode::TOO_MANY_REQUESTS,
ErrorKind::Timeout | ErrorKind::Dependency | ErrorKind::Unavailable => {
StatusCode::SERVICE_UNAVAILABLE
}
ErrorKind::Internal => StatusCode::INTERNAL_SERVER_ERROR,
};
Self::from_valid_status(
status,
ProblemCode::from_error_code(descriptor.code().clone()),
descriptor.public_message(),
)
}
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 {
body: Box::new(ProblemDetails {
type_uri: ProblemType::about_blank(),
title: status.canonical_reason().unwrap_or("HTTP error").to_owned(),
detail: detail.into(),
status,
code,
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.clone());
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().clone());
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;
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.body.status
}
#[must_use]
pub fn body(&self) -> &ProblemDetails {
&self.body
}
#[must_use]
pub fn into_body(self) -> ProblemDetails {
*self.body
}
}
impl From<JsonRejection> for ApiProblem {
fn from(rejection: JsonRejection) -> Self {
let status = rejection.status();
let code = match status {
StatusCode::UNSUPPORTED_MEDIA_TYPE => ProblemCode::UNSUPPORTED_MEDIA_TYPE,
StatusCode::PAYLOAD_TOO_LARGE => ProblemCode::PAYLOAD_TOO_LARGE,
_ => ProblemCode::INVALID_JSON,
};
Self::from_valid_status(status, code, rejection.body_text())
.with_details(serde_json::json!({ "reason": rejection.to_string() }))
}
}
impl IntoResponse for ApiProblem {
fn into_response(self) -> Response {
let mut response = (self.body.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.body.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()
}
fn serialize_problem_status<S>(status: &StatusCode, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_u16(status.as_u16())
}
fn deserialize_problem_status<'de, D>(deserializer: D) -> Result<StatusCode, D::Error>
where
D: serde::Deserializer<'de>,
{
let status = u16::deserialize(deserializer)?;
let status = StatusCode::from_u16(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",
));
}
Ok(status)
}