1use 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
17pub const REQUEST_ID_HEADER: &str = "x-request-id";
19
20#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct RequestId(pub String);
24
25impl RequestId {
26 pub fn as_str(&self) -> &str {
28 &self.0
29 }
30}
31
32fn 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
45pub trait RequestIdExt {
47 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
57pub 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}