use crate::context::request_id::{propagate_or_generate, scope, RequestId, REQUEST_ID_HEADER};
use axum::extract::Request;
use axum::http::header::HeaderName;
use axum::http::HeaderValue;
use axum::middleware::Next;
use axum::response::Response;
use tracing::Instrument;
const X_REQUEST_ID: HeaderName = HeaderName::from_static("x-request-id");
pub async fn request_id_middleware(mut req: Request, next: Next) -> Response {
let inbound = req
.headers()
.get(REQUEST_ID_HEADER)
.and_then(|v| v.to_str().ok());
let id = propagate_or_generate(inbound);
req.extensions_mut().insert(RequestId(id.clone()));
let span = tracing::info_span!("request_id", request_id = %id);
let block_id = id.clone();
let mut response = scope(id.clone(), async move {
let response = next.run(req).await;
tracing::debug!(
request_id = %block_id,
status = response.status().as_u16(),
"{}", crate::i18n::translate_detail("logs-request-id-middleware-completed", &[])
);
response
})
.instrument(span)
.await;
if let Ok(value) = HeaderValue::from_str(id.as_ref()) {
response.headers_mut().insert(X_REQUEST_ID, value);
}
response
}
#[cfg(test)]
mod tests {
use super::*;
use crate::context::request_id::current;
use crate::error::GarrisonError;
use axum::body::Body;
use axum::http::{Request as HttpRequest, StatusCode};
use axum::routing::get;
use axum::{Extension, Router};
use serial_test::serial;
use tower::ServiceExt;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
fn test_router() -> Router {
Router::new()
.route(
"/ping",
get(|req_id: Extension<RequestId>| async move { req_id.0 .0.to_string() }),
)
.route(
"/boom",
get(|| async { GarrisonError::NotLogin("web-not-login::".to_string()) }),
)
.layer(axum::middleware::from_fn(request_id_middleware))
}
#[tokio::test]
async fn valid_inbound_id_echoed_on_success_response() {
let response = test_router()
.oneshot(
HttpRequest::builder()
.uri("/ping")
.header(REQUEST_ID_HEADER, "client-trace-001")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let value = response
.headers()
.get(X_REQUEST_ID.as_str())
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
assert_eq!(value, "client-trace-001");
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(std::str::from_utf8(&body).unwrap(), "client-trace-001");
}
#[tokio::test]
async fn invalid_inbound_id_regenerated() {
for bad in ["a".repeat(129), format!("{}tail", "b".repeat(200))] {
let response = test_router()
.oneshot(
HttpRequest::builder()
.uri("/ping")
.header(REQUEST_ID_HEADER, bad.as_str())
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let value = response
.headers()
.get(X_REQUEST_ID.as_str())
.and_then(|v| v.to_str().ok())
.unwrap_or_default()
.to_string();
assert_ne!(value, bad, "非法入站 id 不应被回传");
assert!(
uuid::Uuid::parse_str(&value).is_ok(),
"重新生成的 id 应为合法 UUID: {value}"
);
}
}
#[tokio::test]
async fn missing_header_generates_uuid_v4() {
let response = test_router()
.oneshot(
HttpRequest::builder()
.uri("/ping")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let value = response
.headers()
.get(X_REQUEST_ID.as_str())
.and_then(|v| v.to_str().ok())
.unwrap_or_default()
.to_string();
let parsed = uuid::Uuid::parse_str(&value).expect("无头时应生成合法 UUID");
assert_eq!(parsed.get_version_num(), 4);
}
#[tokio::test]
async fn error_response_header_matches_body_request_id() {
let response = test_router()
.oneshot(
HttpRequest::builder()
.uri("/boom")
.header(REQUEST_ID_HEADER, "err-corr-001")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
let header_value = response
.headers()
.get(X_REQUEST_ID.as_str())
.and_then(|v| v.to_str().ok())
.unwrap_or_default()
.to_string();
assert_eq!(header_value, "err-corr-001");
let body_json: serde_json::Value = serde_json::from_slice(
&axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap(),
)
.unwrap();
assert_eq!(body_json["request_id"], "err-corr-001");
assert_eq!(body_json["error_id"], "auth.not_login");
assert_eq!(body_json["error_code"], "NOT_LOGIN");
}
struct CollectLayer(std::sync::Arc<std::sync::Mutex<Vec<(String, String)>>>);
impl<S> tracing_subscriber::layer::Layer<S> for CollectLayer
where
S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
{
fn on_event(
&self,
event: &tracing::Event<'_>,
_ctx: tracing_subscriber::layer::Context<'_, S>,
) {
let level = event.metadata().level().to_string();
let mut rendered = String::new();
event.record(
&mut |field: &tracing::field::Field, value: &dyn std::fmt::Debug| {
rendered.push_str(&format!("{}={:?} ", field.name(), value));
},
);
self.0
.lock()
.expect("日志缓冲锁应可用")
.push((level, rendered));
}
}
fn init_capture(
logs: &std::sync::Arc<std::sync::Mutex<Vec<(String, String)>>>,
) -> tracing::subscriber::DefaultGuard {
let guard = tracing_subscriber::registry()
.with(CollectLayer(logs.clone()))
.set_default();
tracing::callsite::rebuild_interest_cache();
guard
}
#[tokio::test]
#[serial]
async fn tracing_event_carries_request_id_field() {
let logs: std::sync::Arc<std::sync::Mutex<Vec<(String, String)>>> =
std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let _guard = init_capture(&logs);
let mut lines: Vec<(String, String)> = Vec::new();
for _ in 0..3 {
let _ = test_router()
.oneshot(
HttpRequest::builder()
.uri("/ping")
.header(REQUEST_ID_HEADER, "span-field-id")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
lines = logs.lock().expect("日志缓冲锁应可用").clone();
if lines
.iter()
.any(|(level, msg)| level == "DEBUG" && msg.contains("span-field-id"))
{
break;
}
tracing::callsite::rebuild_interest_cache();
}
assert!(
lines
.iter()
.any(|(level, msg)| level == "DEBUG" && msg.contains("span-field-id")),
"完成事件应为 debug 级且携带 request_id 字段值 span-field-id,实际: {lines:?}"
);
}
#[tokio::test]
async fn task_local_and_extension_agree() {
let app = Router::new()
.route(
"/consistency",
get(|req_id: Extension<RequestId>| async move {
let tl = current().map(|id| id.to_string()).unwrap_or_default();
(tl == req_id.0 .0.to_string()).to_string()
}),
)
.layer(axum::middleware::from_fn(request_id_middleware));
let response = app
.oneshot(
HttpRequest::builder()
.uri("/consistency")
.header(REQUEST_ID_HEADER, "agree-check")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(std::str::from_utf8(&body).unwrap(), "true");
}
}