1use std::fmt;
2use std::str::FromStr;
3
4use relay_common::time;
5use relay_protocol::{
6 Annotated, Array, Empty, FiniteF64, FromValue, Getter, GetterIter, IntoValue, Object, Val,
7 Value,
8};
9use sentry_release_parser::Release as ParsedRelease;
10use uuid::Uuid;
11
12use crate::processor::ProcessValue;
13use crate::protocol::{
14 AppContext, Breadcrumb, Breakdowns, BrowserContext, ClientSdkInfo, Contexts, Csp, DebugMeta,
15 DefaultContext, DeviceContext, EventType, Exception, ExpectCt, ExpectStaple, Fingerprint,
16 GpuContext, Hpkp, LenientString, Level, LogEntry, Measurements, Metrics, MonitorContext,
17 OsContext, ProfileContext, RelayInfo, Request, ResponseContext, RuntimeContext, Span, SpanId,
18 Stacktrace, Tags, TemplateInfo, Thread, Timestamp, TraceContext, TransactionInfo, User, Values,
19};
20
21#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
23pub struct EventId(pub Uuid);
24
25impl EventId {
26 #[inline]
28 pub fn new() -> Self {
29 Self(Uuid::new_v4())
30 }
31
32 pub fn nil() -> Self {
34 Self(Uuid::nil())
35 }
36
37 #[inline]
39 pub fn is_nil(&self) -> bool {
40 self.0.is_nil()
41 }
42}
43
44impl Default for EventId {
45 #[inline]
46 fn default() -> Self {
47 Self::new()
48 }
49}
50
51relay_protocol::derive_string_meta_structure!(EventId, "event id");
52
53impl ProcessValue for EventId {}
54
55impl fmt::Display for EventId {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 write!(f, "{}", self.0.as_simple())
58 }
59}
60
61impl FromStr for EventId {
62 type Err = <Uuid as FromStr>::Err;
63
64 fn from_str(uuid_str: &str) -> Result<Self, Self::Err> {
65 uuid_str.parse().map(EventId)
66 }
67}
68
69relay_common::impl_str_serde!(EventId, "an event identifier");
70
71impl TryFrom<&SpanId> for EventId {
72 type Error = <EventId as FromStr>::Err;
73
74 fn try_from(value: &SpanId) -> Result<Self, Self::Error> {
75 let s = format!("0000000000000000{value}");
77 s.parse()
78 }
79}
80
81#[derive(Debug, FromValue, IntoValue, ProcessValue, Empty, Clone, PartialEq)]
82pub struct ExtraValue(#[metastructure(max_depth = 7, max_bytes = 16_384)] pub Value);
83
84impl<T: Into<Value>> From<T> for ExtraValue {
85 fn from(value: T) -> ExtraValue {
86 ExtraValue(value.into())
87 }
88}
89
90#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
92pub struct EventProcessingError {
93 #[metastructure(field = "type", required = true)]
95 pub ty: Annotated<String>,
96
97 pub name: Annotated<String>,
99
100 pub value: Annotated<Value>,
102
103 #[metastructure(additional_properties, pii = "maybe")]
105 pub other: Object<Value>,
106}
107
108#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
113pub struct GroupingConfig {
114 #[metastructure(max_chars = 128)]
116 pub id: Annotated<String>,
117 pub enhancements: Annotated<String>,
119}
120
121#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
123#[metastructure(process_func = "process_event", value_type = "Event")]
124pub struct Event {
125 #[metastructure(field = "event_id")]
143 pub id: Annotated<EventId>,
144
145 pub level: Annotated<Level>,
153
154 pub version: Annotated<String>,
156
157 #[metastructure(field = "type")]
182 pub ty: Annotated<EventType>,
183
184 #[metastructure(skip_serialization = "empty")]
195 pub fingerprint: Annotated<Fingerprint>,
196
197 #[metastructure(max_chars = 200, pii = "maybe")]
201 pub culprit: Annotated<String>,
202
203 #[metastructure(max_chars = 200, trim_whitespace = true)]
208 pub transaction: Annotated<String>,
209
210 #[metastructure(skip_serialization = "null")]
212 pub transaction_info: Annotated<TransactionInfo>,
213
214 pub time_spent: Annotated<u64>,
216
217 #[metastructure(legacy_alias = "sentry.interfaces.Message", legacy_alias = "message")]
219 #[metastructure(skip_serialization = "empty")]
220 pub logentry: Annotated<LogEntry>,
221
222 #[metastructure(
224 max_chars = 64, deny_chars = "\r\n",
226 )]
227 pub logger: Annotated<String>,
228
229 #[metastructure(skip_serialization = "empty_deep", max_depth = 7, max_bytes = 8192)]
243 pub modules: Annotated<Object<String>>,
244
245 pub platform: Annotated<String>,
255
256 pub timestamp: Annotated<Timestamp>,
282
283 #[metastructure(omit_from_schema)] pub start_timestamp: Annotated<Timestamp>,
286
287 pub received: Annotated<Timestamp>,
289
290 #[metastructure(pii = "true", max_chars = 256, max_chars_allowance = 20)]
294 pub server_name: Annotated<String>,
295
296 #[metastructure(
301 max_chars = 200, required = false,
304 trim_whitespace = true,
305 nonempty = true,
306 skip_serialization = "empty"
307 )]
308 pub release: Annotated<LenientString>,
309
310 #[metastructure(
318 allow_chars = "a-zA-Z0-9_.-",
319 trim_whitespace = true,
320 required = false,
321 nonempty = true
322 )]
323 pub dist: Annotated<String>,
324
325 #[metastructure(
331 max_chars = 64,
332 nonempty = true,
334 required = false,
335 trim_whitespace = true
336 )]
337 pub environment: Annotated<String>,
338
339 #[metastructure(max_chars = 256, max_chars_allowance = 20)]
341 #[metastructure(omit_from_schema)] pub site: Annotated<String>,
343
344 #[metastructure(legacy_alias = "sentry.interfaces.User")]
346 #[metastructure(skip_serialization = "empty")]
347 pub user: Annotated<User>,
348
349 #[metastructure(legacy_alias = "sentry.interfaces.Http")]
351 #[metastructure(skip_serialization = "empty")]
352 pub request: Annotated<Request>,
353
354 #[metastructure(legacy_alias = "sentry.interfaces.Contexts")]
356 pub contexts: Annotated<Contexts>,
357
358 #[metastructure(legacy_alias = "sentry.interfaces.Breadcrumbs")]
360 #[metastructure(skip_serialization = "empty")]
361 pub breadcrumbs: Annotated<Values<Breadcrumb>>,
362
363 #[metastructure(legacy_alias = "sentry.interfaces.Exception")]
365 #[metastructure(field = "exception")]
366 #[metastructure(skip_serialization = "empty")]
367 pub exceptions: Annotated<Values<Exception>>,
368
369 #[metastructure(skip_serialization = "empty")]
373 #[metastructure(legacy_alias = "sentry.interfaces.Stacktrace")]
374 pub stacktrace: Annotated<Stacktrace>,
375
376 #[metastructure(legacy_alias = "sentry.interfaces.Template")]
380 #[metastructure(omit_from_schema)]
381 pub template: Annotated<TemplateInfo>,
382
383 #[metastructure(skip_serialization = "empty")]
385 pub threads: Annotated<Values<Thread>>,
386
387 #[metastructure(skip_serialization = "empty", pii = "maybe")]
391 pub tags: Annotated<Tags>,
392
393 #[metastructure(max_depth = 7, max_bytes = 262_144)]
403 #[metastructure(pii = "true", skip_serialization = "empty")]
404 pub extra: Annotated<Object<ExtraValue>>,
405
406 #[metastructure(skip_serialization = "empty")]
408 pub debug_meta: Annotated<DebugMeta>,
409
410 #[metastructure(field = "sdk")]
412 #[metastructure(skip_serialization = "empty")]
413 pub client_sdk: Annotated<ClientSdkInfo>,
414
415 #[metastructure(max_depth = 5, max_bytes = 2048)]
417 #[metastructure(skip_serialization = "empty", omit_from_schema)]
418 pub ingest_path: Annotated<Array<RelayInfo>>,
419
420 #[metastructure(skip_serialization = "empty_deep")]
423 pub errors: Annotated<Array<EventProcessingError>>,
424
425 #[metastructure(omit_from_schema)] pub key_id: Annotated<String>,
428
429 #[metastructure(omit_from_schema)] pub project: Annotated<u64>,
432
433 #[metastructure(omit_from_schema)] pub grouping_config: Annotated<Object<Value>>,
436
437 #[metastructure(max_chars = 128)]
439 #[metastructure(omit_from_schema)] pub checksum: Annotated<String>,
441
442 #[metastructure(legacy_alias = "sentry.interfaces.Csp")]
444 #[metastructure(omit_from_schema)] pub csp: Annotated<Csp>,
446
447 #[metastructure(pii = "true", legacy_alias = "sentry.interfaces.Hpkp")]
449 #[metastructure(omit_from_schema)] pub hpkp: Annotated<Hpkp>,
451
452 #[metastructure(pii = "true", legacy_alias = "sentry.interfaces.ExpectCT")]
454 #[metastructure(omit_from_schema)] pub expectct: Annotated<ExpectCt>,
456
457 #[metastructure(pii = "true", legacy_alias = "sentry.interfaces.ExpectStaple")]
459 #[metastructure(omit_from_schema)] pub expectstaple: Annotated<ExpectStaple>,
461
462 #[metastructure(max_bytes = 819200)]
464 #[metastructure(omit_from_schema)] pub spans: Annotated<Array<Span>>,
466
467 #[metastructure(skip_serialization = "empty")]
472 #[metastructure(omit_from_schema)] pub measurements: Annotated<Measurements>,
474
475 #[metastructure(skip_serialization = "empty")]
477 #[metastructure(omit_from_schema)] pub breakdowns: Annotated<Breakdowns>,
479
480 #[metastructure(omit_from_schema)] pub scraping_attempts: Annotated<Value>,
484
485 #[metastructure(omit_from_schema)]
489 pub _metrics: Annotated<Metrics>,
490
491 #[metastructure(omit_from_schema)]
493 pub _dsc: Annotated<Value>,
494
495 #[metastructure(skip_serialization = "empty", trim = false)]
500 pub _performance_issues_spans: Annotated<bool>,
501
502 #[metastructure(additional_properties, pii = "true")]
504 pub other: Object<Value>,
505}
506
507impl Event {
508 pub fn tag_value(&self, tag_key: &str) -> Option<&str> {
513 if let Some(tags) = self.tags.value() {
514 tags.get(tag_key)
515 } else {
516 None
517 }
518 }
519
520 pub fn has_module(&self, module_name: &str) -> bool {
522 self.modules
523 .value()
524 .map(|m| m.contains_key(module_name))
525 .unwrap_or(false)
526 }
527
528 pub fn sdk_name(&self) -> &str {
532 if let Some(client_sdk) = self.client_sdk.value()
533 && let Some(name) = client_sdk.name.as_str()
534 {
535 return name;
536 }
537
538 "unknown"
539 }
540
541 pub fn sdk_version(&self) -> &str {
545 if let Some(client_sdk) = self.client_sdk.value()
546 && let Some(version) = client_sdk.version.as_str()
547 {
548 return version;
549 }
550
551 "unknown"
552 }
553
554 pub fn user_agent(&self) -> Option<&str> {
559 let headers = self.request.value()?.headers.value()?;
560
561 for item in headers.iter() {
562 if let Some((o_k, v)) = item.value()
563 && let Some(k) = o_k.as_str()
564 && k.eq_ignore_ascii_case("user-agent")
565 {
566 return v.as_str();
567 }
568 }
569
570 None
571 }
572
573 pub fn extra_at(&self, path: &str) -> Option<&Value> {
578 let mut path = path.split('.');
579
580 let mut value = &self.extra.value()?.get(path.next()?)?.value()?.0;
582
583 for key in path {
585 if let Value::Object(object) = value {
586 value = object.get(key)?.value()?;
587 } else {
588 return None;
589 }
590 }
591
592 Some(value)
593 }
594
595 pub fn parse_release(&self) -> Option<ParsedRelease<'_>> {
597 sentry_release_parser::Release::parse(self.release.as_str()?).ok()
598 }
599
600 pub fn measurement(&self, name: &str) -> Option<FiniteF64> {
604 let annotated = self.measurements.value()?.get(name)?;
605 Some(*annotated.value()?.value.value()?)
606 }
607
608 pub fn breakdown(&self, breakdown: &str, measurement: &str) -> Option<FiniteF64> {
610 let breakdown = self.breakdowns.value()?.get(breakdown)?.value()?;
611 Some(*breakdown.get(measurement)?.value()?.value.value()?)
612 }
613
614 pub fn context<C: DefaultContext>(&self) -> Option<&C> {
616 self.contexts.value()?.get()
617 }
618
619 pub fn context_mut<C: DefaultContext>(&mut self) -> Option<&mut C> {
621 self.contexts.value_mut().as_mut()?.get_mut()
622 }
623}
624
625fn or_none(string: &Annotated<impl AsRef<str>>) -> Option<&str> {
626 match string.as_str() {
627 None | Some("") => None,
628 Some(other) => Some(other),
629 }
630}
631
632impl Getter for Event {
633 fn get_value(&self, path: &str) -> Option<Val<'_>> {
634 Some(match path.strip_prefix("event.")? {
635 "level" => self.level.value()?.name().into(),
637 "release" => self.release.as_str()?.into(),
638 "dist" => self.dist.as_str()?.into(),
639 "environment" => self.environment.as_str()?.into(),
640 "transaction" => self.transaction.as_str()?.into(),
641 "logger" => self.logger.as_str()?.into(),
642 "platform" => self.platform.as_str().unwrap_or("other").into(),
643
644 "logentry.formatted" => self.logentry.value()?.formatted.value()?.as_ref().into(),
646 "logentry.message" => self.logentry.value()?.message.value()?.as_ref().into(),
647 "user.email" => or_none(&self.user.value()?.email)?.into(),
648 "user.id" => or_none(&self.user.value()?.id)?.into(),
649 "user.ip_address" => self.user.value()?.ip_address.as_str()?.into(),
650 "user.name" => self.user.value()?.name.as_str()?.into(),
651 "user.segment" => or_none(&self.user.value()?.segment)?.into(),
652 "user.geo.city" => self.user.value()?.geo.value()?.city.as_str()?.into(),
653 "user.geo.country_code" => self
654 .user
655 .value()?
656 .geo
657 .value()?
658 .country_code
659 .as_str()?
660 .into(),
661 "user.geo.region" => self.user.value()?.geo.value()?.region.as_str()?.into(),
662 "user.geo.subdivision" => self.user.value()?.geo.value()?.subdivision.as_str()?.into(),
663 "request.method" => self.request.value()?.method.as_str()?.into(),
664 "request.url" => self.request.value()?.url.as_str()?.into(),
665 "transaction.source" => self
666 .transaction_info
667 .value()?
668 .source
669 .value()?
670 .as_str()
671 .into(),
672 "sdk.name" => self.client_sdk.value()?.name.as_str()?.into(),
673 "sdk.version" => self.client_sdk.value()?.version.as_str()?.into(),
674
675 "sentry_user" => self.user.value()?.sentry_user.as_str()?.into(),
677
678 "contexts.app.in_foreground" => {
680 self.context::<AppContext>()?.in_foreground.value()?.into()
681 }
682 "contexts.app.device_app_hash" => self
683 .context::<AppContext>()?
684 .device_app_hash
685 .as_str()?
686 .into(),
687 "contexts.device.arch" => self.context::<DeviceContext>()?.arch.as_str()?.into(),
688 "contexts.device.battery_level" => self
689 .context::<DeviceContext>()?
690 .battery_level
691 .value()?
692 .into(),
693 "contexts.device.brand" => self.context::<DeviceContext>()?.brand.as_str()?.into(),
694 "contexts.device.charging" => self.context::<DeviceContext>()?.charging.value()?.into(),
695 "contexts.device.family" => self.context::<DeviceContext>()?.family.as_str()?.into(),
696 "contexts.device.model" => self.context::<DeviceContext>()?.model.as_str()?.into(),
697 "contexts.device.locale" => self.context::<DeviceContext>()?.locale.as_str()?.into(),
698 "contexts.device.online" => self.context::<DeviceContext>()?.online.value()?.into(),
699 "contexts.device.orientation" => self
700 .context::<DeviceContext>()?
701 .orientation
702 .as_str()?
703 .into(),
704 "contexts.device.name" => self.context::<DeviceContext>()?.name.as_str()?.into(),
705 "contexts.device.screen_density" => self
706 .context::<DeviceContext>()?
707 .screen_density
708 .value()?
709 .into(),
710 "contexts.device.screen_dpi" => {
711 self.context::<DeviceContext>()?.screen_dpi.value()?.into()
712 }
713 "contexts.device.screen_width_pixels" => self
714 .context::<DeviceContext>()?
715 .screen_width_pixels
716 .value()?
717 .into(),
718 "contexts.device.screen_height_pixels" => self
719 .context::<DeviceContext>()?
720 .screen_height_pixels
721 .value()?
722 .into(),
723 "contexts.device.simulator" => {
724 self.context::<DeviceContext>()?.simulator.value()?.into()
725 }
726 "contexts.gpu.vendor_name" => {
727 self.context::<GpuContext>()?.vendor_name.as_str()?.into()
728 }
729 "contexts.gpu.name" => self.context::<GpuContext>()?.name.as_str()?.into(),
730 "contexts.monitor.id" => self.context::<MonitorContext>()?.get("id")?.value()?.into(),
731 "contexts.monitor.slug" => self
732 .context::<MonitorContext>()?
733 .get("slug")?
734 .value()?
735 .into(),
736 "contexts.os" => self.context::<OsContext>()?.os.as_str()?.into(),
737 "contexts.os.build" => self.context::<OsContext>()?.build.as_str()?.into(),
738 "contexts.os.kernel_version" => {
739 self.context::<OsContext>()?.kernel_version.as_str()?.into()
740 }
741 "contexts.os.name" => self.context::<OsContext>()?.name.as_str()?.into(),
742 "contexts.os.version" => self.context::<OsContext>()?.version.as_str()?.into(),
743 "contexts.os.rooted" => self.context::<OsContext>()?.rooted.value()?.into(),
744 "contexts.browser" => self.context::<BrowserContext>()?.browser.as_str()?.into(),
745 "contexts.browser.name" => self.context::<BrowserContext>()?.name.as_str()?.into(),
746 "contexts.browser.version" => {
747 self.context::<BrowserContext>()?.version.as_str()?.into()
748 }
749 "contexts.profile.profile_id" => {
750 (&self.context::<ProfileContext>()?.profile_id.value()?.0).into()
751 }
752 "contexts.device.uuid" => self.context::<DeviceContext>()?.uuid.value()?.into(),
753 "contexts.trace.status" => self
754 .context::<TraceContext>()?
755 .status
756 .value()?
757 .as_str()
758 .into(),
759 "contexts.trace.op" => self.context::<TraceContext>()?.op.as_str()?.into(),
760 "contexts.response.status_code" => self
761 .context::<ResponseContext>()?
762 .status_code
763 .value()?
764 .into(),
765 "contexts.unreal.crash_type" => match self.contexts.value()?.get_key("unreal")? {
766 super::Context::Other(context) => context.get("crash_type")?.value()?.into(),
767 _ => return None,
768 },
769 "contexts.runtime" => self.context::<RuntimeContext>()?.runtime.as_str()?.into(),
770 "contexts.runtime.name" => self.context::<RuntimeContext>()?.name.as_str()?.into(),
771
772 "duration" => {
774 let start = self.start_timestamp.value()?;
775 let end = self.timestamp.value()?;
776 if start <= end && self.ty.value() == Some(&EventType::Transaction) {
777 time::chrono_to_positive_millis(*end - *start).into()
778 } else {
779 return None;
780 }
781 }
782
783 path => {
785 if let Some(rest) = path.strip_prefix("release.") {
786 let release = self.parse_release()?;
787 match rest {
788 "build" => release.build_hash()?.into(),
789 "package" => release.package()?.into(),
790 "version.short" => release.version()?.raw_short().into(),
791 _ => return None,
792 }
793 } else if let Some(rest) = path.strip_prefix("measurements.") {
794 let name = rest.strip_suffix(".value")?;
795 self.measurement(name)?.into()
796 } else if let Some(rest) = path.strip_prefix("breakdowns.") {
797 let (breakdown, measurement) = rest.split_once('.')?;
798 self.breakdown(breakdown, measurement)?.into()
799 } else if let Some(rest) = path.strip_prefix("extra.") {
800 self.extra_at(rest)?.into()
801 } else if let Some(rest) = path.strip_prefix("tags.") {
802 self.tags.value()?.get(rest)?.into()
803 } else if let Some(rest) = path.strip_prefix("request.headers.") {
804 self.request
805 .value()?
806 .headers
807 .value()?
808 .get_header(rest)?
809 .into()
810 } else {
811 return None;
812 }
813 }
814 })
815 }
816
817 fn get_iter(&self, path: &str) -> Option<GetterIter<'_>> {
818 Some(match path.strip_prefix("event.")? {
819 "exception.values" => {
820 GetterIter::new_annotated(self.exceptions.value()?.values.value()?)
821 }
822 _ => return None,
823 })
824 }
825}
826
827#[cfg(test)]
828mod tests {
829 use chrono::{TimeZone, Utc};
830 use relay_protocol::{ErrorKind, HexId, Map, Meta};
831 use similar_asserts::assert_eq;
832 use std::collections::BTreeMap;
833 use uuid::uuid;
834
835 use super::*;
836 use crate::protocol::{
837 Headers, IpAddr, JsonLenientString, PairList, TagEntry, TransactionSource,
838 };
839
840 #[test]
841 fn test_event_roundtrip() {
842 let json = r#"{
844 "event_id": "52df9022835246eeb317dbd739ccd059",
845 "level": "debug",
846 "fingerprint": [
847 "myprint"
848 ],
849 "culprit": "myculprit",
850 "transaction": "mytransaction",
851 "logentry": {
852 "formatted": "mymessage"
853 },
854 "logger": "mylogger",
855 "modules": {
856 "mymodule": "1.0.0"
857 },
858 "platform": "myplatform",
859 "timestamp": 946684800.0,
860 "server_name": "myhost",
861 "release": "myrelease",
862 "dist": "mydist",
863 "environment": "myenv",
864 "tags": [
865 [
866 "tag",
867 "value"
868 ]
869 ],
870 "extra": {
871 "extra": "value"
872 },
873 "other": "value",
874 "_meta": {
875 "event_id": {
876 "": {
877 "err": [
878 "invalid_data"
879 ]
880 }
881 }
882 }
883}"#;
884
885 let event = Annotated::new(Event {
886 id: Annotated(
887 Some("52df9022-8352-46ee-b317-dbd739ccd059".parse().unwrap()),
888 Meta::from_error(ErrorKind::InvalidData),
889 ),
890 level: Annotated::new(Level::Debug),
891 fingerprint: Annotated::new(vec!["myprint".to_owned()].into()),
892 culprit: Annotated::new("myculprit".to_owned()),
893 transaction: Annotated::new("mytransaction".to_owned()),
894 logentry: Annotated::new(LogEntry {
895 formatted: Annotated::new("mymessage".to_owned().into()),
896 ..Default::default()
897 }),
898 logger: Annotated::new("mylogger".to_owned()),
899 modules: {
900 let mut map = Map::new();
901 map.insert("mymodule".to_owned(), Annotated::new("1.0.0".to_owned()));
902 Annotated::new(map)
903 },
904 platform: Annotated::new("myplatform".to_owned()),
905 timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into()),
906 server_name: Annotated::new("myhost".to_owned()),
907 release: Annotated::new("myrelease".to_owned().into()),
908 dist: Annotated::new("mydist".to_owned()),
909 environment: Annotated::new("myenv".to_owned()),
910 tags: {
911 let items = vec![Annotated::new(TagEntry(
912 Annotated::new("tag".to_owned()),
913 Annotated::new("value".to_owned()),
914 ))];
915 Annotated::new(Tags(items.into()))
916 },
917 extra: {
918 let mut map = Map::new();
919 map.insert(
920 "extra".to_owned(),
921 Annotated::new(ExtraValue(Value::String("value".to_owned()))),
922 );
923 Annotated::new(map)
924 },
925 other: {
926 let mut map = Map::new();
927 map.insert(
928 "other".to_owned(),
929 Annotated::new(Value::String("value".to_owned())),
930 );
931 map
932 },
933 ..Default::default()
934 });
935
936 assert_eq!(event, Annotated::from_json(json).unwrap());
937 assert_eq!(json, event.to_json_pretty().unwrap());
938 }
939
940 #[test]
941 fn test_event_default_values() {
942 let json = "{}";
943 let event = Annotated::new(Event::default());
944
945 assert_eq!(event, Annotated::from_json(json).unwrap());
946 assert_eq!(json, event.to_json_pretty().unwrap());
947 }
948
949 #[test]
950 fn test_event_default_values_with_meta() {
951 let json = r#"{
952 "event_id": "52df9022835246eeb317dbd739ccd059",
953 "fingerprint": [
954 "{{ default }}"
955 ],
956 "platform": "other",
957 "_meta": {
958 "event_id": {
959 "": {
960 "err": [
961 "invalid_data"
962 ]
963 }
964 },
965 "fingerprint": {
966 "": {
967 "err": [
968 "invalid_data"
969 ]
970 }
971 },
972 "platform": {
973 "": {
974 "err": [
975 "invalid_data"
976 ]
977 }
978 }
979 }
980}"#;
981
982 let event = Annotated::new(Event {
983 id: Annotated(
984 Some("52df9022-8352-46ee-b317-dbd739ccd059".parse().unwrap()),
985 Meta::from_error(ErrorKind::InvalidData),
986 ),
987 fingerprint: Annotated(
988 Some(vec!["{{ default }}".to_owned()].into()),
989 Meta::from_error(ErrorKind::InvalidData),
990 ),
991 platform: Annotated(
992 Some("other".to_owned()),
993 Meta::from_error(ErrorKind::InvalidData),
994 ),
995 ..Default::default()
996 });
997
998 assert_eq!(event, Annotated::<Event>::from_json(json).unwrap());
999 assert_eq!(json, event.to_json_pretty().unwrap());
1000 }
1001
1002 #[test]
1003 fn test_event_type() {
1004 assert_eq!(
1005 EventType::Default,
1006 *Annotated::<EventType>::from_json("\"default\"")
1007 .unwrap()
1008 .value()
1009 .unwrap()
1010 );
1011 }
1012
1013 #[test]
1014 fn test_fingerprint_empty_string() {
1015 let json = r#"{"fingerprint":[""]}"#;
1016 let event = Annotated::new(Event {
1017 fingerprint: Annotated::new(vec!["".to_owned()].into()),
1018 ..Default::default()
1019 });
1020
1021 assert_eq!(json, event.to_json().unwrap());
1022 assert_eq!(event, Annotated::from_json(json).unwrap());
1023 }
1024
1025 #[test]
1026 fn test_fingerprint_null_values() {
1027 let input = r#"{"fingerprint":[null]}"#;
1028 let output = r#"{}"#;
1029 let event = Annotated::new(Event {
1030 fingerprint: Annotated::new(vec![].into()),
1031 ..Default::default()
1032 });
1033
1034 assert_eq!(event, Annotated::from_json(input).unwrap());
1035 assert_eq!(output, event.to_json().unwrap());
1036 }
1037
1038 #[test]
1039 fn test_empty_threads() {
1040 let input = r#"{"threads": {}}"#;
1041 let output = r#"{}"#;
1042
1043 let event = Annotated::new(Event::default());
1044
1045 assert_eq!(event, Annotated::from_json(input).unwrap());
1046 assert_eq!(output, event.to_json().unwrap());
1047 }
1048
1049 #[test]
1050 fn test_lenient_release() {
1051 let input = r#"{"release":42}"#;
1052 let output = r#"{"release":"42"}"#;
1053 let event = Annotated::new(Event {
1054 release: Annotated::new("42".to_owned().into()),
1055 ..Default::default()
1056 });
1057
1058 assert_eq!(event, Annotated::from_json(input).unwrap());
1059 assert_eq!(output, event.to_json().unwrap());
1060 }
1061
1062 #[test]
1063 fn test_extra_at() {
1064 let json = serde_json::json!({
1065 "extra": {
1066 "a": "string1",
1067 "b": 42,
1068 "c": {
1069 "d": "string2",
1070 "e": null,
1071 },
1072 },
1073 });
1074
1075 let event = Event::from_value(json.into());
1076 let event = event.value().unwrap();
1077
1078 assert_eq!(
1079 Some(&Value::String("string1".to_owned())),
1080 event.extra_at("a")
1081 );
1082 assert_eq!(Some(&Value::I64(42)), event.extra_at("b"));
1083 assert!(matches!(event.extra_at("c"), Some(&Value::Object(_))));
1084 assert_eq!(None, event.extra_at("d"));
1085 assert_eq!(
1086 Some(&Value::String("string2".to_owned())),
1087 event.extra_at("c.d")
1088 );
1089 assert_eq!(None, event.extra_at("c.e"));
1090 assert_eq!(None, event.extra_at("c.f"));
1091 }
1092
1093 #[test]
1094 fn test_scrape_attempts() {
1095 let json = serde_json::json!({
1096 "scraping_attempts": [
1097 {"status": "not_attempted", "url": "http://example.com/embedded.js"},
1098 {"status": "not_attempted", "url": "http://example.com/embedded.js.map"},
1099 ]
1100 });
1101
1102 let event = Event::from_value(json.into());
1103 assert!(!event.value().unwrap().scraping_attempts.meta().has_errors());
1104 }
1105
1106 #[test]
1107 fn test_field_value_provider_event_filled() {
1108 let event = Event {
1109 level: Annotated::new(Level::Info),
1110 release: Annotated::new(LenientString("1.1.1".to_owned())),
1111 environment: Annotated::new("prod".to_owned()),
1112 user: Annotated::new(User {
1113 ip_address: Annotated::new(IpAddr("127.0.0.1".to_owned())),
1114 id: Annotated::new(LenientString("user-id".into())),
1115 segment: Annotated::new("user-seg".into()),
1116 sentry_user: Annotated::new("id:user-id".into()),
1117 ..Default::default()
1118 }),
1119 client_sdk: Annotated::new(ClientSdkInfo {
1120 name: Annotated::new("sentry-javascript".into()),
1121 version: Annotated::new("1.87.0".into()),
1122 ..Default::default()
1123 }),
1124 exceptions: Annotated::new(Values {
1125 values: Annotated::new(vec![Annotated::new(Exception {
1126 value: Annotated::new(JsonLenientString::from(
1127 "canvas.contentDocument".to_owned(),
1128 )),
1129 ..Default::default()
1130 })]),
1131 ..Default::default()
1132 }),
1133 logentry: Annotated::new(LogEntry {
1134 formatted: Annotated::new("formatted".to_owned().into()),
1135 message: Annotated::new("message".to_owned().into()),
1136 ..Default::default()
1137 }),
1138 request: Annotated::new(Request {
1139 headers: Annotated::new(Headers(PairList(vec![Annotated::new((
1140 Annotated::new("user-agent".into()),
1141 Annotated::new("Slurp".into()),
1142 ))]))),
1143 url: Annotated::new("https://sentry.io".into()),
1144 ..Default::default()
1145 }),
1146 transaction: Annotated::new("some-transaction".into()),
1147 transaction_info: Annotated::new(TransactionInfo {
1148 source: Annotated::new(TransactionSource::Route),
1149 ..Default::default()
1150 }),
1151 tags: {
1152 let items = vec![Annotated::new(TagEntry(
1153 Annotated::new("custom".to_owned()),
1154 Annotated::new("custom-value".to_owned()),
1155 ))];
1156 Annotated::new(Tags(items.into()))
1157 },
1158 contexts: Annotated::new({
1159 let mut contexts = Contexts::new();
1160 contexts.add(DeviceContext {
1161 name: Annotated::new("iphone".to_owned()),
1162 family: Annotated::new("iphone-fam".to_owned()),
1163 model: Annotated::new("iphone7,3".to_owned()),
1164 screen_dpi: Annotated::new(560),
1165 screen_width_pixels: Annotated::new(1920),
1166 screen_height_pixels: Annotated::new(1080),
1167 locale: Annotated::new("US".into()),
1168 uuid: Annotated::new(uuid!("abadcade-feed-dead-beef-baddadfeeded")),
1169 charging: Annotated::new(true),
1170 ..DeviceContext::default()
1171 });
1172 contexts.add(OsContext {
1173 name: Annotated::new("iOS".to_owned()),
1174 version: Annotated::new("11.4.2".to_owned()),
1175 kernel_version: Annotated::new("17.4.0".to_owned()),
1176 ..OsContext::default()
1177 });
1178 contexts.add(ProfileContext {
1179 profile_id: Annotated::new(EventId(uuid!(
1180 "abadcade-feed-dead-beef-8addadfeedaa"
1181 ))),
1182 ..ProfileContext::default()
1183 });
1184 let mut monitor_context_fields = BTreeMap::new();
1185 monitor_context_fields.insert(
1186 "id".to_owned(),
1187 Annotated::new(Value::String("123".to_owned())),
1188 );
1189 monitor_context_fields.insert(
1190 "slug".to_owned(),
1191 Annotated::new(Value::String("my_monitor".to_owned())),
1192 );
1193 contexts.add(MonitorContext(monitor_context_fields));
1194 contexts
1195 }),
1196 ..Default::default()
1197 };
1198
1199 assert_eq!(Some(Val::String("info")), event.get_value("event.level"));
1200
1201 assert_eq!(Some(Val::String("1.1.1")), event.get_value("event.release"));
1202 assert_eq!(
1203 Some(Val::String("prod")),
1204 event.get_value("event.environment")
1205 );
1206 assert_eq!(
1207 Some(Val::String("user-id")),
1208 event.get_value("event.user.id")
1209 );
1210 assert_eq!(
1211 Some(Val::String("id:user-id")),
1212 event.get_value("event.sentry_user")
1213 );
1214 assert_eq!(
1215 Some(Val::String("user-seg")),
1216 event.get_value("event.user.segment")
1217 );
1218 assert_eq!(
1219 Some(Val::String("some-transaction")),
1220 event.get_value("event.transaction")
1221 );
1222 assert_eq!(
1223 Some(Val::String("iphone")),
1224 event.get_value("event.contexts.device.name")
1225 );
1226 assert_eq!(
1227 Some(Val::String("iphone-fam")),
1228 event.get_value("event.contexts.device.family")
1229 );
1230 assert_eq!(
1231 Some(Val::String("iOS")),
1232 event.get_value("event.contexts.os.name")
1233 );
1234 assert_eq!(
1235 Some(Val::String("11.4.2")),
1236 event.get_value("event.contexts.os.version")
1237 );
1238 assert_eq!(
1239 Some(Val::String("custom-value")),
1240 event.get_value("event.tags.custom")
1241 );
1242 assert_eq!(None, event.get_value("event.tags.doesntexist"));
1243 assert_eq!(
1244 Some(Val::String("sentry-javascript")),
1245 event.get_value("event.sdk.name")
1246 );
1247 assert_eq!(
1248 Some(Val::String("1.87.0")),
1249 event.get_value("event.sdk.version")
1250 );
1251 assert_eq!(
1252 Some(Val::String("17.4.0")),
1253 event.get_value("event.contexts.os.kernel_version")
1254 );
1255 assert_eq!(
1256 Some(Val::I64(560)),
1257 event.get_value("event.contexts.device.screen_dpi")
1258 );
1259 assert_eq!(
1260 Some(Val::Bool(true)),
1261 event.get_value("event.contexts.device.charging")
1262 );
1263 assert_eq!(
1264 Some(Val::U64(1920)),
1265 event.get_value("event.contexts.device.screen_width_pixels")
1266 );
1267 assert_eq!(
1268 Some(Val::U64(1080)),
1269 event.get_value("event.contexts.device.screen_height_pixels")
1270 );
1271 assert_eq!(
1272 Some(Val::String("US")),
1273 event.get_value("event.contexts.device.locale")
1274 );
1275 assert_eq!(
1276 Some(Val::HexId(HexId(
1277 uuid!("abadcade-feed-dead-beef-baddadfeeded").as_bytes()
1278 ))),
1279 event.get_value("event.contexts.device.uuid")
1280 );
1281 assert_eq!(
1282 Some(Val::String("https://sentry.io")),
1283 event.get_value("event.request.url")
1284 );
1285 assert_eq!(
1286 Some(Val::HexId(HexId(
1287 uuid!("abadcade-feed-dead-beef-8addadfeedaa").as_bytes()
1288 ))),
1289 event.get_value("event.contexts.profile.profile_id")
1290 );
1291 assert_eq!(
1292 Some(Val::String("route")),
1293 event.get_value("event.transaction.source")
1294 );
1295
1296 let mut exceptions = event.get_iter("event.exception.values").unwrap();
1297 let exception = exceptions.next().unwrap();
1298 assert_eq!(
1299 Some(Val::String("canvas.contentDocument")),
1300 exception.get_value("value")
1301 );
1302 assert!(exceptions.next().is_none());
1303
1304 assert_eq!(
1305 Some(Val::String("formatted")),
1306 event.get_value("event.logentry.formatted")
1307 );
1308 assert_eq!(
1309 Some(Val::String("message")),
1310 event.get_value("event.logentry.message")
1311 );
1312 assert_eq!(
1313 Some(Val::String("123")),
1314 event.get_value("event.contexts.monitor.id")
1315 );
1316 assert_eq!(
1317 Some(Val::String("my_monitor")),
1318 event.get_value("event.contexts.monitor.slug")
1319 );
1320 }
1321
1322 #[test]
1323 fn test_field_value_provider_event_empty() {
1324 let event = Event::default();
1325
1326 assert_eq!(None, event.get_value("event.release"));
1327 assert_eq!(None, event.get_value("event.environment"));
1328 assert_eq!(None, event.get_value("event.user.id"));
1329 assert_eq!(None, event.get_value("event.user.segment"));
1330
1331 let event = Event {
1333 user: Annotated::new(User {
1334 ..Default::default()
1335 }),
1336 ..Default::default()
1337 };
1338
1339 assert_eq!(None, event.get_value("event.user.id"));
1340 assert_eq!(None, event.get_value("event.user.segment"));
1341 assert_eq!(None, event.get_value("event.transaction"));
1342 }
1343}