1use std::convert::Infallible;
2use std::fmt;
3use std::ops::{Deref, DerefMut};
4use std::str::FromStr;
5
6use relay_protocol::{
7 Annotated, Array, Empty, ErrorKind, FromValue, IntoValue, Object, SkipSerialization, Value,
8};
9use serde::{Deserialize, Serialize};
10
11use crate::processor::ProcessValue;
12use crate::protocol::{Addr, LockReason, NativeImagePath, RegVal};
13
14#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
19#[metastructure(process_func = "process_frame", value_type = "Frame")]
20pub struct Frame {
21 #[metastructure(max_chars = 512, max_chars_allowance = 20)]
26 #[metastructure(skip_serialization = "empty")]
27 pub function: Annotated<String>,
28
29 #[metastructure(max_chars = 512, max_chars_allowance = 20)]
45 #[metastructure(skip_serialization = "empty")]
46 pub raw_function: Annotated<String>,
47
48 #[metastructure(max_chars = 512)]
56 pub symbol: Annotated<String>,
57
58 #[metastructure(skip_serialization = "empty", pii = "maybe")]
63 pub module: Annotated<String>,
65
66 #[metastructure(skip_serialization = "empty")]
71 pub package: Annotated<String>,
73
74 #[metastructure(max_chars = 256, max_chars_allowance = 40)]
76 #[metastructure(skip_serialization = "empty", pii = "maybe")]
77 pub filename: Annotated<NativeImagePath>,
78
79 #[metastructure(skip_serialization = "empty", pii = "maybe")]
87 pub file_revision: Annotated<String>,
88
89 #[metastructure(max_chars = 256, max_chars_allowance = 40)]
91 #[metastructure(skip_serialization = "empty", pii = "maybe")]
92 pub abs_path: Annotated<NativeImagePath>,
93
94 #[metastructure(skip_serialization = "null")]
96 pub lineno: Annotated<u64>,
97
98 #[metastructure(skip_serialization = "null")]
100 pub colno: Annotated<u64>,
101
102 #[metastructure(skip_serialization = "empty")]
107 pub platform: Annotated<String>,
108
109 #[metastructure(skip_serialization = "empty")]
111 pub pre_context: Annotated<Array<String>>,
112
113 #[metastructure(skip_serialization = "null")]
115 pub context_line: Annotated<String>,
116
117 #[metastructure(skip_serialization = "null")]
119 pub parent_index: Annotated<i64>,
120
121 #[metastructure(skip_serialization = "null")]
123 pub sample_count: Annotated<u64>,
124
125 #[metastructure(skip_serialization = "empty")]
127 pub post_context: Annotated<Array<String>>,
128
129 #[metastructure(skip_serialization = "null")]
135 pub in_app: Annotated<bool>,
136
137 #[metastructure(pii = "true", max_depth = 5, max_bytes = 2048)]
140 pub vars: Annotated<FrameVars>,
141
142 #[metastructure(omit_from_schema)]
144 #[metastructure(skip_serialization = "empty")]
145 pub data: Annotated<FrameData>,
146
147 #[metastructure(skip_serialization = "null")]
149 pub image_addr: Annotated<Addr>,
150
151 #[metastructure(skip_serialization = "null")]
158 pub instruction_addr: Annotated<Addr>,
159
160 #[metastructure(skip_serialization = "empty")]
170 pub addr_mode: Annotated<String>,
171
172 #[metastructure(skip_serialization = "empty")]
176 pub function_id: Annotated<Addr>,
177
178 #[metastructure(skip_serialization = "null")]
183 pub symbol_addr: Annotated<Addr>,
184
185 #[metastructure(max_chars = 128)]
187 #[metastructure(omit_from_schema)]
188 pub trust: Annotated<String>,
189
190 #[metastructure(max_chars = 128)]
192 #[metastructure(omit_from_schema)]
193 pub lang: Annotated<String>,
194
195 #[metastructure(skip_serialization = "null")]
204 pub stack_start: Annotated<bool>,
205
206 #[metastructure(skip_serialization = "null")]
208 pub lock: Annotated<LockReason>,
209
210 #[metastructure(additional_properties)]
212 pub other: Object<Value>,
213}
214
215#[derive(Clone, Debug, Default, PartialEq, Empty, IntoValue, ProcessValue)]
217pub struct FrameVars(#[metastructure(skip_serialization = "empty")] pub Object<Value>);
218
219#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
223pub struct FrameData {
224 #[metastructure(max_chars = 256, max_chars_allowance = 40)]
226 sourcemap: Annotated<String>,
227 #[metastructure(max_chars = 256, max_chars_allowance = 20)]
229 orig_function: Annotated<String>,
230 #[metastructure(max_chars = 256, max_chars_allowance = 40)]
232 orig_filename: Annotated<String>,
233 orig_lineno: Annotated<u64>,
235 orig_colno: Annotated<u64>,
237 orig_in_app: Annotated<i64>,
246 #[metastructure(additional_properties)]
248 pub other: Object<Value>,
249}
250
251impl From<Object<Value>> for FrameVars {
252 fn from(value: Object<Value>) -> Self {
253 FrameVars(value)
254 }
255}
256
257impl FromValue for FrameVars {
258 fn from_value(mut value: Annotated<Value>) -> Annotated<FrameVars> {
259 value = value.map_value(|value| {
260 if let Value::Array(value) = value {
261 Value::Object(
262 value
263 .into_iter()
264 .enumerate()
265 .map(|(i, v)| (i.to_string(), v))
266 .collect(),
267 )
268 } else {
269 value
270 }
271 });
272
273 FromValue::from_value(value).map_value(FrameVars)
274 }
275}
276
277#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
346#[metastructure(process_func = "process_raw_stacktrace", value_type = "Stacktrace")]
347pub struct RawStacktrace {
348 #[metastructure(required = true, nonempty = true, skip_serialization = "empty")]
351 pub frames: Annotated<Array<Frame>>,
352
353 pub registers: Annotated<Object<RegVal>>,
358
359 #[metastructure(skip_serialization = "null")]
362 pub instruction_addr_adjustment: Annotated<InstructionAddrAdjustment>,
363
364 #[metastructure(max_chars = 128)]
366 pub lang: Annotated<String>,
367
368 pub snapshot: Annotated<bool>,
378
379 #[metastructure(additional_properties)]
381 pub other: Object<Value>,
382}
383
384#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, ProcessValue)]
395#[serde(rename_all = "snake_case")]
396#[derive(Default)]
397pub enum InstructionAddrAdjustment {
398 #[default]
400 Auto,
401
402 AllButFirst,
405
406 All,
409
410 None,
413
414 Unknown(String),
418}
419
420impl InstructionAddrAdjustment {
421 pub fn as_str(&self) -> &str {
423 match self {
424 InstructionAddrAdjustment::Auto => "auto",
425 InstructionAddrAdjustment::AllButFirst => "all_but_first",
426 InstructionAddrAdjustment::All => "all",
427 InstructionAddrAdjustment::None => "none",
428 InstructionAddrAdjustment::Unknown(s) => s,
429 }
430 }
431}
432
433impl FromStr for InstructionAddrAdjustment {
434 type Err = Infallible;
435
436 fn from_str(s: &str) -> Result<Self, Self::Err> {
437 match s {
438 "auto" => Ok(Self::Auto),
439 "all_but_first" => Ok(Self::AllButFirst),
440 "all" => Ok(Self::All),
441 "none" => Ok(Self::None),
442 s => Ok(Self::Unknown(s.to_owned())),
443 }
444 }
445}
446
447impl fmt::Display for InstructionAddrAdjustment {
448 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
449 f.write_str(self.as_str())
450 }
451}
452
453impl Empty for InstructionAddrAdjustment {
454 #[inline]
455 fn is_empty(&self) -> bool {
456 matches!(self, Self::Auto)
457 }
458}
459
460impl FromValue for InstructionAddrAdjustment {
461 fn from_value(value: Annotated<Value>) -> Annotated<Self> {
462 match String::from_value(value) {
463 Annotated(Some(value), mut meta) => match value.parse() {
464 Ok(adjustment) => Annotated(Some(adjustment), meta),
465 Err(_) => {
466 meta.add_error(ErrorKind::InvalidData);
467 meta.set_original_value(Some(value));
468 Annotated(None, meta)
469 }
470 },
471 Annotated(None, meta) => Annotated(None, meta),
472 }
473 }
474}
475
476impl IntoValue for InstructionAddrAdjustment {
477 fn into_value(self) -> Value
478 where
479 Self: Sized,
480 {
481 Value::String(match self {
482 Self::Unknown(s) => s,
483 _ => self.as_str().to_owned(),
484 })
485 }
486
487 fn serialize_payload<S>(&self, s: S, _behavior: SkipSerialization) -> Result<S::Ok, S::Error>
488 where
489 Self: Sized,
490 S: serde::Serializer,
491 {
492 serde::Serialize::serialize(self.as_str(), s)
493 }
494}
495
496#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
499#[metastructure(process_func = "process_stacktrace")]
500pub struct Stacktrace(pub RawStacktrace);
501
502impl Deref for Stacktrace {
503 type Target = RawStacktrace;
504
505 fn deref(&self) -> &RawStacktrace {
506 &self.0
507 }
508}
509
510impl DerefMut for Stacktrace {
511 fn deref_mut(&mut self) -> &mut RawStacktrace {
512 &mut self.0
513 }
514}
515
516impl From<RawStacktrace> for Stacktrace {
517 fn from(stacktrace: RawStacktrace) -> Stacktrace {
518 Stacktrace(stacktrace)
519 }
520}
521
522impl From<Stacktrace> for RawStacktrace {
523 fn from(stacktrace: Stacktrace) -> RawStacktrace {
524 stacktrace.0
525 }
526}
527
528#[cfg(test)]
529mod tests {
530 use crate::protocol::{LockReasonType, ThreadId};
531 use similar_asserts::assert_eq;
532
533 use super::*;
534
535 #[test]
536 fn test_frame_roundtrip() {
537 let json = r#"{
538 "function": "main@8",
539 "raw_function": "main",
540 "symbol": "_main@8",
541 "module": "app",
542 "package": "/my/app",
543 "filename": "myfile.rs",
544 "file_revision": "12345",
545 "abs_path": "/path/to",
546 "lineno": 2,
547 "colno": 42,
548 "platform": "rust",
549 "pre_context": [
550 "fn main() {"
551 ],
552 "context_line": "unimplemented!()",
553 "post_context": [
554 "}"
555 ],
556 "in_app": true,
557 "vars": {
558 "variable": "value"
559 },
560 "data": {
561 "sourcemap": "http://example.com/invalid.map"
562 },
563 "image_addr": "0x400",
564 "instruction_addr": "0x404",
565 "addr_mode": "abs",
566 "symbol_addr": "0x404",
567 "trust": "69",
568 "lang": "rust",
569 "stack_start": true,
570 "lock": {
571 "type": 2,
572 "address": "0x07d7437b",
573 "package_name": "io.sentry.samples",
574 "class_name": "MainActivity",
575 "thread_id": 7
576 },
577 "other": "value"
578}"#;
579 let frame = Annotated::new(Frame {
580 function: Annotated::new("main@8".to_owned()),
581 raw_function: Annotated::new("main".to_owned()),
582 symbol: Annotated::new("_main@8".to_owned()),
583 module: Annotated::new("app".to_owned()),
584 package: Annotated::new("/my/app".to_owned()),
585 filename: Annotated::new("myfile.rs".into()),
586 file_revision: Annotated::new("12345".into()),
587 abs_path: Annotated::new("/path/to".into()),
588 lineno: Annotated::new(2),
589 colno: Annotated::new(42),
590 platform: Annotated::new("rust".to_owned()),
591 pre_context: Annotated::new(vec![Annotated::new("fn main() {".to_owned())]),
592 context_line: Annotated::new("unimplemented!()".to_owned()),
593 post_context: Annotated::new(vec![Annotated::new("}".to_owned())]),
594 in_app: Annotated::new(true),
595 vars: {
596 let mut vars = Object::new();
597 vars.insert(
598 "variable".to_owned(),
599 Annotated::new(Value::String("value".to_owned())),
600 );
601 Annotated::new(vars.into())
602 },
603 data: Annotated::new(FrameData {
604 sourcemap: Annotated::new("http://example.com/invalid.map".to_owned()),
605 ..Default::default()
606 }),
607 image_addr: Annotated::new(Addr(0x400)),
608 instruction_addr: Annotated::new(Addr(0x404)),
609 addr_mode: Annotated::new("abs".into()),
610 function_id: Annotated::empty(),
611 symbol_addr: Annotated::new(Addr(0x404)),
612 trust: Annotated::new("69".into()),
613 lang: Annotated::new("rust".into()),
614 stack_start: Annotated::new(true),
615 lock: Annotated::new(LockReason {
616 ty: Annotated::new(LockReasonType::Waiting),
617 address: Annotated::new("0x07d7437b".to_owned()),
618 package_name: Annotated::new("io.sentry.samples".to_owned()),
619 class_name: Annotated::new("MainActivity".to_owned()),
620 thread_id: Annotated::new(ThreadId::Int(7)),
621 other: Default::default(),
622 }),
623 parent_index: Annotated::empty(),
624 sample_count: Annotated::empty(),
625 other: {
626 let mut vars = Object::new();
627 vars.insert(
628 "other".to_owned(),
629 Annotated::new(Value::String("value".to_owned())),
630 );
631 vars
632 },
633 });
634
635 assert_eq!(frame, Annotated::from_json(json).unwrap());
636 assert_eq!(json, frame.to_json_pretty().unwrap());
637 }
638
639 #[test]
640 fn test_frame_default_values() {
641 let json = "{}";
642 let frame = Annotated::new(Frame::default());
643
644 assert_eq!(frame, Annotated::from_json(json).unwrap());
645 assert_eq!(json, frame.to_json_pretty().unwrap());
646 }
647
648 #[test]
649 fn test_stacktrace_roundtrip() {
650 let json = r#"{
651 "frames": [
652 {
653 "function": "foobar"
654 }
655 ],
656 "registers": {
657 "cspr": "0x20000000",
658 "lr": "0x18a31aadc",
659 "pc": "0x18a310ea4",
660 "sp": "0x16fd75060"
661 },
662 "instruction_addr_adjustment": "all_but_first",
663 "lang": "rust",
664 "snapshot": false,
665 "other": "value"
666}"#;
667 let stack = Annotated::new(RawStacktrace {
668 frames: Annotated::new(vec![Annotated::new(Frame {
669 function: Annotated::new("foobar".to_owned()),
670 ..Default::default()
671 })]),
672 registers: {
673 let mut registers = Object::new();
674 registers.insert("cspr".to_owned(), Annotated::new(RegVal(0x2000_0000)));
675 registers.insert("lr".to_owned(), Annotated::new(RegVal(0x1_8a31_aadc)));
676 registers.insert("pc".to_owned(), Annotated::new(RegVal(0x1_8a31_0ea4)));
677 registers.insert("sp".to_owned(), Annotated::new(RegVal(0x1_6fd7_5060)));
678 Annotated::new(registers)
679 },
680 instruction_addr_adjustment: Annotated::new(InstructionAddrAdjustment::AllButFirst),
681 lang: Annotated::new("rust".into()),
682 snapshot: Annotated::new(false),
683 other: {
684 let mut other = Object::new();
685 other.insert(
686 "other".to_owned(),
687 Annotated::new(Value::String("value".to_owned())),
688 );
689 other
690 },
691 });
692
693 assert_eq!(stack, Annotated::from_json(json).unwrap());
694 assert_eq!(json, stack.to_json_pretty().unwrap());
695 }
696
697 #[test]
698 fn test_stacktrace_default_values() {
699 let json = r#"{
701 "frames": [
702 {}
703 ]
704}"#;
705
706 let stack = Annotated::new(RawStacktrace {
707 frames: Annotated::new(vec![Annotated::new(Frame::default())]),
708 ..Default::default()
709 });
710
711 assert_eq!(stack, Annotated::from_json(json).unwrap());
712 assert_eq!(json, stack.to_json_pretty().unwrap());
713 }
714
715 #[test]
716 fn test_frame_vars_null_preserved() {
717 let json = r#"{
718 "vars": {
719 "despacito": null
720 }
721}"#;
722 let frame = Annotated::new(Frame {
723 vars: Annotated::new({
724 let mut vars = Object::new();
725 vars.insert("despacito".to_owned(), Annotated::empty());
726 vars.into()
727 }),
728 ..Default::default()
729 });
730
731 assert_eq!(Annotated::from_json(json).unwrap(), frame);
732 assert_eq!(json, frame.to_json_pretty().unwrap());
733 }
734
735 #[test]
736 fn test_frame_vars_empty_annotated_is_serialized() {
737 let output = r#"{
738 "vars": {
739 "despacito": null,
740 "despacito2": null
741 }
742}"#;
743 let frame = Annotated::new(Frame {
744 vars: Annotated::new({
745 let mut vars = Object::new();
746 vars.insert("despacito".to_owned(), Annotated::empty());
747 vars.insert("despacito2".to_owned(), Annotated::empty());
748 vars.into()
749 }),
750 ..Default::default()
751 });
752
753 assert_eq!(output, frame.to_json_pretty().unwrap());
754 }
755
756 #[test]
757 fn test_frame_empty_context_lines() {
758 let json = r#"{
759 "pre_context": [
760 ""
761 ],
762 "context_line": "",
763 "post_context": [
764 ""
765 ]
766}"#;
767
768 let frame = Annotated::new(Frame {
769 pre_context: Annotated::new(vec![Annotated::new("".to_owned())]),
770 context_line: Annotated::new("".to_owned()),
771 post_context: Annotated::new(vec![Annotated::new("".to_owned())]),
772 ..Frame::default()
773 });
774
775 assert_eq!(frame, Annotated::from_json(json).unwrap());
776 assert_eq!(json, frame.to_json_pretty().unwrap());
777 }
778
779 #[test]
780 fn test_php_frame_vars() {
781 let input = r#"{
786 "vars": ["foo", "bar", "baz", null]
787}"#;
788
789 let output = r#"{
790 "vars": {
791 "0": "foo",
792 "1": "bar",
793 "2": "baz",
794 "3": null
795 }
796}"#;
797
798 let frame = Annotated::new(Frame {
799 vars: Annotated::new({
800 let mut vars = Object::new();
801 vars.insert("0".to_owned(), Annotated::new("foo".to_owned().into()));
802 vars.insert("1".to_owned(), Annotated::new("bar".to_owned().into()));
803 vars.insert("2".to_owned(), Annotated::new("baz".to_owned().into()));
804 vars.insert("3".to_owned(), Annotated::empty());
805 vars.into()
806 }),
807 ..Default::default()
808 });
809
810 assert_eq!(frame, Annotated::from_json(input).unwrap());
811 assert_eq!(output, frame.to_json_pretty().unwrap());
812 }
813}