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"
//! Tracing configuration (SPEC §5 `TracingConfig`).

use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;
use std::time::Duration;

use super::Attributes;
use crate::core::redact::{redact_headers, redact_url};
use crate::core::{Error, Result, TlsConfig};

/// Export protocol.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Protocol {
    /// OTLP over gRPC.
    Grpc,
    /// OTLP over HTTP with protobuf payloads.
    HttpProtobuf,
    /// The service's own ingestion API.
    Native,
}

impl Protocol {
    /// Wire value: `grpc`, `http/protobuf`, `native`.
    pub fn as_str(self) -> &'static str {
        match self {
            Protocol::Grpc => "grpc",
            Protocol::HttpProtobuf => "http/protobuf",
            Protocol::Native => "native",
        }
    }
}

impl FromStr for Protocol {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "grpc" => Ok(Protocol::Grpc),
            "http/protobuf" | "http" | "http-protobuf" => Ok(Protocol::HttpProtobuf),
            "native" => Ok(Protocol::Native),
            other => Err(Error::config(format!("unknown tracing protocol {other:?}"))),
        }
    }
}

/// Sampler (names match `OTEL_TRACES_SAMPLER`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum SamplerKind {
    /// Sample everything.
    AlwaysOn,
    /// Sample nothing.
    AlwaysOff,
    /// Sample `sampler_ratio` of traces.
    TraceIdRatio,
    /// Follow the parent; sample roots (default).
    #[default]
    ParentBasedAlwaysOn,
    /// Follow the parent; drop roots.
    ParentBasedAlwaysOff,
    /// Follow the parent; sample `sampler_ratio` of roots.
    ParentBasedTraceIdRatio,
}

impl SamplerKind {
    /// Wire value, e.g. `parentbased_always_on`.
    pub fn as_str(self) -> &'static str {
        match self {
            SamplerKind::AlwaysOn => "always_on",
            SamplerKind::AlwaysOff => "always_off",
            SamplerKind::TraceIdRatio => "traceidratio",
            SamplerKind::ParentBasedAlwaysOn => "parentbased_always_on",
            SamplerKind::ParentBasedAlwaysOff => "parentbased_always_off",
            SamplerKind::ParentBasedTraceIdRatio => "parentbased_traceidratio",
        }
    }
}

impl FromStr for SamplerKind {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "always_on" => Ok(SamplerKind::AlwaysOn),
            "always_off" => Ok(SamplerKind::AlwaysOff),
            "traceidratio" => Ok(SamplerKind::TraceIdRatio),
            "parentbased_always_on" => Ok(SamplerKind::ParentBasedAlwaysOn),
            "parentbased_always_off" => Ok(SamplerKind::ParentBasedAlwaysOff),
            "parentbased_traceidratio" => Ok(SamplerKind::ParentBasedTraceIdRatio),
            other => Err(Error::config(format!("unknown sampler {other:?}"))),
        }
    }
}

/// Context propagation format.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PropagatorKind {
    /// W3C `traceparent` / `tracestate`.
    TraceContext,
    /// W3C `baggage`.
    Baggage,
    /// Zipkin B3 single header (`b3`).
    B3,
    /// Zipkin B3 multiple headers (`X-B3-*`).
    B3Multi,
    /// A propagator the template does not ship (`datadog`, `sw8`, …); the service package must
    /// supply it through [`init_tracing_with_propagators`](super::init_tracing_with_propagators).
    Other(String),
}

impl PropagatorKind {
    /// Wire value, e.g. `tracecontext`.
    pub fn as_str(&self) -> &str {
        match self {
            PropagatorKind::TraceContext => "tracecontext",
            PropagatorKind::Baggage => "baggage",
            PropagatorKind::B3 => "b3",
            PropagatorKind::B3Multi => "b3multi",
            PropagatorKind::Other(s) => s,
        }
    }
}

impl FromStr for PropagatorKind {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self> {
        let t = s.trim().to_ascii_lowercase();
        Ok(match t.as_str() {
            "tracecontext" => PropagatorKind::TraceContext,
            "baggage" => PropagatorKind::Baggage,
            "b3" => PropagatorKind::B3,
            "b3multi" => PropagatorKind::B3Multi,
            "" => return Err(Error::config("empty propagator name")),
            _ => PropagatorKind::Other(t),
        })
    }
}

