use crate::context::request_id::{
inject_request_id_into_error_body, propagate_or_generate, scope, REQUEST_ID_HEADER,
};
use http_body_util::BodyExt;
use std::sync::Arc;
use tracing::Instrument;
use warp::http::header::{HeaderName, HeaderValue, CONTENT_LENGTH, CONTENT_TYPE};
use warp::reply::{Reply as _, Response};
use warp::Filter;
const X_REQUEST_ID: HeaderName = HeaderName::from_static("x-request-id");
pub fn with_request_id<T, R>(
route: T,
) -> impl Filter<Extract = (Response,), Error = warp::Rejection> + Clone
where
T: Filter<Extract = (R,), Error = warp::Rejection> + Clone + Send + Sync + 'static,
R: warp::reply::Reply + Send + 'static,
{
warp::any()
.and(warp::header::optional::<String>(REQUEST_ID_HEADER))
.and(route)
.and_then(|inbound: Option<String>, reply: R| async move {
let id = propagate_or_generate(inbound.as_deref());
let span = tracing::info_span!("request_id", request_id = %id);
let response = scope(id.clone(), async move {
post_process(id, reply.into_response()).await
})
.instrument(span)
.await;
Ok::<_, warp::Rejection>(response)
})
}
async fn post_process(id: Arc<str>, mut response: Response) -> Response {
if let Ok(value) = HeaderValue::from_str(id.as_ref()) {
response.headers_mut().insert(X_REQUEST_ID, value);
}
tracing::debug!(
request_id = %id,
status = response.status().as_u16(),
"{}", crate::i18n::translate_detail("logs-request-id-middleware-completed", &[])
);
let status = response.status();
let is_error = status.is_client_error() || status.is_server_error();
let is_json = response
.headers()
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.starts_with("application/json"));
if !(is_error && is_json) {
return response;
}
let (mut parts, body) = response.into_parts();
let bytes = match BodyExt::collect(body).await {
Ok(collected) => collected.to_bytes(),
Err(e) => {
tracing::error!(error = %e, "{}", crate::i18n::translate_detail("logs-warp-request-id-body-collect-failed", &[]));
let fallback =
crate::error::GarrisonError::Internal("warp-body-collect-failed::".to_string());
let mut rebuilt =
warp::reply::with_status(warp::reply::json(&fallback.to_json_body()), parts.status)
.into_response();
parts.headers.remove(CONTENT_LENGTH);
*rebuilt.headers_mut() = parts.headers;
return rebuilt;
},
};
if bytes.len() > MAX_INJECT_BODY_SIZE {
return pass_through_original(parts, bytes.to_vec());
}
let mut json = match serde_json::from_slice::<serde_json::Value>(&bytes) {
Ok(v) => v,
Err(_) => {
return pass_through_original(parts, bytes.to_vec());
},
};
inject_request_id_into_error_body(&mut json);
parts.headers.remove(CONTENT_LENGTH);
let mut rebuilt = warp::reply::with_status(warp::reply::json(&json), status).into_response();
for (name, value) in parts.headers.iter() {
if name != CONTENT_TYPE {
rebuilt.headers_mut().append(name, value.clone());
}
}
rebuilt
}
const MAX_INJECT_BODY_SIZE: usize = 4096;
fn pass_through_original(parts: warp::http::response::Parts, body: Vec<u8>) -> Response {
let mut rebuilt = warp::reply::Reply::into_response(body);
*rebuilt.status_mut() = parts.status;
*rebuilt.headers_mut() = parts.headers;
rebuilt
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::GarrisonError;
use serial_test::serial;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use warp::test::request;
fn error_routes() -> impl Filter<Extract = (GarrisonError,), Error = warp::Rejection> + Clone {
warp::path("boom").map(|| GarrisonError::NotLogin("web-not-login::".to_string()))
}
fn rate_limited_routes(
) -> impl Filter<Extract = (GarrisonError,), Error = warp::Rejection> + Clone {
warp::path("limited").map(|| GarrisonError::RateLimited {
retry_after_secs: 30,
})
}
fn ok_routes() -> impl Filter<Extract = (&'static str,), Error = warp::Rejection> + Clone {
warp::path("ping").map(|| "pong")
}
#[tokio::test]
async fn valid_inbound_id_echoed_on_success_response() {
let routes = ok_routes().with(warp::wrap_fn(with_request_id));
let res = request()
.path("/ping")
.header(REQUEST_ID_HEADER, "warp-corr-001")
.reply(&routes)
.await;
assert_eq!(res.status(), 200);
let value = res
.headers()
.get(X_REQUEST_ID.as_str())
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
assert_eq!(value, "warp-corr-001");
}
#[tokio::test]
async fn invalid_inbound_id_regenerated() {
let routes = ok_routes().with(warp::wrap_fn(with_request_id));
for bad in ["a".repeat(129), format!("{}tail", "b".repeat(200))] {
let res = request()
.path("/ping")
.header(REQUEST_ID_HEADER, bad.as_str())
.reply(&routes)
.await;
let value = res
.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 routes = ok_routes().with(warp::wrap_fn(with_request_id));
let res = request().path("/ping").reply(&routes).await;
let value = res
.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_body_request_id_backfilled_matching_header() {
let routes = error_routes().with(warp::wrap_fn(with_request_id));
let res = request()
.path("/boom")
.header(REQUEST_ID_HEADER, "warp-err-corr-001")
.reply(&routes)
.await;
assert_eq!(res.status(), 401);
let header = res
.headers()
.get(X_REQUEST_ID.as_str())
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
assert_eq!(header, "warp-err-corr-001");
let body_json: serde_json::Value = serde_json::from_slice(res.body()).unwrap();
assert_eq!(body_json["request_id"], "warp-err-corr-001");
assert_eq!(body_json["error_code"], "NOT_LOGIN");
assert_eq!(body_json["error_id"], "auth.not_login");
}
#[tokio::test]
async fn error_body_request_id_generated_when_missing() {
let routes = error_routes().with(warp::wrap_fn(with_request_id));
let res = request().path("/boom").reply(&routes).await;
let header = res
.headers()
.get(X_REQUEST_ID.as_str())
.and_then(|v| v.to_str().ok())
.unwrap_or_default()
.to_string();
let body_json: serde_json::Value = serde_json::from_slice(res.body()).unwrap();
assert_eq!(
body_json["request_id"].as_str().unwrap(),
header,
"错误体 request_id 应与响应头一致"
);
assert!(uuid::Uuid::parse_str(&header).is_ok());
}
#[tokio::test]
async fn rate_limited_retry_after_header() {
let routes = rate_limited_routes().with(warp::wrap_fn(with_request_id));
let res = request().path("/limited").reply(&routes).await;
assert_eq!(res.status(), 429);
let value = res
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
assert_eq!(value, "30");
let body_json: serde_json::Value = serde_json::from_slice(res.body()).unwrap();
assert_eq!(body_json["error_id"], "ratelimit.rate_limited");
}
#[tokio::test]
async fn non_json_error_response_not_backfilled() {
let routes = warp::path("raw")
.map(|| warp::http::StatusCode::FORBIDDEN)
.with(warp::wrap_fn(with_request_id));
let res = request()
.path("/raw")
.header(REQUEST_ID_HEADER, "warp-nonjson-001")
.reply(&routes)
.await;
assert_eq!(res.status(), 403);
let value = res
.headers()
.get(X_REQUEST_ID.as_str())
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
assert_eq!(value, "warp-nonjson-001");
assert!(res.body().is_empty());
}
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 routes = ok_routes().with(warp::wrap_fn(with_request_id));
let mut lines: Vec<(String, String)> = Vec::new();
for _ in 0..3 {
let _ = request()
.path("/ping")
.header(REQUEST_ID_HEADER, "warp-span-id")
.reply(&routes)
.await;
lines = logs.lock().expect("日志缓冲锁应可用").clone();
if lines
.iter()
.any(|(level, msg)| level == "DEBUG" && msg.contains("warp-span-id"))
{
break;
}
tracing::callsite::rebuild_interest_cache();
}
assert!(
lines
.iter()
.any(|(level, msg)| level == "DEBUG" && msg.contains("warp-span-id")),
"完成事件应为 debug 级且携带 request_id 字段值 warp-span-id,实际: {lines:?}"
);
}
struct JsonLabeledRaw(Vec<u8>);
impl warp::reply::Reply for JsonLabeledRaw {
fn into_response(self) -> Response {
let mut res = warp::reply::Reply::into_response(self.0);
res.headers_mut()
.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
*res.status_mut() = warp::http::StatusCode::FORBIDDEN;
res
}
}
#[tokio::test]
async fn non_json_body_with_json_label_passthrough_single_content_type() {
let routes = warp::path("raw")
.map(|| JsonLabeledRaw(b"not-json-body{".to_vec()))
.with(warp::wrap_fn(with_request_id));
let res = request()
.path("/raw")
.header(REQUEST_ID_HEADER, "warp-nonjson-002")
.reply(&routes)
.await;
assert_eq!(res.status(), 403);
assert_eq!(res.body().as_ref(), b"not-json-body{", "body 应原样透传");
let content_types: Vec<_> = res
.headers()
.get_all(CONTENT_TYPE.as_str())
.iter()
.collect();
assert_eq!(
content_types.len(),
1,
"Content-Type 不得重复,实际: {content_types:?}"
);
assert!(res.headers().get(X_REQUEST_ID.as_str()).is_some());
let body_str = String::from_utf8_lossy(res.body());
assert!(
!body_str.contains("request_id"),
"透传体不得被注入 request_id 字段: {body_str}"
);
}
#[tokio::test]
async fn oversized_error_body_skips_injection_and_passthrough() {
let oversized = serde_json::json!({ "pad": "x".repeat(8 * 1024) }).to_string();
let expected_len = oversized.len();
let routes = warp::path("big")
.map(move || JsonLabeledRaw(oversized.clone().into_bytes()))
.with(warp::wrap_fn(with_request_id));
let res = request()
.path("/big")
.header(REQUEST_ID_HEADER, "warp-oversize-001")
.reply(&routes)
.await;
assert_eq!(res.status(), 403);
assert_eq!(
res.body().len(),
expected_len,
"超大 body 应原样透传(长度不变)"
);
let body_str = String::from_utf8_lossy(res.body());
assert!(
!body_str.contains("request_id"),
"超大错误体不得被注入 request_id 字段"
);
assert!(res.headers().get(X_REQUEST_ID.as_str()).is_some());
let content_types: Vec<_> = res
.headers()
.get_all(CONTENT_TYPE.as_str())
.iter()
.collect();
assert_eq!(
content_types.len(),
1,
"Content-Type 不得重复,实际: {content_types:?}"
);
}
}