Skip to main content

strands/telemetry/
config.rs

1//! OpenTelemetry setup: [`setup_tracer`] and [`setup_meter`] build providers with OTLP HTTP and
2//! console exporters configured from the environment, and register them globally.
3
4use std::fmt;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::{Mutex, PoisonError};
7
8use opentelemetry::baggage::BaggageExt;
9use opentelemetry::propagation::TextMapCompositePropagator;
10use opentelemetry::trace::{Span as _, TracerProvider as _};
11use opentelemetry::{Context, KeyValue, global};
12use opentelemetry_sdk::Resource;
13use opentelemetry_sdk::metrics::SdkMeterProvider;
14use opentelemetry_sdk::propagation::{BaggagePropagator, TraceContextPropagator};
15use opentelemetry_sdk::resource::TelemetryResourceDetector;
16use opentelemetry_sdk::trace::{SdkTracer, SdkTracerProvider, Span, SpanData, SpanProcessor};
17use tracing_opentelemetry::OpenTelemetryLayer;
18use tracing_subscriber::layer::SubscriberExt;
19use tracing_subscriber::registry::LookupSpan;
20use tracing_subscriber::util::SubscriberInitExt;
21
22use super::utils::{EnvLookup, process_env, service_meter, service_name, service_name_from};
23use crate::error::{Error, Result};
24
25const DEFAULT_SERVICE_NAMESPACE: &str = "strands";
26const DEFAULT_DEPLOYMENT_ENVIRONMENT: &str = "development";
27
28static TRACER_PROVIDER: ProviderSlot<SdkTracerProvider> = Mutex::new(None);
29static METER_PROVIDER: ProviderSlot<SdkMeterProvider> = Mutex::new(None);
30static NEXT_REGISTRATION: AtomicU64 = AtomicU64::new(0);
31
32/// A provider registered by `setup_*`, with the id its guards release it by.
33pub(crate) struct Registration<P> {
34    id: u64,
35    provider: P,
36}
37
38/// Where `setup_*` keeps the provider it registered.
39pub(crate) type ProviderSlot<P> = Mutex<Option<Registration<P>>>;
40
41/// Empties the slot if it still holds registration `id`, so the next `setup_*` builds a new
42/// provider instead of returning a stopped one.
43pub(crate) fn release<P>(slot: &ProviderSlot<P>, id: u64) {
44    let mut slot = slot.lock().unwrap_or_else(PoisonError::into_inner);
45    if slot.as_ref().is_some_and(|registration| registration.id == id) {
46        *slot = None;
47    }
48}
49
50fn register<P: Clone>(slot: &mut Option<Registration<P>>, provider: &P) -> u64 {
51    let id = NEXT_REGISTRATION.fetch_add(1, Ordering::Relaxed);
52    *slot = Some(Registration {
53        id,
54        provider: provider.clone(),
55    });
56    id
57}
58
59/// Which exporters a provider gets.
60#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, bon::Builder)]
61pub struct TelemetryExporters {
62    /// OTLP over HTTP, configured by the `OTEL_EXPORTER_OTLP_*` variables (endpoint, headers,
63    /// protocol, timeout).
64    #[builder(default)]
65    pub otlp: bool,
66    /// Prints to stdout, for debugging.
67    #[builder(default)]
68    pub console: bool,
69}
70
71crate::callback::callback! {
72    /// Selects baggage keys for the baggage span processor (`BaggageKeyPredicate`).
73    pub struct BaggageKeyPredicate(Fn(&str) -> bool);
74}
75
76/// The predicates of [`BaggageProcessor::Predicates`] (`BaggageKeyPredicates`); a key is stamped
77/// when any of them selects it.
78pub type BaggageKeyPredicates = Vec<BaggageKeyPredicate>;
79
80/// Which baggage entries the tracer stamps onto every span as attributes.
81///
82/// ```
83/// use strands::telemetry::BaggageProcessor;
84///
85/// let tenant_keys = BaggageProcessor::predicate(|key| key.starts_with("tenant."));
86/// # let _ = tenant_keys;
87/// ```
88#[derive(Clone)]
89#[non_exhaustive]
90pub enum BaggageProcessor {
91    /// Every key.
92    AllKeys,
93    /// The keys any predicate selects.
94    Predicates(BaggageKeyPredicates),
95}
96
97impl BaggageProcessor {
98    /// The keys one predicate selects.
99    pub fn predicate(predicate: impl Fn(&str) -> bool + Send + Sync + 'static) -> Self {
100        Self::Predicates(vec![BaggageKeyPredicate::new(predicate)])
101    }
102
103    fn selects(&self, key: &str) -> bool {
104        match self {
105            Self::AllKeys => true,
106            Self::Predicates(predicates) => predicates.iter().any(|predicate| predicate(key)),
107        }
108    }
109}
110
111impl fmt::Debug for BaggageProcessor {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        match self {
114            Self::AllKeys => f.write_str("AllKeys"),
115            Self::Predicates(predicates) => f.debug_tuple("Predicates").field(&predicates.len()).finish(),
116        }
117    }
118}
119
120/// Copies the parent context's baggage onto each span as attributes (`BaggageSpanProcessor`).
121#[derive(Debug)]
122pub(crate) struct BaggageSpanProcessor {
123    keys: BaggageProcessor,
124}
125
126impl BaggageSpanProcessor {
127    pub(crate) fn new(keys: BaggageProcessor) -> Self {
128        Self { keys }
129    }
130}
131
132impl SpanProcessor for BaggageSpanProcessor {
133    fn on_start(&self, span: &mut Span, cx: &Context) {
134        for (key, (value, _)) in cx.baggage() {
135            if self.keys.selects(key.as_str()) {
136                span.set_attribute(KeyValue::new(key.clone(), value.to_string()));
137            }
138        }
139    }
140
141    fn on_end(&self, _span: SpanData) {}
142
143    fn force_flush(&self) -> opentelemetry_sdk::error::OTelSdkResult {
144        Ok(())
145    }
146
147    fn shutdown_with_timeout(&self, _timeout: std::time::Duration) -> opentelemetry_sdk::error::OTelSdkResult {
148        Ok(())
149    }
150}
151
152/// Configuration for [`setup_tracer`] (`TracerConfig`).
153#[derive(Debug, Clone, Default, bon::Builder)]
154pub struct TracerConfig {
155    /// A provider the caller built; it is registered as is, and `exporters` and
156    /// `baggage_processor` are ignored. Defaults to one with the [`exporters`](Self::exporters).
157    pub provider: Option<SdkTracerProvider>,
158    /// The exporters of the provider the SDK builds.
159    #[builder(default)]
160    pub exporters: TelemetryExporters,
161    /// Stamps baggage entries onto spans as attributes.
162    pub baggage_processor: Option<BaggageProcessor>,
163}
164
165/// Configuration for [`setup_meter`] (`MeterConfig`).
166#[derive(Debug, Clone, Default, bon::Builder)]
167pub struct MeterConfig {
168    /// A provider the caller built; it is registered as is and `exporters` is ignored.
169    pub provider: Option<SdkMeterProvider>,
170    /// The exporters (periodic readers) of the provider the SDK builds.
171    #[builder(default)]
172    pub exporters: TelemetryExporters,
173}
174
175/// The tracer provider [`setup_tracer`] registered. Dropping the guard flushes the provider;
176/// [`shutdown`](Self::shutdown) flushes and stops it.
177///
178/// Every call of [`setup_tracer`] returns a guard; the guards of repeat calls share the first
179/// call's provider. Shutting any of them down stops that provider for all and clears the
180/// registration, so the next [`setup_tracer`] builds and registers a new one.
181#[must_use = "dropping the guard flushes the provider; keep it for the life of the program"]
182pub struct TracerGuard {
183    provider: SdkTracerProvider,
184    stopped: bool,
185    slot: &'static ProviderSlot<SdkTracerProvider>,
186    registration: u64,
187}
188
189impl fmt::Debug for TracerGuard {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        f.debug_struct("TracerGuard")
192            .field("provider", &self.provider)
193            .field("stopped", &self.stopped)
194            .finish_non_exhaustive()
195    }
196}
197
198impl TracerGuard {
199    /// The registered provider.
200    #[must_use]
201    pub fn provider(&self) -> &SdkTracerProvider {
202        &self.provider
203    }
204
205    /// The `tracing` layer that exports the agent's spans through the provider. Add it to the
206    /// application's subscriber, or let [`try_init_subscriber`](Self::try_init_subscriber) do it.
207    ///
208    /// The layer does not export the code location, target, thread or busy/idle time attributes
209    /// `tracing-opentelemetry` adds by default, so spans carry the SDK's attributes only. The SDK's
210    /// spans are `INFO` spans with target `strands::telemetry`: a filter in front of the layer
211    /// (an `EnvFilter` on the registry, for example) must let them through, or the layer exports
212    /// nothing. Give the layer its own filter instead to keep other layers quieter:
213    ///
214    /// ```no_run
215    /// use strands::telemetry::tracing_subscriber::filter::LevelFilter;
216    /// use strands::telemetry::tracing_subscriber::layer::{Layer, SubscriberExt};
217    /// use strands::telemetry::tracing_subscriber::util::SubscriberInitExt;
218    /// use strands::telemetry::{TelemetryExporters, TracerConfig, setup_tracer};
219    ///
220    /// let telemetry = setup_tracer(TracerConfig {
221    ///     exporters: TelemetryExporters { otlp: true, console: false },
222    ///     ..Default::default()
223    /// })?;
224    /// strands::telemetry::tracing_subscriber::registry()
225    ///     .with(telemetry.layer())
226    ///     .with(strands::telemetry::tracing_subscriber::fmt::layer().with_filter(LevelFilter::WARN))
227    ///     .init();
228    /// # Ok::<(), strands::Error>(())
229    /// ```
230    #[must_use]
231    pub fn layer<S>(&self) -> OpenTelemetryLayer<S, SdkTracer>
232    where
233        S: tracing::Subscriber + for<'span> LookupSpan<'span>,
234    {
235        otel_layer(self.provider.tracer(service_name()))
236    }
237
238    /// Installs a global subscriber with only [`layer`](Self::layer), for programs that have no
239    /// subscriber of their own; any other layers belong on a registry the program builds.
240    ///
241    /// ```no_run
242    /// use strands::telemetry::{TelemetryExporters, TracerConfig, setup_tracer};
243    ///
244    /// let telemetry = setup_tracer(TracerConfig {
245    ///     exporters: TelemetryExporters { otlp: true, console: false },
246    ///     ..Default::default()
247    /// })?;
248    /// telemetry.try_init_subscriber()?;
249    /// # Ok::<(), strands::Error>(())
250    /// ```
251    ///
252    /// # Errors
253    ///
254    /// A global subscriber is already set.
255    pub fn try_init_subscriber(&self) -> Result<()> {
256        tracing_subscriber::registry()
257            .with(self.layer())
258            .try_init()
259            .map_err(Error::other)
260    }
261
262    /// Flushes and stops the provider, and clears its registration.
263    ///
264    /// # Errors
265    ///
266    /// The provider failed to export what it held or was already stopped.
267    pub fn shutdown(mut self) -> Result<()> {
268        self.stopped = true;
269        release(self.slot, self.registration);
270        self.provider.shutdown().map_err(Error::other)
271    }
272}
273
274impl Drop for TracerGuard {
275    fn drop(&mut self) {
276        if self.stopped {
277            return;
278        }
279        if let Err(error) = self.provider.force_flush() {
280            tracing::warn!("error=<{error}> | failed to flush tracer provider on exit");
281        }
282    }
283}
284
285/// The meter provider [`setup_meter`] registered. Dropping the guard flushes the provider;
286/// [`shutdown`](Self::shutdown) flushes and stops it.
287///
288/// Every call of [`setup_meter`] returns a guard; the guards of repeat calls share the first
289/// call's provider. Shutting any of them down stops that provider for all and clears the
290/// registration, so the next [`setup_meter`] builds and registers a new one.
291#[must_use = "dropping the guard flushes the provider; keep it for the life of the program"]
292pub struct MeterGuard {
293    provider: SdkMeterProvider,
294    stopped: bool,
295    slot: &'static ProviderSlot<SdkMeterProvider>,
296    registration: u64,
297}
298
299impl fmt::Debug for MeterGuard {
300    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301        f.debug_struct("MeterGuard")
302            .field("provider", &self.provider)
303            .field("stopped", &self.stopped)
304            .finish_non_exhaustive()
305    }
306}
307
308impl MeterGuard {
309    /// The registered provider.
310    #[must_use]
311    pub fn provider(&self) -> &SdkMeterProvider {
312        &self.provider
313    }
314
315    /// Flushes and stops the provider, and clears its registration.
316    ///
317    /// # Errors
318    ///
319    /// The provider failed to export what it held or was already stopped.
320    pub fn shutdown(mut self) -> Result<()> {
321        self.stopped = true;
322        release(self.slot, self.registration);
323        self.provider.shutdown().map_err(Error::other)
324    }
325}
326
327impl Drop for MeterGuard {
328    fn drop(&mut self) {
329        if self.stopped {
330            return;
331        }
332        if let Err(error) = self.provider.force_flush() {
333            tracing::warn!("error=<{error}> | failed to flush meter provider on exit");
334        }
335    }
336}
337
338/// The layer the SDK's spans export through: without the location, target, thread and timing
339/// attributes `tracing-opentelemetry` adds by default, so spans carry the SDK's attributes only.
340pub(crate) fn otel_layer<S>(tracer: SdkTracer) -> OpenTelemetryLayer<S, SdkTracer>
341where
342    S: tracing::Subscriber + for<'span> LookupSpan<'span>,
343{
344    tracing_opentelemetry::layer()
345        .with_tracer(tracer)
346        .with_location(false)
347        .with_target(false)
348        .with_threads(false)
349        .with_tracked_inactivity(false)
350}
351
352/// A tracer from the global provider, scoped to the service name, for custom spans.
353#[must_use]
354pub fn get_tracer() -> global::BoxedTracer {
355    global::tracer(service_name())
356}
357
358/// A meter from the global provider, scoped to the service name, for custom metrics; a no-op
359/// until a provider is registered.
360#[must_use]
361pub fn get_meter() -> opentelemetry::metrics::Meter {
362    service_meter()
363}
364
365/// Sets up and registers the global tracer provider.
366///
367/// Without a custom provider this builds one with the configured exporters and the service
368/// resource, and registers the W3C trace context and baggage propagators. A second call logs a
369/// warning and returns a guard for the provider already registered; once a guard has been
370/// [shut down](TracerGuard::shutdown), the next call registers a new provider.
371///
372/// # Errors
373///
374/// The OTLP exporter could not be built from the environment.
375pub fn setup_tracer(config: TracerConfig) -> Result<TracerGuard> {
376    let installed = install_tracer(&TRACER_PROVIDER, config, &process_env)?;
377    if installed.registered {
378        global::set_tracer_provider(installed.provider.clone());
379    }
380    if installed.registered && !installed.custom {
381        global::set_text_map_propagator(TextMapCompositePropagator::new(vec![
382            Box::new(TraceContextPropagator::new()),
383            Box::new(BaggagePropagator::new()),
384        ]));
385    }
386    Ok(TracerGuard::new(installed, &TRACER_PROVIDER))
387}
388
389impl TracerGuard {
390    pub(crate) fn new(installed: InstalledTracer, slot: &'static ProviderSlot<SdkTracerProvider>) -> Self {
391        Self {
392            provider: installed.provider,
393            stopped: false,
394            slot,
395            registration: installed.registration,
396        }
397    }
398}
399
400/// Sets up and registers the global meter provider. A second call logs a warning
401/// and returns a guard for the provider already registered; once a guard has been
402/// [shut down](MeterGuard::shutdown), the next call registers a new provider.
403///
404/// # Errors
405///
406/// The OTLP exporter could not be built from the environment.
407pub fn setup_meter(config: MeterConfig) -> Result<MeterGuard> {
408    let installed = install_meter(&METER_PROVIDER, config, &process_env)?;
409    if installed.registered {
410        global::set_meter_provider(installed.provider.clone());
411    }
412    Ok(MeterGuard::new(installed, &METER_PROVIDER))
413}
414
415impl MeterGuard {
416    pub(crate) fn new(installed: InstalledMeter, slot: &'static ProviderSlot<SdkMeterProvider>) -> Self {
417        Self {
418            provider: installed.provider,
419            stopped: false,
420            slot,
421            registration: installed.registration,
422        }
423    }
424}
425
426pub(crate) struct InstalledTracer {
427    pub(crate) provider: SdkTracerProvider,
428    /// The provider is new, not the one an earlier call registered.
429    pub(crate) registered: bool,
430    pub(crate) custom: bool,
431    pub(crate) registration: u64,
432}
433
434pub(crate) struct InstalledMeter {
435    pub(crate) provider: SdkMeterProvider,
436    /// The provider is new, not the one an earlier call registered.
437    pub(crate) registered: bool,
438    pub(crate) registration: u64,
439}
440
441pub(crate) fn install_tracer(
442    slot: &ProviderSlot<SdkTracerProvider>,
443    config: TracerConfig,
444    env: EnvLookup<'_>,
445) -> Result<InstalledTracer> {
446    let mut slot = slot.lock().unwrap_or_else(PoisonError::into_inner);
447    if let Some(existing) = slot.as_ref() {
448        tracing::warn!("tracer provider already initialized, returning existing provider");
449        return Ok(InstalledTracer {
450            provider: existing.provider.clone(),
451            registered: false,
452            custom: false,
453            registration: existing.id,
454        });
455    }
456    let custom = config.provider.is_some();
457    let provider = match config.provider {
458        Some(provider) => {
459            if config.baggage_processor.is_some() {
460                tracing::warn!(
461                    "baggage_processor=<ignored> | custom provider is owned by the caller, add BaggageSpanProcessor to it"
462                );
463            }
464            provider
465        }
466        None => build_tracer_provider(config.exporters, config.baggage_processor, env)?,
467    };
468    let registration = register(&mut slot, &provider);
469    Ok(InstalledTracer {
470        provider,
471        registered: true,
472        custom,
473        registration,
474    })
475}
476
477pub(crate) fn install_meter(
478    slot: &ProviderSlot<SdkMeterProvider>,
479    config: MeterConfig,
480    env: EnvLookup<'_>,
481) -> Result<InstalledMeter> {
482    let mut slot = slot.lock().unwrap_or_else(PoisonError::into_inner);
483    if let Some(existing) = slot.as_ref() {
484        tracing::warn!("meter provider already initialized, returning existing provider");
485        return Ok(InstalledMeter {
486            provider: existing.provider.clone(),
487            registered: false,
488            registration: existing.id,
489        });
490    }
491    let provider = match config.provider {
492        Some(provider) => provider,
493        None => build_meter_provider(config.exporters, env)?,
494    };
495    let registration = register(&mut slot, &provider);
496    Ok(InstalledMeter {
497        provider,
498        registered: true,
499        registration,
500    })
501}
502
503/// The span exporters a configuration asks for, OTLP first.
504#[derive(Debug, Clone, Copy, PartialEq, Eq)]
505pub(crate) enum ExporterKind {
506    Otlp,
507    Console,
508}
509
510pub(crate) fn exporter_kinds(exporters: TelemetryExporters) -> Vec<ExporterKind> {
511    let mut kinds = Vec::new();
512    if exporters.otlp {
513        kinds.push(ExporterKind::Otlp);
514    }
515    if exporters.console {
516        kinds.push(ExporterKind::Console);
517    }
518    kinds
519}
520
521fn build_tracer_provider(
522    exporters: TelemetryExporters,
523    baggage_processor: Option<BaggageProcessor>,
524    env: EnvLookup<'_>,
525) -> Result<SdkTracerProvider> {
526    let mut builder = SdkTracerProvider::builder().with_resource(otel_resource(env));
527    if let Some(keys) = baggage_processor {
528        tracing::info!("enabling baggage span processor");
529        builder = builder.with_span_processor(BaggageSpanProcessor::new(keys));
530    }
531    for kind in exporter_kinds(exporters) {
532        builder = match kind {
533            ExporterKind::Otlp => builder.with_batch_exporter(
534                opentelemetry_otlp::SpanExporter::builder()
535                    .with_http()
536                    .build()
537                    .map_err(Error::other)?,
538            ),
539            ExporterKind::Console => builder.with_simple_exporter(opentelemetry_stdout::SpanExporter::default()),
540        };
541    }
542    Ok(builder.build())
543}
544
545fn build_meter_provider(exporters: TelemetryExporters, env: EnvLookup<'_>) -> Result<SdkMeterProvider> {
546    let mut builder = SdkMeterProvider::builder().with_resource(otel_resource(env));
547    for kind in exporter_kinds(exporters) {
548        builder = match kind {
549            ExporterKind::Otlp => builder.with_periodic_exporter(
550                opentelemetry_otlp::MetricExporter::builder()
551                    .with_http()
552                    .build()
553                    .map_err(Error::other)?,
554            ),
555            ExporterKind::Console => builder.with_periodic_exporter(opentelemetry_stdout::MetricExporter::default()),
556        };
557    }
558    Ok(builder.build())
559}
560
561/// The service resource: the SDK defaults, then `OTEL_RESOURCE_ATTRIBUTES`
562/// and `OTEL_SERVICE_NAME` over them.
563pub(crate) fn otel_resource(env: EnvLookup<'_>) -> Resource {
564    let namespace = env("OTEL_SERVICE_NAMESPACE")
565        .filter(|value| !value.is_empty())
566        .unwrap_or_else(|| DEFAULT_SERVICE_NAMESPACE.to_owned());
567    let environment = env("OTEL_DEPLOYMENT_ENVIRONMENT")
568        .filter(|value| !value.is_empty())
569        .unwrap_or_else(|| DEFAULT_DEPLOYMENT_ENVIRONMENT.to_owned());
570    Resource::builder_empty()
571        .with_detector(Box::new(TelemetryResourceDetector))
572        .with_attributes([
573            KeyValue::new("service.name", service_name_from(env)),
574            KeyValue::new("service.namespace", namespace),
575            KeyValue::new("deployment.environment", environment),
576            KeyValue::new("telemetry.sdk.name", "opentelemetry"),
577            KeyValue::new("telemetry.sdk.language", "rust"),
578        ])
579        .with_attributes(env_resource_attributes(env))
580        .build()
581}
582
583/// `OTEL_RESOURCE_ATTRIBUTES` (`key=value` pairs, comma separated, percent-encoded) and
584/// `OTEL_SERVICE_NAME`, as the OpenTelemetry environment detector reads them.
585fn env_resource_attributes(env: EnvLookup<'_>) -> Vec<KeyValue> {
586    let mut attributes: Vec<KeyValue> = env("OTEL_RESOURCE_ATTRIBUTES")
587        .unwrap_or_default()
588        .split(',')
589        .filter_map(|pair| {
590            let (key, value) = pair.split_once('=')?;
591            let key = key.trim();
592            (!key.is_empty()).then(|| KeyValue::new(percent_decode(key), percent_decode(value.trim())))
593        })
594        .collect();
595    if let Some(name) = env("OTEL_SERVICE_NAME").filter(|name| !name.is_empty()) {
596        attributes.push(KeyValue::new("service.name", name));
597    }
598    attributes
599}
600
601fn percent_decode(text: &str) -> String {
602    let bytes = text.as_bytes();
603    let mut decoded = Vec::with_capacity(bytes.len());
604    let mut index = 0;
605    while index < bytes.len() {
606        let escaped = (bytes[index] == b'%')
607            .then(|| text.get(index + 1..index + 3))
608            .flatten()
609            .and_then(|hex| u8::from_str_radix(hex, 16).ok());
610        match escaped {
611            Some(byte) => {
612                decoded.push(byte);
613                index += 3;
614            }
615            None => {
616                decoded.push(bytes[index]);
617                index += 1;
618            }
619        }
620    }
621    String::from_utf8_lossy(&decoded).into_owned()
622}