footing 0.1.1

Feature-gated foundations for Rust backend services
Documentation
//! Tracing configuration, context, and subscriber initialization.

use std::fmt;

use serde::{Deserialize, Deserializer, Serialize};
use time::format_description::well_known::Rfc3339;
use tracing_subscriber::{
    EnvFilter,
    fmt::{
        self as tracing_fmt,
        format::Writer,
        time::{FormatTime, OffsetTime, UtcTime},
    },
    layer::SubscriberExt,
    util::SubscriberInitExt,
};

use super::error::ObservabilityError;

const RUST_LOG_ENV: &str = "RUST_LOG";
const MAX_TRACE_CONTEXT_VALUE_LENGTH: usize = 128;

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Runtime configuration for tracing.
///
/// Use [`TracingConfig::try_new`] when the service name comes from an
/// untrusted source. Tracing initialization also validates the final value.
pub struct TracingConfig {
    service_name: String,
    json: bool,
    env_filter: Option<String>,
    time_zone: LogTimeZone,
}

impl TracingConfig {
    #[must_use]
    /// Creates a new instance.
    pub fn new(service_name: impl Into<String>) -> Self {
        Self {
            service_name: service_name.into().trim().to_owned(),
            json: false,
            env_filter: None,
            time_zone: LogTimeZone::Utc,
        }
    }

    /// Attempts to create and validate a tracing configuration.
    pub fn try_new(service_name: impl Into<String>) -> Result<Self, ObservabilityError> {
        let config = Self::new(service_name);
        config.validate()?;
        Ok(config)
    }

    #[must_use]
    /// Configures JSON and returns the updated value.
    pub fn with_json(mut self, json: bool) -> Self {
        self.json = json;
        self
    }

    #[must_use]
    /// Configures env filter and returns the updated value.
    pub fn with_env_filter(mut self, env_filter: impl Into<String>) -> Self {
        self.env_filter = Some(env_filter.into().trim().to_owned());
        self
    }

    #[must_use]
    /// Configures time zone and returns the updated value.
    pub const fn with_time_zone(mut self, time_zone: LogTimeZone) -> Self {
        self.time_zone = time_zone;
        self
    }

    #[must_use]
    /// Returns the service name.
    pub fn service_name(&self) -> &str {
        &self.service_name
    }

    #[must_use]
    /// Returns the JSON.
    pub const fn json(&self) -> bool {
        self.json
    }

    #[must_use]
    /// Returns the env filter.
    pub fn env_filter(&self) -> Option<&str> {
        self.env_filter.as_deref()
    }

    #[must_use]
    /// Returns the time zone.
    pub const fn time_zone(&self) -> LogTimeZone {
        self.time_zone
    }

    /// Validates this value.
    pub fn validate(&self) -> Result<(), ObservabilityError> {
        validate_service_name(&self.service_name)
    }
}

/// Timestamp timezone used by tracing output.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum LogTimeZone {
    /// RFC3339 UTC timestamps.
    #[default]
    Utc,
    /// RFC3339 timestamps using the process local UTC offset captured at startup.
    Local,
}

impl LogTimeZone {
    /// Returns the stable configuration.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Utc => "utc",
            Self::Local => "local",
        }
    }
}

#[derive(Debug, Clone)]
enum Rfc3339Timer {
    Utc(UtcTime<Rfc3339>),
    Local(OffsetTime<Rfc3339>),
}

impl Rfc3339Timer {
    fn new(time_zone: LogTimeZone) -> Result<Self, ObservabilityError> {
        match time_zone {
            LogTimeZone::Utc => Ok(Self::Utc(UtcTime::rfc_3339())),
            LogTimeZone::Local => Ok(Self::Local(
                OffsetTime::local_rfc_3339().map_err(ObservabilityError::LocalTimeOffset)?,
            )),
        }
    }
}

impl FormatTime for Rfc3339Timer {
    fn format_time(&self, writer: &mut Writer<'_>) -> fmt::Result {
        match self {
            Self::Utc(timer) => timer.format_time(writer),
            Self::Local(timer) => timer.format_time(writer),
        }
    }
}

/// Initializes the component.
pub fn init(service_name: &str, json: bool) -> Result<(), ObservabilityError> {
    try_init(&TracingConfig::new(service_name).with_json(json))
}

#[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))
    }
}

/// Attempts to initialize the component.
pub fn try_init(config: &TracingConfig) -> Result<(), ObservabilityError> {
    config.validate()?;
    let env_filter = env_filter(config)?;
    let timer = Rfc3339Timer::new(config.time_zone)?;

    if config.json {
        tracing_subscriber::registry()
            .with(env_filter)
            .with(tracing_fmt::layer().with_timer(timer).json())
            .try_init()?;
    } else {
        tracing_subscriber::registry()
            .with(env_filter)
            .with(tracing_fmt::layer().with_timer(timer))
            .try_init()?;
    }

    Ok(())
}

fn env_filter(config: &TracingConfig) -> Result<EnvFilter, ObservabilityError> {
    env_filter_from(config, std::env::var(RUST_LOG_ENV).ok())
}

pub(super) fn env_filter_from(
    config: &TracingConfig,
    env_value: Option<String>,
) -> Result<EnvFilter, ObservabilityError> {
    config.validate()?;

    if let Some(value) = env_value
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
    {
        return Ok(EnvFilter::try_new(value)?);
    }

    if let Some(value) = config
        .env_filter
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
    {
        return Ok(EnvFilter::try_new(value)?);
    }

    Ok(EnvFilter::try_new("info,tower_http=info")?)
}

fn validate_service_name(value: &str) -> Result<(), ObservabilityError> {
    if value.is_empty()
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
    {
        return Err(ObservabilityError::InvalidServiceName);
    }

    Ok(())
}

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)
}