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    /// Starts tracing on `ctx`, parsing or originating W3C Trace Context and seeding response headers.
120    ///
121    /// # Arguments
122    ///
123    /// - `&mut Context` - Incoming request context.
124    ///
125    /// # Returns
126    ///
127    /// - `TraceContext` - Established trace context.
128    pub fn start_request(&self, ctx: &mut Context) -> TraceContext {
129        let incoming_tp: Option<String> = ctx.get_request().try_get_header_back(HEADER_TRACEPARENT);
130        let tracestate: Option<String> = ctx.get_request().try_get_header_back(HEADER_TRACESTATE);
131        let incoming_req_id: Option<String> = ctx.get_request().try_get_header_back(X_REQUEST_ID);
132        let (trace_id, parent_span_id, sampled): (String, Option<String>, bool) =
133            match incoming_tp.as_deref().and_then(parse_traceparent) {
134                Some((tid, pid, is_sampled)) => (tid, Some(pid), is_sampled),
135                None => (
136                    generate_trace_id(),
137                    None,
138                    self.get_config().get_default_sampled(),
139                ),
140            };
141        let span_id: String = generate_span_id();
142        let request_id: String = incoming_req_id
143            .filter(|id: &String| !id.trim().is_empty())
144            .unwrap_or_else(|| trace_id.clone());
145        let trace_ctx: TraceContext = TraceContext {
146            trace_id,
147            span_id,
148            parent_span_id,
149            request_id,
150            sampled,
151            tracestate,
152        };
153        if self.get_config().get_emit_traceparent() {
154            ctx.get_mut_response()
155                .set_header(HEADER_TRACEPARENT, trace_ctx.to_traceparent());
156        }
157        if self.get_config().get_emit_request_id() {
158            ctx.get_mut_response()
159                .set_header(X_REQUEST_ID, trace_ctx.get_request_id());
160        }
161        ctx.set_attribute(ATTR_TRACE_CONTEXT, trace_ctx.clone());
162        ctx.set_attribute(ATTR_TRACE_STARTED_AT, Instant::now());
163        trace_ctx
164    }
165
166    /// Finalizes tracing on `ctx`, setting `Server-Timing` and exporting a [`SpanRecord`].
167    ///
168    /// # Arguments
169    ///
170    /// - `&mut Context` - Active request/response context.
171    pub fn finish_request(&self, ctx: &mut Context) {
172        let Self {
173            config, exporters, ..
174        } = self;
175        let Some(trace_ctx) = ctx.try_get_attribute::<TraceContext, _>(ATTR_TRACE_CONTEXT) else {
176            return;
177        };
178        let duration_us: u64 = ctx
179            .try_get_attribute::<Instant, _>(ATTR_TRACE_STARTED_AT)
180            .map(|started: Instant| started.elapsed().as_micros().min(u64::MAX as u128) as u64)
181            .unwrap_or(0);
182        if config.get_emit_traceparent()
183            && ctx
184                .get_response()
185                .try_get_header_back(HEADER_TRACEPARENT)
186                .is_none()
187        {
188            ctx.get_mut_response()
189                .set_header(HEADER_TRACEPARENT, trace_ctx.to_traceparent());
190        }
191        if config.get_emit_request_id()
192            && ctx
193                .get_response()
194                .try_get_header_back(X_REQUEST_ID)
195                .is_none()
196        {
197            ctx.get_mut_response()
198                .set_header(X_REQUEST_ID, trace_ctx.get_request_id());
199        }
200        if config.get_emit_server_timing() {
201            let dur_ms: f64 = (duration_us as f64) / 1_000.0;
202            let header_val: String =
203                format!("{};dur={dur_ms:.2}", config.get_server_timing_label());
204            ctx.get_mut_response().set_header(SERVER_TIMING, header_val);
205        }
206        if !exporters.is_empty() {
207            let record: SpanRecord = SpanRecord {
208                trace_id: trace_ctx.get_trace_id().clone(),
209                span_id: trace_ctx.get_span_id().clone(),
210                parent_span_id: trace_ctx.get_parent_span_id(),
211                request_id: trace_ctx.get_request_id().clone(),
212                method: ctx.get_request().get_method().to_string(),
213                path: ctx.get_request().get_path().clone(),
214                status_code: ctx.get_response().get_status_code(),
215                duration_us,
216                sampled: trace_ctx.get_sampled(),
217            };
218            for exporter in exporters.iter() {
219                exporter.export(&record);
220            }
221        }
222    }
223}
224
225/// Implements [`ServerHook`] for [`TracingRequestHook`].
226impl ServerHook for TracingRequestHook {
227    /// Constructs a per-request [`TracingRequestHook`].
228    ///
229    /// # Arguments
230    ///
231    /// - `&mut Stream` - Connection stream.
232    /// - `&mut Context` - Request context.
233    ///
234    /// # Returns
235    ///
236    /// - `Self` - Hook instance.
237    async fn new(_: &mut Stream, _: &mut Context) -> Self {
238        Self
239    }
240
241    /// Initializes W3C Trace Context and correlation headers at the very start of the pipeline.
242    ///
243    /// # Arguments
244    ///
245    /// - `Self` - Hook instance.
246    /// - `&mut Stream` - Connection stream.
247    /// - `&mut Context` - Request context.
248    ///
249    /// # Returns
250    ///
251    /// - `Status` - Always `Status::Continue`.
252    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
253        let Some(plugin) = TracingPlugin::get() else {
254            return Status::Continue;
255        };
256        let _: TraceContext = plugin.start_request(ctx);
257        Status::Continue
258    }
259}
260
261/// Implements [`ServerHook`] for [`TracingResponseHook`].
262impl ServerHook for TracingResponseHook {
263    /// Constructs a per-response [`TracingResponseHook`].
264    ///
265    /// # Arguments
266    ///
267    /// - `&mut Stream` - Connection stream.
268    /// - `&mut Context` - Request context.
269    ///
270    /// # Returns
271    ///
272    /// - `Self` - Hook instance.
273    async fn new(_: &mut Stream, _: &mut Context) -> Self {
274        Self
275    }
276
277    /// Records `Server-Timing` and exports the completed request span.
278    ///
279    /// # Arguments
280    ///
281    /// - `Self` - Hook instance.
282    /// - `&mut Stream` - Connection stream.
283    /// - `&mut Context` - Request context.
284    ///
285    /// # Returns
286    ///
287    /// - `Status` - Always `Status::Continue`.
288    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
289        let Some(plugin) = TracingPlugin::get() else {
290            return Status::Continue;
291        };
292        plugin.finish_request(ctx);
293        Status::Continue
294    }
295}