grow-apache-skywalking 0.2.0

Rust SDK for Apache SkyWalking by Grow Codes
Documentation
// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
//! Context propagation: W3C trace context + baggage (OpenTelemetry SDK), Zipkin B3 (own
//! implementation, so the template does not pull in the Zipkin exporter), and carrier helpers.

use std::collections::HashMap;

use opentelemetry::propagation::{
    text_map_propagator::FieldIter, Extractor, Injector, TextMapCompositePropagator,
    TextMapPropagator,
};
use opentelemetry::trace::{SpanContext, SpanId, TraceContextExt, TraceFlags, TraceId, TraceState};
use opentelemetry::Context;
use opentelemetry_sdk::propagation::{BaggagePropagator, TraceContextPropagator};

use super::PropagatorKind;
use crate::core::{Error, Result};

/// A boxed propagator as accepted by [`build_propagator`].
pub type BoxedPropagator = Box<dyn TextMapPropagator + Send + Sync>;

const B3_SINGLE: &str = "b3";
const B3_TRACE_ID: &str = "x-b3-traceid";
const B3_SPAN_ID: &str = "x-b3-spanid";
const B3_SAMPLED: &str = "x-b3-sampled";
const B3_FLAGS: &str = "x-b3-flags";

/// Zipkin B3 propagator. Injects either the single `b3` header or the `X-B3-*` headers;
/// extracts both forms (single header first). 64-bit trace ids are left-padded to 128 bits.
#[derive(Debug, Clone)]
pub struct B3Propagator {
    multi: bool,
    fields: Vec<String>,
}

impl B3Propagator {
    /// Single-header (`b3`) encoding.
    pub fn single() -> Self {
        B3Propagator {
            multi: false,
            fields: vec![B3_SINGLE.to_string()],
        }
    }

    /// Multi-header (`X-B3-TraceId`, `X-B3-SpanId`, `X-B3-Sampled`) encoding.
    pub fn multi() -> Self {
        B3Propagator {
            multi: true,
            fields: [B3_TRACE_ID, B3_SPAN_ID, B3_SAMPLED, B3_FLAGS]
                .iter()
                .map(|s| s.to_string())
                .collect(),
        }
    }

    fn parse_ids(trace: &str, span: &str) -> Option<(TraceId, SpanId)> {
        let valid = |s: &str, lens: &[usize]| {
            lens.contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit())
        };
        if !valid(trace, &[16, 32]) || !valid(span, &[16]) {
            return None;
        }
        let trace = TraceId::from_hex(&format!("{trace:0>32}")).ok()?;
        let span = SpanId::from_hex(span).ok()?;
        (trace != TraceId::INVALID && span != SpanId::INVALID).then_some((trace, span))
    }

    fn sampled(flag: Option<&str>, debug: bool) -> TraceFlags {
        match flag {
            _ if debug => TraceFlags::SAMPLED,
            Some("1") | Some("d") | Some("true") => TraceFlags::SAMPLED,
            // B3 leaves an absent decision to the receiver; treat it as sampled (defer).
            None => TraceFlags::SAMPLED,
            _ => TraceFlags::default(),
        }
    }

    fn extract_single(value: &str) -> Option<SpanContext> {
        let parts: Vec<&str> = value.trim().split('-').collect();
        if parts.len() < 2 {
            return None;
        }
        let (trace, span) = Self::parse_ids(parts[0], parts[1])?;
        let flags = Self::sampled(parts.get(2).copied(), parts.get(2) == Some(&"d"));
        Some(SpanContext::new(
            trace,
            span,
            flags,
            true,
            TraceState::default(),
        ))
    }

    fn extract_multi(extractor: &dyn Extractor) -> Option<SpanContext> {
        let (trace, span) = Self::parse_ids(
            extractor.get(B3_TRACE_ID)?.trim(),
            extractor.get(B3_SPAN_ID)?.trim(),
        )?;
        let debug = extractor.get(B3_FLAGS).map(str::trim) == Some("1");
        let flags = Self::sampled(extractor.get(B3_SAMPLED).map(str::trim), debug);
        Some(SpanContext::new(
            trace,
            span,
            flags,
            true,
            TraceState::default(),
        ))
    }
}

impl TextMapPropagator for B3Propagator {
    fn inject_context(&self, cx: &Context, injector: &mut dyn Injector) {
        let span = cx.span();
        let sc = span.span_context();
        if !sc.is_valid() {
            return;
        }
        let sampled = if sc.is_sampled() { "1" } else { "0" };
        if self.multi {
            injector.set(B3_TRACE_ID, sc.trace_id().to_string());
            injector.set(B3_SPAN_ID, sc.span_id().to_string());
            injector.set(B3_SAMPLED, sampled.to_string());
        } else {
            injector.set(
                B3_SINGLE,
                format!("{}-{}-{}", sc.trace_id(), sc.span_id(), sampled),
            );
        }
    }

