use std::{
panic::{AssertUnwindSafe, catch_unwind},
sync::Arc,
};
use axum::{
Json,
body::Bytes,
http::{StatusCode, header},
response::{IntoResponse, Response},
};
use serde::Serialize;
#[derive(Clone, Debug)]
pub struct RequestId(pub String);
#[derive(Clone, Copy, Debug)]
pub struct RuntimeRejection<'a> {
pub status: StatusCode,
pub code: &'static str,
pub request_id: &'a str,
}
pub(crate) type RejectionFormatter =
Arc<dyn for<'a> Fn(RuntimeRejection<'a>) -> Option<Bytes> + Send + Sync>;
const MAX_FORMATTED_PROBLEM_BYTES: usize = 16 * 1024;
pub(super) fn rejection_response(
status: StatusCode,
code: &'static str,
id: &RequestId,
formatter: Option<&RejectionFormatter>,
) -> Response {
let formatted = formatter.and_then(|formatter| {
catch_unwind(AssertUnwindSafe(|| {
formatter(RuntimeRejection {
status,
code,
request_id: &id.0,
})
}))
.ok()
.flatten()
.filter(|body| !body.is_empty() && body.len() <= MAX_FORMATTED_PROBLEM_BYTES)
});
if let Some(body) = formatted {
problem_headers((status, body).into_response())
} else {
Problem::response(status, code, id)
}
}
#[derive(Clone, Debug, Serialize)]
pub struct Problem {
#[serde(rename = "type")]
pub kind: &'static str,
pub title: &'static str,
pub status: u16,
pub code: &'static str,
pub request_id: String,
}
impl Problem {
pub(super) fn response(status: StatusCode, code: &'static str, id: &RequestId) -> Response {
let problem = Self {
kind: "about:blank",
title: status.canonical_reason().unwrap_or("Request failed"),
status: status.as_u16(),
code,
request_id: id.0.clone(),
};
problem_headers((status, Json(problem)).into_response())
}
}
fn problem_headers(mut response: Response) -> Response {
response.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/problem+json"),
);
response.headers_mut().insert(
header::CONNECTION,
header::HeaderValue::from_static("close"),
);
response
}