footing 0.1.3

Feature-gated foundations for Rust backend services
Documentation
//! Validated request identifiers and W3C trace-parent values.

use std::fmt;

use serde::{Deserialize, Deserializer, Serialize};
use thiserror::Error;
use uuid::Uuid;

use crate::result::{ClassifyError, ErrorKind};

/// Request identifier header name.
pub const REQUEST_ID_HEADER_NAME: &str = "x-request-id";
/// Traceparent header name.
pub const TRACEPARENT_HEADER_NAME: &str = "traceparent";
/// Maximum supported request identifier length.
pub const MAX_REQUEST_ID_LENGTH: usize = 128;
/// Traceparent length.
pub const TRACEPARENT_LENGTH: usize = 55;

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
/// Represents request identifier.
pub struct RequestId(String);

impl RequestId {
    /// Creates a new instance.
    pub fn new(value: impl Into<String>) -> Result<Self, RequestIdError> {
        let value = value.into();
        validate_request_id(&value)?;
        Ok(Self(value))
    }

    /// Attempts to create and validate a request identifier.
    pub fn try_new(value: impl Into<String>) -> Result<Self, RequestIdError> {
        Self::new(value)
    }

    #[must_use]
    /// Generates the value.
    pub fn generate() -> Self {
        Self(format!("req_{}", Uuid::now_v7().simple()))
    }

    #[must_use]
    /// Returns this value as str.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    #[must_use]
    /// Parses the value.
    pub fn parse(value: &str) -> Option<Self> {
        Self::new(value).ok()
    }
}

