1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use super::*;
/// Inherent implementation of [`TraceContext`].
impl TraceContext {
/// Formats this context as a canonical W3C `traceparent` header value.
///
/// # Returns
///
/// - `String` - Canonical `00-<trace_id>-<span_id>-<flags>` value.
pub fn to_traceparent(&self) -> String {
format_traceparent(self.get_trace_id(), self.get_span_id(), self.get_sampled())
}
}
/// Default construction for [`TracingConfig`].
impl Default for TracingConfig {
/// Constructs a default [`TracingConfig`] emitting `traceparent`, `X-Request-Id`, and `Server-Timing`.
fn default() -> Self {
Self {
emit_traceparent: true,
emit_request_id: true,
emit_server_timing: true,
server_timing_label: DEFAULT_SERVER_TIMING_LABEL.to_owned(),
default_sampled: true,
}
}
}
/// Inherent builders for [`TracingConfig`].
impl TracingConfig {
/// Enables or disables emitting `Server-Timing` response headers.
///
/// # Arguments
///
/// - `bool` - Whether to emit `Server-Timing`.
///
/// # Returns
///
/// - `Self` - Updated configuration.
pub fn with_server_timing(mut self, enabled: bool) -> Self {
self.set_emit_server_timing(enabled);
self
}
/// Configures the default sampled flag for newly originated traces.
///
/// # Arguments
///
/// - `bool` - Default sampled flag.
///
/// # Returns
///
/// - `Self` - Updated configuration.
pub fn with_default_sampled(mut self, sampled: bool) -> Self {
self.set_default_sampled(sampled);
self
}
}
/// Inherent implementation of [`TracingPlugin`].
impl TracingPlugin {
/// Initializes the global [`TracingPlugin`] once with `config` and optional `exporters`.
///
/// # Arguments
///
/// - `TracingConfig` - Header propagation and timing configuration.
/// - `Vec<SharedSpanExporter>` - Span exporters invoked after response handling.
///
/// # Returns
///
/// - `&'static Self` - Reference to the initialized global plugin.
pub fn init(config: TracingConfig, exporters: Vec<SharedSpanExporter>) -> &'static Self {
TRACING_PLUGIN.get_or_init(|| Self {
config,
exporters: Arc::new(exporters),
})
}
/// Initializes the global [`TracingPlugin`] once with default configuration and no exporters.
///
/// # Returns
///
/// - `&'static Self` - Reference to the initialized global plugin.
pub fn init_default() -> &'static Self {
Self::init(TracingConfig::default(), Vec::new())
}
/// Returns the initialized global [`TracingPlugin`], if initialized.
///
/// # Returns
///
/// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
pub fn get() -> Option<&'static Self> {
TRACING_PLUGIN.get()
}
/// Returns the active [`TracingConfig`].
///
/// # Returns
///
/// - `&TracingConfig` - Active tracing configuration.
pub fn get_config(&self) -> &TracingConfig {
&self.config
}
/// Retrieves the active [`TraceContext`] stored in `ctx`.
///
/// # Arguments
///
/// - `&Context` - Request context.
///
/// # Returns
///
/// - `Option<TraceContext>` - Active trace context, if tracing ran on this request.
pub fn current(ctx: &Context) -> Option<TraceContext> {
ctx.try_get_attribute(ATTR_TRACE_CONTEXT)
}
/// Builds a [`TraceContext`] from `ctx` and emits early response correlation headers without intermediate clones.
///
/// # Arguments
///
/// - `&mut Context` - Incoming request context.
///
/// # Returns
///
/// - `TraceContext` - Constructed trace context.
#[inline]
fn build_and_emit_start(&self, ctx: &mut Context) -> TraceContext {
let Self { config, .. } = self;
let request: &Request = ctx.get_request();
let (trace_bytes, parent_bytes, sampled): ([u8; 32], Option<[u8; 16]>, bool) =
match get_request_header_back_ref(request, HEADER_TRACEPARENT)
.and_then(parse_traceparent_stack)
{
Some((tid, pid, is_sampled)) => (tid, Some(pid), is_sampled),
None => (
generate_trace_id_bytes(),
None,
config.get_default_sampled(),
),
};
let span_bytes: [u8; 16] = generate_span_id_bytes();
let tracestate: Option<String> =
get_request_header_back_ref(request, HEADER_TRACESTATE).map(str::to_owned);
let incoming_req_id: Option<String> = get_request_header_back_ref(request, X_REQUEST_ID)
.filter(|id: &&str| !id.trim().is_empty())
.map(str::to_owned);
let trace_id: String = from_utf8(&trace_bytes).unwrap_or_default().to_owned();
let span_id: String = from_utf8(&span_bytes).unwrap_or_default().to_owned();
let parent_span_id: Option<String> =
parent_bytes.map(|pid: [u8; 16]| from_utf8(&pid).unwrap_or_default().to_owned());
let request_id: String = incoming_req_id.unwrap_or_else(|| trace_id.clone());
if config.get_emit_traceparent() {
let mut tp_buf: [u8; TRACEPARENT_LEN] = [0u8; TRACEPARENT_LEN];
if let Some(tp_str) =
format_traceparent_stack(&trace_bytes, &span_bytes, sampled, &mut tp_buf)
{
ctx.get_mut_response()
.set_header(HEADER_TRACEPARENT, tp_str);
}
}
if config.get_emit_request_id() {
ctx.get_mut_response().set_header(X_REQUEST_ID, &request_id);
}
TraceContext {
trace_id,
span_id,
parent_span_id,
request_id,
sampled,
tracestate,
}
}
/// Stores an attribute under preformatted `map_key`, reusing any existing key allocation.
///
/// # Arguments
///
/// - `&mut Context` - Request context.
/// - `&'static str` - Preformatted external map key.
/// - `V` - Value to store.
#[inline]
fn put_preformatted_attr<V>(ctx: &mut Context, map_key: &'static str, value: V)
where
V: Send + Sync + 'static,
{
if let Some(slot) = ctx.get_mut_attributes().get_mut(map_key) {
*slot = Arc::new(value);
} else {
ctx.get_mut_attributes()
.insert(map_key.to_owned(), Arc::new(value));
}
}
/// Starts tracing on `ctx` directly for hook invocation, moving [`TraceContext`] without cloning it.
///
/// # Arguments
///
/// - `&mut Context` - Incoming request context.
#[inline]
pub(crate) fn start_request_hook(&self, ctx: &mut Context) {
let Self {
config, exporters, ..
} = self;
let trace_ctx: TraceContext = self.build_and_emit_start(ctx);
Self::put_preformatted_attr(ctx, ATTR_TRACE_CONTEXT_MAP_KEY, trace_ctx);
if config.get_emit_server_timing() || !exporters.is_empty() {
Self::put_preformatted_attr(ctx, ATTR_TRACE_STARTED_AT_MAP_KEY, Instant::now());
}
}
/// Starts tracing on `ctx`, parsing or originating W3C Trace Context and seeding response headers.
///
/// # Arguments
///
/// - `&mut Context` - Incoming request context.
///
/// # Returns
///
/// - `TraceContext` - Established trace context.
pub fn start_request(&self, ctx: &mut Context) -> TraceContext {
let trace_ctx: TraceContext = self.build_and_emit_start(ctx);
Self::put_preformatted_attr(ctx, ATTR_TRACE_CONTEXT_MAP_KEY, trace_ctx.clone());
Self::put_preformatted_attr(ctx, ATTR_TRACE_STARTED_AT_MAP_KEY, Instant::now());
trace_ctx
}
/// Finalizes tracing on `ctx`, setting `Server-Timing` and exporting a [`SpanRecord`].
///
/// # Arguments
///
/// - `&mut Context` - Active request/response context.
pub fn finish_request(&self, ctx: &mut Context) {
let Self {
config, exporters, ..
} = self;
let has_trace_ctx: bool = ctx
.get_attributes()
.get(ATTR_TRACE_CONTEXT_MAP_KEY)
.and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<TraceContext>())
.is_some();
if !has_trace_ctx {
return;
}
let need_tp: bool =
config.get_emit_traceparent() && !ctx.get_response().has_header(HEADER_TRACEPARENT);
let need_req_id: bool =
config.get_emit_request_id() && !ctx.get_response().has_header(X_REQUEST_ID);
let need_timing: bool = config.get_emit_server_timing();
let has_exporters: bool = !exporters.is_empty();
let duration_us: u64 = if need_timing || has_exporters {
ctx.get_attributes()
.get(ATTR_TRACE_STARTED_AT_MAP_KEY)
.and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<Instant>())
.map(|started: &Instant| started.elapsed().as_micros().min(u64::MAX as u128) as u64)
.unwrap_or(0)
} else {
0
};
if need_tp || need_req_id {
let mut tp_buf: [u8; TRACEPARENT_LEN] = [0u8; TRACEPARENT_LEN];
let mut tp_fallback: Option<String> = None;
let mut tp_stack_ok: bool = false;
let mut req_id_copy: Option<String> = None;
if let Some(trace_ctx) = ctx
.get_attributes()
.get(ATTR_TRACE_CONTEXT_MAP_KEY)
.and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<TraceContext>())
{
if need_tp {
if format_traceparent_stack(
trace_ctx.get_trace_id().as_bytes(),
trace_ctx.get_span_id().as_bytes(),
trace_ctx.get_sampled(),
&mut tp_buf,
)
.is_some()
{
tp_stack_ok = true;
} else {
tp_fallback = Some(trace_ctx.to_traceparent());
}
}
if need_req_id {
req_id_copy = Some(trace_ctx.get_request_id().clone());
}
}
if need_tp {
if tp_stack_ok {
if let Ok(tp_str) = from_utf8(&tp_buf) {
ctx.get_mut_response()
.set_header(HEADER_TRACEPARENT, tp_str);
}
} else if let Some(tp_str) = tp_fallback {
ctx.get_mut_response()
.set_header(HEADER_TRACEPARENT, tp_str);
}
}
if let Some(req_id) = req_id_copy {
ctx.get_mut_response().set_header(X_REQUEST_ID, req_id);
}
}
if need_timing {
let mut timing_buf: [u8; SERVER_TIMING_STACK_CAP] = [0u8; SERVER_TIMING_STACK_CAP];
if let Some(timing_str) = format_server_timing_stack(
config.get_server_timing_label(),
duration_us,
&mut timing_buf,
) {
ctx.get_mut_response().set_header(SERVER_TIMING, timing_str);
} else {
let dur_ms: f64 = (duration_us as f64) / 1_000.0;
let header_val: String =
format!("{};dur={dur_ms:.2}", config.get_server_timing_label());
ctx.get_mut_response().set_header(SERVER_TIMING, header_val);
}
}
if has_exporters
&& let Some(trace_ctx) = ctx
.get_attributes()
.get(ATTR_TRACE_CONTEXT_MAP_KEY)
.and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<TraceContext>())
{
let record: SpanRecord = SpanRecord {
trace_id: trace_ctx.get_trace_id().clone(),
span_id: trace_ctx.get_span_id().clone(),
parent_span_id: trace_ctx.get_parent_span_id(),
request_id: trace_ctx.get_request_id().clone(),
method: ctx.get_request().get_method().to_string(),
path: ctx.get_request().get_path().clone(),
status_code: ctx.get_response().get_status_code(),
duration_us,
sampled: trace_ctx.get_sampled(),
};
for exporter in exporters.iter() {
exporter.export(&record);
}
}
}
}
/// Implements [`ServerHook`] for [`TracingRequestHook`].
impl ServerHook for TracingRequestHook {
/// Constructs a per-request [`TracingRequestHook`].
///
/// # Arguments
///
/// - `&mut Stream` - Connection stream.
/// - `&mut Context` - Request context.
///
/// # Returns
///
/// - `Self` - Hook instance.
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
/// Initializes W3C Trace Context and correlation headers at the very start of the pipeline.
///
/// # Arguments
///
/// - `Self` - Hook instance.
/// - `&mut Stream` - Connection stream.
/// - `&mut Context` - Request context.
///
/// # Returns
///
/// - `Status` - Always `Status::Continue`.
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = TracingPlugin::get() else {
return Status::Continue;
};
plugin.start_request_hook(ctx);
Status::Continue
}
}
/// Implements [`ServerHook`] for [`TracingResponseHook`].
impl ServerHook for TracingResponseHook {
/// Constructs a per-response [`TracingResponseHook`].
///
/// # Arguments
///
/// - `&mut Stream` - Connection stream.
/// - `&mut Context` - Request context.
///
/// # Returns
///
/// - `Self` - Hook instance.
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
/// Records `Server-Timing` and exports the completed request span.
///
/// # Arguments
///
/// - `Self` - Hook instance.
/// - `&mut Stream` - Connection stream.
/// - `&mut Context` - Request context.
///
/// # Returns
///
/// - `Status` - Always `Status::Continue`.
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = TracingPlugin::get() else {
return Status::Continue;
};
plugin.finish_request(ctx);
Status::Continue
}
}