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<SharedSpanExporter>` - 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<SharedSpanExporter>) -> &'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    /// Builds a [`TraceContext`] from `ctx` and emits early response correlation headers without intermediate clones.
120    ///
121    /// # Arguments
122    ///
123    /// - `&mut Context` - Incoming request context.
124    ///
125    /// # Returns
126    ///
127    /// - `TraceContext` - Constructed trace context.
128    #[inline]
129    fn build_and_emit_start(&self, ctx: &mut Context) -> TraceContext {
130        let Self { config, .. } = self;
131        let request: &Request = ctx.get_request();
132        let (trace_bytes, parent_bytes, sampled): ([u8; 32], Option<[u8; 16]>, bool) =
133            match get_request_header_back_ref(request, HEADER_TRACEPARENT)
134                .and_then(parse_traceparent_stack)
135            {
136                Some((tid, pid, is_sampled)) => (tid, Some(pid), is_sampled),
137                None => (
138                    generate_trace_id_bytes(),
139                    None,
140                    config.get_default_sampled(),
141                ),
142            };
143        let span_bytes: [u8; 16] = generate_span_id_bytes();
144        let tracestate: Option<String> =
145            get_request_header_back_ref(request, HEADER_TRACESTATE).map(str::to_owned);
146        let incoming_req_id: Option<String> = get_request_header_back_ref(request, X_REQUEST_ID)
147            .filter(|id: &&str| !id.trim().is_empty())
148            .map(str::to_owned);
149        let trace_id: String = from_utf8(&trace_bytes).unwrap_or_default().to_owned();
150        let span_id: String = from_utf8(&span_bytes).unwrap_or_default().to_owned();
151        let parent_span_id: Option<String> =
152            parent_bytes.map(|pid: [u8; 16]| from_utf8(&pid).unwrap_or_default().to_owned());
153        let request_id: String = incoming_req_id.unwrap_or_else(|| trace_id.clone());
154        if config.get_emit_traceparent() {
155            let mut tp_buf: [u8; TRACEPARENT_LEN] = [0u8; TRACEPARENT_LEN];
156            if let Some(tp_str) =
157                format_traceparent_stack(&trace_bytes, &span_bytes, sampled, &mut tp_buf)
158            {
159                ctx.get_mut_response()
160                    .set_header(HEADER_TRACEPARENT, tp_str);
161            }
162        }
163        if config.get_emit_request_id() {
164            ctx.get_mut_response().set_header(X_REQUEST_ID, &request_id);
165        }
166        TraceContext {
167            trace_id,
168            span_id,
169            parent_span_id,
170            request_id,
171            sampled,
172            tracestate,
173        }
174    }
175
176    /// Stores an attribute under preformatted `map_key`, reusing any existing key allocation.
177    ///
178    /// # Arguments
179    ///
180    /// - `&mut Context` - Request context.
181    /// - `&'static str` - Preformatted external map key.
182    /// - `V` - Value to store.
183    #[inline]
184    fn put_preformatted_attr<V>(ctx: &mut Context, map_key: &'static str, value: V)
185    where
186        V: Send + Sync + 'static,
187    {
188        if let Some(slot) = ctx.get_mut_attributes().get_mut(map_key) {
189            *slot = Arc::new(value);
190        } else {
191            ctx.get_mut_attributes()
192                .insert(map_key.to_owned(), Arc::new(value));
193        }
194    }
195
196    /// Starts tracing on `ctx` directly for hook invocation, moving [`TraceContext`] without cloning it.
197    ///
198    /// # Arguments
199    ///
200    /// - `&mut Context` - Incoming request context.
201    #[inline]
202    pub(crate) fn start_request_hook(&self, ctx: &mut Context) {
203        let Self {
204            config, exporters, ..
205        } = self;
206        let trace_ctx: TraceContext = self.build_and_emit_start(ctx);
207        Self::put_preformatted_attr(ctx, ATTR_TRACE_CONTEXT_MAP_KEY, trace_ctx);
208        if config.get_emit_server_timing() || !exporters.is_empty() {
209            Self::put_preformatted_attr(ctx, ATTR_TRACE_STARTED_AT_MAP_KEY, Instant::now());
210        }
211    }
212
213    /// Starts tracing on `ctx`, parsing or originating W3C Trace Context and seeding response headers.
214    ///
215    /// # Arguments
216    ///
217    /// - `&mut Context` - Incoming request context.
218    ///
219    /// # Returns
220    ///
221    /// - `TraceContext` - Established trace context.
222    pub fn start_request(&self, ctx: &mut Context) -> TraceContext {
223        let trace_ctx: TraceContext = self.build_and_emit_start(ctx);
224        Self::put_preformatted_attr(ctx, ATTR_TRACE_CONTEXT_MAP_KEY, trace_ctx.clone());
225        Self::put_preformatted_attr(ctx, ATTR_TRACE_STARTED_AT_MAP_KEY, Instant::now());
226        trace_ctx
227    }
228
229    /// Finalizes tracing on `ctx`, setting `Server-Timing` and exporting a [`SpanRecord`].
230    ///
231    /// # Arguments
232    ///
233    /// - `&mut Context` - Active request/response context.
234    pub fn finish_request(&self, ctx: &mut Context) {
235        let Self {
236            config, exporters, ..
237        } = self;
238        let has_trace_ctx: bool = ctx
239            .get_attributes()
240            .get(ATTR_TRACE_CONTEXT_MAP_KEY)
241            .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<TraceContext>())
242            .is_some();
243        if !has_trace_ctx {
244            return;
245        }
246        let need_tp: bool =
247            config.get_emit_traceparent() && !ctx.get_response().has_header(HEADER_TRACEPARENT);
248        let need_req_id: bool =
249            config.get_emit_request_id() && !ctx.get_response().has_header(X_REQUEST_ID);
250        let need_timing: bool = config.get_emit_server_timing();
251        let has_exporters: bool = !exporters.is_empty();
252        let duration_us: u64 = if need_timing || has_exporters {
253            ctx.get_attributes()
254                .get(ATTR_TRACE_STARTED_AT_MAP_KEY)
255                .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<Instant>())
256                .map(|started: &Instant| started.elapsed().as_micros().min(u64::MAX as u128) as u64)
257                .unwrap_or(0)
258        } else {
259            0
260        };
261        if need_tp || need_req_id {
262            let mut tp_buf: [u8; TRACEPARENT_LEN] = [0u8; TRACEPARENT_LEN];
263            let mut tp_fallback: Option<String> = None;
264            let mut tp_stack_ok: bool = false;
265            let mut req_id_copy: Option<String> = None;
266            if let Some(trace_ctx) = ctx
267                .get_attributes()
268                .get(ATTR_TRACE_CONTEXT_MAP_KEY)
269                .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<TraceContext>())
270            {
271                if need_tp {
272                    if format_traceparent_stack(
273                        trace_ctx.get_trace_id().as_bytes(),
274                        trace_ctx.get_span_id().as_bytes(),
275                        trace_ctx.get_sampled(),
276                        &mut tp_buf,
277                    )
278                    .is_some()
279                    {
280                        tp_stack_ok = true;
281                    } else {
282                        tp_fallback = Some(trace_ctx.to_traceparent());
283                    }
284                }
285                if need_req_id {
286                    req_id_copy = Some(trace_ctx.get_request_id().clone());
287                }
288            }
289            if need_tp {
290                if tp_stack_ok {
291                    if let Ok(tp_str) = from_utf8(&tp_buf) {
292                        ctx.get_mut_response()
293                            .set_header(HEADER_TRACEPARENT, tp_str);
294                    }
295                } else if let Some(tp_str) = tp_fallback {
296                    ctx.get_mut_response()
297                        .set_header(HEADER_TRACEPARENT, tp_str);
298                }
299            }
300            if let Some(req_id) = req_id_copy {
301                ctx.get_mut_response().set_header(X_REQUEST_ID, req_id);
302            }
303        }
304        if need_timing {
305            let mut timing_buf: [u8; SERVER_TIMING_STACK_CAP] = [0u8; SERVER_TIMING_STACK_CAP];
306            if let Some(timing_str) = format_server_timing_stack(
307                config.get_server_timing_label(),
308                duration_us,
309                &mut timing_buf,
310            ) {
311                ctx.get_mut_response().set_header(SERVER_TIMING, timing_str);
312            } else {
313                let dur_ms: f64 = (duration_us as f64) / 1_000.0;
314                let header_val: String =
315                    format!("{};dur={dur_ms:.2}", config.get_server_timing_label());
316                ctx.get_mut_response().set_header(SERVER_TIMING, header_val);
317            }
318        }
319        if has_exporters
320            && let Some(trace_ctx) = ctx
321                .get_attributes()
322                .get(ATTR_TRACE_CONTEXT_MAP_KEY)
323                .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<TraceContext>())
324        {
325            let record: SpanRecord = SpanRecord {
326                trace_id: trace_ctx.get_trace_id().clone(),
327                span_id: trace_ctx.get_span_id().clone(),
328                parent_span_id: trace_ctx.get_parent_span_id(),
329                request_id: trace_ctx.get_request_id().clone(),
330                method: ctx.get_request().get_method().to_string(),
331                path: ctx.get_request().get_path().clone(),
332                status_code: ctx.get_response().get_status_code(),
333                duration_us,
334                sampled: trace_ctx.get_sampled(),
335            };
336            for exporter in exporters.iter() {
337                exporter.export(&record);
338            }
339        }
340    }
341}
342
343/// Implements [`ServerHook`] for [`TracingRequestHook`].
344impl ServerHook for TracingRequestHook {
345    /// Constructs a per-request [`TracingRequestHook`].
346    ///
347    /// # Arguments
348    ///
349    /// - `&mut Stream` - Connection stream.
350    /// - `&mut Context` - Request context.
351    ///
352    /// # Returns
353    ///
354    /// - `Self` - Hook instance.
355    async fn new(_: &mut Stream, _: &mut Context) -> Self {
356        Self
357    }
358
359    /// Initializes W3C Trace Context and correlation headers at the very start of the pipeline.
360    ///
361    /// # Arguments
362    ///
363    /// - `Self` - Hook instance.
364    /// - `&mut Stream` - Connection stream.
365    /// - `&mut Context` - Request context.
366    ///
367    /// # Returns
368    ///
369    /// - `Status` - Always `Status::Continue`.
370    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
371        let Some(plugin) = TracingPlugin::get() else {
372            return Status::Continue;
373        };
374        plugin.start_request_hook(ctx);
375        Status::Continue
376    }
377}
378
379/// Implements [`ServerHook`] for [`TracingResponseHook`].
380impl ServerHook for TracingResponseHook {
381    /// Constructs a per-response [`TracingResponseHook`].
382    ///
383    /// # Arguments
384    ///
385    /// - `&mut Stream` - Connection stream.
386    /// - `&mut Context` - Request context.
387    ///
388    /// # Returns
389    ///
390    /// - `Self` - Hook instance.
391    async fn new(_: &mut Stream, _: &mut Context) -> Self {
392        Self
393    }
394
395    /// Records `Server-Timing` and exports the completed request span.
396    ///
397    /// # Arguments
398    ///
399    /// - `Self` - Hook instance.
400    /// - `&mut Stream` - Connection stream.
401    /// - `&mut Context` - Request context.
402    ///
403    /// # Returns
404    ///
405    /// - `Status` - Always `Status::Continue`.
406    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
407        let Some(plugin) = TracingPlugin::get() else {
408            return Status::Continue;
409        };
410        plugin.finish_request(ctx);
411        Status::Continue
412    }
413}