fastrace_reqwest/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use fastrace::prelude::*;
4use reqwest::header::HeaderMap;
5use reqwest::header::HeaderName;
6use reqwest::header::HeaderValue;
7
8/// The standard [W3C Trace Context](https://www.w3.org/TR/trace-context/) header name for passing trace information.
9///
10/// This is the header key used to propagate trace context between services according to
11/// the W3C Trace Context specification.
12pub const TRACEPARENT_HEADER: &str = "traceparent";
13
14/// Creates a [`HeaderMap`] containing trace context headers from the current span context.
15///
16/// This function extracts the current span context from the local thread and formats it
17/// according to the W3C Trace Context specification as a `traceparent` header.
18///
19/// # Returns
20///
21/// * If a local parent span exists: A `HeaderMap` containing the traceparent header with the
22///   encoded span context
23/// * If no local parent span exists: An empty `HeaderMap`
24///
25/// # Example
26///
27/// ```
28/// use fastrace::prelude::*;
29/// use fastrace_reqwest::traceparent_headers;
30/// use reqwest::Client;
31///
32/// #[fastrace::trace]
33/// async fn send_request() {
34///     let client = Client::new();
35///     let response = client
36///         .get("https://example.com")
37///         .headers(traceparent_headers())
38///         .send()
39///         .await
40///         .unwrap();
41/// }
42/// ```
43pub fn traceparent_headers() -> HeaderMap {
44    if let Some(parent) = SpanContext::current_local_parent() {
45        let key = HeaderName::from_static(TRACEPARENT_HEADER);
46        let value = HeaderValue::from_str(&parent.encode_w3c_traceparent()).unwrap();
47        [(key, value)].into_iter().collect()
48    } else {
49        HeaderMap::new()
50    }
51}