Skip to main content

weida_core/
trace.rs

1//! W3C Trace Context propagation.
2//!
3//! v0 propagates `traceparent`/`tracestate` in transfer metadata and logs the
4//! ids through `tracing` (master doc ยง58); an OpenTelemetry SDK is outside this
5//! crate. This module is the codec only: it never generates identifiers,
6//! because randomness belongs to the runtime, not to the model.
7
8use std::fmt;
9
10/// Wire cap for the DATA `traceparent` field, in bytes.
11pub const MAX_TRACEPARENT_BYTES: usize = 128;
12
13/// Wire cap for the DATA `tracestate` field, in bytes.
14pub const MAX_TRACESTATE_BYTES: usize = 512;
15
16/// Length of a `traceparent` value for version `00`.
17const TRACEPARENT_LEN: usize = 55;
18
19/// The `sampled` flag bit.
20pub const FLAG_SAMPLED: u8 = 0x01;
21
22/// A W3C Trace Context `traceparent`.
23#[derive(Clone, Copy, PartialEq, Eq, Hash)]
24pub struct TraceContext {
25    /// 16-byte trace identifier; never all zero.
26    pub trace_id: [u8; 16],
27    /// 8-byte span identifier of the sender's span; never all zero.
28    pub span_id: [u8; 8],
29    /// Trace flags byte; bit 0 is `sampled`.
30    pub flags: u8,
31}
32
33/// Why a `traceparent` value was rejected.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum TraceError {
36    /// Not exactly 55 bytes (the only length defined for version `00`).
37    Length,
38    /// Hyphens are not at offsets 2, 35 and 52.
39    Layout,
40    /// A field contained a byte that is not a lowercase hex digit.
41    NotHex,
42    /// Version `ff` is forbidden by the specification.
43    ForbiddenVersion,
44    /// `trace_id` or `span_id` was all zero.
45    ZeroId,
46}
47
48impl fmt::Display for TraceError {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        match self {
51            TraceError::Length => f.write_str("traceparent must be exactly 55 bytes"),
52            TraceError::Layout => f.write_str("traceparent field layout is malformed"),
53            TraceError::NotHex => f.write_str("traceparent contains a non-hex-digit byte"),
54            TraceError::ForbiddenVersion => f.write_str("traceparent version ff is forbidden"),
55            TraceError::ZeroId => f.write_str("traceparent trace-id/span-id must not be all zero"),
56        }
57    }
58}
59
60impl std::error::Error for TraceError {}
61
62const fn hex_val(b: u8) -> Option<u8> {
63    match b {
64        b'0'..=b'9' => Some(b - b'0'),
65        // The specification mandates lowercase; uppercase is rejected rather
66        // than normalised, because hostile input gets no leniency.
67        b'a'..=b'f' => Some(b - b'a' + 10),
68        _ => None,
69    }
70}
71
72fn decode_hex(src: &[u8], dst: &mut [u8]) -> Result<(), TraceError> {
73    debug_assert_eq!(src.len(), dst.len() * 2);
74    // `as_chunks` over `chunks_exact`: the pair width is a constant, so the
75    // compiler gets `[u8; 2]` and the indexing below needs no bounds checks.
76    let (pairs, _remainder) = src.as_chunks::<2>();
77    for (out, &[hi, lo]) in dst.iter_mut().zip(pairs) {
78        let hi = hex_val(hi).ok_or(TraceError::NotHex)?;
79        let lo = hex_val(lo).ok_or(TraceError::NotHex)?;
80        *out = (hi << 4) | lo;
81    }
82    Ok(())
83}
84
85/// Writes `bytes` as lowercase hex into `dst`, which holds exactly two digits
86/// per byte.
87fn put_hex(dst: &mut [u8], bytes: &[u8]) {
88    const HEX: &[u8; 16] = b"0123456789abcdef";
89    debug_assert_eq!(dst.len(), bytes.len() * 2);
90    let (pairs, _remainder) = dst.as_chunks_mut::<2>();
91    for (pair, b) in pairs.iter_mut().zip(bytes) {
92        *pair = [HEX[(*b >> 4) as usize], HEX[(*b & 0x0f) as usize]];
93    }
94}
95
96impl TraceContext {
97    /// Builds a context from raw identifiers.
98    ///
99    /// Returns `None` if either identifier is all zero, which the W3C
100    /// specification forbids.
101    pub const fn new(trace_id: [u8; 16], span_id: [u8; 8], flags: u8) -> Option<TraceContext> {
102        if is_zero_16(&trace_id) || is_zero_8(&span_id) {
103            return None;
104        }
105        Some(TraceContext {
106            trace_id,
107            span_id,
108            flags,
109        })
110    }
111
112    /// Parses a `traceparent` header value.
113    ///
114    /// Only version `00` layout is accepted: exactly 55 bytes,
115    /// `vv-<32 hex>-<16 hex>-<2 hex>`, lowercase hex, version not `ff`, neither
116    /// identifier all zero.
117    pub fn parse_traceparent(value: &str) -> Result<TraceContext, TraceError> {
118        let b = value.as_bytes();
119        if b.len() != TRACEPARENT_LEN {
120            return Err(TraceError::Length);
121        }
122        if b[2] != b'-' || b[35] != b'-' || b[52] != b'-' {
123            return Err(TraceError::Layout);
124        }
125
126        let mut version = [0u8; 1];
127        decode_hex(&b[0..2], &mut version)?;
128        if version[0] == 0xff {
129            return Err(TraceError::ForbiddenVersion);
130        }
131
132        let mut trace_id = [0u8; 16];
133        decode_hex(&b[3..35], &mut trace_id)?;
134        let mut span_id = [0u8; 8];
135        decode_hex(&b[36..52], &mut span_id)?;
136        let mut flags = [0u8; 1];
137        decode_hex(&b[53..55], &mut flags)?;
138
139        TraceContext::new(trace_id, span_id, flags[0]).ok_or(TraceError::ZeroId)
140    }
141
142    /// Formats the context as a version-`00` `traceparent` value.
143    pub fn to_traceparent(&self) -> String {
144        self.render().as_str().to_owned()
145    }
146
147    fn render(&self) -> Rendered {
148        let mut out = [b'-'; TRACEPARENT_LEN];
149        out[0] = b'0';
150        out[1] = b'0';
151        put_hex(&mut out[3..35], &self.trace_id);
152        put_hex(&mut out[36..52], &self.span_id);
153        put_hex(&mut out[53..55], &[self.flags]);
154        Rendered(out)
155    }
156
157    /// The trace id as 32 lowercase hex digits, for log fields.
158    pub fn trace_id_hex(&self) -> String {
159        let mut s = String::with_capacity(32);
160        push_hex(&mut s, &self.trace_id);
161        s
162    }
163
164    /// The span id as 16 lowercase hex digits, for log fields.
165    pub fn span_id_hex(&self) -> String {
166        let mut s = String::with_capacity(16);
167        push_hex(&mut s, &self.span_id);
168        s
169    }
170
171    /// True if the `sampled` flag is set.
172    pub const fn is_sampled(&self) -> bool {
173        self.flags & FLAG_SAMPLED != 0
174    }
175
176    /// Same trace, new span. Returns `None` for an all-zero span id.
177    pub const fn with_span_id(&self, span_id: [u8; 8]) -> Option<TraceContext> {
178        TraceContext::new(self.trace_id, span_id, self.flags)
179    }
180}
181
182const fn is_zero_16(v: &[u8; 16]) -> bool {
183    let mut i = 0;
184    while i < 16 {
185        if v[i] != 0 {
186            return false;
187        }
188        i += 1;
189    }
190    true
191}
192
193const fn is_zero_8(v: &[u8; 8]) -> bool {
194    let mut i = 0;
195    while i < 8 {
196        if v[i] != 0 {
197            return false;
198        }
199        i += 1;
200    }
201    true
202}
203
204fn push_hex(s: &mut String, bytes: &[u8]) {
205    const HEX: &[u8; 16] = b"0123456789abcdef";
206    for b in bytes {
207        s.push(HEX[(*b >> 4) as usize] as char);
208        s.push(HEX[(*b & 0x0f) as usize] as char);
209    }
210}
211
212impl fmt::Display for TraceContext {
213    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214        f.write_str(self.render().as_str())
215    }
216}
217
218/// A rendered `traceparent`: fixed size, lowercase ASCII by construction.
219struct Rendered([u8; TRACEPARENT_LEN]);
220
221impl Rendered {
222    fn as_str(&self) -> &str {
223        core::str::from_utf8(&self.0).expect("a traceparent is ascii")
224    }
225}
226
227impl fmt::Debug for TraceContext {
228    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229        write!(f, "TraceContext({self})")
230    }
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    const VALID: &str = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
238
239    #[test]
240    fn parses_the_w3c_example() {
241        let t = TraceContext::parse_traceparent(VALID).unwrap();
242        assert_eq!(t.trace_id_hex(), "4bf92f3577b34da6a3ce929d0e0e4736");
243        assert_eq!(t.span_id_hex(), "00f067aa0ba902b7");
244        assert_eq!(t.flags, 1);
245        assert!(t.is_sampled());
246    }
247
248    #[test]
249    fn format_parse_roundtrip() {
250        let t = TraceContext::parse_traceparent(VALID).unwrap();
251        assert_eq!(t.to_traceparent(), VALID);
252        assert_eq!(
253            TraceContext::parse_traceparent(&t.to_traceparent()).unwrap(),
254            t
255        );
256    }
257
258    #[test]
259    fn formats_a_cleared_flags_byte() {
260        let t = TraceContext::new([0x11; 16], [0x22; 8], 0).unwrap();
261        assert_eq!(
262            t.to_traceparent(),
263            "00-11111111111111111111111111111111-2222222222222222-00"
264        );
265        assert!(!t.is_sampled());
266    }
267
268    #[test]
269    fn rejects_invalid_values() {
270        let cases = [
271            (
272                "ff-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
273                TraceError::ForbiddenVersion,
274            ),
275            (
276                "00-00000000000000000000000000000000-00f067aa0ba902b7-01",
277                TraceError::ZeroId,
278            ),
279            (
280                "00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000000-01",
281                TraceError::ZeroId,
282            ),
283            (
284                "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-0",
285                TraceError::Length,
286            ),
287            (
288                "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-011",
289                TraceError::Length,
290            ),
291            ("", TraceError::Length),
292            (
293                "00_4bf92f3577b34da6a3ce929d0e0e4736_00f067aa0ba902b7_01",
294                TraceError::Layout,
295            ),
296            (
297                "00-4bf92f3577b34da6a3ce929d0e0e4736+00f067aa0ba902b7-01",
298                TraceError::Layout,
299            ),
300            (
301                "00-4BF92F3577B34DA6A3CE929D0E0E4736-00f067aa0ba902b7-01",
302                TraceError::NotHex,
303            ),
304            (
305                "00-4bf92f3577b34da6a3ce929d0e0e473g-00f067aa0ba902b7-01",
306                TraceError::NotHex,
307            ),
308        ];
309        for (input, want) in cases {
310            assert_eq!(
311                TraceContext::parse_traceparent(input),
312                Err(want),
313                "input {input:?}"
314            );
315        }
316    }
317
318    #[test]
319    fn future_versions_parse_with_the_v00_layout() {
320        // Version 01 with the version-00 layout is still readable; only `ff`
321        // is forbidden outright.
322        let t = TraceContext::parse_traceparent(
323            "01-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
324        )
325        .unwrap();
326        assert_eq!(t.span_id_hex(), "00f067aa0ba902b7");
327    }
328
329    #[test]
330    fn formatted_value_fits_the_wire_cap() {
331        let t = TraceContext::parse_traceparent(VALID).unwrap();
332        assert!(t.to_traceparent().len() <= MAX_TRACEPARENT_BYTES);
333        assert_eq!(t.to_traceparent().len(), TRACEPARENT_LEN);
334    }
335
336    #[test]
337    fn zero_ids_are_unconstructable() {
338        assert!(TraceContext::new([0; 16], [1; 8], 0).is_none());
339        assert!(TraceContext::new([1; 16], [0; 8], 0).is_none());
340        let t = TraceContext::new([1; 16], [1; 8], 0).unwrap();
341        assert!(t.with_span_id([0; 8]).is_none());
342        assert_eq!(t.with_span_id([9; 8]).unwrap().trace_id, [1; 16]);
343    }
344}