Skip to main content

seiva_http/
request_id.rs

1//! Per-request correlation id.
2//!
3//! [`request_id`] is an axum middleware that assigns every request a
4//! [`RequestId`] (honouring an inbound `x-request-id` when present), stores it in
5//! the request extensions for extractors and the permission guard to read, and
6//! echoes it on the response. [`Problem`](crate::problem::Problem) carries it in
7//! the body so a client can quote one id to an operator.
8
9use std::sync::atomic::{AtomicU64, Ordering};
10use std::time::{SystemTime, UNIX_EPOCH};
11
12use axum::extract::Request;
13use axum::http::HeaderValue;
14use axum::middleware::Next;
15use axum::response::Response;
16
17/// The header carrying the correlation id, in and out.
18pub const REQUEST_ID_HEADER: &str = "x-request-id";
19
20/// A request's correlation id, stored in the request extensions by
21/// [`request_id`] and readable by extractors via [`RequestIdExt`].
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct RequestId(pub String);
24
25impl RequestId {
26    /// The id as a string slice.
27    pub fn as_str(&self) -> &str {
28        &self.0
29    }
30}
31
32/// Mints a fresh id without pulling in a UUID dependency: the wall-clock time in
33/// nanoseconds, salted by a monotonic process-wide counter so two requests in the
34/// same nanosecond still differ.
35fn mint() -> String {
36    static COUNTER: AtomicU64 = AtomicU64::new(0);
37    let nanos = SystemTime::now()
38        .duration_since(UNIX_EPOCH)
39        .map(|d| d.as_nanos())
40        .unwrap_or(0);
41    let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
42    format!("{nanos:032x}{seq:016x}")
43}
44
45/// Convenience to read the [`RequestId`] out of a set of request extensions.
46pub trait RequestIdExt {
47    /// The correlation id, if the [`request_id`] middleware ran.
48    fn request_id(&self) -> Option<String>;
49}
50
51impl RequestIdExt for axum::http::Extensions {
52    fn request_id(&self) -> Option<String> {
53        self.get::<RequestId>().map(|id| id.0.clone())
54    }
55}
56
57/// Middleware that assigns a [`RequestId`], stores it in the extensions and
58/// echoes it on the response's `x-request-id` header. Reuses an inbound
59/// `x-request-id` when the client sent a syntactically valid one.
60pub async fn request_id(mut request: Request, next: Next) -> Response {
61    let id = request
62        .headers()
63        .get(REQUEST_ID_HEADER)
64        .and_then(|value| value.to_str().ok())
65        .filter(|value| !value.is_empty())
66        .map(ToOwned::to_owned)
67        .unwrap_or_else(mint);
68
69    request.extensions_mut().insert(RequestId(id.clone()));
70    let mut response = next.run(request).await;
71    if let Ok(value) = HeaderValue::from_str(&id) {
72        response.headers_mut().insert(REQUEST_ID_HEADER, value);
73    }
74    response
75}