use axum::body::Body;
use axum::http::header::CONTENT_TYPE;
use axum::http::{HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use seiva_ports::BoxError;
pub const PROBLEM_JSON: &str = "application/problem+json";
#[derive(Debug, Clone)]
pub struct Problem {
pub type_uri: Box<str>,
pub title: Box<str>,
pub status: StatusCode,
pub detail: Option<Box<str>>,
pub instance: Option<Box<str>>,
pub request_id: Option<Box<str>>,
}
impl Problem {
pub fn new(status: StatusCode, title: impl Into<String>) -> Self {
Self {
type_uri: "about:blank".into(),
title: title.into().into_boxed_str(),
status,
detail: None,
instance: None,
request_id: None,
}
}
pub fn unauthorized(detail: impl Into<String>) -> Self {
Self::new(StatusCode::UNAUTHORIZED, "Unauthorized").with_detail(detail)
}
pub fn forbidden(detail: impl Into<String>) -> Self {
Self::new(StatusCode::FORBIDDEN, "Forbidden").with_detail(detail)
}
pub fn not_found(detail: impl Into<String>) -> Self {
Self::new(StatusCode::NOT_FOUND, "Not Found").with_detail(detail)
}
pub fn unprocessable_entity(detail: impl Into<String>) -> Self {
Self::new(StatusCode::UNPROCESSABLE_ENTITY, "Unprocessable Entity").with_detail(detail)
}
pub fn too_many_requests(detail: impl Into<String>) -> Self {
Self::new(StatusCode::TOO_MANY_REQUESTS, "Too Many Requests").with_detail(detail)
}
pub fn internal(detail: impl Into<String>) -> Self {
Self::new(StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error").with_detail(detail)
}
#[must_use]
pub fn with_type(mut self, type_uri: impl Into<String>) -> Self {
self.type_uri = type_uri.into().into_boxed_str();
self
}
#[must_use]
pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
self.detail = Some(detail.into().into_boxed_str());
self
}
#[must_use]
pub fn with_instance(mut self, instance: impl Into<String>) -> Self {
self.instance = Some(instance.into().into_boxed_str());
self
}
#[must_use]
pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
self.request_id = Some(request_id.into().into_boxed_str());
self
}
#[must_use]
pub fn with_request_id_opt(mut self, request_id: Option<String>) -> Self {
self.request_id = request_id.map(String::into_boxed_str);
self
}
fn to_json(&self) -> serde_json::Value {
let mut map = serde_json::Map::new();
map.insert("type".to_owned(), self.type_uri.as_ref().into());
map.insert("title".to_owned(), self.title.as_ref().into());
map.insert("status".to_owned(), self.status.as_u16().into());
if let Some(detail) = &self.detail {
map.insert("detail".to_owned(), detail.as_ref().into());
}
if let Some(instance) = &self.instance {
map.insert("instance".to_owned(), instance.as_ref().into());
}
if let Some(request_id) = &self.request_id {
map.insert("request_id".to_owned(), request_id.as_ref().into());
}
serde_json::Value::Object(map)
}
}
impl std::fmt::Display for Problem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} {}", self.status.as_u16(), self.title)?;
if let Some(detail) = &self.detail {
write!(f, ": {detail}")?;
}
Ok(())
}
}
impl std::error::Error for Problem {}
impl IntoResponse for Problem {
fn into_response(self) -> Response {
let body = serde_json::to_vec(&self.to_json()).unwrap_or_else(|_| b"{}".to_vec());
let mut response = Response::new(Body::from(body));
*response.status_mut() = self.status;
response
.headers_mut()
.insert(CONTENT_TYPE, HeaderValue::from_static(PROBLEM_JSON));
if let Some(request_id) = &self.request_id {
if let Ok(value) = HeaderValue::from_str(request_id) {
response.headers_mut().insert("x-request-id", value);
}
}
response
}
}
impl From<BoxError> for Problem {
fn from(error: BoxError) -> Self {
Problem::internal(error.to_string())
}
}
const _: () = assert!(
std::mem::size_of::<Problem>() <= 112,
"Problem must stay small enough that Result<_, Problem> does not trip \
clippy::result_large_err; box or restructure a field before growing it",
);