1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
use reqwest::header::{HeaderName, HeaderValue};
use reqwest::Request;
use std::str::FromStr;
use tracing::Span;

/// Injects the given OpenTelemetry Context into a reqwest::Request headers to allow propagation downstream.
pub fn inject_opentelemetry_context_into_request(mut request: Request) -> Request {
    #[cfg(feature = "opentelemetry_0_20")]
    opentelemetry_0_20_pkg::global::get_text_map_propagator(|injector| {
        use tracing_opentelemetry_0_21_pkg::OpenTelemetrySpanExt;
        let context = Span::current().context();
        injector.inject_context(&context, &mut RequestCarrier::new(&mut request))
    });

    #[cfg(feature = "opentelemetry_0_21")]
    opentelemetry_0_21_pkg::global::get_text_map_propagator(|injector| {
        use tracing_opentelemetry_0_22_pkg::OpenTelemetrySpanExt;
        let context = Span::current().context();
        injector.inject_context(&context, &mut RequestCarrier::new(&mut request))
    });

    #[cfg(feature = "opentelemetry_0_22")]
    opentelemetry_0_22_pkg::global::get_text_map_propagator(|injector| {
        use tracing_opentelemetry_0_23_pkg::OpenTelemetrySpanExt;
        let context = Span::current().context();
        injector.inject_context(&context, &mut RequestCarrier::new(&mut request))
    });

    #[cfg(feature = "opentelemetry_0_23")]
    opentelemetry_0_23_pkg::global::get_text_map_propagator(|injector| {
        use tracing_opentelemetry_0_24_pkg::OpenTelemetrySpanExt;
        let context = Span::current().context();
        injector.inject_context(&context, &mut RequestCarrier::new(&mut request))
    });

    #[cfg(feature = "opentelemetry_0_24")]
    opentelemetry_0_24_pkg::global::get_text_map_propagator(|injector| {
        use tracing_opentelemetry_0_25_pkg::OpenTelemetrySpanExt;
        let context = Span::current().context();
        injector.inject_context(&context, &mut RequestCarrier::new(&mut request))
    });

    #[cfg(feature = "opentelemetry_0_25")]
    opentelemetry_0_25_pkg::global::get_text_map_propagator(|injector| {
        use tracing_opentelemetry_0_26_pkg::OpenTelemetrySpanExt;
        let context = Span::current().context();
        injector.inject_context(&context, &mut RequestCarrier::new(&mut request))
    });

    #[cfg(feature = "opentelemetry_0_26")]
    opentelemetry_0_26_pkg::global::get_text_map_propagator(|injector| {
        use tracing_opentelemetry_0_27_pkg::OpenTelemetrySpanExt;
        let context = Span::current().context();
        injector.inject_context(&context, &mut RequestCarrier::new(&mut request))
    });

    #[cfg(feature = "opentelemetry_0_27")]
    opentelemetry_0_27_pkg::global::get_text_map_propagator(|injector| {
        use tracing_opentelemetry_0_28_pkg::OpenTelemetrySpanExt;
        let context = Span::current().context();
        injector.inject_context(&context, &mut RequestCarrier::new(&mut request))
    });

    request
}

// "traceparent" => https://www.w3.org/TR/trace-context/#trace-context-http-headers-format

/// Injector used via opentelemetry propagator to tell the extractor how to insert the "traceparent" header value
/// This will allow the propagator to inject opentelemetry context into a standard data structure. Will basically
/// insert a "traceparent" string value "{version}-{trace_id}-{span_id}-{trace-flags}" of the spans context into the headers.
/// Listeners can then re-hydrate the context to add additional spans to the same trace.
struct RequestCarrier<'a> {
    request: &'a mut Request,
}

impl<'a> RequestCarrier<'a> {
    pub fn new(request: &'a mut Request) -> Self {
        RequestCarrier { request }
    }
}

impl<'a> RequestCarrier<'a> {
    fn set_inner(&mut self, key: &str, value: String) {
        let header_name = HeaderName::from_str(key).expect("Must be header name");
        let header_value = HeaderValue::from_str(&value).expect("Must be a header value");
        self.request.headers_mut().insert(header_name, header_value);
    }
}

#[cfg(feature = "opentelemetry_0_20")]
impl<'a> opentelemetry_0_20_pkg::propagation::Injector for RequestCarrier<'a> {
    fn set(&mut self, key: &str, value: String) {
        self.set_inner(key, value)
    }
}

#[cfg(feature = "opentelemetry_0_21")]
impl<'a> opentelemetry_0_21_pkg::propagation::Injector for RequestCarrier<'a> {
    fn set(&mut self, key: &str, value: String) {
        self.set_inner(key, value)
    }
}

#[cfg(feature = "opentelemetry_0_22")]
impl<'a> opentelemetry_0_22_pkg::propagation::Injector for RequestCarrier<'a> {
    fn set(&mut self, key: &str, value: String) {
        self.set_inner(key, value)
    }
}

#[cfg(feature = "opentelemetry_0_23")]
impl<'a> opentelemetry_0_23_pkg::propagation::Injector for RequestCarrier<'a> {
    fn set(&mut self, key: &str, value: String) {
        self.set_inner(key, value)
    }
}

