1use relay_protocol::{
2 Annotated, Array, Empty, Error, FromValue, HexId, IntoValue, Meta, Object, Remark, RemarkType,
3 SkipSerialization, Val, Value,
4};
5use serde::Serializer;
6use std::fmt;
7use std::ops::Deref;
8use std::str::FromStr;
9use uuid::Uuid;
10
11use crate::processor::ProcessValue;
12use crate::protocol::{OperationType, OriginType, SpanData, SpanLink, SpanStatus};
13
14#[derive(Clone, Copy, PartialEq, Empty, ProcessValue)]
30pub struct TraceId(Uuid);
31
32impl TraceId {
33 pub fn random() -> Self {
35 Self(Uuid::new_v4())
36 }
37
38 pub fn try_from_or_random<T>(value: T) -> Annotated<Self>
42 where
43 T: TryInto<Self> + AsRef<[u8]> + Copy,
44 {
45 value.try_into().map(Annotated::new).unwrap_or_else(|_| {
46 let mut meta = Meta::default();
47 let rule_id = match value.as_ref().is_empty() {
48 true => "trace_id.missing",
49 false => "trace_id.invalid",
50 };
51 meta.add_remark(Remark::new(RemarkType::Substituted, rule_id));
52 Annotated(Some(TraceId::random()), meta)
53 })
54 }
55
56 pub fn try_from_slice_or_random(value: &[u8]) -> Annotated<Self> {
58 Self::try_from_or_random(value)
59 }
60
61 pub fn try_from_str_or_random(value: &str) -> Annotated<Self> {
63 Self::try_from_or_random(value)
64 }
65}
66
67relay_common::impl_str_serde!(TraceId, "a trace identifier");
68
69impl FromStr for TraceId {
70 type Err = Error;
71
72 fn from_str(s: &str) -> Result<Self, Self::Err> {
73 Uuid::parse_str(s)
74 .map(Into::into)
75 .map_err(|_| Error::invalid("the trace id is not valid"))
76 }
77}
78
79impl TryFrom<&str> for TraceId {
80 type Error = Error;
81
82 fn try_from(value: &str) -> Result<Self, Self::Error> {
83 value.parse()
84 }
85}
86
87impl TryFrom<&[u8]> for TraceId {
88 type Error = Error;
89
90 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
91 let uuid =
92 Uuid::from_slice(value).map_err(|_| Error::invalid("the trace id is not valid"))?;
93 Ok(Self(uuid))
94 }
95}
96
97impl fmt::Display for TraceId {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 write!(f, "{}", self.0.as_simple())
100 }
101}
102
103impl fmt::Debug for TraceId {
104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105 write!(f, "TraceId(\"{}\")", self.0.as_simple())
106 }
107}
108
109impl From<Uuid> for TraceId {
110 fn from(uuid: Uuid) -> Self {
111 TraceId(uuid)
112 }
113}
114
115impl Deref for TraceId {
116 type Target = Uuid;
117
118 fn deref(&self) -> &Self::Target {
119 &self.0
120 }
121}
122
123impl FromValue for TraceId {
124 fn from_value(value: Annotated<Value>) -> Annotated<Self>
125 where
126 Self: Sized,
127 {
128 match value {
129 Annotated(Some(Value::String(value)), mut meta) => match value.parse() {
130 Ok(trace_id) => Annotated(Some(trace_id), meta),
131 Err(_) => {
132 meta.add_error(Error::invalid("not a valid trace id"));
133 meta.set_original_value(Some(value));
134 Annotated(None, meta)
135 }
136 },
137 Annotated(None, meta) => Annotated(None, meta),
138 Annotated(Some(value), mut meta) => {
139 meta.add_error(Error::expected("trace id"));
140 meta.set_original_value(Some(value));
141 Annotated(None, meta)
142 }
143 }
144 }
145}
146
147impl IntoValue for TraceId {
148 fn into_value(self) -> Value
149 where
150 Self: Sized,
151 {
152 Value::String(self.to_string())
153 }
154
155 fn serialize_payload<S>(&self, s: S, _behavior: SkipSerialization) -> Result<S::Ok, S::Error>
156 where
157 Self: Sized,
158 S: Serializer,
159 {
160 s.collect_str(self)
161 }
162}
163
164#[derive(Clone, Copy, Default, Eq, Hash, PartialEq, Ord, PartialOrd)]
167pub struct SpanId([u8; 8]);
168
169relay_common::impl_str_serde!(SpanId, "a span identifier");
170
171impl FromStr for SpanId {
172 type Err = Error;
173
174 fn from_str(s: &str) -> Result<Self, Self::Err> {
175 match u64::from_str_radix(s, 16) {
176 Ok(id) if s.len() == 16 && id > 0 => Ok(Self(id.to_be_bytes())),
177 _ => Err(Error::invalid("not a valid span id")),
178 }
179 }
180}
181
182impl TryFrom<&[u8]> for SpanId {
183 type Error = Error;
184
185 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
186 match <[u8; 8]>::try_from(value) {
187 Ok(bytes) if !bytes.iter().all(|&x| x == 0) => Ok(Self(bytes)),
188 _ => Err(Error::invalid("not a valid span id")),
189 }
190 }
191}
192
193impl fmt::Debug for SpanId {
194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195 write!(f, "SpanId(\"")?;
196 for b in self.0 {
197 write!(f, "{b:02x}")?;
198 }
199 write!(f, "\")")
200 }
201}
202
203impl fmt::Display for SpanId {
204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 for b in self.0 {
206 write!(f, "{b:02x}")?;
207 }
208 Ok(())
209 }
210}
211
212impl FromValue for SpanId {
213 fn from_value(value: Annotated<Value>) -> Annotated<Self> {
214 match value {
215 Annotated(Some(Value::String(value)), mut meta) => match value.parse() {
216 Ok(span_id) => Annotated::new(span_id),
217 Err(e) => {
218 meta.add_error(e);
219 meta.set_original_value(Some(value));
220 Annotated(None, meta)
221 }
222 },
223 Annotated(None, meta) => Annotated(None, meta),
224 Annotated(Some(value), mut meta) => {
225 meta.add_error(Error::expected("span id"));
226 meta.set_original_value(Some(value));
227 Annotated(None, meta)
228 }
229 }
230 }
231}
232
233impl Empty for SpanId {
234 fn is_empty(&self) -> bool {
235 false
236 }
237}
238
239impl IntoValue for SpanId {
240 fn into_value(self) -> Value
241 where
242 Self: Sized,
243 {
244 Value::String(self.to_string())
245 }
246
247 fn serialize_payload<S>(&self, s: S, _behavior: SkipSerialization) -> Result<S::Ok, S::Error>
248 where
249 Self: Sized,
250 S: serde::Serializer,
251 {
252 s.collect_str(self)
253 }
254}
255
256impl ProcessValue for SpanId {}
257
258impl std::ops::Deref for SpanId {
259 type Target = [u8];
260
261 fn deref(&self) -> &Self::Target {
262 &self.0
263 }
264}
265
266impl<'a> From<&'a SpanId> for Val<'a> {
267 fn from(value: &'a SpanId) -> Self {
268 Val::HexId(HexId(&value.0))
269 }
270}
271
272#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
274#[metastructure(process_func = "process_trace_context")]
275pub struct TraceContext {
276 #[metastructure(required = true)]
278 pub trace_id: Annotated<TraceId>,
279
280 #[metastructure(required = true)]
282 pub span_id: Annotated<SpanId>,
283
284 pub parent_span_id: Annotated<SpanId>,
286
287 #[metastructure(max_chars = 128)]
289 pub op: Annotated<OperationType>,
290
291 pub status: Annotated<SpanStatus>,
294
295 pub exclusive_time: Annotated<f64>,
298
299 pub client_sample_rate: Annotated<f64>,
304
305 #[metastructure(max_chars = 128, allow_chars = "a-zA-Z0-9_.")]
307 pub origin: Annotated<OriginType>,
308
309 pub sampled: Annotated<bool>,
313
314 #[metastructure(pii = "maybe", skip_serialization = "null")]
316 pub data: Annotated<SpanData>,
317
318 #[metastructure(pii = "maybe", skip_serialization = "null")]
320 pub links: Annotated<Array<SpanLink>>,
321
322 #[metastructure(additional_properties, retain = true, pii = "maybe")]
324 pub other: Object<Value>,
325}
326
327impl super::DefaultContext for TraceContext {
328 fn default_key() -> &'static str {
329 "trace"
330 }
331
332 fn from_context(context: super::Context) -> Option<Self> {
333 match context {
334 super::Context::Trace(c) => Some(*c),
335 _ => None,
336 }
337 }
338
339 fn cast(context: &super::Context) -> Option<&Self> {
340 match context {
341 super::Context::Trace(c) => Some(c),
342 _ => None,
343 }
344 }
345
346 fn cast_mut(context: &mut super::Context) -> Option<&mut Self> {
347 match context {
348 super::Context::Trace(c) => Some(c),
349 _ => None,
350 }
351 }
352
353 fn into_context(self) -> super::Context {
354 super::Context::Trace(Box::new(self))
355 }
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361 use crate::protocol::{Context, Route};
362
363 #[test]
364 fn test_trace_id_as_u128() {
365 let trace_id: TraceId = "4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap();
367 assert_eq!(trace_id.as_u128(), 0x4c79f60c11214eb38604f4ae0781bfb2);
368
369 let empty_trace_id: Result<TraceId, Error> = "".parse();
371 assert!(empty_trace_id.is_err());
372
373 let short_trace_id: Result<TraceId, Error> = "4c79f60c11214eb38604f4ae0781bfb".parse(); assert!(short_trace_id.is_err());
376
377 let long_trace_id: Result<TraceId, Error> = "4c79f60c11214eb38604f4ae0781bfb2a".parse(); assert!(long_trace_id.is_err());
379
380 let invalid_trace_id: Result<TraceId, Error> = "4c79f60c11214eb38604f4ae0781bfbg".parse(); assert!(invalid_trace_id.is_err());
383 }
384
385 #[test]
386 fn test_trace_context_roundtrip() {
387 let json = r#"{
388 "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
389 "span_id": "fa90fdead5f74052",
390 "parent_span_id": "fa90fdead5f74053",
391 "op": "http",
392 "status": "ok",
393 "exclusive_time": 0.0,
394 "client_sample_rate": 0.5,
395 "origin": "auto.http",
396 "data": {
397 "route": {
398 "name": "/users",
399 "params": {
400 "tok": "test"
401 },
402 "custom_field": "something"
403 },
404 "custom_field_empty": ""
405 },
406 "links": [
407 {
408 "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
409 "span_id": "ea90fdead5f74052",
410 "sampled": true,
411 "attributes": {
412 "sentry.link.type": "previous_trace"
413 }
414 }
415 ],
416 "other": "value",
417 "type": "trace"
418}"#;
419 let context = Annotated::new(Context::Trace(Box::new(TraceContext {
420 trace_id: Annotated::new("4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap()),
421 span_id: Annotated::new("fa90fdead5f74052".parse().unwrap()),
422 parent_span_id: Annotated::new("fa90fdead5f74053".parse().unwrap()),
423 op: Annotated::new("http".into()),
424 status: Annotated::new(SpanStatus::Ok),
425 exclusive_time: Annotated::new(0.0),
426 client_sample_rate: Annotated::new(0.5),
427 origin: Annotated::new("auto.http".to_owned()),
428 data: Annotated::new(SpanData {
429 route: Annotated::new(Route {
430 name: Annotated::new("/users".into()),
431 params: Annotated::new({
432 let mut map = Object::new();
433 map.insert(
434 "tok".to_owned(),
435 Annotated::new(Value::String("test".into())),
436 );
437 map
438 }),
439 other: Object::from([(
440 "custom_field".into(),
441 Annotated::new(Value::String("something".into())),
442 )]),
443 }),
444 other: Object::from([(
445 "custom_field_empty".into(),
446 Annotated::new(Value::String("".into())),
447 )]),
448 ..Default::default()
449 }),
450 links: Annotated::new(Array::from(vec![Annotated::new(SpanLink {
451 trace_id: Annotated::new("4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap()),
452 span_id: Annotated::new("ea90fdead5f74052".parse().unwrap()),
453 sampled: Annotated::new(true),
454 attributes: Annotated::new({
455 let mut map: std::collections::BTreeMap<String, Annotated<Value>> =
456 Object::new();
457 map.insert(
458 "sentry.link.type".into(),
459 Annotated::new(Value::String("previous_trace".into())),
460 );
461 map
462 }),
463 ..Default::default()
464 })])),
465 other: {
466 let mut map = Object::new();
467 map.insert(
468 "other".to_owned(),
469 Annotated::new(Value::String("value".to_owned())),
470 );
471 map
472 },
473 sampled: Annotated::empty(),
474 })));
475
476 assert_eq!(context, Annotated::from_json(json).unwrap());
477 assert_eq!(json, context.to_json_pretty().unwrap());
478 }
479
480 #[test]
481 fn test_trace_context_normalization() {
482 let json = r#"{
483 "trace_id": "4C79F60C11214EB38604F4AE0781BFB2",
484 "span_id": "FA90FDEAD5F74052",
485 "type": "trace"
486}"#;
487 let context = Annotated::new(Context::Trace(Box::new(TraceContext {
488 trace_id: Annotated::new("4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap()),
489 span_id: Annotated::new("fa90fdead5f74052".parse().unwrap()),
490 ..Default::default()
491 })));
492
493 assert_eq!(context, Annotated::from_json(json).unwrap());
494 }
495
496 #[test]
497 fn test_trace_id_formatting() {
498 let test_cases = [
499 (
501 r#"{
502 "trace_id": "b1e2a9dc9b8e4cd0af0e80e6b83b56e6",
503 "type": "trace"
504}"#,
505 "b1e2a9dc-9b8e-4cd0-af0e-80e6b83b56e6",
506 true,
507 ),
508 (
510 r#"{
511 "trace_id": "b1e2a9dc-9b8e-4cd0-af0e-80e6b83b56e6",
512 "type": "trace"
513}"#,
514 "b1e2a9dc9b8e4cd0af0e80e6b83b56e6",
515 false,
516 ),
517 (
519 r#"{
520 "trace_id": "b1e2a9dc9b8e4cd0af0e80e6b83b56e6",
521 "type": "trace"
522}"#,
523 "B1E2A9DC9B8E4CD0AF0E80E6B83B56E6",
524 true,
525 ),
526 (
528 r#"{
529 "trace_id": "B1E2A9DC9B8E4CD0AF0E80E6B83B56E6",
530 "type": "trace"
531}"#,
532 "b1e2a9dc9b8e4cd0af0e80e6b83b56e6",
533 false,
534 ),
535 ];
536
537 for (json, trace_id_str, is_to_json) in test_cases {
538 let context = Annotated::new(Context::Trace(Box::new(TraceContext {
539 trace_id: Annotated::new(trace_id_str.parse().unwrap()),
540 ..Default::default()
541 })));
542
543 if is_to_json {
544 assert_eq!(json, context.to_json_pretty().unwrap());
545 } else {
546 assert_eq!(context, Annotated::from_json(json).unwrap());
547 }
548 }
549 }
550
551 #[test]
552 fn test_trace_context_with_routes() {
553 let json = r#"{
554 "trace_id": "4C79F60C11214EB38604F4AE0781BFB2",
555 "span_id": "FA90FDEAD5F74052",
556 "type": "trace",
557 "data": {
558 "route": "HomeRoute"
559 }
560}"#;
561 let context = Annotated::new(Context::Trace(Box::new(TraceContext {
562 trace_id: Annotated::new("4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap()),
563 span_id: Annotated::new("fa90fdead5f74052".parse().unwrap()),
564 data: Annotated::new(SpanData {
565 route: Annotated::new(Route {
566 name: Annotated::new("HomeRoute".into()),
567 ..Default::default()
568 }),
569 ..Default::default()
570 }),
571 ..Default::default()
572 })));
573
574 assert_eq!(context, Annotated::from_json(json).unwrap());
575 }
576
577 #[test]
578 fn test_try_from_or_random() {
579 let valid_str = "4c79f60c11214eb38604f4ae0781bfb2";
581 let annotated = TraceId::try_from_str_or_random(valid_str);
582 assert_eq!(
583 annotated.value().unwrap().as_u128(),
584 0x4c79f60c11214eb38604f4ae0781bfb2
585 );
586 assert!(annotated.meta().is_empty());
587
588 let invalid_str = "invalid";
590 let annotated = TraceId::try_from_str_or_random(invalid_str);
591 assert!(annotated.value().is_some()); assert_ne!(annotated.value().unwrap().as_u128(), 0);
593 assert_eq!(annotated.meta().iter_remarks().count(), 1);
594 let remark = annotated.meta().iter_remarks().next().unwrap();
595 assert_eq!(remark.rule_id(), "trace_id.invalid");
596
597 let empty_str = "";
599 let annotated = TraceId::try_from_str_or_random(empty_str);
600 assert!(annotated.value().is_some());
601 let remark = annotated.meta().iter_remarks().next().unwrap();
602 assert_eq!(remark.rule_id(), "trace_id.missing");
603
604 let valid_bytes = b"\x4c\x79\xf6\x0c\x11\x21\x4e\xb3\x86\x04\xf4\xae\x07\x81\xbf\xb2";
606 let annotated = TraceId::try_from_slice_or_random(valid_bytes.as_slice());
607 assert_eq!(
608 annotated.value().unwrap().as_u128(),
609 0x4c79f60c11214eb38604f4ae0781bfb2
610 );
611
612 let invalid_bytes = b"\x00";
614 let annotated = TraceId::try_from_slice_or_random(invalid_bytes.as_slice());
615 let remark = annotated.meta().iter_remarks().next().unwrap();
616 assert_eq!(remark.rule_id(), "trace_id.invalid");
617 }
618}