fusion_stack/
request_id.rs1use std::sync::Arc;
10
11use laravel::http::Request;
12
13pub const HEADER: &str = "x-request-id";
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct RequestId(Arc<str>);
19
20impl RequestId {
21 #[must_use]
23 pub fn as_str(&self) -> &str {
24 &self.0
25 }
26}
27
28fn is_valid(id: &str) -> bool {
30 (1..=128).contains(&id.len())
31 && id
32 .bytes()
33 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-'))
34}
35
36fn generate() -> String {
38 format!("req_{}", ulid::Ulid::new().to_string().to_lowercase())
39}
40
41#[must_use]
44pub fn of(request: &Request) -> String {
45 if let Some(id) = request.extension::<RequestId>() {
46 return id.as_str().to_owned();
47 }
48 request
49 .header(HEADER)
50 .filter(|id| is_valid(id))
51 .map_or_else(generate, str::to_owned)
52}
53
54pub(crate) fn assign(request: &mut Request) -> RequestId {
56 let id = RequestId(of(request).into());
57 request.extensions_mut().insert(id.clone());
58 id
59}
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64
65 #[test]
66 fn generated_ids_are_req_and_a_lowercase_ulid() {
67 let id = generate();
68 assert!(id.starts_with("req_"), "{id}");
69 assert_eq!(id.len(), 30);
70 assert!(
71 id[4..]
72 .bytes()
73 .all(|byte| byte.is_ascii_digit() || byte.is_ascii_lowercase()),
74 "{id}"
75 );
76 assert_ne!(generate(), id);
77 }
78
79 #[test]
80 fn only_ids_that_cannot_forge_log_lines_are_kept() {
81 assert!(is_valid("client.abc-123:7_x"));
82 assert!(is_valid(&"a".repeat(128)));
83 assert!(!is_valid(&"a".repeat(129)));
84 assert!(!is_valid(""));
85 assert!(!is_valid("has spaces!"));
86 assert!(!is_valid("line\nbreak"));
87 }
88}