#[cfg(feature = "opentelemetry_0_24")]
impl<'a> opentelemetry_0_24_pkg::propagation::Injector for RequestCarrier<'a> {
    fn set(&mut self, key: &str, value: String) {
        self.set_inner(key, value)
    }
}

#[cfg(feature = "opentelemetry_0_25")]
impl<'a> opentelemetry_0_25_pkg::propagation::Injector for RequestCarrier<'a> {
    fn set(&mut self, key: &str, value: String) {
        self.set_inner(key, value)
    }
}

#[cfg(feature = "opentelemetry_0_26")]
impl<'a> opentelemetry_0_26_pkg::propagation::Injector for RequestCarrier<'a> {
    fn set(&mut self, key: &str, value: String) {
        self.set_inner(key, value)
    }
}

#[cfg(feature = "opentelemetry_0_27")]
impl<'a> opentelemetry_0_27_pkg::propagation::Injector for RequestCarrier<'a> {
    fn set(&mut self, key: &str, value: String) {
        self.set_inner(key, value)
    }
}

#[cfg(test)]
mod test {
    use std::sync::OnceLock;

    use crate::{DisableOtelPropagation, TracingMiddleware};
    use reqwest::Response;
    use reqwest_middleware::{ClientBuilder, ClientWithMiddleware, Extension};
    use tracing::{info_span, Instrument, Level};

    use tracing_subscriber::{filter, layer::SubscriberExt, Registry};
    use wiremock::{matchers::any, Mock, MockServer, ResponseTemplate};

