servlet 1.2.0

A small application runtime with an explicit operational contract
Documentation
//! Safe runtime failures and server-generated correlation identifiers.

use std::{
    panic::{AssertUnwindSafe, catch_unwind},
    sync::Arc,
};

use axum::{
    Json,
    body::Bytes,
    http::{StatusCode, header},
    response::{IntoResponse, Response},
};
use serde::Serialize;

/// Server-generated identifier, available as an Axum request extension.
/// Incoming request IDs and forwarding headers never influence this value.
#[derive(Clone, Debug)]
pub struct RequestId(pub String);

/// Safe facts for a rejection that Servlet generated before the handler responded.
#[derive(Clone, Copy, Debug)]
pub struct RuntimeRejection<'a> {
    /// The status chosen by Servlet.
    pub status: StatusCode,
    /// The stable rejection code.
    pub code: &'static str,
    /// Servlet's trusted request identifier, also set on the response header.
    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)
    }
}

/// RFC 9457 problem details for failures generated by Servlet.
#[derive(Clone, Debug, Serialize)]
pub struct Problem {
    /// A stable problem type URI.
    #[serde(rename = "type")]
    pub kind: &'static str,
    /// A fixed, safe summary.
    pub title: &'static str,
    /// HTTP status code.
    pub status: u16,
    /// Stable machine-readable failure code.
    pub code: &'static str,
    /// Correlation with the response header and local telemetry.
    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
}