fusion-stack-laravel-rust 0.3.0

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
Documentation
//! `X-Request-Id`: a valid incoming ID is kept, otherwise the request gets a `req_` ID. Error
//! documents repeat it in `meta.request_id`.
//!
//! Laravel for Rust assigns its own ID before any middleware runs and keeps an incoming one under
//! the same rules, but generates 32 hex digits. Fusion Stack generates `req_` and a lowercase ULID
//! instead, as the PHP package does, and sends that. The framework's own log lines for a request
//! that arrived without an ID still carry the framework's ID.

use std::sync::Arc;

use laravel::http::Request;

/// The header that carries the ID, on the request and on the response.
pub const HEADER: &str = "x-request-id";

/// The request's Fusion Stack ID, a request extension. Read it with [`of`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestId(Arc<str>);

impl RequestId {
    /// The ID as a string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Whether an incoming ID can be kept: 1 to 128 ASCII letters, digits, `.`, `_`, `:` or `-`.
fn is_valid(id: &str) -> bool {
    (1..=128).contains(&id.len())
        && id
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-'))
}

/// A new ID: `req_` and a lowercase ULID.
fn generate() -> String {
    format!("req_{}", ulid::Ulid::new().to_string().to_lowercase())
}

/// The request's ID: the one assigned by the middleware, or else a valid incoming one, or else a
/// new one.
#[must_use]
pub fn of(request: &Request) -> String {
    if let Some(id) = request.extension::<RequestId>() {
        return id.as_str().to_owned();
    }
    request
        .header(HEADER)
        .filter(|id| is_valid(id))
        .map_or_else(generate, str::to_owned)
}

/// Assigns the request its ID before the rest of the application runs.
pub(crate) fn assign(request: &mut Request) -> RequestId {
    let id = RequestId(of(request).into());
    request.extensions_mut().insert(id.clone());
    id
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn generated_ids_are_req_and_a_lowercase_ulid() {
        let id = generate();
        assert!(id.starts_with("req_"), "{id}");
        assert_eq!(id.len(), 30);
        assert!(
            id[4..]
                .bytes()
                .all(|byte| byte.is_ascii_digit() || byte.is_ascii_lowercase()),
            "{id}"
        );
        assert_ne!(generate(), id);
    }

    #[test]
    fn only_ids_that_cannot_forge_log_lines_are_kept() {
        assert!(is_valid("client.abc-123:7_x"));
        assert!(is_valid(&"a".repeat(128)));
        assert!(!is_valid(&"a".repeat(129)));
        assert!(!is_valid(""));
        assert!(!is_valid("has spaces!"));
        assert!(!is_valid("line\nbreak"));
    }
}