1use std::collections::hash_map::RandomState;
4use std::fmt;
5use std::hash::{BuildHasher, Hasher};
6use std::sync::atomic::{AtomicU64, Ordering};
7
8#[derive(Clone, Copy, PartialEq, Eq, Hash)]
10pub struct TraceId(pub [u8; 16]);
11
12#[derive(Clone, Copy, PartialEq, Eq, Hash)]
14pub struct SpanId(pub [u8; 8]);
15
16impl TraceId {
17 pub fn random() -> Self {
19 let a = random_u64().to_be_bytes();
20 let b = random_u64().to_be_bytes();
21 let mut out = [0u8; 16];
22 out[..8].copy_from_slice(&a);
23 out[8..].copy_from_slice(&b);
24 if out == [0u8; 16] {
25 out[15] = 1;
26 }
27 Self(out)
28 }
29
30 pub fn to_hex(&self) -> String {
31 hex(&self.0)
32 }
33}
34
35impl SpanId {
36 pub fn random() -> Self {
38 let mut out = random_u64().to_be_bytes();
39 if out == [0u8; 8] {
40 out[7] = 1;
41 }
42 Self(out)
43 }
44
45 pub fn to_hex(&self) -> String {
46 hex(&self.0)
47 }
48}
49
50impl fmt::Debug for TraceId {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 write!(f, "TraceId({})", self.to_hex())
53 }
54}
55
56impl fmt::Debug for SpanId {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 write!(f, "SpanId({})", self.to_hex())
59 }
60}
61
62fn random_u64() -> u64 {
66 static COUNTER: AtomicU64 = AtomicU64::new(0);
67 let mut hasher = RandomState::new().build_hasher();
68 hasher.write_u64(COUNTER.fetch_add(1, Ordering::Relaxed));
69 hasher.write_u64(now_unix_nanos());
70 hasher.finish()
71}
72
73fn hex(bytes: &[u8]) -> String {
74 const DIGITS: &[u8; 16] = b"0123456789abcdef";
75 let mut out = String::with_capacity(bytes.len() * 2);
76 for b in bytes {
77 out.push(char::from(DIGITS.get(usize::from(b >> 4)).copied().unwrap_or(b'0')));
78 out.push(char::from(DIGITS.get(usize::from(b & 0x0f)).copied().unwrap_or(b'0')));
79 }
80 out
81}
82
83fn parse_hex<const N: usize>(text: &str) -> Option<[u8; N]> {
84 if text.len() != N * 2 || !text.bytes().all(|b| b.is_ascii_hexdigit()) {
85 return None;
86 }
87 let mut out = [0u8; N];
88 for (i, slot) in out.iter_mut().enumerate() {
89 let pair = text.get(i * 2..i * 2 + 2)?;
90 *slot = u8::from_str_radix(pair, 16).ok()?;
91 }
92 Some(out)
93}
94
95pub fn now_unix_nanos() -> u64 {
97 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
98 {
99 0
100 }
101 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
102 {
103 std::time::SystemTime::now()
104 .duration_since(std::time::UNIX_EPOCH)
105 .map(|d| u64::try_from(d.as_nanos()).unwrap_or(u64::MAX))
106 .unwrap_or(0)
107 }
108}
109
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub struct TraceParent {
113 pub trace_id: TraceId,
114 pub span_id: SpanId,
115 pub sampled: bool,
116}
117
118impl TraceParent {
119 pub fn parse(header: &str) -> Option<Self> {
122 let mut parts = header.trim().split('-');
123 let version = parts.next()?;
124 let trace = parts.next()?;
125 let span = parts.next()?;
126 let flags = parts.next()?;
127 if version.len() != 2 || version.eq_ignore_ascii_case("ff") || parse_hex::<1>(version).is_none() {
128 return None;
129 }
130 if version == "00" && parts.next().is_some() {
132 return None;
133 }
134 let trace_id = parse_hex::<16>(&trace.to_ascii_lowercase())?;
135 let span_id = parse_hex::<8>(&span.to_ascii_lowercase())?;
136 let flags = parse_hex::<1>(&flags.to_ascii_lowercase())?;
137 if trace_id == [0u8; 16] || span_id == [0u8; 8] {
138 return None;
139 }
140 Some(Self { trace_id: TraceId(trace_id), span_id: SpanId(span_id), sampled: flags[0] & 1 == 1 })
141 }
142
143 pub fn to_header(&self) -> String {
145 format!("00-{}-{}-{}", self.trace_id.to_hex(), self.span_id.to_hex(), if self.sampled { "01" } else { "00" })
146 }
147}
148
149#[derive(Clone, Debug, PartialEq)]
151pub enum AttrValue {
152 Str(String),
153 Int(i64),
154 Double(f64),
155 Bool(bool),
156}
157
158impl From<&str> for AttrValue {
159 fn from(v: &str) -> Self {
160 AttrValue::Str(v.to_owned())
161 }
162}
163impl From<String> for AttrValue {
164 fn from(v: String) -> Self {
165 AttrValue::Str(v)
166 }
167}
168impl From<i64> for AttrValue {
169 fn from(v: i64) -> Self {
170 AttrValue::Int(v)
171 }
172}
173impl From<u64> for AttrValue {
174 fn from(v: u64) -> Self {
175 AttrValue::Int(i64::try_from(v).unwrap_or(i64::MAX))
176 }
177}
178impl From<u32> for AttrValue {
179 fn from(v: u32) -> Self {
180 AttrValue::Int(i64::from(v))
181 }
182}
183impl From<bool> for AttrValue {
184 fn from(v: bool) -> Self {
185 AttrValue::Bool(v)
186 }
187}
188impl From<f64> for AttrValue {
189 fn from(v: f64) -> Self {
190 AttrValue::Double(v)
191 }
192}
193
194pub type Attributes = Vec<(String, AttrValue)>;
196
197#[derive(Clone, Copy, Debug, PartialEq, Eq)]
199pub enum SpanKind {
200 Internal,
201 Server,
202}
203
204impl SpanKind {
205 pub fn code(self) -> i64 {
207 match self {
208 SpanKind::Internal => 1,
209 SpanKind::Server => 2,
210 }
211 }
212}
213
214#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
216pub enum StatusCode {
217 #[default]
218 Unset,
219 Ok,
220 Error,
221}
222
223impl StatusCode {
224 pub fn code(self) -> i64 {
226 match self {
227 StatusCode::Unset => 0,
228 StatusCode::Ok => 1,
229 StatusCode::Error => 2,
230 }
231 }
232}
233
234#[derive(Clone, Debug, PartialEq)]
236pub struct SpanEvent {
237 pub time_unix_nano: u64,
238 pub name: String,
239 pub attributes: Attributes,
240}
241
242#[derive(Clone, Debug, PartialEq)]
244pub struct Span {
245 pub trace_id: TraceId,
246 pub span_id: SpanId,
247 pub parent_span_id: Option<SpanId>,
248 pub name: String,
249 pub kind: SpanKind,
250 pub start_unix_nano: u64,
251 pub end_unix_nano: u64,
252 pub attributes: Attributes,
253 pub events: Vec<SpanEvent>,
254 pub status: StatusCode,
255 pub status_message: String,
256 pub dropped_events: u32,
258}
259
260pub const MAX_EVENTS_PER_SPAN: usize = 128;
262
263impl Span {
264 pub fn new(trace_id: TraceId, parent: Option<SpanId>, name: impl Into<String>, start_unix_nano: u64) -> Self {
265 Self {
266 trace_id,
267 span_id: SpanId::random(),
268 parent_span_id: parent,
269 name: name.into(),
270 kind: SpanKind::Internal,
271 start_unix_nano,
272 end_unix_nano: start_unix_nano,
273 attributes: Vec::new(),
274 events: Vec::new(),
275 status: StatusCode::Unset,
276 status_message: String::new(),
277 dropped_events: 0,
278 }
279 }
280
281 pub fn set(&mut self, key: &str, value: impl Into<AttrValue>) {
283 let value = value.into();
284 match self.attributes.iter_mut().find(|(k, _)| k == key) {
285 Some(slot) => slot.1 = value,
286 None => self.attributes.push((key.to_owned(), value)),
287 }
288 }
289
290 pub fn attr(&self, key: &str) -> Option<&AttrValue> {
292 self.attributes.iter().find(|(k, _)| k == key).map(|(_, v)| v)
293 }
294
295 pub fn add_event(&mut self, name: &str, time_unix_nano: u64, attributes: Attributes) {
297 if self.events.len() >= MAX_EVENTS_PER_SPAN {
298 self.dropped_events = self.dropped_events.saturating_add(1);
299 return;
300 }
301 self.events.push(SpanEvent { time_unix_nano, name: name.to_owned(), attributes });
302 }
303
304 pub fn error(&mut self, message: &str) {
306 self.status = StatusCode::Error;
307 self.status_message = truncate(message, 1024);
308 }
309}
310
311pub fn truncate(text: &str, max: usize) -> String {
313 if text.len() <= max {
314 return text.to_owned();
315 }
316 let mut end = max;
317 while end > 0 && !text.is_char_boundary(end) {
318 end -= 1;
319 }
320 let mut out = text.get(..end).unwrap_or_default().to_owned();
321 out.push('…');
322 out
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328
329 #[test]
330 fn ids_are_random_and_non_zero() {
331 let a = TraceId::random();
332 let b = TraceId::random();
333 assert_ne!(a, b);
334 assert_ne!(a.0, [0; 16]);
335 assert_eq!(a.to_hex().len(), 32);
336 assert_eq!(SpanId::random().to_hex().len(), 16);
337 }
338
339 #[test]
340 fn traceparent_parsing() {
341 let tp = TraceParent::parse("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01").unwrap();
342 assert_eq!(tp.trace_id.to_hex(), "4bf92f3577b34da6a3ce929d0e0e4736");
343 assert_eq!(tp.span_id.to_hex(), "00f067aa0ba902b7");
344 assert!(tp.sampled);
345 assert_eq!(tp.to_header(), "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01");
346 assert!(
347 TraceParent::parse("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00").is_some_and(|t| !t.sampled)
348 );
349 for bad in [
350 "",
351 "ff-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
352 "00-00000000000000000000000000000000-00f067aa0ba902b7-01",
353 "00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000000-01",
354 "00-4bf92f3577b34da6a3ce929d0e0e473-00f067aa0ba902b7-01",
355 "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01-extra",
356 "00-xyz",
357 ] {
358 assert!(TraceParent::parse(bad).is_none(), "{bad}");
359 }
360 }
361
362 #[test]
363 fn truncate_respects_char_boundaries() {
364 assert_eq!(truncate("héllo", 2), "h…");
365 assert_eq!(truncate("abc", 5), "abc");
366 }
367}