    fn extract_with_context(&self, cx: &Context, extractor: &dyn Extractor) -> Context {
        let sc = extractor
            .get(B3_SINGLE)
            .and_then(Self::extract_single)
            .or_else(|| Self::extract_multi(extractor));
        match sc {
            Some(sc) => cx.with_remote_span_context(sc),
            None => cx.clone(),
        }
    }

    fn fields(&self) -> FieldIter<'_> {
        FieldIter::new(&self.fields)
    }
}

/// Builds the composite propagator for `kinds`. `extra` supplies propagators the template does
/// not ship (matched by [`PropagatorKind::Other`] name); unknown names → `CONFIG`.
pub fn build_propagator(
    kinds: &[PropagatorKind],
    mut extra: HashMap<String, BoxedPropagator>,
) -> Result<TextMapCompositePropagator> {
    let mut list: Vec<BoxedPropagator> = Vec::with_capacity(kinds.len());
    for kind in kinds {
        list.push(match kind {
            PropagatorKind::TraceContext => Box::new(TraceContextPropagator::new()),
            PropagatorKind::Baggage => Box::new(BaggagePropagator::new()),
            PropagatorKind::B3 => Box::new(B3Propagator::single()),
            PropagatorKind::B3Multi => Box::new(B3Propagator::multi()),
            PropagatorKind::Other(name) => extra.remove(name).ok_or_else(|| {
                Error::config(format!(
                    "propagator {name:?} is not supported by this package"
                ))
            })?,
        });
    }
    Ok(TextMapCompositePropagator::new(list))
}

/// Injector/extractor over an `http::HeaderMap` (invalid header values are skipped).
pub(crate) mod headers {
    use super::{Extractor, Injector};

    /// Mutable header carrier.
    pub struct HeaderInjector<'a>(pub &'a mut http::HeaderMap);
    /// Read-only header carrier.
    pub struct HeaderExtractor<'a>(pub &'a http::HeaderMap);

    impl Injector for HeaderInjector<'_> {
        fn set(&mut self, key: &str, value: String) {
            if let (Ok(name), Ok(value)) = (
                http::header::HeaderName::from_bytes(key.as_bytes()),
                http::header::HeaderValue::from_str(&value),
            ) {
                self.0.insert(name, value);
            }
        }
    }

    impl Extractor for HeaderExtractor<'_> {
        fn get(&self, key: &str) -> Option<&str> {
            self.0.get(key).and_then(|v| v.to_str().ok())
        }
        fn keys(&self) -> Vec<&str> {
            self.0.keys().map(|k| k.as_str()).collect()
        }
    }
}

/// Case-insensitive view of a string map for extraction (HTTP header names are not
/// case-sensitive, but `HashMap` lookups are).
struct MapExtractor<'a>(HashMap<String, &'a str>);

impl<'a> MapExtractor<'a> {
    fn new(carrier: &'a HashMap<String, String>) -> Self {
        MapExtractor(
            carrier
                .iter()
                .map(|(k, v)| (k.to_ascii_lowercase(), v.as_str()))
                .collect(),
        )
    }
}

impl Extractor for MapExtractor<'_> {
    fn get(&self, key: &str) -> Option<&str> {
        self.0.get(&key.to_ascii_lowercase()).copied()
    }
    fn keys(&self) -> Vec<&str> {
        self.0.keys().map(String::as_str).collect()
    }
}

/// Injects the current context into `carrier` with the global propagator.
pub fn inject(carrier: &mut HashMap<String, String>) {
    inject_context(&super::active_context(), carrier);
}

/// Injects `cx` into `carrier` with the global propagator.
pub fn inject_context(cx: &Context, carrier: &mut HashMap<String, String>) {
    opentelemetry::global::get_text_map_propagator(|p| p.inject_context(cx, carrier));
}

/// Extracts a context from `carrier` (keys matched case-insensitively) with the global
/// propagator. Returns the current context when nothing valid is found.
pub fn extract(carrier: &HashMap<String, String>) -> Context {
    let ex = MapExtractor::new(carrier);
    opentelemetry::global::get_text_map_propagator(|p| p.extract(&ex))
}

/// Injects the current context into HTTP headers.
pub fn inject_headers(headers: &mut http::HeaderMap) {
    inject_headers_context(&super::active_context(), headers);
}

/// Injects `cx` into HTTP headers.
pub fn inject_headers_context(cx: &Context, headers: &mut http::HeaderMap) {
    opentelemetry::global::get_text_map_propagator(|p| {
        p.inject_context(cx, &mut headers::HeaderInjector(headers))
    });
}

/// Extracts a context from HTTP headers.
pub fn extract_headers(headers: &http::HeaderMap) -> Context {
    opentelemetry::global::get_text_map_propagator(|p| {
        p.extract(&headers::HeaderExtractor(headers))
    })
}