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<SharedSpanExporter>) -> &'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 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 #[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 #[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 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 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
343impl ServerHook for TracingRequestHook {
345 async fn new(_: &mut Stream, _: &mut Context) -> Self {
356 Self
357 }
358
359 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
379impl ServerHook for TracingResponseHook {
381 async fn new(_: &mut Stream, _: &mut Context) -> Self {
392 Self
393 }
394
395 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}