    async fn make_echo_request_in_otel_context(client: ClientWithMiddleware) -> Response {
        static TELEMETRY: OnceLock<()> = OnceLock::new();

        TELEMETRY.get_or_init(|| {
            let subscriber = Registry::default().with(
                filter::Targets::new().with_target("reqwest_tracing::otel::test", Level::DEBUG),
            );

            #[cfg(feature = "opentelemetry_0_20")]
            let subscriber = {
                use opentelemetry_0_20_pkg::trace::TracerProvider;
                use opentelemetry_stdout_0_1::SpanExporterBuilder;

                let exporter = SpanExporterBuilder::default()
                    .with_writer(std::io::sink())
                    .build();

                let provider = opentelemetry_0_20_pkg::sdk::trace::TracerProvider::builder()
                    .with_simple_exporter(exporter)
                    .build();

                let tracer = provider.versioned_tracer("reqwest", None::<&str>, None::<&str>, None);
                let _ = opentelemetry_0_20_pkg::global::set_tracer_provider(provider);
                opentelemetry_0_20_pkg::global::set_text_map_propagator(
                    opentelemetry_0_20_pkg::sdk::propagation::TraceContextPropagator::new(),
                );

                let telemetry = tracing_opentelemetry_0_21_pkg::layer().with_tracer(tracer);
                subscriber.with(telemetry)
            };

            #[cfg(feature = "opentelemetry_0_21")]
            let subscriber = {
                use opentelemetry_0_21_pkg::trace::TracerProvider;
                use opentelemetry_stdout_0_2::SpanExporterBuilder;

                let exporter = SpanExporterBuilder::default()
                    .with_writer(std::io::sink())
                    .build();

                let provider = opentelemetry_sdk_0_21::trace::TracerProvider::builder()
                    .with_simple_exporter(exporter)
                    .build();

                let tracer = provider.versioned_tracer("reqwest", None::<&str>, None::<&str>, None);
                let _ = opentelemetry_0_21_pkg::global::set_tracer_provider(provider);
                opentelemetry_0_21_pkg::global::set_text_map_propagator(
                    opentelemetry_sdk_0_21::propagation::TraceContextPropagator::new(),
                );

                let telemetry = tracing_opentelemetry_0_22_pkg::layer().with_tracer(tracer);
                subscriber.with(telemetry)
            };

            #[cfg(feature = "opentelemetry_0_22")]
            let subscriber = {
                use opentelemetry_0_22_pkg::trace::TracerProvider;
                use opentelemetry_stdout_0_3::SpanExporterBuilder;

                let exporter = SpanExporterBuilder::default()
                    .with_writer(std::io::sink())
                    .build();

                let provider = opentelemetry_sdk_0_22::trace::TracerProvider::builder()
                    .with_simple_exporter(exporter)
                    .build();

                let tracer = provider.versioned_tracer("reqwest", None::<&str>, None::<&str>, None);
                let _ = opentelemetry_0_22_pkg::global::set_tracer_provider(provider);
                opentelemetry_0_22_pkg::global::set_text_map_propagator(
                    opentelemetry_sdk_0_22::propagation::TraceContextPropagator::new(),
                );

                let telemetry = tracing_opentelemetry_0_23_pkg::layer().with_tracer(tracer);
                subscriber.with(telemetry)
            };

            #[cfg(feature = "opentelemetry_0_23")]
            let subscriber = {
                use opentelemetry_0_23_pkg::trace::TracerProvider;
                use opentelemetry_stdout_0_4::SpanExporterBuilder;

                let exporter = SpanExporterBuilder::default()
                    .with_writer(std::io::sink())
                    .build();

                let provider = opentelemetry_sdk_0_23::trace::TracerProvider::builder()
                    .with_simple_exporter(exporter)
                    .build();

                let tracer = provider.tracer_builder("reqwest").build();
                let _ = opentelemetry_0_23_pkg::global::set_tracer_provider(provider);
                opentelemetry_0_23_pkg::global::set_text_map_propagator(
                    opentelemetry_sdk_0_23::propagation::TraceContextPropagator::new(),
                );

                let telemetry = tracing_opentelemetry_0_24_pkg::layer().with_tracer(tracer);
                subscriber.with(telemetry)
            };

            #[cfg(feature = "opentelemetry_0_24")]
            let subscriber = {
                use opentelemetry_0_24_pkg::trace::TracerProvider;
                use opentelemetry_stdout_0_5::SpanExporterBuilder;

                let exporter = SpanExporterBuilder::default()
                    .with_writer(std::io::sink())
                    .build();

                let provider = opentelemetry_sdk_0_24::trace::TracerProvider::builder()
                    .with_simple_exporter(exporter)
                    .build();

                let tracer = provider.tracer_builder("reqwest").build();
                let _ = opentelemetry_0_24_pkg::global::set_tracer_provider(provider);
                opentelemetry_0_24_pkg::global::set_text_map_propagator(
                    opentelemetry_sdk_0_24::propagation::TraceContextPropagator::new(),
                );

                let telemetry = tracing_opentelemetry_0_25_pkg::layer().with_tracer(tracer);
                subscriber.with(telemetry)
            };

            #[cfg(feature = "opentelemetry_0_25")]
            let subscriber = {
                use opentelemetry_0_25_pkg::trace::TracerProvider;

                let provider = opentelemetry_sdk_0_25::trace::TracerProvider::builder().build();

                let tracer = provider.tracer_builder("reqwest").build();
                let _ = opentelemetry_0_25_pkg::global::set_tracer_provider(provider);
                opentelemetry_0_25_pkg::global::set_text_map_propagator(
                    opentelemetry_sdk_0_25::propagation::TraceContextPropagator::new(),
                );

                let telemetry = tracing_opentelemetry_0_26_pkg::layer().with_tracer(tracer);
                subscriber.with(telemetry)
            };

            #[cfg(feature = "opentelemetry_0_26")]
            let subscriber = {
                use opentelemetry_0_26_pkg::trace::TracerProvider;

                let provider = opentelemetry_sdk_0_26::trace::TracerProvider::builder().build();

                let tracer = provider.tracer_builder("reqwest").build();
                let _ = opentelemetry_0_26_pkg::global::set_tracer_provider(provider);
                opentelemetry_0_26_pkg::global::set_text_map_propagator(
                    opentelemetry_sdk_0_26::propagation::TraceContextPropagator::new(),
                );

                let telemetry = tracing_opentelemetry_0_27_pkg::layer().with_tracer(tracer);
                subscriber.with(telemetry)
            };

            #[cfg(feature = "opentelemetry_0_27")]
            let subscriber = {
                use opentelemetry_0_27_pkg::trace::TracerProvider;

                let provider = opentelemetry_sdk_0_27::trace::TracerProvider::builder().build();

                let tracer = provider.tracer("reqwest");
                let _ = opentelemetry_0_27_pkg::global::set_tracer_provider(provider);
                opentelemetry_0_27_pkg::global::set_text_map_propagator(
                    opentelemetry_sdk_0_27::propagation::TraceContextPropagator::new(),
                );

                let telemetry = tracing_opentelemetry_0_28_pkg::layer().with_tracer(tracer);
                subscriber.with(telemetry)
            };

            tracing::subscriber::set_global_default(subscriber).unwrap();
        });

        // Mock server - sends all request headers back in the response
        let server = MockServer::start().await;
        Mock::given(any())
            .respond_with(|req: &wiremock::Request| {
                req.headers
                    .iter()
                    .fold(ResponseTemplate::new(200), |resp, (k, v)| {
                        resp.append_header(k.clone(), v.clone())
                    })
            })
            .mount(&server)
            .await;

        client
            .get(server.uri())
            .send()
            .instrument(info_span!("some_span"))
            .await
            .unwrap()
    }

    #[tokio::test]
    async fn tracing_middleware_propagates_otel_data_even_when_the_span_is_disabled() {
        let client = ClientBuilder::new(reqwest::Client::new())
            .with(TracingMiddleware::default())
            .build();

        let resp = make_echo_request_in_otel_context(client).await;

        assert!(
            resp.headers().contains_key("traceparent"),
            "by default, the tracing middleware will propagate otel contexts"
        );
    }

    #[tokio::test]
    async fn context_no_propagated() {
        let client = ClientBuilder::new(reqwest::Client::new())
            .with_init(Extension(DisableOtelPropagation))
            .with(TracingMiddleware::default())
            .build();

        let resp = make_echo_request_in_otel_context(client).await;

        assert!(
            !resp.headers().contains_key("traceparent"),
            "request should not contain traceparent if context propagation is disabled"
        );
    }
}