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, Fingerprint, GpuContext, LenientString,
16 Level, LogEntry, Measurements, Metrics, MonitorContext, OsContext, ProfileContext, RelayInfo,
17 Request, ResponseContext, RuntimeContext, Span, SpanId, Stacktrace, Tags, TemplateInfo, Thread,
18 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 = Event::MAX_CULPRIT_CHARS, pii = "maybe")]
201 pub culprit: Annotated<String>,
202
203 #[metastructure(max_chars = Event::MAX_TRANSACTION_CHARS, 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 = Event::MAX_RELEASE_CHARS, 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 = Event::MAX_ENVIRONMENT_CHARS,
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(max_bytes = 819200)]
449 #[metastructure(omit_from_schema)] pub spans: Annotated<Array<Span>>,
451
452 #[metastructure(skip_serialization = "empty")]
457 #[metastructure(omit_from_schema)] pub measurements: Annotated<Measurements>,
459
460 #[metastructure(skip_serialization = "empty")]
462 #[metastructure(omit_from_schema)] pub breakdowns: Annotated<Breakdowns>,
464
465 #[metastructure(omit_from_schema)] pub scraping_attempts: Annotated<Value>,
469
470 #[metastructure(omit_from_schema)]
474 pub _metrics: Annotated<Metrics>,
475
476 #[metastructure(omit_from_schema)]
478 pub _dsc: Annotated<Value>,
479
480 #[metastructure(
485 field = "_performance_issues_spans",
486 skip_serialization = "empty",
487 trim = false
488 )]
489 pub performance_issues_spans: Annotated<bool>,
490
491 #[metastructure(additional_properties, pii = "true")]
493 pub other: Object<Value>,
494}
495
496impl Event {
497 pub const MAX_TRANSACTION_CHARS: usize = 200;
499
500 pub const MAX_RELEASE_CHARS: usize = 200;
502
503 pub const MAX_ENVIRONMENT_CHARS: usize = 64;
505
506 pub const MAX_CULPRIT_CHARS: usize = 200;
508
509 pub fn tag_value(&self, tag_key: &str) -> Option<&str> {
514 if let Some(tags) = self.tags.value() {
515 tags.get(tag_key)
516 } else {
517 None
518 }
519 }
520
521 pub fn has_module(&self, module_name: &str) -> bool {
523 self.modules
524 .value()
525 .map(|m| m.contains_key(module_name))
526 .unwrap_or(false)
527 }
528
529 pub fn sdk_name(&self) -> &str {
533 if let Some(client_sdk) = self.client_sdk.value()
534 && let Some(name) = client_sdk.name.as_str()
535 {
536 return name;
537 }
538
539 "unknown"
540 }
541
542 pub fn sdk_version(&self) -> &str {
546 if let Some(client_sdk) = self.client_sdk.value()
547 && let Some(version) = client_sdk.version.as_str()
548 {
549 return version;
550 }
551
552 "unknown"
553 }
554
555 pub fn user_agent(&self) -> Option<&str> {
560 let headers = self.request.value()?.headers.value()?;
561
562 for item in headers.iter() {
563 if let Some((o_k, v)) = item.value()
564 && let Some(k) = o_k.as_str()
565 && k.eq_ignore_ascii_case("user-agent")
566 {
567 return v.as_str();
568 }
569 }
570
571 None
572 }
573
574 pub fn extra_at(&self, path: &str) -> Option<&Value> {
579 let mut path = path.split('.');
580
581 let mut value = &self.extra.value()?.get(path.next()?)?.value()?.0;
583
584 for key in path {
586 if let Value::Object(object) = value {
587 value = object.get(key)?.value()?;
588 } else {
589 return None;
590 }
591 }
592
593 Some(value)
594 }
595
596 pub fn parse_release(&self) -> Option<ParsedRelease<'_>> {
598 sentry_release_parser::Release::parse(self.release.as_str()?).ok()
599 }
600
601 pub fn measurement(&self, name: &str) -> Option<FiniteF64> {
605 let annotated = self.measurements.value()?.get(name)?;
606 Some(*annotated.value()?.value.value()?)
607 }
608
609 pub fn breakdown(&self, breakdown: &str, measurement: &str) -> Option<FiniteF64> {
611 let breakdown = self.breakdowns.value()?.get(breakdown)?.value()?;
612 Some(*breakdown.get(measurement)?.value()?.value.value()?)
613 }
614
615 pub fn context<C: DefaultContext>(&self) -> Option<&C> {
617 self.contexts.value()?.get()
618 }
619
620 pub fn context_mut<C: DefaultContext>(&mut self) -> Option<&mut C> {
622 self.contexts.value_mut().as_mut()?.get_mut()
623 }
624}
625
626fn or_none(string: &Annotated<impl AsRef<str>>) -> Option<&str> {
627 match string.as_str() {
628 None | Some("") => None,
629 Some(other) => Some(other),
630 }
631}
632
633impl Getter for Event {
634 fn get_value(&self, path: &str) -> Option<Val<'_>> {
635 Some(match path.strip_prefix("event.")? {
636 "level" => self.level.value()?.name().into(),
638 "release" => self.release.as_str()?.into(),
639 "dist" => self.dist.as_str()?.into(),
640 "environment" => self.environment.as_str()?.into(),
641 "transaction" => self.transaction.as_str()?.into(),
642 "logger" => self.logger.as_str()?.into(),
643 "platform" => self.platform.as_str().unwrap_or("other").into(),
644
645 "logentry.formatted" => self.logentry.value()?.formatted.value()?.as_ref().into(),
647 "logentry.message" => self.logentry.value()?.message.value()?.as_ref().into(),
648 "user.email" => or_none(&self.user.value()?.email)?.into(),
649 "user.id" => or_none(&self.user.value()?.id)?.into(),
650 "user.ip_address" => self.user.value()?.ip_address.as_str()?.into(),
651 "user.name" => self.user.value()?.name.as_str()?.into(),
652 "user.segment" => or_none(&self.user.value()?.segment)?.into(),
653 "user.geo.city" => self.user.value()?.geo.value()?.city.as_str()?.into(),
654 "user.geo.country_code" => self
655 .user
656 .value()?
657 .geo
658 .value()?
659 .country_code
660 .as_str()?
661 .into(),
662 "user.geo.region" => self.user.value()?.geo.value()?.region.as_str()?.into(),
663 "user.geo.subdivision" => self.user.value()?.geo.value()?.subdivision.as_str()?.into(),
664 "request.method" => self.request.value()?.method.as_str()?.into(),
665 "request.url" => self.request.value()?.url.as_str()?.into(),
666 "transaction.source" => self
667 .transaction_info
668 .value()?
669 .source
670 .value()?
671 .as_str()
672 .into(),
673 "sdk.name" => self.client_sdk.value()?.name.as_str()?.into(),
674 "sdk.version" => self.client_sdk.value()?.version.as_str()?.into(),
675
676 "contexts.app.in_foreground" => {
678 self.context::<AppContext>()?.in_foreground.value()?.into()
679 }
680 "contexts.app.device_app_hash" => self
681 .context::<AppContext>()?
682 .device_app_hash
683 .as_str()?
684 .into(),
685 "contexts.device.arch" => self.context::<DeviceContext>()?.arch.as_str()?.into(),
686 "contexts.device.battery_level" => self
687 .context::<DeviceContext>()?
688 .battery_level
689 .value()?
690 .into(),
691 "contexts.device.brand" => self.context::<DeviceContext>()?.brand.as_str()?.into(),
692 "contexts.device.charging" => self.context::<DeviceContext>()?.charging.value()?.into(),
693 "contexts.device.family" => self.context::<DeviceContext>()?.family.as_str()?.into(),
694 "contexts.device.model" => self.context::<DeviceContext>()?.model.as_str()?.into(),
695 "contexts.device.locale" => self.context::<DeviceContext>()?.locale.as_str()?.into(),
696 "contexts.device.online" => self.context::<DeviceContext>()?.online.value()?.into(),
697 "contexts.device.orientation" => self
698 .context::<DeviceContext>()?
699 .orientation
700 .as_str()?
701 .into(),
702 "contexts.device.name" => self.context::<DeviceContext>()?.name.as_str()?.into(),
703 "contexts.device.screen_density" => self
704 .context::<DeviceContext>()?
705 .screen_density
706 .value()?
707 .into(),
708 "contexts.device.screen_dpi" => {
709 self.context::<DeviceContext>()?.screen_dpi.value()?.into()
710 }
711 "contexts.device.screen_width_pixels" => self
712 .context::<DeviceContext>()?
713 .screen_width_pixels
714 .value()?
715 .into(),
716 "contexts.device.screen_height_pixels" => self
717 .context::<DeviceContext>()?
718 .screen_height_pixels
719 .value()?
720 .into(),
721 "contexts.device.simulator" => {
722 self.context::<DeviceContext>()?.simulator.value()?.into()
723 }
724 "contexts.gpu.vendor_name" => {
725 self.context::<GpuContext>()?.vendor_name.as_str()?.into()
726 }
727 "contexts.gpu.name" => self.context::<GpuContext>()?.name.as_str()?.into(),
728 "contexts.monitor.id" => self.context::<MonitorContext>()?.get("id")?.value()?.into(),
729 "contexts.monitor.slug" => self
730 .context::<MonitorContext>()?
731 .get("slug")?
732 .value()?
733 .into(),
734 "contexts.os" => self.context::<OsContext>()?.os.as_str()?.into(),
735 "contexts.os.build" => self.context::<OsContext>()?.build.as_str()?.into(),
736 "contexts.os.kernel_version" => {
737 self.context::<OsContext>()?.kernel_version.as_str()?.into()
738 }
739 "contexts.os.name" => self.context::<OsContext>()?.name.as_str()?.into(),
740 "contexts.os.version" => self.context::<OsContext>()?.version.as_str()?.into(),
741 "contexts.os.rooted" => self.context::<OsContext>()?.rooted.value()?.into(),
742 "contexts.browser" => self.context::<BrowserContext>()?.browser.as_str()?.into(),
743 "contexts.browser.name" => self.context::<BrowserContext>()?.name.as_str()?.into(),
744 "contexts.browser.version" => {
745 self.context::<BrowserContext>()?.version.as_str()?.into()
746 }
747 "contexts.profile.profile_id" => {
748 (&self.context::<ProfileContext>()?.profile_id.value()?.0).into()
749 }
750 "contexts.device.uuid" => self.context::<DeviceContext>()?.uuid.value()?.into(),
751 "contexts.trace.status" => self
752 .context::<TraceContext>()?
753 .status
754 .value()?
755 .as_str()
756 .into(),
757 "contexts.trace.op" => self.context::<TraceContext>()?.op.as_str()?.into(),
758 "contexts.response.status_code" => self
759 .context::<ResponseContext>()?
760 .status_code
761 .value()?
762 .into(),
763 "contexts.unreal.crash_type" => match self.contexts.value()?.get_key("unreal")? {
764 super::Context::Other(context) => context.get("crash_type")?.value()?.into(),
765 _ => return None,
766 },
767 "contexts.runtime" => self.context::<RuntimeContext>()?.runtime.as_str()?.into(),
768 "contexts.runtime.name" => self.context::<RuntimeContext>()?.name.as_str()?.into(),
769
770 "duration" => {
772 let start = self.start_timestamp.value()?;
773 let end = self.timestamp.value()?;
774 if start <= end && self.ty.value() == Some(&EventType::Transaction) {
775 time::chrono_to_positive_millis(*end - *start).into()
776 } else {
777 return None;
778 }
779 }
780
781 path => {
783 if let Some(rest) = path.strip_prefix("release.") {
784 let release = self.parse_release()?;
785 match rest {
786 "build" => release.build_hash()?.into(),
787 "package" => release.package()?.into(),
788 "version.short" => release.version()?.raw_short().into(),
789 _ => return None,
790 }
791 } else if let Some(rest) = path.strip_prefix("measurements.") {
792 let name = rest.strip_suffix(".value")?;
793 self.measurement(name)?.into()
794 } else if let Some(rest) = path.strip_prefix("breakdowns.") {
795 let (breakdown, measurement) = rest.split_once('.')?;
796 self.breakdown(breakdown, measurement)?.into()
797 } else if let Some(rest) = path.strip_prefix("extra.") {
798 self.extra_at(rest)?.into()
799 } else if let Some(rest) = path.strip_prefix("tags.") {
800 self.tags.value()?.get(rest)?.into()
801 } else {
802 let rest = path.strip_prefix("request.headers.")?;
803 self.request
804 .value()?
805 .headers
806 .value()?
807 .get_header(rest)?
808 .into()
809 }
810 }
811 })
812 }
813
814 fn get_iter(&self, path: &str) -> Option<GetterIter<'_>> {
815 Some(match path.strip_prefix("event.")? {
816 "exception.values" => {
817 GetterIter::new_annotated(self.exceptions.value()?.values.value()?)
818 }
819 _ => return None,
820 })
821 }
822}
823
824#[cfg(test)]
825mod tests {
826 use chrono::{TimeZone, Utc};
827 use relay_protocol::{ErrorKind, HexId, Map, Meta};
828 use similar_asserts::assert_eq;
829 use std::collections::BTreeMap;
830 use uuid::uuid;
831
832 use super::*;
833 use crate::protocol::{
834 Headers, IpAddr, JsonLenientString, PairList, TagEntry, TransactionSource,
835 };
836
837 #[test]
838 fn test_event_roundtrip() {
839 let json = r#"{
841 "event_id": "52df9022835246eeb317dbd739ccd059",
842 "level": "debug",
843 "fingerprint": [
844 "myprint"
845 ],
846 "culprit": "myculprit",
847 "transaction": "mytransaction",
848 "logentry": {
849 "formatted": "mymessage"
850 },
851 "logger": "mylogger",
852 "modules": {
853 "mymodule": "1.0.0"
854 },
855 "platform": "myplatform",
856 "timestamp": 946684800.0,
857 "server_name": "myhost",
858 "release": "myrelease",
859 "dist": "mydist",
860 "environment": "myenv",
861 "tags": [
862 [
863 "tag",
864 "value"
865 ]
866 ],
867 "extra": {
868 "extra": "value"
869 },
870 "other": "value",
871 "_meta": {
872 "event_id": {
873 "": {
874 "err": [
875 "invalid_data"
876 ]
877 }
878 }
879 }
880}"#;
881
882 let event = Annotated::new(Event {
883 id: Annotated(
884 Some("52df9022-8352-46ee-b317-dbd739ccd059".parse().unwrap()),
885 Meta::from_error(ErrorKind::InvalidData),
886 ),
887 level: Annotated::new(Level::Debug),
888 fingerprint: Annotated::new(vec!["myprint".to_owned()].into()),
889 culprit: Annotated::new("myculprit".to_owned()),
890 transaction: Annotated::new("mytransaction".to_owned()),
891 logentry: Annotated::new(LogEntry {
892 formatted: Annotated::new("mymessage".to_owned().into()),
893 ..Default::default()
894 }),
895 logger: Annotated::new("mylogger".to_owned()),
896 modules: {
897 let mut map = Map::new();
898 map.insert("mymodule".to_owned(), Annotated::new("1.0.0".to_owned()));
899 Annotated::new(map)
900 },
901 platform: Annotated::new("myplatform".to_owned()),
902 timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into()),
903 server_name: Annotated::new("myhost".to_owned()),
904 release: Annotated::new("myrelease".to_owned().into()),
905 dist: Annotated::new("mydist".to_owned()),
906 environment: Annotated::new("myenv".to_owned()),
907 tags: {
908 let items = vec![Annotated::new(TagEntry(
909 Annotated::new("tag".to_owned()),
910 Annotated::new("value".to_owned()),
911 ))];
912 Annotated::new(Tags(items.into()))
913 },
914 extra: {
915 let mut map = Map::new();
916 map.insert(
917 "extra".to_owned(),
918 Annotated::new(ExtraValue(Value::String("value".to_owned()))),
919 );
920 Annotated::new(map)
921 },
922 other: {
923 let mut map = Map::new();
924 map.insert(
925 "other".to_owned(),
926 Annotated::new(Value::String("value".to_owned())),
927 );
928 map
929 },
930 ..Default::default()
931 });
932
933 assert_eq!(event, Annotated::from_json(json).unwrap());
934 assert_eq!(json, event.to_json_pretty().unwrap());
935 }
936
937 #[test]
938 fn test_event_default_values() {
939 let json = "{}";
940 let event = Annotated::new(Event::default());
941
942 assert_eq!(event, Annotated::from_json(json).unwrap());
943 assert_eq!(json, event.to_json_pretty().unwrap());
944 }
945
946 #[test]
947 fn test_event_default_values_with_meta() {
948 let json = r#"{
949 "event_id": "52df9022835246eeb317dbd739ccd059",
950 "fingerprint": [
951 "{{ default }}"
952 ],
953 "platform": "other",
954 "_meta": {
955 "event_id": {
956 "": {
957 "err": [
958 "invalid_data"
959 ]
960 }
961 },
962 "fingerprint": {
963 "": {
964 "err": [
965 "invalid_data"
966 ]
967 }
968 },
969 "platform": {
970 "": {
971 "err": [
972 "invalid_data"
973 ]
974 }
975 }
976 }
977}"#;
978
979 let event = Annotated::new(Event {
980 id: Annotated(
981 Some("52df9022-8352-46ee-b317-dbd739ccd059".parse().unwrap()),
982 Meta::from_error(ErrorKind::InvalidData),
983 ),
984 fingerprint: Annotated(
985 Some(vec!["{{ default }}".to_owned()].into()),
986 Meta::from_error(ErrorKind::InvalidData),
987 ),
988 platform: Annotated(
989 Some("other".to_owned()),
990 Meta::from_error(ErrorKind::InvalidData),
991 ),
992 ..Default::default()
993 });
994
995 assert_eq!(event, Annotated::<Event>::from_json(json).unwrap());
996 assert_eq!(json, event.to_json_pretty().unwrap());
997 }
998
999 #[test]
1000 fn test_event_type() {
1001 assert_eq!(
1002 EventType::Default,
1003 *Annotated::<EventType>::from_json("\"default\"")
1004 .unwrap()
1005 .value()
1006 .unwrap()
1007 );
1008 }
1009
1010 #[test]
1011 fn test_fingerprint_empty_string() {
1012 let json = r#"{"fingerprint":[""]}"#;
1013 let event = Annotated::new(Event {
1014 fingerprint: Annotated::new(vec!["".to_owned()].into()),
1015 ..Default::default()
1016 });
1017
1018 assert_eq!(json, event.to_json().unwrap());
1019 assert_eq!(event, Annotated::from_json(json).unwrap());
1020 }
1021
1022 #[test]
1023 fn test_fingerprint_null_values() {
1024 let input = r#"{"fingerprint":[null]}"#;
1025 let output = r#"{}"#;
1026 let event = Annotated::new(Event {
1027 fingerprint: Annotated::new(vec![].into()),
1028 ..Default::default()
1029 });
1030
1031 assert_eq!(event, Annotated::from_json(input).unwrap());
1032 assert_eq!(output, event.to_json().unwrap());
1033 }
1034
1035 #[test]
1036 fn test_empty_threads() {
1037 let input = r#"{"threads": {}}"#;
1038 let output = r#"{}"#;
1039
1040 let event = Annotated::new(Event::default());
1041
1042 assert_eq!(event, Annotated::from_json(input).unwrap());
1043 assert_eq!(output, event.to_json().unwrap());
1044 }
1045
1046 #[test]
1047 fn test_lenient_release() {
1048 let input = r#"{"release":42}"#;
1049 let output = r#"{"release":"42"}"#;
1050 let event = Annotated::new(Event {
1051 release: Annotated::new("42".to_owned().into()),
1052 ..Default::default()
1053 });
1054
1055 assert_eq!(event, Annotated::from_json(input).unwrap());
1056 assert_eq!(output, event.to_json().unwrap());
1057 }
1058
1059 #[test]
1060 fn test_extra_at() {
1061 let json = serde_json::json!({
1062 "extra": {
1063 "a": "string1",
1064 "b": 42,
1065 "c": {
1066 "d": "string2",
1067 "e": null,
1068 },
1069 },
1070 });
1071
1072 let event = Event::from_value(json.into());
1073 let event = event.value().unwrap();
1074
1075 assert_eq!(
1076 Some(&Value::String("string1".to_owned())),
1077 event.extra_at("a")
1078 );
1079 assert_eq!(Some(&Value::I64(42)), event.extra_at("b"));
1080 assert!(matches!(event.extra_at("c"), Some(&Value::Object(_))));
1081 assert_eq!(None, event.extra_at("d"));
1082 assert_eq!(
1083 Some(&Value::String("string2".to_owned())),
1084 event.extra_at("c.d")
1085 );
1086 assert_eq!(None, event.extra_at("c.e"));
1087 assert_eq!(None, event.extra_at("c.f"));
1088 }
1089
1090 #[test]
1091 fn test_scrape_attempts() {
1092 let json = serde_json::json!({
1093 "scraping_attempts": [
1094 {"status": "not_attempted", "url": "http://example.com/embedded.js"},
1095 {"status": "not_attempted", "url": "http://example.com/embedded.js.map"},
1096 ]
1097 });
1098
1099 let event = Event::from_value(json.into());
1100 assert!(!event.value().unwrap().scraping_attempts.meta().has_errors());
1101 }
1102
1103 #[test]
1104 fn test_field_value_provider_event_filled() {
1105 let event = Event {
1106 level: Annotated::new(Level::Info),
1107 release: Annotated::new(LenientString("1.1.1".to_owned())),
1108 environment: Annotated::new("prod".to_owned()),
1109 user: Annotated::new(User {
1110 ip_address: Annotated::new(IpAddr("127.0.0.1".to_owned())),
1111 id: Annotated::new(LenientString("user-id".into())),
1112 segment: Annotated::new("user-seg".into()),
1113 ..Default::default()
1114 }),
1115 client_sdk: Annotated::new(ClientSdkInfo {
1116 name: Annotated::new("sentry-javascript".into()),
1117 version: Annotated::new("1.87.0".into()),
1118 ..Default::default()
1119 }),
1120 exceptions: Annotated::new(Values {
1121 values: Annotated::new(vec![Annotated::new(Exception {
1122 value: Annotated::new(JsonLenientString::from(
1123 "canvas.contentDocument".to_owned(),
1124 )),
1125 ..Default::default()
1126 })]),
1127 ..Default::default()
1128 }),
1129 logentry: Annotated::new(LogEntry {
1130 formatted: Annotated::new("formatted".to_owned().into()),
1131 message: Annotated::new("message".to_owned().into()),
1132 ..Default::default()
1133 }),
1134 request: Annotated::new(Request {
1135 headers: Annotated::new(Headers(PairList(vec![Annotated::new((
1136 Annotated::new("user-agent".into()),
1137 Annotated::new("Slurp".into()),
1138 ))]))),
1139 url: Annotated::new("https://sentry.io".into()),
1140 ..Default::default()
1141 }),
1142 transaction: Annotated::new("some-transaction".into()),
1143 transaction_info: Annotated::new(TransactionInfo {
1144 source: Annotated::new(TransactionSource::Route),
1145 ..Default::default()
1146 }),
1147 tags: {
1148 let items = vec![Annotated::new(TagEntry(
1149 Annotated::new("custom".to_owned()),
1150 Annotated::new("custom-value".to_owned()),
1151 ))];
1152 Annotated::new(Tags(items.into()))
1153 },
1154 contexts: Annotated::new({
1155 let mut contexts = Contexts::new();
1156 contexts.add(DeviceContext {
1157 name: Annotated::new("iphone".to_owned()),
1158 family: Annotated::new("iphone-fam".to_owned()),
1159 model: Annotated::new("iphone7,3".to_owned()),
1160 screen_dpi: Annotated::new(560),
1161 screen_width_pixels: Annotated::new(1920),
1162 screen_height_pixels: Annotated::new(1080),
1163 locale: Annotated::new("US".into()),
1164 uuid: Annotated::new(uuid!("abadcade-feed-dead-beef-baddadfeeded")),
1165 charging: Annotated::new(true),
1166 ..DeviceContext::default()
1167 });
1168 contexts.add(OsContext {
1169 name: Annotated::new("iOS".to_owned()),
1170 version: Annotated::new("11.4.2".to_owned()),
1171 kernel_version: Annotated::new("17.4.0".to_owned()),
1172 ..OsContext::default()
1173 });
1174 contexts.add(ProfileContext {
1175 profile_id: Annotated::new(EventId(uuid!(
1176 "abadcade-feed-dead-beef-8addadfeedaa"
1177 ))),
1178 ..ProfileContext::default()
1179 });
1180 let mut monitor_context_fields = BTreeMap::new();
1181 monitor_context_fields.insert(
1182 "id".to_owned(),
1183 Annotated::new(Value::String("123".to_owned())),
1184 );
1185 monitor_context_fields.insert(
1186 "slug".to_owned(),
1187 Annotated::new(Value::String("my_monitor".to_owned())),
1188 );
1189 contexts.add(MonitorContext(monitor_context_fields));
1190 contexts
1191 }),
1192 ..Default::default()
1193 };
1194
1195 assert_eq!(Some(Val::String("info")), event.get_value("event.level"));
1196
1197 assert_eq!(Some(Val::String("1.1.1")), event.get_value("event.release"));
1198 assert_eq!(
1199 Some(Val::String("prod")),
1200 event.get_value("event.environment")
1201 );
1202 assert_eq!(
1203 Some(Val::String("user-id")),
1204 event.get_value("event.user.id")
1205 );
1206 assert_eq!(
1207 Some(Val::String("user-seg")),
1208 event.get_value("event.user.segment")
1209 );
1210 assert_eq!(
1211 Some(Val::String("some-transaction")),
1212 event.get_value("event.transaction")
1213 );
1214 assert_eq!(
1215 Some(Val::String("iphone")),
1216 event.get_value("event.contexts.device.name")
1217 );
1218 assert_eq!(
1219 Some(Val::String("iphone-fam")),
1220 event.get_value("event.contexts.device.family")
1221 );
1222 assert_eq!(
1223 Some(Val::String("iOS")),
1224 event.get_value("event.contexts.os.name")
1225 );
1226 assert_eq!(
1227 Some(Val::String("11.4.2")),
1228 event.get_value("event.contexts.os.version")
1229 );
1230 assert_eq!(
1231 Some(Val::String("custom-value")),
1232 event.get_value("event.tags.custom")
1233 );
1234 assert_eq!(None, event.get_value("event.tags.doesntexist"));
1235 assert_eq!(
1236 Some(Val::String("sentry-javascript")),
1237 event.get_value("event.sdk.name")
1238 );
1239 assert_eq!(
1240 Some(Val::String("1.87.0")),
1241 event.get_value("event.sdk.version")
1242 );
1243 assert_eq!(
1244 Some(Val::String("17.4.0")),
1245 event.get_value("event.contexts.os.kernel_version")
1246 );
1247 assert_eq!(
1248 Some(Val::I64(560)),
1249 event.get_value("event.contexts.device.screen_dpi")
1250 );
1251 assert_eq!(
1252 Some(Val::Bool(true)),
1253 event.get_value("event.contexts.device.charging")
1254 );
1255 assert_eq!(
1256 Some(Val::U64(1920)),
1257 event.get_value("event.contexts.device.screen_width_pixels")
1258 );
1259 assert_eq!(
1260 Some(Val::U64(1080)),
1261 event.get_value("event.contexts.device.screen_height_pixels")
1262 );
1263 assert_eq!(
1264 Some(Val::String("US")),
1265 event.get_value("event.contexts.device.locale")
1266 );
1267 assert_eq!(
1268 Some(Val::HexId(HexId(
1269 uuid!("abadcade-feed-dead-beef-baddadfeeded").as_bytes()
1270 ))),
1271 event.get_value("event.contexts.device.uuid")
1272 );
1273 assert_eq!(
1274 Some(Val::String("https://sentry.io")),
1275 event.get_value("event.request.url")
1276 );
1277 assert_eq!(
1278 Some(Val::HexId(HexId(
1279 uuid!("abadcade-feed-dead-beef-8addadfeedaa").as_bytes()
1280 ))),
1281 event.get_value("event.contexts.profile.profile_id")
1282 );
1283 assert_eq!(
1284 Some(Val::String("route")),
1285 event.get_value("event.transaction.source")
1286 );
1287
1288 let mut exceptions = event.get_iter("event.exception.values").unwrap();
1289 let exception = exceptions.next().unwrap();
1290 assert_eq!(
1291 Some(Val::String("canvas.contentDocument")),
1292 exception.get_value("value")
1293 );
1294 assert!(exceptions.next().is_none());
1295
1296 assert_eq!(
1297 Some(Val::String("formatted")),
1298 event.get_value("event.logentry.formatted")
1299 );
1300 assert_eq!(
1301 Some(Val::String("message")),
1302 event.get_value("event.logentry.message")
1303 );
1304 assert_eq!(
1305 Some(Val::String("123")),
1306 event.get_value("event.contexts.monitor.id")
1307 );
1308 assert_eq!(
1309 Some(Val::String("my_monitor")),
1310 event.get_value("event.contexts.monitor.slug")
1311 );
1312 }
1313
1314 #[test]
1315 fn test_field_value_provider_event_empty() {
1316 let event = Event::default();
1317
1318 assert_eq!(None, event.get_value("event.release"));
1319 assert_eq!(None, event.get_value("event.environment"));
1320 assert_eq!(None, event.get_value("event.user.id"));
1321 assert_eq!(None, event.get_value("event.user.segment"));
1322
1323 let event = Event {
1325 user: Annotated::new(User {
1326 ..Default::default()
1327 }),
1328 ..Default::default()
1329 };
1330
1331 assert_eq!(None, event.get_value("event.user.id"));
1332 assert_eq!(None, event.get_value("event.user.segment"));
1333 assert_eq!(None, event.get_value("event.transaction"));
1334 }
1335}