Skip to main content

hyperlane_plugin_tracing/
impl.rs

1use super::*;
2
3/// Inherent implementation of [`TraceContext`].
4impl TraceContext {
5    /// Formats this context as a canonical W3C `traceparent` header value.
6    ///
7    /// # Returns
8    ///
9    /// - `String` - Canonical `00-<trace_id>-<span_id>-<flags>` value.
10    pub fn to_traceparent(&self) -> String {
11        format_traceparent(self.get_trace_id(), self.get_span_id(), self.get_sampled())
12    }
13}
14
15/// Default construction for [`TracingConfig`].
16impl Default for TracingConfig {
17    /// Constructs a default [`TracingConfig`] emitting `traceparent`, `X-Request-Id`, and `Server-Timing`.
18    fn default() -> Self {
19        Self {
20            emit_traceparent: true,
21            emit_request_id: true,
22            emit_server_timing: true,
23            server_timing_label: DEFAULT_SERVER_TIMING_LABEL.to_owned(),
24            default_sampled: true,
25        }
26    }
27}
28
29/// Inherent builders for [`TracingConfig`].
30impl TracingConfig {
31    /// Enables or disables emitting `Server-Timing` response headers.
32    ///
33    /// # Arguments
34    ///
35    /// - `bool` - Whether to emit `Server-Timing`.
36    ///
37    /// # Returns
38    ///
39    /// - `Self` - Updated configuration.
40    pub fn with_server_timing(mut self, enabled: bool) -> Self {
41        self.set_emit_server_timing(enabled);
42        self
43    }
44
45    /// Configures the default sampled flag for newly originated traces.
46    ///
47    /// # Arguments
48    ///
49    /// - `bool` - Default sampled flag.
50    ///
51    /// # Returns
52    ///
53    /// - `Self` - Updated configuration.
54    pub fn with_default_sampled(mut self, sampled: bool) -> Self {
55        self.set_default_sampled(sampled);
56        self
57    }
58}
59
60/// Inherent implementation of [`TracingPlugin`].
61impl TracingPlugin {
62    /// Initializes the global [`TracingPlugin`] once with `config` and optional `exporters`.
63    ///
64    /// # Arguments
65    ///
66    /// - `TracingConfig` - Header propagation and timing configuration.
67    /// - `Vec<Arc<dyn SpanExporter>>` - Span exporters invoked after response handling.
68    ///
69    /// # Returns
70    ///
71    /// - `&'static Self` - Reference to the initialized global plugin.
72    pub fn init(config: TracingConfig, exporters: Vec<Arc<dyn SpanExporter>>) -> &'static Self {
73        TRACING_PLUGIN.get_or_init(|| Self {
74            config,
75            exporters: Arc::new(exporters),
76        })
77    }
78
79    /// Initializes the global [`TracingPlugin`] once with default configuration and no exporters.
80    ///
81    /// # Returns
82    ///
83    /// - `&'static Self` - Reference to the initialized global plugin.
84    pub fn init_default() -> &'static Self {
85        Self::init(TracingConfig::default(), Vec::new())
86    }
87
88    /// Returns the initialized global [`TracingPlugin`], if initialized.
89    ///
90    /// # Returns
91    ///
92    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
93    pub fn get() -> Option<&'static Self> {
94        TRACING_PLUGIN.get()
95    }
96
97    /// Returns the active [`TracingConfig`].
98    ///
99    /// # Returns
100    ///
101    /// - `&TracingConfig` - Active tracing configuration.
102    pub fn get_config(&self) -> &TracingConfig {
103        &self.config
104    }
105
106    /// Retrieves the active [`TraceContext`] stored in `ctx`.
107    ///
108    /// # Arguments
109    ///
110    /// - `&Context` - Request context.
111    ///
112    /// # Returns
113    ///
114    /// - `Option<TraceContext>` - Active trace context, if tracing ran on this request.
115    pub fn current(ctx: &Context) -> Option<TraceContext> {
116        ctx.try_get_attribute(ATTR_TRACE_CONTEXT)
117    }
118
119    /// Extracts or originates stack-allocated W3C trace/span identifiers and emits early response headers.
120    ///
121    /// # Arguments
122    ///
123    /// - `&mut Context` - Incoming request context.
124    ///
125    /// # Returns
126    ///
127    /// - `PreparedTraceStart` - Extracted or newly originated trace identifiers.
128    #[inline]
129    fn prepare_and_emit_start(&self, ctx: &mut Context) -> PreparedTraceStart {
130        let Self { config, .. } = self;
131        let request: &Request = ctx.get_request();
132        let (trace_bytes, span_bytes, parent_bytes, sampled): (
133            [u8; 32],
134            [u8; 16],
135            Option<[u8; 16]>,
136            bool,
137        ) = match get_request_header_back_ref(request, HEADER_TRACEPARENT)
138            .and_then(parse_traceparent_stack)
139        {
140            Some((tid, pid, is_sampled)) => (tid, generate_span_id_bytes(), Some(pid), is_sampled),
141            None => {
142                let (tid, sid): ([u8; 32], [u8; 16]) = generate_trace_and_span_id_bytes();
143                (tid, sid, None, config.get_default_sampled())
144            }
145        };
146        let tracestate: Option<String> =
147            get_request_header_back_ref(request, HEADER_TRACESTATE).map(str::to_owned);
148        let incoming_req_id: Option<String> = get_request_header_back_ref(request, X_REQUEST_ID)
149            .filter(|id: &&str| !id.trim().is_empty())
150            .map(str::to_owned);
151        let emit_tp: bool = config.get_emit_traceparent();
152        let emit_req: bool = config.get_emit_request_id();
153        if emit_tp || emit_req {
154            let response: &mut Response = ctx.get_mut_response();
155            if emit_tp {
156                let mut tp_buf: [u8; TRACEPARENT_LEN] = [0u8; TRACEPARENT_LEN];
157                if let Some(tp_str) =
158                    format_traceparent_stack(&trace_bytes, &span_bytes, sampled, &mut tp_buf)
159                {
160                    response.set_header(HEADER_TRACEPARENT, tp_str);
161                }
162            }
163            if emit_req {
164                let req_str: &str = incoming_req_id
165                    .as_deref()
166                    .unwrap_or_else(|| from_utf8(&trace_bytes).unwrap_or_default());
167                response.set_header(X_REQUEST_ID, req_str);
168            }
169        }
170        PreparedTraceStart {
171            trace_bytes,
172            span_bytes,
173            parent_bytes,
174            sampled,
175            incoming_req_id,
176            tracestate,
177        }
178    }
179
180    /// Stores a `Copy`/`Send` attribute under `map_key`, reusing any unique existing `Arc` slot in place.
181    ///
182    /// # Arguments
183    ///
184    /// - `&mut Context` - Request context.
185    /// - `&'static str` - Preformatted external map key.
186    /// - `V` - Value to store.
187    #[inline]
188    fn put_preformatted_attr<V>(ctx: &mut Context, map_key: &'static str, value: V)
189    where
190        V: Send + Sync + 'static,
191    {
192        if let Some(slot) = ctx.get_mut_attributes().get_mut(map_key) {
193            if let Some(any_mut) = Arc::get_mut(slot)
194                && let Some(existing) = any_mut.downcast_mut::<V>()
195            {
196                *existing = value;
197                return;
198            }
199            *slot = Arc::new(value);
200        } else {
201            ctx.get_mut_attributes()
202                .insert(map_key.to_owned(), Arc::new(value));
203        }
204    }
205
206    /// Stores or updates [`TraceContext`] in `ctx` from stack slices, reusing unique `Arc` and `String` buffers in place.
207    ///
208    /// # Arguments
209    ///
210    /// - `&mut Context` - Request context.
211    /// - `&str` - 32-char lowercase hex trace ID.
212    /// - `&str` - 16-char lowercase hex span ID.
213    /// - `Option<&str>` - Optional 16-char parent span ID.
214    /// - `Option<String>` - Optional incoming `X-Request-Id`.
215    /// - `bool` - W3C sampled flag.
216    /// - `Option<String>` - Optional incoming `tracestate`.
217    #[inline]
218    fn store_trace_context_in_place(
219        ctx: &mut Context,
220        trace_str: &str,
221        span_str: &str,
222        parent_str: Option<&str>,
223        incoming_req_id: Option<String>,
224        sampled: bool,
225        tracestate: Option<String>,
226    ) {
227        if let Some(slot) = ctx.get_mut_attributes().get_mut(ATTR_TRACE_CONTEXT_MAP_KEY) {
228            if let Some(any_mut) = Arc::get_mut(slot)
229                && let Some(existing) = any_mut.downcast_mut::<TraceContext>()
230            {
231                reuse_string(&mut existing.trace_id, trace_str);
232                reuse_string(&mut existing.span_id, span_str);
233                reuse_opt_string(&mut existing.parent_span_id, parent_str);
234                if let Some(req_id) = incoming_req_id {
235                    existing.request_id = req_id;
236                } else {
237                    reuse_string(&mut existing.request_id, trace_str);
238                }
239                existing.sampled = sampled;
240                existing.tracestate = tracestate;
241                return;
242            }
243            let trace_id: String = trace_str.to_owned();
244            let request_id: String = incoming_req_id.unwrap_or_else(|| trace_id.clone());
245            *slot = Arc::new(TraceContext {
246                trace_id,
247                span_id: span_str.to_owned(),
248                parent_span_id: parent_str.map(str::to_owned),
249                request_id,
250                sampled,
251                tracestate,
252            });
253            return;
254        }
255        let trace_id: String = trace_str.to_owned();
256        let request_id: String = incoming_req_id.unwrap_or_else(|| trace_id.clone());
257        ctx.set_attribute(
258            ATTR_TRACE_CONTEXT,
259            TraceContext {
260                trace_id,
261                span_id: span_str.to_owned(),
262                parent_span_id: parent_str.map(str::to_owned),
263                request_id,
264                sampled,
265                tracestate,
266            },
267        );
268    }
269
270    /// Starts tracing on `ctx` directly for hook invocation, reusing unique attribute slots without heap allocation.
271    ///
272    /// # Arguments
273    ///
274    /// - `&mut Context` - Incoming request context.
275    #[inline]
276    pub(crate) fn start_request_hook(&self, ctx: &mut Context) {
277        let Self {
278            config, exporters, ..
279        } = self;
280        let prepared: PreparedTraceStart = self.prepare_and_emit_start(ctx);
281        let trace_str: &str = from_utf8(&prepared.trace_bytes).unwrap_or_default();
282        let span_str: &str = from_utf8(&prepared.span_bytes).unwrap_or_default();
283        let parent_str: Option<&str> = prepared
284            .parent_bytes
285            .as_ref()
286            .and_then(|pid: &[u8; 16]| from_utf8(pid).ok());
287        Self::store_trace_context_in_place(
288            ctx,
289            trace_str,
290            span_str,
291            parent_str,
292            prepared.incoming_req_id,
293            prepared.sampled,
294            prepared.tracestate,
295        );
296        if config.get_emit_server_timing() || !exporters.is_empty() {
297            ctx.set_attribute(ATTR_TRACE_STARTED_AT, Instant::now());
298        }
299    }
300
301    /// Starts tracing on `ctx`, parsing or originating W3C Trace Context and seeding response headers.
302    ///
303    /// # Arguments
304    ///
305    /// - `&mut Context` - Incoming request context.
306    ///
307    /// # Returns
308    ///
309    /// - `TraceContext` - Established trace context.
310    pub fn start_request(&self, ctx: &mut Context) -> TraceContext {
311        let prepared: PreparedTraceStart = self.prepare_and_emit_start(ctx);
312        let trace_str: &str = from_utf8(&prepared.trace_bytes).unwrap_or_default();
313        let span_str: &str = from_utf8(&prepared.span_bytes).unwrap_or_default();
314        let parent_str: Option<&str> = prepared
315            .parent_bytes
316            .as_ref()
317            .and_then(|pid: &[u8; 16]| from_utf8(pid).ok());
318        let trace_id: String = trace_str.to_owned();
319        let span_id: String = span_str.to_owned();
320        let parent_span_id: Option<String> = parent_str.map(str::to_owned);
321        let request_id: String = prepared.incoming_req_id.unwrap_or_else(|| trace_id.clone());
322        let trace_ctx: TraceContext = TraceContext {
323            trace_id,
324            span_id,
325            parent_span_id,
326            request_id,
327            sampled: prepared.sampled,
328            tracestate: prepared.tracestate,
329        };
330        if let Some(slot) = ctx.get_mut_attributes().get_mut(ATTR_TRACE_CONTEXT_MAP_KEY)
331            && let Some(any_mut) = Arc::get_mut(slot)
332            && let Some(existing) = any_mut.downcast_mut::<TraceContext>()
333        {
334            reuse_string(&mut existing.trace_id, trace_ctx.get_trace_id());
335            reuse_string(&mut existing.span_id, trace_ctx.get_span_id());
336            reuse_opt_string(
337                &mut existing.parent_span_id,
338                trace_ctx.parent_span_id.as_deref(),
339            );
340            reuse_string(&mut existing.request_id, trace_ctx.get_request_id());
341            existing.sampled = trace_ctx.get_sampled();
342            reuse_opt_string(&mut existing.tracestate, trace_ctx.tracestate.as_deref());
343        } else {
344            Self::put_preformatted_attr(ctx, ATTR_TRACE_CONTEXT_MAP_KEY, trace_ctx.clone());
345        }
346        Self::put_preformatted_attr(ctx, ATTR_TRACE_STARTED_AT_MAP_KEY, Instant::now());
347        trace_ctx
348    }
349
350    /// Finalizes tracing on `ctx`, setting `Server-Timing` and exporting a [`SpanRecord`].
351    ///
352    /// # Arguments
353    ///
354    /// - `&mut Context` - Active request/response context.
355    pub fn finish_request(&self, ctx: &mut Context) {
356        let Self {
357            config, exporters, ..
358        } = self;
359        let resp_headers: &ResponseHeaders = ctx.get_response().get_headers();
360        let need_tp: bool =
361            config.get_emit_traceparent() && !resp_headers.contains_key(HEADER_TRACEPARENT);
362        let need_req_id: bool =
363            config.get_emit_request_id() && !resp_headers.contains_key(X_REQUEST_ID);
364        let need_timing: bool = config.get_emit_server_timing();
365        let has_exporters: bool = !exporters.is_empty();
366        if !need_tp && !need_req_id && !need_timing && !has_exporters {
367            return;
368        }
369        let has_trace_ctx: bool = ctx
370            .get_attributes()
371            .get(ATTR_TRACE_CONTEXT_MAP_KEY)
372            .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<TraceContext>())
373            .is_some();
374        if !has_trace_ctx {
375            return;
376        }
377        let duration_us: u64 = if need_timing || has_exporters {
378            ctx.get_attributes()
379                .get(ATTR_TRACE_STARTED_AT_MAP_KEY)
380                .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<Instant>())
381                .map(|started: &Instant| started.elapsed().as_micros().min(u64::MAX as u128) as u64)
382                .unwrap_or(0)
383        } else {
384            0
385        };
386        if need_tp || need_req_id {
387            let mut tp_buf: [u8; TRACEPARENT_LEN] = [0u8; TRACEPARENT_LEN];
388            let mut tp_fallback: Option<String> = None;
389            let mut tp_stack_ok: bool = false;
390            let mut req_id_copy: Option<String> = None;
391            if let Some(trace_ctx) = ctx
392                .get_attributes()
393                .get(ATTR_TRACE_CONTEXT_MAP_KEY)
394                .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<TraceContext>())
395            {
396                if need_tp {
397                    if format_traceparent_stack(
398                        trace_ctx.get_trace_id().as_bytes(),
399                        trace_ctx.get_span_id().as_bytes(),
400                        trace_ctx.get_sampled(),
401                        &mut tp_buf,
402                    )
403                    .is_some()
404                    {
405                        tp_stack_ok = true;
406                    } else {
407                        tp_fallback = Some(trace_ctx.to_traceparent());
408                    }
409                }
410                if need_req_id {
411                    req_id_copy = Some(trace_ctx.get_request_id().clone());
412                }
413            }
414            let response: &mut Response = ctx.get_mut_response();
415            if need_tp {
416                if tp_stack_ok {
417                    if let Ok(tp_str) = from_utf8(&tp_buf) {
418                        response.set_header(HEADER_TRACEPARENT, tp_str);
419                    }
420                } else if let Some(tp_str) = tp_fallback {
421                    response.set_header(HEADER_TRACEPARENT, &tp_str);
422                }
423            }
424            if let Some(req_id) = req_id_copy {
425                response.set_header(X_REQUEST_ID, &req_id);
426            }
427        }
428        if need_timing {
429            let mut timing_buf: [u8; SERVER_TIMING_STACK_CAP] = [0u8; SERVER_TIMING_STACK_CAP];
430            let response: &mut Response = ctx.get_mut_response();
431            if let Some(timing_str) = format_server_timing_stack(
432                config.get_server_timing_label(),
433                duration_us,
434                &mut timing_buf,
435            ) {
436                response.set_header(SERVER_TIMING, timing_str);
437            } else {
438                let dur_ms: f64 = (duration_us as f64) / 1_000.0;
439                let header_val: String =
440                    format!("{};dur={dur_ms:.2}", config.get_server_timing_label());
441                response.set_header(SERVER_TIMING, &header_val);
442            }
443        }
444        if has_exporters
445            && let Some(trace_ctx) = ctx
446                .get_attributes()
447                .get(ATTR_TRACE_CONTEXT_MAP_KEY)
448                .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<TraceContext>())
449        {
450            let record: SpanRecord = SpanRecord {
451                trace_id: trace_ctx.get_trace_id().clone(),
452                span_id: trace_ctx.get_span_id().clone(),
453                parent_span_id: trace_ctx.get_parent_span_id(),
454                request_id: trace_ctx.get_request_id().clone(),
455                method: ctx.get_request().get_method().to_string(),
456                path: ctx.get_request().get_path().clone(),
457                status_code: ctx.get_response().get_status_code(),
458                duration_us,
459                sampled: trace_ctx.get_sampled(),
460            };
461            for exporter in exporters.iter() {
462                exporter.export(&record);
463            }
464        }
465    }
466}
467
468/// Implements [`ServerHook`] for [`TracingRequestHook`].
469impl ServerHook for TracingRequestHook {
470    /// Constructs a per-request [`TracingRequestHook`].
471    ///
472    /// # Arguments
473    ///
474    /// - `&mut Stream` - Connection stream.
475    /// - `&mut Context` - Request context.
476    ///
477    /// # Returns
478    ///
479    /// - `Self` - Hook instance.
480    async fn new(_: &mut Stream, _: &mut Context) -> Self {
481        Self
482    }
483
484    /// Initializes W3C Trace Context and correlation headers at the very start of the pipeline.
485    ///
486    /// # Arguments
487    ///
488    /// - `Self` - Hook instance.
489    /// - `&mut Stream` - Connection stream.
490    /// - `&mut Context` - Request context.
491    ///
492    /// # Returns
493    ///
494    /// - `Status` - Always `Status::Continue`.
495    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
496        let Some(plugin) = TracingPlugin::get() else {
497            return Status::Continue;
498        };
499        plugin.start_request_hook(ctx);
500        Status::Continue
501    }
502}
503
504/// Implements [`ServerHook`] for [`TracingResponseHook`].
505impl ServerHook for TracingResponseHook {
506    /// Constructs a per-response [`TracingResponseHook`].
507    ///
508    /// # Arguments
509    ///
510    /// - `&mut Stream` - Connection stream.
511    /// - `&mut Context` - Request context.
512    ///
513    /// # Returns
514    ///
515    /// - `Self` - Hook instance.
516    async fn new(_: &mut Stream, _: &mut Context) -> Self {
517        Self
518    }
519
520    /// Records `Server-Timing` and exports the completed request span.
521    ///
522    /// # Arguments
523    ///
524    /// - `Self` - Hook instance.
525    /// - `&mut Stream` - Connection stream.
526    /// - `&mut Context` - Request context.
527    ///
528    /// # Returns
529    ///
530    /// - `Status` - Always `Status::Continue`.
531    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
532        let Some(plugin) = TracingPlugin::get() else {
533            return Status::Continue;
534        };
535        plugin.finish_request(ctx);
536        Status::Continue
537    }
538}