footing 0.6.6

Feature-gated foundations for Rust backend services
Documentation
//! Trace identifiers independent of log formatting and subscriber setup.

use serde::{Deserialize, Deserializer, Serialize};

const MAX_TRACE_CONTEXT_VALUE_LENGTH: usize = 128;

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
/// Context associated with trace.
pub struct TraceContext {
    trace_id: Option<String>,
    span_id: Option<String>,
    request_id: Option<String>,
}

impl TraceContext {
    #[must_use]
    /// Creates a new instance.
    pub fn new(
        trace_id: Option<String>,
        span_id: Option<String>,
        request_id: Option<String>,
    ) -> Self {
        Self {
            trace_id: normalize_trace_context_value(trace_id),
            span_id: normalize_trace_context_value(span_id),
            request_id: normalize_trace_context_value(request_id),
        }
    }

    #[must_use]
    /// Returns the trace identifier.
    pub fn trace_id(&self) -> Option<&str> {
        self.trace_id.as_deref()
    }

    #[must_use]
    /// Returns the span identifier.
    pub fn span_id(&self) -> Option<&str> {
        self.span_id.as_deref()
    }

    #[must_use]
    /// Returns the request identifier.
    pub fn request_id(&self) -> Option<&str> {
        self.request_id.as_deref()
    }

    #[must_use]
    /// Returns whether the collection is empty.
    pub const fn is_empty(&self) -> bool {
        self.trace_id.is_none() && self.span_id.is_none() && self.request_id.is_none()
    }
}

impl<'de> Deserialize<'de> for TraceContext {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct TraceContextWire {
            #[serde(default)]
            trace_id: Option<String>,
            #[serde(default)]
            span_id: Option<String>,
            #[serde(default)]
            request_id: Option<String>,
        }

        let wire = TraceContextWire::deserialize(deserializer)?;
        Ok(Self::new(wire.trace_id, wire.span_id, wire.request_id))
    }
}

fn normalize_trace_context_value(value: Option<String>) -> Option<String> {
    let value = value?.trim().to_owned();
    if value.is_empty()
        || value.len() > MAX_TRACE_CONTEXT_VALUE_LENGTH
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
    {
        return None;
    }

    Some(value)
}