impl TryFrom<&str> for RequestId {
    type Error = RequestIdError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl TryFrom<String> for RequestId {
    type Error = RequestIdError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl Default for RequestId {
    fn default() -> Self {
        Self::generate()
    }
}

impl fmt::Display for RequestId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for RequestId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
/// Errors that can occur while handling request identifier.
pub enum RequestIdError {
    #[error("request id must not be empty")]
    /// Indicates empty.
    Empty,
    #[error("request id must be less than or equal to {max} bytes")]
    /// The value exceeds the supported length.
    TooLong {
        #[doc = "The configured upper bound."]
        max: usize,
    },
    #[error("request id contains unsupported characters")]
    /// The characters is invalid.
    InvalidCharacters,
}

impl ClassifyError for RequestIdError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::Empty => "request_id_empty",
            Self::TooLong { .. } => "request_id_too_long",
            Self::InvalidCharacters => "request_id_invalid_characters",
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
/// Represents trace parent.
pub struct TraceParent(String);

impl TraceParent {
    /// Creates a new instance.
    pub fn new(value: impl Into<String>) -> Result<Self, TraceParentError> {
        let value = value.into().trim().to_owned();
        validate_traceparent(&value)?;
        Ok(Self(value))
    }

    /// Attempts to create and validate a W3C `traceparent`.
    pub fn try_new(value: impl Into<String>) -> Result<Self, TraceParentError> {
        Self::new(value)
    }

    #[must_use]
    /// Parses the value.
    pub fn parse(value: &str) -> Option<Self> {
        Self::new(value).ok()
    }

    #[must_use]
    /// Returns this value as str.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    #[must_use]
    /// Consumes this value and returns string.
    pub fn into_string(self) -> String {
        self.0
    }

    #[must_use]
    /// Returns the version.
    pub fn version(&self) -> &str {
        self.0.get(0..2).unwrap_or("")
    }

    #[must_use]
    /// Returns the trace identifier.
    pub fn trace_id(&self) -> &str {
        self.0.get(3..35).unwrap_or("")
    }

    #[must_use]
    /// Returns the span identifier.
    pub fn span_id(&self) -> &str {
        self.0.get(36..52).unwrap_or("")
    }

    #[must_use]
    /// Returns the trace flags.
    pub fn trace_flags(&self) -> &str {
        self.0.get(53..55).unwrap_or("")
    }

    #[must_use]
    /// Returns the sampled.
    pub fn sampled(&self) -> bool {
        parse_hex_byte(self.trace_flags().as_bytes()).is_some_and(|flags| flags & 1 == 1)
    }
}

impl TryFrom<&str> for TraceParent {
    type Error = TraceParentError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl TryFrom<String> for TraceParent {
    type Error = TraceParentError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl fmt::Display for TraceParent {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for TraceParent {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
/// Errors that can occur while handling trace parent.
pub enum TraceParentError {
    #[error("traceparent header shape is invalid")]
    /// The format is invalid.
    InvalidFormat,
    #[error("traceparent version is invalid")]
    /// The version is invalid.
    InvalidVersion,
    #[error("traceparent trace id is invalid")]
    /// The trace identifier is invalid.
    InvalidTraceId,
    #[error("traceparent span id is invalid")]
    /// The span identifier is invalid.
    InvalidSpanId,
    #[error("traceparent flags are invalid")]
    /// The flags is invalid.
    InvalidFlags,
}

impl ClassifyError for TraceParentError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::InvalidFormat => "traceparent_invalid_format",
            Self::InvalidVersion => "traceparent_invalid_version",
            Self::InvalidTraceId => "traceparent_invalid_trace_id",
            Self::InvalidSpanId => "traceparent_invalid_span_id",
            Self::InvalidFlags => "traceparent_invalid_flags",
        })
    }
}

#[must_use]
/// Returns whether this value is valid request identifier.
pub fn is_valid_request_id(value: &str) -> bool {
    validate_request_id(value).is_ok()
}

fn validate_request_id(value: &str) -> Result<(), RequestIdError> {
    if value.is_empty() {
        return Err(RequestIdError::Empty);
    }

    if value.len() > MAX_REQUEST_ID_LENGTH {
        return Err(RequestIdError::TooLong {
            max: MAX_REQUEST_ID_LENGTH,
        });
    }

    if !value
        .bytes()
        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
    {
        return Err(RequestIdError::InvalidCharacters);
    }

    Ok(())
}

#[must_use]
/// Returns whether this value is valid traceparent.
pub fn is_valid_traceparent(value: &str) -> bool {
    validate_traceparent(value).is_ok()
}

fn validate_traceparent(value: &str) -> Result<(), TraceParentError> {
    let bytes = value.as_bytes();

    if bytes.len() != TRACEPARENT_LENGTH
        || bytes.get(2) != Some(&b'-')
        || bytes.get(35) != Some(&b'-')
        || bytes.get(52) != Some(&b'-')
    {
        return Err(TraceParentError::InvalidFormat);
    }

    let version = bytes.get(0..2).ok_or(TraceParentError::InvalidFormat)?;
    let trace_id = bytes.get(3..35).ok_or(TraceParentError::InvalidFormat)?;
    let span_id = bytes.get(36..52).ok_or(TraceParentError::InvalidFormat)?;
    let flags = bytes.get(53..55).ok_or(TraceParentError::InvalidFormat)?;

    if !is_lower_hex(version) || version == b"ff" {
        return Err(TraceParentError::InvalidVersion);
    }

    if !is_lower_hex(trace_id) || trace_id.iter().all(|byte| *byte == b'0') {
        return Err(TraceParentError::InvalidTraceId);
    }

    if !is_lower_hex(span_id) || span_id.iter().all(|byte| *byte == b'0') {
        return Err(TraceParentError::InvalidSpanId);
    }

    if !is_lower_hex(flags) {
        return Err(TraceParentError::InvalidFlags);
    }

    Ok(())
}

fn is_lower_hex(bytes: &[u8]) -> bool {
    bytes
        .iter()
        .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
}

fn parse_hex_byte(bytes: &[u8]) -> Option<u8> {
    if bytes.len() != 2 || !is_lower_hex(bytes) {
        return None;
    }

    let high = *bytes.first()?;
    let low = *bytes.get(1)?;
    Some(hex_value(high)? << 4 | hex_value(low)?)
}

fn hex_value(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        _ => None,
    }
}