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 let path = path.strip_prefix("event.").or_else(|| {
636 let ty = self.ty.value()?.as_str();
637 path.strip_prefix(ty)?.strip_prefix('.')
638 })?;
639
640 Some(match path {
641 "level" => self.level.value()?.name().into(),
643 "release" => self.release.as_str()?.into(),
644 "dist" => self.dist.as_str()?.into(),
645 "environment" => self.environment.as_str()?.into(),
646 "transaction" => self.transaction.as_str()?.into(),
647 "logger" => self.logger.as_str()?.into(),
648 "platform" => self.platform.as_str().unwrap_or("other").into(),
649
650 "logentry.formatted" => self.logentry.value()?.formatted.value()?.as_ref().into(),
652 "logentry.message" => self.logentry.value()?.message.value()?.as_ref().into(),
653 "user.email" => or_none(&self.user.value()?.email)?.into(),
654 "user.id" => or_none(&self.user.value()?.id)?.into(),
655 "user.ip_address" => self.user.value()?.ip_address.as_str()?.into(),
656 "user.name" => self.user.value()?.name.as_str()?.into(),
657 "user.segment" => or_none(&self.user.value()?.segment)?.into(),
658 "user.geo.city" => self.user.value()?.geo.value()?.city.as_str()?.into(),
659 "user.geo.country_code" => self
660 .user
661 .value()?
662 .geo
663 .value()?
664 .country_code
665 .as_str()?
666 .into(),
667 "user.geo.region" => self.user.value()?.geo.value()?.region.as_str()?.into(),
668 "user.geo.subdivision" => self.user.value()?.geo.value()?.subdivision.as_str()?.into(),
669 "request.method" => self.request.value()?.method.as_str()?.into(),
670 "request.url" => self.request.value()?.url.as_str()?.into(),
671 "transaction.source" => self
672 .transaction_info
673 .value()?
674 .source
675 .value()?
676 .as_str()
677 .into(),
678 "sdk.name" => self.client_sdk.value()?.name.as_str()?.into(),
679 "sdk.version" => self.client_sdk.value()?.version.as_str()?.into(),
680
681 "contexts.app.in_foreground" => {
683 self.context::<AppContext>()?.in_foreground.value()?.into()
684 }
685 "contexts.app.device_app_hash" => self
686 .context::<AppContext>()?
687 .device_app_hash
688 .as_str()?
689 .into(),
690 "contexts.device.arch" => self.context::<DeviceContext>()?.arch.as_str()?.into(),
691 "contexts.device.battery_level" => self
692 .context::<DeviceContext>()?
693 .battery_level
694 .value()?
695 .into(),
696 "contexts.device.brand" => self.context::<DeviceContext>()?.brand.as_str()?.into(),
697 "contexts.device.charging" => self.context::<DeviceContext>()?.charging.value()?.into(),
698 "contexts.device.family" => self.context::<DeviceContext>()?.family.as_str()?.into(),
699 "contexts.device.model" => self.context::<DeviceContext>()?.model.as_str()?.into(),
700 "contexts.device.locale" => self.context::<DeviceContext>()?.locale.as_str()?.into(),
701 "contexts.device.online" => self.context::<DeviceContext>()?.online.value()?.into(),
702 "contexts.device.orientation" => self
703 .context::<DeviceContext>()?
704 .orientation
705 .as_str()?
706 .into(),
707 "contexts.device.name" => self.context::<DeviceContext>()?.name.as_str()?.into(),
708 "contexts.device.screen_density" => self
709 .context::<DeviceContext>()?
710 .screen_density
711 .value()?
712 .into(),
713 "contexts.device.screen_dpi" => {
714 self.context::<DeviceContext>()?.screen_dpi.value()?.into()
715 }
716 "contexts.device.screen_width_pixels" => self
717 .context::<DeviceContext>()?
718 .screen_width_pixels
719 .value()?
720 .into(),
721 "contexts.device.screen_height_pixels" => self
722 .context::<DeviceContext>()?
723 .screen_height_pixels
724 .value()?
725 .into(),
726 "contexts.device.simulator" => {
727 self.context::<DeviceContext>()?.simulator.value()?.into()
728 }
729 "contexts.gpu.vendor_name" => {
730 self.context::<GpuContext>()?.vendor_name.as_str()?.into()
731 }
732 "contexts.gpu.name" => self.context::<GpuContext>()?.name.as_str()?.into(),
733 "contexts.monitor.id" => self.context::<MonitorContext>()?.get("id")?.value()?.into(),
734 "contexts.monitor.slug" => self
735 .context::<MonitorContext>()?
736 .get("slug")?
737 .value()?
738 .into(),
739 "contexts.os" => self.context::<OsContext>()?.os.as_str()?.into(),
740 "contexts.os.build" => self.context::<OsContext>()?.build.as_str()?.into(),
741 "contexts.os.kernel_version" => {
742 self.context::<OsContext>()?.kernel_version.as_str()?.into()
743 }
744 "contexts.os.name" => self.context::<OsContext>()?.name.as_str()?.into(),
745 "contexts.os.version" => self.context::<OsContext>()?.version.as_str()?.into(),
746 "contexts.os.rooted" => self.context::<OsContext>()?.rooted.value()?.into(),
747 "contexts.browser" => self.context::<BrowserContext>()?.browser.as_str()?.into(),
748 "contexts.browser.name" => self.context::<BrowserContext>()?.name.as_str()?.into(),
749 "contexts.browser.version" => {
750 self.context::<BrowserContext>()?.version.as_str()?.into()
751 }
752 "contexts.profile.profile_id" => {
753 (&self.context::<ProfileContext>()?.profile_id.value()?.0).into()
754 }
755 "contexts.device.uuid" => self.context::<DeviceContext>()?.uuid.value()?.into(),
756 "contexts.trace.status" => self
757 .context::<TraceContext>()?
758 .status
759 .value()?
760 .as_str()
761 .into(),
762 "contexts.trace.op" => self.context::<TraceContext>()?.op.as_str()?.into(),
763 "contexts.response.status_code" => self
764 .context::<ResponseContext>()?
765 .status_code
766 .value()?
767 .into(),
768 "contexts.unreal.crash_type" => match self.contexts.value()?.get_key("unreal")? {
769 super::Context::Other(context) => context.get("crash_type")?.value()?.into(),
770 _ => return None,
771 },
772 "contexts.runtime" => self.context::<RuntimeContext>()?.runtime.as_str()?.into(),
773 "contexts.runtime.name" => self.context::<RuntimeContext>()?.name.as_str()?.into(),
774
775 "duration" => {
777 let start = self.start_timestamp.value()?;
778 let end = self.timestamp.value()?;
779 if start <= end && self.ty.value() == Some(&EventType::Transaction) {
780 time::chrono_to_positive_millis(*end - *start).into()
781 } else {
782 return None;
783 }
784 }
785
786 path => {
788 if let Some(rest) = path.strip_prefix("release.") {
789 let release = self.parse_release()?;
790 match rest {
791 "build" => release.build_hash()?.into(),
792 "package" => release.package()?.into(),
793 "version.short" => release.version()?.raw_short().into(),
794 _ => return None,
795 }
796 } else if let Some(rest) = path.strip_prefix("measurements.") {
797 let name = rest.strip_suffix(".value")?;
798 self.measurement(name)?.into()
799 } else if let Some(rest) = path.strip_prefix("breakdowns.") {
800 let (breakdown, measurement) = rest.split_once('.')?;
801 self.breakdown(breakdown, measurement)?.into()
802 } else if let Some(rest) = path.strip_prefix("extra.") {
803 self.extra_at(rest)?.into()
804 } else if let Some(rest) = path.strip_prefix("tags.") {
805 self.tags.value()?.get(rest)?.into()
806 } else {
807 let rest = path.strip_prefix("request.headers.")?;
808 self.request
809 .value()?
810 .headers
811 .value()?
812 .get_header(rest)?
813 .into()
814 }
815 }
816 })
817 }
818
819 fn get_iter(&self, path: &str) -> Option<GetterIter<'_>> {
820 let path = path.strip_prefix("event.").or_else(|| {
821 let ty = self.ty.value()?.as_str();
822 path.strip_prefix(ty)?.strip_prefix('.')
823 })?;
824
825 Some(match path {
826 "exception.values" => {
827 GetterIter::new_annotated(self.exceptions.value()?.values.value()?)
828 }
829 _ => return None,
830 })
831 }
832}
833
834#[cfg(test)]
835mod tests {
836 use chrono::{TimeZone, Utc};
837 use relay_protocol::{ErrorKind, HexId, Map, Meta};
838 use similar_asserts::assert_eq;
839 use std::collections::BTreeMap;
840 use uuid::uuid;
841
842 use super::*;
843 use crate::protocol::{
844 Headers, IpAddr, JsonLenientString, PairList, TagEntry, TransactionSource,
845 };
846
847 #[test]
848 fn test_event_roundtrip() {
849 let json = r#"{
851 "event_id": "52df9022835246eeb317dbd739ccd059",
852 "level": "debug",
853 "fingerprint": [
854 "myprint"
855 ],
856 "culprit": "myculprit",
857 "transaction": "mytransaction",
858 "logentry": {
859 "formatted": "mymessage"
860 },
861 "logger": "mylogger",
862 "modules": {
863 "mymodule": "1.0.0"
864 },
865 "platform": "myplatform",
866 "timestamp": 946684800.0,
867 "server_name": "myhost",
868 "release": "myrelease",
869 "dist": "mydist",
870 "environment": "myenv",
871 "tags": [
872 [
873 "tag",
874 "value"
875 ]
876 ],
877 "extra": {
878 "extra": "value"
879 },
880 "other": "value",
881 "_meta": {
882 "event_id": {
883 "": {
884 "err": [
885 "invalid_data"
886 ]
887 }
888 }
889 }
890}"#;
891
892 let event = Annotated::new(Event {
893 id: Annotated(
894 Some("52df9022-8352-46ee-b317-dbd739ccd059".parse().unwrap()),
895 Meta::from_error(ErrorKind::InvalidData),
896 ),
897 level: Annotated::new(Level::Debug),
898 fingerprint: Annotated::new(vec!["myprint".to_owned()].into()),
899 culprit: Annotated::new("myculprit".to_owned()),
900 transaction: Annotated::new("mytransaction".to_owned()),
901 logentry: Annotated::new(LogEntry {
902 formatted: Annotated::new("mymessage".to_owned().into()),
903 ..Default::default()
904 }),
905 logger: Annotated::new("mylogger".to_owned()),
906 modules: {
907 let mut map = Map::new();
908 map.insert("mymodule".to_owned(), Annotated::new("1.0.0".to_owned()));
909 Annotated::new(map)
910 },
911 platform: Annotated::new("myplatform".to_owned()),
912 timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into()),
913 server_name: Annotated::new("myhost".to_owned()),
914 release: Annotated::new("myrelease".to_owned().into()),
915 dist: Annotated::new("mydist".to_owned()),
916 environment: Annotated::new("myenv".to_owned()),
917 tags: {
918 let items = vec![Annotated::new(TagEntry(
919 Annotated::new("tag".to_owned()),
920 Annotated::new("value".to_owned()),
921 ))];
922 Annotated::new(Tags(items.into()))
923 },
924 extra: {
925 let mut map = Map::new();
926 map.insert(
927 "extra".to_owned(),
928 Annotated::new(ExtraValue(Value::String("value".to_owned()))),
929 );
930 Annotated::new(map)
931 },
932 other: {
933 let mut map = Map::new();
934 map.insert(
935 "other".to_owned(),
936 Annotated::new(Value::String("value".to_owned())),
937 );
938 map
939 },
940 ..Default::default()
941 });
942
943 assert_eq!(event, Annotated::from_json(json).unwrap());
944 assert_eq!(json, event.to_json_pretty().unwrap());
945 }
946
947 #[test]
948 fn test_event_default_values() {
949 let json = "{}";
950 let event = Annotated::new(Event::default());
951
952 assert_eq!(event, Annotated::from_json(json).unwrap());
953 assert_eq!(json, event.to_json_pretty().unwrap());
954 }
955
956 #[test]
957 fn test_event_default_values_with_meta() {
958 let json = r#"{
959 "event_id": "52df9022835246eeb317dbd739ccd059",
960 "fingerprint": [
961 "{{ default }}"
962 ],
963 "platform": "other",
964 "_meta": {
965 "event_id": {
966 "": {
967 "err": [
968 "invalid_data"
969 ]
970 }
971 },
972 "fingerprint": {
973 "": {
974 "err": [
975 "invalid_data"
976 ]
977 }
978 },
979 "platform": {
980 "": {
981 "err": [
982 "invalid_data"
983 ]
984 }
985 }
986 }
987}"#;
988
989 let event = Annotated::new(Event {
990 id: Annotated(
991 Some("52df9022-8352-46ee-b317-dbd739ccd059".parse().unwrap()),
992 Meta::from_error(ErrorKind::InvalidData),
993 ),
994 fingerprint: Annotated(
995 Some(vec!["{{ default }}".to_owned()].into()),
996 Meta::from_error(ErrorKind::InvalidData),
997 ),
998 platform: Annotated(
999 Some("other".to_owned()),
1000 Meta::from_error(ErrorKind::InvalidData),
1001 ),
1002 ..Default::default()
1003 });
1004
1005 assert_eq!(event, Annotated::<Event>::from_json(json).unwrap());
1006 assert_eq!(json, event.to_json_pretty().unwrap());
1007 }
1008
1009 #[test]
1010 fn test_event_type() {
1011 assert_eq!(
1012 EventType::Default,
1013 *Annotated::<EventType>::from_json("\"default\"")
1014 .unwrap()
1015 .value()
1016 .unwrap()
1017 );
1018 }
1019
1020 #[test]
1021 fn test_fingerprint_empty_string() {
1022 let json = r#"{"fingerprint":[""]}"#;
1023 let event = Annotated::new(Event {
1024 fingerprint: Annotated::new(vec!["".to_owned()].into()),
1025 ..Default::default()
1026 });
1027
1028 assert_eq!(json, event.to_json().unwrap());
1029 assert_eq!(event, Annotated::from_json(json).unwrap());
1030 }
1031
1032 #[test]
1033 fn test_fingerprint_null_values() {
1034 let input = r#"{"fingerprint":[null]}"#;
1035 let output = r#"{}"#;
1036 let event = Annotated::new(Event {
1037 fingerprint: Annotated::new(vec![].into()),
1038 ..Default::default()
1039 });
1040
1041 assert_eq!(event, Annotated::from_json(input).unwrap());
1042 assert_eq!(output, event.to_json().unwrap());
1043 }
1044
1045 #[test]
1046 fn test_empty_threads() {
1047 let input = r#"{"threads": {}}"#;
1048 let output = r#"{}"#;
1049
1050 let event = Annotated::new(Event::default());
1051
1052 assert_eq!(event, Annotated::from_json(input).unwrap());
1053 assert_eq!(output, event.to_json().unwrap());
1054 }
1055
1056 #[test]
1057 fn test_lenient_release() {
1058 let input = r#"{"release":42}"#;
1059 let output = r#"{"release":"42"}"#;
1060 let event = Annotated::new(Event {
1061 release: Annotated::new("42".to_owned().into()),
1062 ..Default::default()
1063 });
1064
1065 assert_eq!(event, Annotated::from_json(input).unwrap());
1066 assert_eq!(output, event.to_json().unwrap());
1067 }
1068
1069 #[test]
1070 fn test_extra_at() {
1071 let json = serde_json::json!({
1072 "extra": {
1073 "a": "string1",
1074 "b": 42,
1075 "c": {
1076 "d": "string2",
1077 "e": null,
1078 },
1079 },
1080 });
1081
1082 let event = Event::from_value(json.into());
1083 let event = event.value().unwrap();
1084
1085 assert_eq!(
1086 Some(&Value::String("string1".to_owned())),
1087 event.extra_at("a")
1088 );
1089 assert_eq!(Some(&Value::I64(42)), event.extra_at("b"));
1090 assert!(matches!(event.extra_at("c"), Some(&Value::Object(_))));
1091 assert_eq!(None, event.extra_at("d"));
1092 assert_eq!(
1093 Some(&Value::String("string2".to_owned())),
1094 event.extra_at("c.d")
1095 );
1096 assert_eq!(None, event.extra_at("c.e"));
1097 assert_eq!(None, event.extra_at("c.f"));
1098 }
1099
1100 #[test]
1101 fn test_scrape_attempts() {
1102 let json = serde_json::json!({
1103 "scraping_attempts": [
1104 {"status": "not_attempted", "url": "http://example.com/embedded.js"},
1105 {"status": "not_attempted", "url": "http://example.com/embedded.js.map"},
1106 ]
1107 });
1108
1109 let event = Event::from_value(json.into());
1110 assert!(!event.value().unwrap().scraping_attempts.meta().has_errors());
1111 }
1112
1113 #[test]
1114 fn test_field_value_provider_event_filled() {
1115 let event = Event {
1116 level: Annotated::new(Level::Info),
1117 release: Annotated::new(LenientString("1.1.1".to_owned())),
1118 environment: Annotated::new("prod".to_owned()),
1119 user: Annotated::new(User {
1120 ip_address: Annotated::new(IpAddr("127.0.0.1".to_owned())),
1121 id: Annotated::new(LenientString("user-id".into())),
1122 segment: Annotated::new("user-seg".into()),
1123 ..Default::default()
1124 }),
1125 client_sdk: Annotated::new(ClientSdkInfo {
1126 name: Annotated::new("sentry-javascript".into()),
1127 version: Annotated::new("1.87.0".into()),
1128 ..Default::default()
1129 }),
1130 exceptions: Annotated::new(Values {
1131 values: Annotated::new(vec![Annotated::new(Exception {
1132 value: Annotated::new(JsonLenientString::from(
1133 "canvas.contentDocument".to_owned(),
1134 )),
1135 ..Default::default()
1136 })]),
1137 ..Default::default()
1138 }),
1139 logentry: Annotated::new(LogEntry {
1140 formatted: Annotated::new("formatted".to_owned().into()),
1141 message: Annotated::new("message".to_owned().into()),
1142 ..Default::default()
1143 }),
1144 request: Annotated::new(Request {
1145 headers: Annotated::new(Headers(PairList(vec![Annotated::new((
1146 Annotated::new("user-agent".into()),
1147 Annotated::new("Slurp".into()),
1148 ))]))),
1149 url: Annotated::new("https://sentry.io".into()),
1150 ..Default::default()
1151 }),
1152 transaction: Annotated::new("some-transaction".into()),
1153 transaction_info: Annotated::new(TransactionInfo {
1154 source: Annotated::new(TransactionSource::Route),
1155 ..Default::default()
1156 }),
1157 tags: {
1158 let items = vec![Annotated::new(TagEntry(
1159 Annotated::new("custom".to_owned()),
1160 Annotated::new("custom-value".to_owned()),
1161 ))];
1162 Annotated::new(Tags(items.into()))
1163 },
1164 contexts: Annotated::new({
1165 let mut contexts = Contexts::new();
1166 contexts.add(DeviceContext {
1167 name: Annotated::new("iphone".to_owned()),
1168 family: Annotated::new("iphone-fam".to_owned()),
1169 model: Annotated::new("iphone7,3".to_owned()),
1170 screen_dpi: Annotated::new(560),
1171 screen_width_pixels: Annotated::new(1920),
1172 screen_height_pixels: Annotated::new(1080),
1173 locale: Annotated::new("US".into()),
1174 uuid: Annotated::new(uuid!("abadcade-feed-dead-beef-baddadfeeded")),
1175 charging: Annotated::new(true),
1176 ..DeviceContext::default()
1177 });
1178 contexts.add(OsContext {
1179 name: Annotated::new("iOS".to_owned()),
1180 version: Annotated::new("11.4.2".to_owned()),
1181 kernel_version: Annotated::new("17.4.0".to_owned()),
1182 ..OsContext::default()
1183 });
1184 contexts.add(ProfileContext {
1185 profile_id: Annotated::new(EventId(uuid!(
1186 "abadcade-feed-dead-beef-8addadfeedaa"
1187 ))),
1188 ..ProfileContext::default()
1189 });
1190 let mut monitor_context_fields = BTreeMap::new();
1191 monitor_context_fields.insert(
1192 "id".to_owned(),
1193 Annotated::new(Value::String("123".to_owned())),
1194 );
1195 monitor_context_fields.insert(
1196 "slug".to_owned(),
1197 Annotated::new(Value::String("my_monitor".to_owned())),
1198 );
1199 contexts.add(MonitorContext(monitor_context_fields));
1200 contexts
1201 }),
1202 ..Default::default()
1203 };
1204
1205 assert_eq!(Some(Val::String("info")), event.get_value("event.level"));
1206
1207 assert_eq!(Some(Val::String("1.1.1")), event.get_value("event.release"));
1208 assert_eq!(
1209 Some(Val::String("prod")),
1210 event.get_value("event.environment")
1211 );
1212 assert_eq!(
1213 Some(Val::String("user-id")),
1214 event.get_value("event.user.id")
1215 );
1216 assert_eq!(
1217 Some(Val::String("user-seg")),
1218 event.get_value("event.user.segment")
1219 );
1220 assert_eq!(
1221 Some(Val::String("some-transaction")),
1222 event.get_value("event.transaction")
1223 );
1224 assert_eq!(
1225 Some(Val::String("iphone")),
1226 event.get_value("event.contexts.device.name")
1227 );
1228 assert_eq!(
1229 Some(Val::String("iphone-fam")),
1230 event.get_value("event.contexts.device.family")
1231 );
1232 assert_eq!(
1233 Some(Val::String("iOS")),
1234 event.get_value("event.contexts.os.name")
1235 );
1236 assert_eq!(
1237 Some(Val::String("11.4.2")),
1238 event.get_value("event.contexts.os.version")
1239 );
1240 assert_eq!(
1241 Some(Val::String("custom-value")),
1242 event.get_value("event.tags.custom")
1243 );
1244 assert_eq!(None, event.get_value("event.tags.doesntexist"));
1245 assert_eq!(
1246 Some(Val::String("sentry-javascript")),
1247 event.get_value("event.sdk.name")
1248 );
1249 assert_eq!(
1250 Some(Val::String("1.87.0")),
1251 event.get_value("event.sdk.version")
1252 );
1253 assert_eq!(
1254 Some(Val::String("17.4.0")),
1255 event.get_value("event.contexts.os.kernel_version")
1256 );
1257 assert_eq!(
1258 Some(Val::I64(560)),
1259 event.get_value("event.contexts.device.screen_dpi")
1260 );
1261 assert_eq!(
1262 Some(Val::Bool(true)),
1263 event.get_value("event.contexts.device.charging")
1264 );
1265 assert_eq!(
1266 Some(Val::U64(1920)),
1267 event.get_value("event.contexts.device.screen_width_pixels")
1268 );
1269 assert_eq!(
1270 Some(Val::U64(1080)),
1271 event.get_value("event.contexts.device.screen_height_pixels")
1272 );
1273 assert_eq!(
1274 Some(Val::String("US")),
1275 event.get_value("event.contexts.device.locale")
1276 );
1277 assert_eq!(
1278 Some(Val::HexId(HexId(
1279 uuid!("abadcade-feed-dead-beef-baddadfeeded").as_bytes()
1280 ))),
1281 event.get_value("event.contexts.device.uuid")
1282 );
1283 assert_eq!(
1284 Some(Val::String("https://sentry.io")),
1285 event.get_value("event.request.url")
1286 );
1287 assert_eq!(
1288 Some(Val::HexId(HexId(
1289 uuid!("abadcade-feed-dead-beef-8addadfeedaa").as_bytes()
1290 ))),
1291 event.get_value("event.contexts.profile.profile_id")
1292 );
1293 assert_eq!(
1294 Some(Val::String("route")),
1295 event.get_value("event.transaction.source")
1296 );
1297
1298 let mut exceptions = event.get_iter("event.exception.values").unwrap();
1299 let exception = exceptions.next().unwrap();
1300 assert_eq!(
1301 Some(Val::String("canvas.contentDocument")),
1302 exception.get_value("value")
1303 );
1304 assert!(exceptions.next().is_none());
1305
1306 assert_eq!(
1307 Some(Val::String("formatted")),
1308 event.get_value("event.logentry.formatted")
1309 );
1310 assert_eq!(
1311 Some(Val::String("message")),
1312 event.get_value("event.logentry.message")
1313 );
1314 assert_eq!(
1315 Some(Val::String("123")),
1316 event.get_value("event.contexts.monitor.id")
1317 );
1318 assert_eq!(
1319 Some(Val::String("my_monitor")),
1320 event.get_value("event.contexts.monitor.slug")
1321 );
1322 }
1323
1324 #[test]
1325 fn test_field_value_provider_event_empty() {
1326 let event = Event::default();
1327
1328 assert_eq!(None, event.get_value("event.release"));
1329 assert_eq!(None, event.get_value("event.environment"));
1330 assert_eq!(None, event.get_value("event.user.id"));
1331 assert_eq!(None, event.get_value("event.user.segment"));
1332
1333 let event = Event {
1335 user: Annotated::new(User {
1336 ..Default::default()
1337 }),
1338 ..Default::default()
1339 };
1340
1341 assert_eq!(None, event.get_value("event.user.id"));
1342 assert_eq!(None, event.get_value("event.user.segment"));
1343 assert_eq!(None, event.get_value("event.transaction"));
1344 }
1345
1346 #[test]
1347 fn test_field_value_provider_event_type_prefix() {
1348 let event = Event {
1349 ty: Annotated::new(EventType::Transaction),
1350 transaction: Annotated::new("/users".to_owned()),
1351 release: Annotated::new(LenientString("1.1.1".to_owned())),
1352 ..Default::default()
1353 };
1354
1355 assert_eq!(
1356 Some(Val::String("/users")),
1357 event.get_value("event.transaction")
1358 );
1359 assert_eq!(
1360 Some(Val::String("/users")),
1361 event.get_value("transaction.transaction")
1362 );
1363 assert_eq!(
1364 Some(Val::String("1.1.1")),
1365 event.get_value("transaction.release")
1366 );
1367
1368 assert_eq!(None, event.get_value("error.release"));
1370 assert_eq!(None, event.get_value("transactionrelease"));
1372 }
1373}