opentelemetry/global/
propagation.rs

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