Skip to main content

fusion_stack/
request_id.rs

1//! `X-Request-Id`: a valid incoming ID is kept, otherwise the request gets a `req_` ID. Error
2//! documents repeat it in `meta.request_id`.
3//!
4//! Laravel for Rust assigns its own ID before any middleware runs and keeps an incoming one under
5//! the same rules, but generates 32 hex digits. Fusion Stack generates `req_` and a lowercase ULID
6//! instead, as the PHP package does, and sends that. The framework's own log lines for a request
7//! that arrived without an ID still carry the framework's ID.
8
9use std::sync::Arc;
10
11use laravel::http::Request;
12
13/// The header that carries the ID, on the request and on the response.
14pub const HEADER: &str = "x-request-id";
15
16/// The request's Fusion Stack ID, a request extension. Read it with [`of`].
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct RequestId(Arc<str>);
19
20impl RequestId {
21    /// The ID as a string.
22    #[must_use]
23    pub fn as_str(&self) -> &str {
24        &self.0
25    }
26}
27
28/// Whether an incoming ID can be kept: 1 to 128 ASCII letters, digits, `.`, `_`, `:` or `-`.
29fn 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
36/// A new ID: `req_` and a lowercase ULID.
37fn generate() -> String {
38    format!("req_{}", ulid::Ulid::new().to_string().to_lowercase())
39}
40
41/// The request's ID: the one assigned by the middleware, or else a valid incoming one, or else a
42/// new one.
43#[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
54/// Assigns the request its ID before the rest of the application runs.
55pub(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}