/// Payload compression.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Compression {
    /// gzip (default).
    #[default]
    Gzip,
    /// No compression.
    None,
}

/// Batch span processor settings.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TraceBatchConfig {
    /// Maximum queued spans (default 2048).
    pub max_queue_size: usize,
    /// Maximum spans per export (default 512).
    pub max_export_batch_size: usize,
    /// Delay between exports (default 5 s).
    pub scheduled_delay: Duration,
    /// Deadline per export (default 30 s).
    pub export_timeout: Duration,
}

impl Default for TraceBatchConfig {
    fn default() -> Self {
        TraceBatchConfig {
            max_queue_size: 2048,
            max_export_batch_size: 512,
            scheduled_delay: Duration::from_millis(5000),
            export_timeout: Duration::from_millis(30_000),
        }
    }
}

/// Tracing setup options (SPEC §5). Create with [`TracingConfig::new`] and adjust fields or
/// use the `with_*` methods.
#[derive(Clone, PartialEq)]
#[non_exhaustive]
pub struct TracingConfig {
    /// `service.name` resource attribute (required).
    pub service_name: String,
    /// `service.version`.
    pub service_version: Option<String>,
    /// `deployment.environment`.
    pub environment: Option<String>,
    /// Extra resource attributes.
    pub resource_attributes: Attributes,
    /// Exporter endpoint (service default when `None`).
    pub endpoint: Option<String>,
    /// Export protocol (service default).
    pub protocol: Protocol,
    /// Extra export headers (auth headers are redacted in `Debug`).
    pub headers: BTreeMap<String, String>,
    /// Sampler (default `parentbased_always_on`).
    pub sampler: SamplerKind,
    /// Ratio for the ratio samplers (default 1.0).
    pub sampler_ratio: f64,
    /// Propagators (default `tracecontext`, `baggage`).
    pub propagators: Vec<PropagatorKind>,
    /// Batch processor settings.
    pub batch: TraceBatchConfig,
    /// TLS settings for the exporter.
    pub tls: Option<TlsConfig>,
    /// Compression (default gzip).
    pub compression: Compression,
    /// Install the provider and propagator globally (default `true`).
    pub set_global: bool,
    /// `protocol` was set through [`TracingConfig::with_protocol`].
    protocol_set: bool,
    /// `propagators` were set through [`TracingConfig::with_propagators`].
    propagators_set: bool,
}

impl fmt::Debug for TracingConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TracingConfig")
            .field("service_name", &self.service_name)
            .field("service_version", &self.service_version)
            .field("environment", &self.environment)
            .field("resource_attributes", &self.resource_attributes)
            .field("endpoint", &self.endpoint.as_deref().map(redact_url))
            .field("protocol", &self.protocol)
            .field("headers", &redact_headers(self.headers.iter()))
            .field("sampler", &self.sampler)
            .field("sampler_ratio", &self.sampler_ratio)
            .field("propagators", &self.propagators)
            .field("batch", &self.batch)
            .field("tls", &self.tls)
            .field("compression", &self.compression)
            .field("set_global", &self.set_global)
            .finish()
    }
}

impl TracingConfig {
    /// Defaults for `service_name` (protocol `http/protobuf` until the service overrides it).
    pub fn new(service_name: impl Into<String>) -> Self {
        TracingConfig {
            service_name: service_name.into(),
            service_version: None,
            environment: None,
            resource_attributes: Attributes::new(),
            endpoint: None,
            protocol: Protocol::HttpProtobuf,
            headers: BTreeMap::new(),
            sampler: SamplerKind::default(),
            sampler_ratio: 1.0,
            propagators: vec![PropagatorKind::TraceContext, PropagatorKind::Baggage],
            batch: TraceBatchConfig::default(),
            tls: None,
            compression: Compression::Gzip,
            set_global: true,
            protocol_set: false,
            propagators_set: false,
        }
    }

