use std::future::Future;
use std::sync::Arc;
pub const REQUEST_ID_HEADER: &str = "X-Request-ID";
pub const RETRY_AFTER_HEADER: &str = "Retry-After";
pub const REQUEST_ID_BODY_FIELD: &str = "request_id";
pub const MAX_INBOUND_LEN: usize = 128;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestId(pub Arc<str>);
tokio::task_local! {
static REQUEST_ID: Arc<str>;
}
pub fn current() -> Option<Arc<str>> {
REQUEST_ID.try_with(Arc::clone).ok()
}
pub async fn scope<R, F>(id: Arc<str>, f: F) -> R
where
F: Future<Output = R>,
{
REQUEST_ID.scope(id, f).await
}
pub fn generate() -> Arc<str> {
Arc::from(uuid::Uuid::new_v4().to_string().as_str())
}
pub fn is_valid_inbound_request_id(id: &str) -> bool {
!id.is_empty() && id.len() <= MAX_INBOUND_LEN && id.bytes().all(|b| (0x21..=0x7E).contains(&b))
}
pub fn propagate_or_generate(inbound: Option<&str>) -> Arc<str> {
match inbound {
Some(id) if is_valid_inbound_request_id(id) => Arc::from(id),
_ => generate(),
}
}
pub fn inject_request_id_into_error_body(body: &mut serde_json::Value) {
if let Some(id) = current() {
if let Some(obj) = body.as_object_mut() {
obj.insert(
REQUEST_ID_BODY_FIELD.to_string(),
serde_json::Value::String(id.to_string()),
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn propagate_or_generate_valid_inbound_passthrough() {
let id = propagate_or_generate(Some("550e8400-e29b-41d4-a716-446655440000"));
assert_eq!(id.as_ref(), "550e8400-e29b-41d4-a716-446655440000");
let custom = propagate_or_generate(Some("req-abc_123"));
assert_eq!(custom.as_ref(), "req-abc_123");
}
#[test]
fn propagate_or_generate_crlf_inbound_regenerated() {
let inbound = "id\r\nEvil: 1";
let id = propagate_or_generate(Some(inbound));
assert_ne!(id.as_ref(), inbound);
assert!(
uuid::Uuid::parse_str(&id).is_ok(),
"重新生成的 id 应为合法 UUID,实际: {id}"
);
}
#[test]
fn propagate_or_generate_oversized_and_non_ascii_regenerated() {
let oversized = "a".repeat(MAX_INBOUND_LEN + 1);
let id = propagate_or_generate(Some(&oversized));
assert_ne!(id.as_ref(), oversized);
assert!(uuid::Uuid::parse_str(&id).is_ok());
let non_ascii = "请求标识";
let id = propagate_or_generate(Some(non_ascii));
assert_ne!(id.as_ref(), non_ascii);
assert!(uuid::Uuid::parse_str(&id).is_ok());
for bad in ["a\u{0}b", "a\u{7f}b", "a b"] {
let id = propagate_or_generate(Some(bad));
assert_ne!(id.as_ref(), bad, "非法 id {bad:?} 不应被传播");
assert!(uuid::Uuid::parse_str(&id).is_ok());
}
}
#[test]
fn propagate_or_generate_none_generates_uuid_v4() {
let id = propagate_or_generate(None);
let parsed = uuid::Uuid::parse_str(&id).expect("None 入站应生成合法 UUID");
assert_eq!(parsed.get_version_num(), 4, "应为 UUID v4");
}
#[tokio::test]
async fn current_visible_only_within_scope() {
assert_eq!(current(), None, "scope 外 current() 应为 None");
let id: Arc<str> = Arc::from("scope-test-id");
let observed = scope(id.clone(), async { current() }).await;
assert_eq!(observed.as_deref(), Some(id.as_ref()));
assert_eq!(current(), None, "scope 结束后 current() 应恢复 None");
}
#[test]
fn generate_10k_times_no_duplicates() {
let mut seen = std::collections::HashSet::with_capacity(10_000);
for _ in 0..10_000 {
assert!(seen.insert(generate()), "生成出重复 request id");
}
assert_eq!(seen.len(), 10_000);
}
#[test]
fn is_valid_inbound_request_id_boundaries() {
assert!(!is_valid_inbound_request_id(""), "空串非法");
assert!(is_valid_inbound_request_id(&"a".repeat(127)));
assert!(is_valid_inbound_request_id(&"a".repeat(128)));
assert!(!is_valid_inbound_request_id(&"a".repeat(129)), "超长非法");
assert!(is_valid_inbound_request_id(
"!#$%&'()*+,-./:;<=>?@[]^_`{|}~"
));
}
#[tokio::test]
async fn inject_into_error_body_inside_scope() {
let mut body = serde_json::json!({"error_code": "NOT_LOGIN"});
let id: Arc<str> = Arc::from("inject-test-id");
scope(id.clone(), async {
inject_request_id_into_error_body(&mut body);
})
.await;
assert_eq!(body["request_id"], "inject-test-id");
assert_eq!(body["error_code"], "NOT_LOGIN", "既有字段不被覆盖");
}
#[test]
fn inject_into_error_body_outside_scope_is_noop() {
let mut body = serde_json::json!({"error_code": "NOT_LOGIN"});
inject_request_id_into_error_body(&mut body);
assert!(body.get(REQUEST_ID_BODY_FIELD).is_none());
}
#[test]
fn request_id_wrapper_eq_and_debug() {
let a = RequestId(Arc::from("x"));
let b = a.clone();
assert_eq!(a, b);
assert!(format!("{a:?}").contains("x"));
}
}