wasmcloud_tracing/
http.rs

1use opentelemetry::propagation::{Extractor, Injector, TextMapPropagator};
2use opentelemetry_sdk::propagation::TraceContextPropagator;
3use tracing::span::Span;
4use tracing_opentelemetry::OpenTelemetrySpanExt;
5
6/// Helper for injecting headers into HTTP Requests. This is used for OpenTelemetry context
7/// propagation over HTTP.
8/// See [this](https://github.com/open-telemetry/opentelemetry-rust/blob/main/examples/tracing-http-propagator/README.md)
9/// for example usage.
10pub struct HeaderInjector<'a>(pub &'a mut http::HeaderMap);
11
12impl Injector for HeaderInjector<'_> {
13    /// Set a key and value in the HeaderMap.  Does nothing if the key or value are not valid inputs.
14    fn set(&mut self, key: &str, value: String) {
15        if let Ok(name) = http::header::HeaderName::from_bytes(key.as_bytes()) {
16            if let Ok(val) = http::header::HeaderValue::from_str(&value) {
17                self.0.insert(name, val);
18            }
19        }
20    }
21}
22
23impl HeaderInjector<'_> {
24    /// Injects the context from the current span into the headers
25    pub fn inject_context(&mut self) {
26        let ctx_propagator = TraceContextPropagator::new();
27        ctx_propagator.inject_context(&Span::current().context(), self);
28    }
29}
30
31/// Helper for extracting headers from HTTP Requests. This is used for OpenTelemetry context
32/// propagation over HTTP.
33/// See [this](https://github.com/open-telemetry/opentelemetry-rust/blob/main/examples/tracing-http-propagator/README.md)
34/// for example usage.
35pub struct HeaderExtractor<'a>(pub &'a http::HeaderMap);
36
37impl Extractor for HeaderExtractor<'_> {
38    /// Get a value for a key from the HeaderMap.  If the value is not valid ASCII, returns None.
39    fn get(&self, key: &str) -> Option<&str> {
40        self.0.get(key).and_then(|value| value.to_str().ok())
41    }
42
43    /// Collect all the keys from the HeaderMap.
44    fn keys(&self) -> Vec<&str> {
45        self.0
46            .keys()
47            .map(|value| value.as_str())
48            .collect::<Vec<_>>()
49    }
50}