opentelemetry/global/
propagation.rs

1use crate::propagation::TextMapPropagator;
2use crate::trace::noop::NoopTextMapPropagator;
3use once_cell::sync::Lazy;
4use std::sync::RwLock;
5
6/// The current global `TextMapPropagator` propagator.
7static GLOBAL_TEXT_MAP_PROPAGATOR: Lazy<RwLock<Box<dyn TextMapPropagator + Send + Sync>>> =
8    Lazy::new(|| RwLock::new(Box::new(NoopTextMapPropagator::new())));
9
10/// The global default `TextMapPropagator` propagator.
11static DEFAULT_TEXT_MAP_PROPAGATOR: Lazy<NoopTextMapPropagator> =
12    Lazy::new(NoopTextMapPropagator::new);
13
14/// Sets the given [`TextMapPropagator`] propagator as the current global propagator.
15pub fn set_text_map_propagator<P: TextMapPropagator + Send + Sync + 'static>(propagator: P) {
16    let _lock = GLOBAL_TEXT_MAP_PROPAGATOR
17        .write()
18        .map(|mut global_propagator| *global_propagator = Box::new(propagator));
19}
20
21/// Executes a closure with a reference to the current global [`TextMapPropagator`] propagator.
22pub fn get_text_map_propagator<T, F>(mut f: F) -> T
23where
24    F: FnMut(&dyn TextMapPropagator) -> T,
25{
26    GLOBAL_TEXT_MAP_PROPAGATOR
27        .read()
28        .map(|propagator| f(&**propagator))
29        .unwrap_or_else(|_| f(&*DEFAULT_TEXT_MAP_PROPAGATOR as &dyn TextMapPropagator))
30}