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