hyperlane_plugin_tracing/
impl.rs1use super::*;
2
3impl TraceContext {
5 pub fn to_traceparent(&self) -> String {
11 format_traceparent(self.get_trace_id(), self.get_span_id(), self.get_sampled())
12 }
13}
14
15impl Default for TracingConfig {
17 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
29impl TracingConfig {
31 pub fn with_server_timing(mut self, enabled: bool) -> Self {
41 self.set_emit_server_timing(enabled);
42 self
43 }
44
45 pub fn with_default_sampled(mut self, sampled: bool) -> Self {
55 self.set_default_sampled(sampled);
56 self
57 }
58}
59
60impl TracingPlugin {
62 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 pub fn init_default() -> &'static Self {
85 Self::init(TracingConfig::default(), Vec::new())
86 }
87
88 pub fn get() -> Option<&'static Self> {
94 TRACING_PLUGIN.get()
95 }
96
97 pub fn get_config(&self) -> &TracingConfig {
103 &self.config
104 }
105
106 pub fn current(ctx: &Context) -> Option<TraceContext> {
116 ctx.try_get_attribute(ATTR_TRACE_CONTEXT)
117 }
118
119 #[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 headers: &mut ResponseHeaders = ctx.get_mut_response().get_mut_headers();
155 let extra: usize = usize::from(emit_tp) + usize::from(emit_req);
156 if headers.capacity() < headers.len() + extra {
157 headers.reserve(extra);
158 }
159 if emit_tp {
160 let mut tp_buf: [u8; TRACEPARENT_LEN] = [0u8; TRACEPARENT_LEN];
161 if let Some(tp_str) =
162 format_traceparent_stack(&trace_bytes, &span_bytes, sampled, &mut tp_buf)
163 {
164 set_response_header_fast(headers, HEADER_TRACEPARENT, tp_str);
165 }
166 }
167 if emit_req {
168 let req_str: &str = incoming_req_id
169 .as_deref()
170 .unwrap_or_else(|| from_utf8(&trace_bytes).unwrap_or_default());
171 set_response_header_fast(headers, X_REQUEST_ID, req_str);
172 }
173 }
174 PreparedTraceStart {
175 trace_bytes,
176 span_bytes,
177 parent_bytes,
178 sampled,
179 incoming_req_id,
180 tracestate,
181 }
182 }
183
184 #[inline]
192 fn put_preformatted_attr<V>(ctx: &mut Context, map_key: &'static str, value: V)
193 where
194 V: Send + Sync + 'static,
195 {
196 if let Some(slot) = ctx.get_mut_attributes().get_mut(map_key) {
197 if let Some(any_mut) = Arc::get_mut(slot)
198 && let Some(existing) = any_mut.downcast_mut::<V>()
199 {
200 *existing = value;
201 return;
202 }
203 *slot = Arc::new(value);
204 } else {
205 ctx.get_mut_attributes()
206 .insert(map_key.to_owned(), Arc::new(value));
207 }
208 }
209
210 #[inline]
222 fn store_trace_context_in_place(
223 ctx: &mut Context,
224 trace_str: &str,
225 span_str: &str,
226 parent_str: Option<&str>,
227 incoming_req_id: Option<String>,
228 sampled: bool,
229 tracestate: Option<String>,
230 ) {
231 if let Some(slot) = ctx.get_mut_attributes().get_mut(ATTR_TRACE_CONTEXT_MAP_KEY) {
232 if let Some(any_mut) = Arc::get_mut(slot)
233 && let Some(existing) = any_mut.downcast_mut::<TraceContext>()
234 {
235 reuse_string(&mut existing.trace_id, trace_str);
236 reuse_string(&mut existing.span_id, span_str);
237 reuse_opt_string(&mut existing.parent_span_id, parent_str);
238 if let Some(req_id) = incoming_req_id {
239 existing.request_id = req_id;
240 } else {
241 reuse_string(&mut existing.request_id, trace_str);
242 }
243 existing.sampled = sampled;
244 existing.tracestate = tracestate;
245 return;
246 }
247 let trace_id: String = trace_str.to_owned();
248 let request_id: String = incoming_req_id.unwrap_or_else(|| trace_id.clone());
249 *slot = Arc::new(TraceContext {
250 trace_id,
251 span_id: span_str.to_owned(),
252 parent_span_id: parent_str.map(str::to_owned),
253 request_id,
254 sampled,
255 tracestate,
256 });
257 return;
258 }
259 let trace_id: String = trace_str.to_owned();
260 let request_id: String = incoming_req_id.unwrap_or_else(|| trace_id.clone());
261 ctx.get_mut_attributes().insert(
262 ATTR_TRACE_CONTEXT_MAP_KEY.to_owned(),
263 Arc::new(TraceContext {
264 trace_id,
265 span_id: span_str.to_owned(),
266 parent_span_id: parent_str.map(str::to_owned),
267 request_id,
268 sampled,
269 tracestate,
270 }),
271 );
272 }
273
274 #[inline]
280 pub(crate) fn start_request_hook(&self, ctx: &mut Context) {
281 let Self {
282 config, exporters, ..
283 } = self;
284 let prepared: PreparedTraceStart = self.prepare_and_emit_start(ctx);
285 let trace_str: &str = from_utf8(&prepared.trace_bytes).unwrap_or_default();
286 let span_str: &str = from_utf8(&prepared.span_bytes).unwrap_or_default();
287 let parent_str: Option<&str> = prepared
288 .parent_bytes
289 .as_ref()
290 .and_then(|pid: &[u8; 16]| from_utf8(pid).ok());
291 Self::store_trace_context_in_place(
292 ctx,
293 trace_str,
294 span_str,
295 parent_str,
296 prepared.incoming_req_id,
297 prepared.sampled,
298 prepared.tracestate,
299 );
300 if config.get_emit_server_timing() || !exporters.is_empty() {
301 Self::put_preformatted_attr(ctx, ATTR_TRACE_STARTED_AT_MAP_KEY, Instant::now());
302 }
303 }
304
305 pub fn start_request(&self, ctx: &mut Context) -> TraceContext {
315 let prepared: PreparedTraceStart = self.prepare_and_emit_start(ctx);
316 let trace_str: &str = from_utf8(&prepared.trace_bytes).unwrap_or_default();
317 let span_str: &str = from_utf8(&prepared.span_bytes).unwrap_or_default();
318 let parent_str: Option<&str> = prepared
319 .parent_bytes
320 .as_ref()
321 .and_then(|pid: &[u8; 16]| from_utf8(pid).ok());
322 let trace_id: String = trace_str.to_owned();
323 let span_id: String = span_str.to_owned();
324 let parent_span_id: Option<String> = parent_str.map(str::to_owned);
325 let request_id: String = prepared.incoming_req_id.unwrap_or_else(|| trace_id.clone());
326 let trace_ctx: TraceContext = TraceContext {
327 trace_id,
328 span_id,
329 parent_span_id,
330 request_id,
331 sampled: prepared.sampled,
332 tracestate: prepared.tracestate,
333 };
334 if let Some(slot) = ctx.get_mut_attributes().get_mut(ATTR_TRACE_CONTEXT_MAP_KEY)
335 && let Some(any_mut) = Arc::get_mut(slot)
336 && let Some(existing) = any_mut.downcast_mut::<TraceContext>()
337 {
338 reuse_string(&mut existing.trace_id, trace_ctx.get_trace_id());
339 reuse_string(&mut existing.span_id, trace_ctx.get_span_id());
340 reuse_opt_string(
341 &mut existing.parent_span_id,
342 trace_ctx.parent_span_id.as_deref(),
343 );
344 reuse_string(&mut existing.request_id, trace_ctx.get_request_id());
345 existing.sampled = trace_ctx.get_sampled();
346 reuse_opt_string(&mut existing.tracestate, trace_ctx.tracestate.as_deref());
347 } else {
348 Self::put_preformatted_attr(ctx, ATTR_TRACE_CONTEXT_MAP_KEY, trace_ctx.clone());
349 }
350 Self::put_preformatted_attr(ctx, ATTR_TRACE_STARTED_AT_MAP_KEY, Instant::now());
351 trace_ctx
352 }
353
354 pub fn finish_request(&self, ctx: &mut Context) {
360 let Self {
361 config, exporters, ..
362 } = self;
363 let has_trace_ctx: bool = ctx
364 .get_attributes()
365 .get(ATTR_TRACE_CONTEXT_MAP_KEY)
366 .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<TraceContext>())
367 .is_some();
368 if !has_trace_ctx {
369 return;
370 }
371 let resp_headers: &ResponseHeaders = ctx.get_response().get_headers();
372 let need_tp: bool =
373 config.get_emit_traceparent() && !resp_headers.contains_key(HEADER_TRACEPARENT);
374 let need_req_id: bool =
375 config.get_emit_request_id() && !resp_headers.contains_key(X_REQUEST_ID);
376 let need_timing: bool = config.get_emit_server_timing();
377 let has_exporters: bool = !exporters.is_empty();
378 let duration_us: u64 = if need_timing || has_exporters {
379 ctx.get_attributes()
380 .get(ATTR_TRACE_STARTED_AT_MAP_KEY)
381 .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<Instant>())
382 .map(|started: &Instant| started.elapsed().as_micros().min(u64::MAX as u128) as u64)
383 .unwrap_or(0)
384 } else {
385 0
386 };
387 if need_tp || need_req_id {
388 let mut tp_buf: [u8; TRACEPARENT_LEN] = [0u8; TRACEPARENT_LEN];
389 let mut tp_fallback: Option<String> = None;
390 let mut tp_stack_ok: bool = false;
391 let mut req_id_copy: Option<String> = None;
392 if let Some(trace_ctx) = ctx
393 .get_attributes()
394 .get(ATTR_TRACE_CONTEXT_MAP_KEY)
395 .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<TraceContext>())
396 {
397 if need_tp {
398 if format_traceparent_stack(
399 trace_ctx.get_trace_id().as_bytes(),
400 trace_ctx.get_span_id().as_bytes(),
401 trace_ctx.get_sampled(),
402 &mut tp_buf,
403 )
404 .is_some()
405 {
406 tp_stack_ok = true;
407 } else {
408 tp_fallback = Some(trace_ctx.to_traceparent());
409 }
410 }
411 if need_req_id {
412 req_id_copy = Some(trace_ctx.get_request_id().clone());
413 }
414 }
415 let headers: &mut ResponseHeaders = ctx.get_mut_response().get_mut_headers();
416 if need_tp {
417 if tp_stack_ok {
418 if let Ok(tp_str) = from_utf8(&tp_buf) {
419 set_response_header_fast(headers, HEADER_TRACEPARENT, tp_str);
420 }
421 } else if let Some(tp_str) = tp_fallback {
422 set_response_header_fast(headers, HEADER_TRACEPARENT, &tp_str);
423 }
424 }
425 if let Some(req_id) = req_id_copy {
426 set_response_header_fast(headers, X_REQUEST_ID, &req_id);
427 }
428 }
429 if need_timing {
430 let mut timing_buf: [u8; SERVER_TIMING_STACK_CAP] = [0u8; SERVER_TIMING_STACK_CAP];
431 let headers: &mut ResponseHeaders = ctx.get_mut_response().get_mut_headers();
432 if let Some(timing_str) = format_server_timing_stack(
433 config.get_server_timing_label(),
434 duration_us,
435 &mut timing_buf,
436 ) {
437 set_response_header_fast(headers, SERVER_TIMING, timing_str);
438 } else {
439 let dur_ms: f64 = (duration_us as f64) / 1_000.0;
440 let header_val: String =
441 format!("{};dur={dur_ms:.2}", config.get_server_timing_label());
442 set_response_header_fast(headers, SERVER_TIMING, &header_val);
443 }
444 }
445 if has_exporters
446 && let Some(trace_ctx) = ctx
447 .get_attributes()
448 .get(ATTR_TRACE_CONTEXT_MAP_KEY)
449 .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<TraceContext>())
450 {
451 let record: SpanRecord = SpanRecord {
452 trace_id: trace_ctx.get_trace_id().clone(),
453 span_id: trace_ctx.get_span_id().clone(),
454 parent_span_id: trace_ctx.get_parent_span_id(),
455 request_id: trace_ctx.get_request_id().clone(),
456 method: ctx.get_request().get_method().to_string(),
457 path: ctx.get_request().get_path().clone(),
458 status_code: ctx.get_response().get_status_code(),
459 duration_us,
460 sampled: trace_ctx.get_sampled(),
461 };
462 for exporter in exporters.iter() {
463 exporter.export(&record);
464 }
465 }
466 }
467}
468
469impl ServerHook for TracingRequestHook {
471 async fn new(_: &mut Stream, _: &mut Context) -> Self {
482 Self
483 }
484
485 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
497 let Some(plugin) = TracingPlugin::get() else {
498 return Status::Continue;
499 };
500 plugin.start_request_hook(ctx);
501 Status::Continue
502 }
503}
504
505impl ServerHook for TracingResponseHook {
507 async fn new(_: &mut Stream, _: &mut Context) -> Self {
518 Self
519 }
520
521 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
533 let Some(plugin) = TracingPlugin::get() else {
534 return Status::Continue;
535 };
536 plugin.finish_request(ctx);
537 Status::Continue
538 }
539}