    /// The protocol when the caller chose one: set with [`with_protocol`](Self::with_protocol)
    /// or assigned a value other than the template default. `None` means "use the service
    /// default" (the `protocol` field still holds the template default `http/protobuf`).
    pub fn explicit_protocol(&self) -> Option<Protocol> {
        (self.protocol_set || self.protocol != Protocol::HttpProtobuf).then_some(self.protocol)
    }

    /// The propagators when the caller chose them: set with
    /// [`with_propagators`](Self::with_propagators) or assigned a list other than the default
    /// `tracecontext, baggage`. `None` means "use the service default".
    pub fn explicit_propagators(&self) -> Option<&[PropagatorKind]> {
        let default = [PropagatorKind::TraceContext, PropagatorKind::Baggage];
        (self.propagators_set || self.propagators[..] != default[..])
            .then_some(self.propagators.as_slice())
    }

    /// Sets `service_version`.
    pub fn with_service_version(mut self, v: impl Into<String>) -> Self {
        self.service_version = Some(v.into());
        self
    }
    /// Sets `environment`.
    pub fn with_environment(mut self, env: impl Into<String>) -> Self {
        self.environment = Some(env.into());
        self
    }
    /// Adds a resource attribute.
    pub fn with_resource_attribute(
        mut self,
        key: impl Into<String>,
        value: impl Into<super::AttrValue>,
    ) -> Self {
        self.resource_attributes.insert(key.into(), value.into());
        self
    }
    /// Sets `endpoint`.
    pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.endpoint = Some(endpoint.into());
        self
    }
    /// Sets `protocol`.
    pub fn with_protocol(mut self, protocol: Protocol) -> Self {
        self.protocol = protocol;
        self.protocol_set = true;
        self
    }
    /// Adds an export header.
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(name.into(), value.into());
        self
    }
    /// Sets the sampler and ratio.
    pub fn with_sampler(mut self, sampler: SamplerKind, ratio: f64) -> Self {
        self.sampler = sampler;
        self.sampler_ratio = ratio;
        self
    }
    /// Replaces the propagators.
    pub fn with_propagators(mut self, propagators: Vec<PropagatorKind>) -> Self {
        self.propagators = propagators;
        self.propagators_set = true;
        self
    }
    /// Sets the batch settings.
    pub fn with_batch(mut self, batch: TraceBatchConfig) -> Self {
        self.batch = batch;
        self
    }
    /// Sets TLS.
    pub fn with_tls(mut self, tls: TlsConfig) -> Self {
        self.tls = Some(tls);
        self
    }
    /// Sets compression.
    pub fn with_compression(mut self, compression: Compression) -> Self {
        self.compression = compression;
        self
    }
    /// Sets `set_global`.
    pub fn with_set_global(mut self, set_global: bool) -> Self {
        self.set_global = set_global;
        self
    }

    /// Checks the service name, sampler ratio, batch sizes, durations and endpoint scheme.
    pub fn validate(&self) -> Result<()> {
        if self.service_name.trim().is_empty() {
            return Err(Error::config("tracing serviceName must not be empty"));
        }
        if !(0.0..=1.0).contains(&self.sampler_ratio) {
            return Err(Error::config(
                "tracing samplerRatio must be between 0 and 1",
            ));
        }
        let b = &self.batch;
        if b.max_queue_size == 0 || b.max_export_batch_size == 0 {
            return Err(Error::config("tracing batch sizes must be positive"));
        }
        if b.max_export_batch_size > b.max_queue_size {
            return Err(Error::config(
                "tracing batch maxExportBatchSize must not exceed maxQueueSize",
            ));
        }
        if b.scheduled_delay.is_zero() || b.export_timeout.is_zero() {
            return Err(Error::config("tracing batch durations must be positive"));
        }
        if let Some(endpoint) = &self.endpoint {
            let ok = url::Url::parse(endpoint)
                .map(|u| matches!(u.scheme(), "http" | "https"))
                .unwrap_or(false);
            if !ok {
                return Err(Error::config(
                    "tracing endpoint must be an http or https URL",
                ));
            }
        }
        Ok(())
    }
}