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};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Protocol {
Grpc,
HttpProtobuf,
Native,
}
impl Protocol {
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:?}"))),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum SamplerKind {
AlwaysOn,
AlwaysOff,
TraceIdRatio,
#[default]
ParentBasedAlwaysOn,
ParentBasedAlwaysOff,
ParentBasedTraceIdRatio,
}
impl SamplerKind {
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:?}"))),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PropagatorKind {
TraceContext,
Baggage,
B3,
B3Multi,
Other(String),
}
impl PropagatorKind {
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),
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Compression {
#[default]
Gzip,
None,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TraceBatchConfig {
pub max_queue_size: usize,
pub max_export_batch_size: usize,
pub scheduled_delay: Duration,
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),
}
}
}
#[derive(Clone, PartialEq)]
#[non_exhaustive]
pub struct TracingConfig {
pub service_name: String,
pub service_version: Option<String>,
pub environment: Option<String>,
pub resource_attributes: Attributes,
pub endpoint: Option<String>,
pub protocol: Protocol,
pub headers: BTreeMap<String, String>,
pub sampler: SamplerKind,
pub sampler_ratio: f64,
pub propagators: Vec<PropagatorKind>,
pub batch: TraceBatchConfig,
pub tls: Option<TlsConfig>,
pub compression: Compression,
pub set_global: bool,
protocol_set: bool,
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 {
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,
}
}
pub fn explicit_protocol(&self) -> Option<Protocol> {
(self.protocol_set || self.protocol != Protocol::HttpProtobuf).then_some(self.protocol)
}
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())
}
pub fn with_service_version(mut self, v: impl Into<String>) -> Self {
self.service_version = Some(v.into());
self
}
pub fn with_environment(mut self, env: impl Into<String>) -> Self {
self.environment = Some(env.into());
self
}
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
}
pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.endpoint = Some(endpoint.into());
self
}
pub fn with_protocol(mut self, protocol: Protocol) -> Self {
self.protocol = protocol;
self.protocol_set = true;
self
}
pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.insert(name.into(), value.into());
self
}
pub fn with_sampler(mut self, sampler: SamplerKind, ratio: f64) -> Self {
self.sampler = sampler;
self.sampler_ratio = ratio;
self
}
pub fn with_propagators(mut self, propagators: Vec<PropagatorKind>) -> Self {
self.propagators = propagators;
self.propagators_set = true;
self
}
pub fn with_batch(mut self, batch: TraceBatchConfig) -> Self {
self.batch = batch;
self
}
pub fn with_tls(mut self, tls: TlsConfig) -> Self {
self.tls = Some(tls);
self
}
pub fn with_compression(mut self, compression: Compression) -> Self {
self.compression = compression;
self
}
pub fn with_set_global(mut self, set_global: bool) -> Self {
self.set_global = set_global;
self
}
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(())
}
}