|
6 | 6 | use std::collections::BTreeMap; |
7 | 7 |
|
8 | 8 | use http::HeaderMap; |
| 9 | +use opentelemetry::Context; |
9 | 10 | use opentelemetry::propagation::{Extractor, Injector, TextMapPropagator}; |
10 | 11 | use opentelemetry_sdk::propagation::TraceContextPropagator; |
11 | 12 | use tracing_opentelemetry::OpenTelemetrySpanExt as _; |
@@ -177,9 +178,108 @@ impl tonic::service::Interceptor for TraceContextInterceptor { |
177 | 178 | } |
178 | 179 | } |
179 | 180 |
|
| 181 | +/// Reads W3C trace-context propagation fields from process environment |
| 182 | +/// variables (`TRACEPARENT` and `TRACESTATE`). |
| 183 | +/// |
| 184 | +/// CI systems (GitHub Actions, GitLab CI, Jenkins OpenTelemetry plugins) |
| 185 | +/// export these variables to propagate the pipeline trace to child processes. |
| 186 | +/// Both upper-case and lower-case spellings are accepted; blank values are |
| 187 | +/// treated as unset. |
| 188 | +#[derive(Debug, Clone, Default)] |
| 189 | +struct EnvTraceContext { |
| 190 | + traceparent: Option<String>, |
| 191 | + tracestate: Option<String>, |
| 192 | +} |
| 193 | + |
| 194 | +impl EnvTraceContext { |
| 195 | + fn from_env() -> Self { |
| 196 | + Self { |
| 197 | + traceparent: read_env("TRACEPARENT"), |
| 198 | + tracestate: read_env("TRACESTATE"), |
| 199 | + } |
| 200 | + } |
| 201 | +} |
| 202 | + |
| 203 | +/// Read an environment variable by its upper-case name, falling back to the |
| 204 | +/// lower-case spelling, trimming whitespace and discarding blank values. |
| 205 | +fn read_env(upper: &str) -> Option<String> { |
| 206 | + std::env::var(upper) |
| 207 | + .ok() |
| 208 | + .or_else(|| std::env::var(upper.to_ascii_lowercase()).ok()) |
| 209 | + .map(|value| value.trim().to_string()) |
| 210 | + .filter(|value| !value.is_empty()) |
| 211 | +} |
| 212 | + |
| 213 | +impl Extractor for EnvTraceContext { |
| 214 | + fn get(&self, key: &str) -> Option<&str> { |
| 215 | + match key { |
| 216 | + "traceparent" => self.traceparent.as_deref(), |
| 217 | + "tracestate" => self.tracestate.as_deref(), |
| 218 | + _ => None, |
| 219 | + } |
| 220 | + } |
| 221 | + |
| 222 | + fn keys(&self) -> Vec<&str> { |
| 223 | + let mut keys = Vec::new(); |
| 224 | + if self.traceparent.is_some() { |
| 225 | + keys.push("traceparent"); |
| 226 | + } |
| 227 | + if self.tracestate.is_some() { |
| 228 | + keys.push("tracestate"); |
| 229 | + } |
| 230 | + keys |
| 231 | + } |
| 232 | +} |
| 233 | + |
| 234 | +/// Passively forwards a W3C trace context captured from the process |
| 235 | +/// environment onto outbound tonic requests. |
| 236 | +/// |
| 237 | +/// Unlike [`TraceContextInterceptor`], this does not require an active |
| 238 | +/// OpenTelemetry span or an `SdkTracerProvider`; it reads `TRACEPARENT` |
| 239 | +/// (and optionally `TRACESTATE`) once at construction and injects them as |
| 240 | +/// gRPC metadata. This lets short-lived clients (e.g. the CLI on a CI runner) |
| 241 | +/// extend a pipeline trace to the gateway without any collector configuration. |
| 242 | +/// |
| 243 | +/// When `TRACEPARENT` is unset or invalid the captured context carries no |
| 244 | +/// valid span, so injection is a no-op. |
| 245 | +#[derive(Debug, Clone)] |
| 246 | +pub struct EnvTraceContextInterceptor { |
| 247 | + context: Context, |
| 248 | +} |
| 249 | + |
| 250 | +impl EnvTraceContextInterceptor { |
| 251 | + /// Capture the W3C trace context from the process environment. |
| 252 | + #[must_use] |
| 253 | + pub fn from_env() -> Self { |
| 254 | + Self { |
| 255 | + context: context_from(&EnvTraceContext::from_env()), |
| 256 | + } |
| 257 | + } |
| 258 | +} |
| 259 | + |
| 260 | +/// Extract a [`Context`] from an [`Extractor`] using a fresh base context, so |
| 261 | +/// the result depends only on the extractor and not on any ambient context. |
| 262 | +fn context_from(extractor: &impl Extractor) -> Context { |
| 263 | + TraceContextPropagator::new().extract_with_context(&Context::new(), extractor) |
| 264 | +} |
| 265 | + |
| 266 | +impl tonic::service::Interceptor for EnvTraceContextInterceptor { |
| 267 | + fn call( |
| 268 | + &mut self, |
| 269 | + mut request: tonic::Request<()>, |
| 270 | + ) -> Result<tonic::Request<()>, tonic::Status> { |
| 271 | + TraceContextPropagator::new().inject_context( |
| 272 | + &self.context, |
| 273 | + &mut MetadataMapInjector::new(request.metadata_mut()), |
| 274 | + ); |
| 275 | + Ok(request) |
| 276 | + } |
| 277 | +} |
| 278 | + |
180 | 279 | #[cfg(test)] |
181 | 280 | mod tests { |
182 | 281 | use super::*; |
| 282 | + use tonic::service::Interceptor as _; |
183 | 283 |
|
184 | 284 | fn env_test_exporter() -> ( |
185 | 285 | opentelemetry_sdk::trace::SdkTracerProvider, |
@@ -330,4 +430,58 @@ mod tests { |
330 | 430 | Some("value") |
331 | 431 | ); |
332 | 432 | } |
| 433 | + |
| 434 | + fn interceptor_with(extractor: EnvTraceContext) -> EnvTraceContextInterceptor { |
| 435 | + EnvTraceContextInterceptor { |
| 436 | + context: context_from(&extractor), |
| 437 | + } |
| 438 | + } |
| 439 | + |
| 440 | + #[test] |
| 441 | + fn env_interceptor_forwards_valid_traceparent() { |
| 442 | + let traceparent = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"; |
| 443 | + let mut interceptor = interceptor_with(EnvTraceContext { |
| 444 | + traceparent: Some(traceparent.to_string()), |
| 445 | + tracestate: Some("vendor=value".to_string()), |
| 446 | + }); |
| 447 | + |
| 448 | + let request = interceptor.call(tonic::Request::new(())).unwrap(); |
| 449 | + |
| 450 | + assert_eq!( |
| 451 | + request |
| 452 | + .metadata() |
| 453 | + .get("traceparent") |
| 454 | + .and_then(|value| value.to_str().ok()), |
| 455 | + Some(traceparent) |
| 456 | + ); |
| 457 | + assert_eq!( |
| 458 | + request |
| 459 | + .metadata() |
| 460 | + .get("tracestate") |
| 461 | + .and_then(|value| value.to_str().ok()), |
| 462 | + Some("vendor=value") |
| 463 | + ); |
| 464 | + } |
| 465 | + |
| 466 | + #[test] |
| 467 | + fn env_interceptor_is_noop_without_traceparent() { |
| 468 | + let mut interceptor = interceptor_with(EnvTraceContext::default()); |
| 469 | + |
| 470 | + let request = interceptor.call(tonic::Request::new(())).unwrap(); |
| 471 | + |
| 472 | + assert!(request.metadata().get("traceparent").is_none()); |
| 473 | + assert!(request.metadata().get("tracestate").is_none()); |
| 474 | + } |
| 475 | + |
| 476 | + #[test] |
| 477 | + fn env_interceptor_is_noop_for_invalid_traceparent() { |
| 478 | + let mut interceptor = interceptor_with(EnvTraceContext { |
| 479 | + traceparent: Some("not-a-valid-traceparent".to_string()), |
| 480 | + tracestate: None, |
| 481 | + }); |
| 482 | + |
| 483 | + let request = interceptor.call(tonic::Request::new(())).unwrap(); |
| 484 | + |
| 485 | + assert!(request.metadata().get("traceparent").is_none()); |
| 486 | + } |
333 | 487 | } |
0 commit comments