Skip to main content

ledgence_worker_api/
trace.rs

1//! Portable W3C carriers and the narrow bridge used by optional tracing adapters.
2use crate::{CloudEvent, Result};
3use serde::{Deserialize, Serialize};
4
5/// Origin and processing contexts have the same wire format but different lifetimes.
6#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
7#[serde(deny_unknown_fields)]
8pub struct TraceContext {
9    pub traceparent: String,
10    #[serde(skip_serializing_if = "Option::is_none")]
11    pub tracestate: Option<String>,
12}
13impl TraceContext {
14    pub fn validate(&self) -> Result<()> {
15        crate::validate_traceparent(&self.traceparent)?;
16        if let Some(state) = &self.tracestate {
17            crate::validate_tracestate(state)?;
18        }
19        Ok(())
20    }
21
22    /// The immutable event creation context, never an active execution context.
23    pub fn from_event(event: &CloudEvent) -> Option<Self> {
24        event.traceparent().map(|parent| Self {
25            traceparent: parent.to_owned(),
26            tracestate: event
27                .value()
28                .get("tracestate")
29                .and_then(serde_json::Value::as_str)
30                .map(str::to_owned),
31        })
32    }
33}
34
35/// Connect existing instrumentation to a context provider without exposing its SDK.
36/// Set a parent and links before reading/materializing a span's context. `None`
37/// explicitly starts a root, independently of any ambient transport span.
38/// Hooks must be nonblocking and nonpanicking; returned carriers must validate.
39/// Never perform export I/O here: allocation hooks may run inside a transaction.
40pub trait TraceBridge: Send + Sync {
41    fn set_parent(&self, span: &tracing::Span, parent: Option<&TraceContext>);
42    fn add_link(&self, span: &tracing::Span, context: &TraceContext);
43    fn context(&self, span: &tracing::Span) -> Option<TraceContext>;
44}
45
46/// Disabled tracing retains ordinary diagnostic spans and creates no trace IDs.
47#[derive(Debug, Default)]
48pub struct NoopTraceBridge;
49impl TraceBridge for NoopTraceBridge {
50    fn set_parent(&self, _: &tracing::Span, _: Option<&TraceContext>) {}
51    fn add_link(&self, _: &tracing::Span, _: &TraceContext) {}
52    fn context(&self, _: &tracing::Span) -> Option<TraceContext> {
53        None
54    }
55}