servlet 1.0.0

A small application runtime with an explicit operational contract
Documentation
//! Bounded W3C trace context without process-global propagator registration.

use axum::http::{HeaderMap, HeaderName, HeaderValue};
use opentelemetry::{
    Context,
    propagation::{Extractor, Injector, TextMapPropagator},
    trace::{SpanContext, TraceContextExt},
};
use opentelemetry_sdk::propagation::TraceContextPropagator;
use tracing::{Dispatch, span::Id};
use tracing_opentelemetry::get_otel_context;
use tracing_subscriber::{Registry, registry::LookupSpan};

const MAX_CONTEXT_BYTES: usize = 512;

/// Native OpenTelemetry context of the current span or its nearest traced ancestor.
/// Trace identity is diagnostic data, never authenticated application identity.
pub fn current_trace_context() -> Option<SpanContext> {
    current_context().map(|context| context.span().span_context().clone())
}

fn current_context() -> Option<Context> {
    tracing::Span::current()
        .with_subscriber(|(id, dispatch)| span_context(id, dispatch))
        .flatten()
}

pub(super) fn span_context(id: &Id, dispatch: &Dispatch) -> Option<Context> {
    let native = |id: &Id| {
        get_otel_context(id, dispatch).filter(|context| context.span().span_context().is_valid())
    };
    native(id).or_else(|| {
        // Walk recorded parents so an explicit root stays isolated from the
        // ambient OpenTelemetry context of a different entered span.
        let registry = dispatch.downcast_ref::<Registry>()?;
        registry
            .span(id)?
            .scope()
            .skip(1)
            .find_map(|parent| native(&parent.id()))
    })
}

/// Explicitly propagate the entered span to an approved outbound destination.
///
/// Replaces existing traceparent/tracestate and removes baggage. Returns whether
/// valid context was injected. Calling this is the application's destination
/// approval; clients must not blindly forward these headers across redirects.
pub fn inject_trace_context(headers: &mut HeaderMap) -> bool {
    headers.remove("traceparent");
    headers.remove("tracestate");
    headers.remove("baggage");
    let Some(context) = current_context() else {
        return false;
    };
    TraceContextPropagator::new().inject_context(&context, &mut HeadersOut(headers));
    true
}

pub(crate) fn extract_trace_context(headers: &HeaderMap) -> Context {
    let mut parents = headers.get_all("traceparent").iter();
    let parent = parents
        .next()
        .and_then(|value| value.to_str().ok())
        .filter(|value| value.len() <= MAX_CONTEXT_BYTES && parents.next().is_none());
    let state = joined_state(headers);
    // Start from an empty context: neither arbitrary baggage nor an ambient
    // application's identity can leak into a newly accepted network request.
    TraceContextPropagator::new()
        .extract_with_context(&Context::new(), &HeadersIn { parent, state })
}

fn joined_state(headers: &HeaderMap) -> Option<String> {
    let mut state = String::new();
    for value in headers.get_all("tracestate") {
        let value = value.to_str().ok()?;
        let separator = usize::from(!state.is_empty());
        if state
            .len()
            .saturating_add(value.len())
            .saturating_add(separator)
            > MAX_CONTEXT_BYTES
        {
            return None;
        }
        if separator != 0 {
            state.push(',');
        }
        state.push_str(value);
    }
    (!state.is_empty()).then_some(state)
}

struct HeadersIn<'a> {
    parent: Option<&'a str>,
    state: Option<String>,
}
impl Extractor for HeadersIn<'_> {
    fn get(&self, key: &str) -> Option<&str> {
        match key {
            "traceparent" => self.parent,
            "tracestate" => self.state.as_deref(),
            _ => None,
        }
    }
    fn keys(&self) -> Vec<&str> {
        vec!["traceparent", "tracestate"]
    }
}
struct HeadersOut<'a>(&'a mut HeaderMap);
impl Injector for HeadersOut<'_> {
    fn set(&mut self, key: &str, value: String) {
        if value.len() > MAX_CONTEXT_BYTES {
            return;
        }
        if let (Ok(key), Ok(value)) = (
            HeaderName::from_bytes(key.as_bytes()),
            HeaderValue::from_str(&value),
        ) {
            self.0.insert(key, value);
        }
    }
}

#[cfg(test)]
#[path = "propagation_test.rs"]
mod propagation_test;