seiva_http/problem.rs
1//! RFC 9457 `application/problem+json` error responses.
2//!
3//! [`Problem`] — the transport-neutral error DATA — lives in `seiva-contract`
4//! (ADR 0003), so a module's `facade` can map its error to a `Problem` without
5//! depending on this HTTP crate. This module re-exports it and provides
6//! [`ProblemResponse`], the axum `IntoResponse` wrapper that renders a `Problem`
7//! as `application/problem+json`. Every extractor rejection and middleware
8//! response in this crate wraps the `Problem` in a `ProblemResponse`, and the
9//! `#[seiva::controller]` macro does the same at the HTTP edge.
10
11use axum::body::Body;
12use axum::http::header::CONTENT_TYPE;
13use axum::http::HeaderValue;
14use axum::response::{IntoResponse, Response};
15
16// The error data and the fail-closed expose flag are transport-neutral, so they
17// live in `seiva-contract`; re-exported here so `seiva_http::Problem` and
18// `seiva_http::problem::{set_expose_error_details, expose_error_details}` are
19// unchanged for every existing caller.
20pub use seiva_contract::{expose_error_details, set_expose_error_details, Problem};
21
22/// The media type mandated by RFC 9457 for a problem document.
23pub const PROBLEM_JSON: &str = "application/problem+json";
24
25/// The axum `IntoResponse` wrapper around a transport-neutral [`Problem`].
26///
27/// `Problem` itself is transport-free (it has no `IntoResponse`), so the HTTP edge
28/// wraps it in this to render it: `application/problem+json` with the problem's
29/// status, mirroring the `request_id` into an `x-request-id` header. Extractors use
30/// it as their `Rejection`, middleware return it, and the generated controller maps
31/// a facade's `Problem` error through it.
32#[derive(Debug, Clone)]
33pub struct ProblemResponse(pub Problem);
34
35impl From<Problem> for ProblemResponse {
36 fn from(problem: Problem) -> Self {
37 Self(problem)
38 }
39}
40
41impl IntoResponse for ProblemResponse {
42 fn into_response(self) -> Response {
43 let problem = self.0;
44 let body = serde_json::to_vec(&problem.to_json()).unwrap_or_else(|_| b"{}".to_vec());
45 let mut response = Response::new(Body::from(body));
46 *response.status_mut() = problem.status;
47 response
48 .headers_mut()
49 .insert(CONTENT_TYPE, HeaderValue::from_static(PROBLEM_JSON));
50 if let Some(request_id) = &problem.request_id {
51 if let Ok(value) = HeaderValue::from_str(request_id) {
52 response.headers_mut().insert("x-request-id", value);
53 }
54 }
55 response
56 }
57}