use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use axum::extract::Request;
use axum::middleware::{Next, from_fn};
use axum::response::Response;
use crate::context::Context;
pub const REQUEST_ID: &str = "x-request-id";
pub const ACCEPT_LANGUAGE: &str = "accept-language";
pub fn layer()
-> axum::middleware::FromFnLayer<impl FnMut(Request, Next) -> WithContext + Clone, (), (Request,)> {
from_fn(|request: Request, next: Next| with_context(request, next))
}
pub type WithContext = std::pin::Pin<Box<dyn Future<Output = Response> + Send>>;
fn with_context(request: Request, next: Next) -> WithContext {
Box::pin(run(request, next))
}
async fn run(mut request: Request, next: Next) -> Response {
let id = request
.headers()
.get(REQUEST_ID)
.and_then(|value| value.to_str().ok())
.filter(|id| !id.is_empty() && id.len() <= 128 && id.chars().all(is_safe))
.map(ToString::to_string)
.unwrap_or_else(request_id);
let locale = request
.headers()
.get(ACCEPT_LANGUAGE)
.and_then(|value| value.to_str().ok())
.and_then(crate::i18n::Locale::negotiate);
let ctx = match locale {
Some(locale) => Context::new(&id).with_locale(locale),
None => Context::new(&id),
};
request.extensions_mut().insert(ctx);
let mut response = next.run(request).await;
if let Ok(value) = id.parse() {
response.headers_mut().insert(REQUEST_ID, value);
}
response
}
fn is_safe(c: char) -> bool {
c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | ':')
}
fn request_id() -> String {
static COUNTER: AtomicU64 = AtomicU64::new(0);
static START: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
let start = *START.get_or_init(|| {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|since| since.as_micros() as u64)
.unwrap_or(0)
});
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
format!("{start:x}-{n:x}")
}