1use std::collections::hash_map::DefaultHasher;
6
7use std::hash::{Hash, Hasher};
8use std::mem;
9use std::sync::OnceLock;
10
11use itertools::Itertools;
12use regex::Regex;
13use relay_base_schema::metrics::{
14 DurationUnit, FractionUnit, MetricUnit, can_be_valid_metric_name,
15};
16use relay_conventions::attributes::*;
17use relay_conventions::interpolate;
18use relay_conventions::measurements::{
19 APP_START_COLD, APP_START_WARM, FRAMES_FROZEN, FRAMES_FROZEN_RATE, FRAMES_SLOW,
20 FRAMES_SLOW_RATE, FRAMES_TOTAL, STALL_PERCENTAGE,
21};
22use relay_event_schema::processor::{self, ProcessingAction, ProcessingState, Processor};
23use relay_event_schema::protocol::{
24 AsPair, Attributes, AutoInferSetting, ClientSdkInfo, Contexts, DebugImage, DeviceClass, Event,
25 EventId, EventType, Exception, Headers, IpAddr, Level, LogEntry, Measurement, Measurements,
26 PerformanceScoreContext, ReplayContext, Request, Span, SpanId, SpanV2, Tags, Timestamp,
27 TraceContext, TraceId, User, VALID_PLATFORMS,
28};
29use relay_protocol::{
30 Annotated, Empty, Error, ErrorKind, FiniteF64, FromValue, Getter, Meta, Object, Remark,
31 RemarkType, TryFromFloatError, Value,
32};
33use relay_sampling::DynamicSamplingContext;
34use smallvec::SmallVec;
35use uuid::Uuid;
36
37use crate::normalize::request;
38use crate::span::ai::enrich_ai_event_data;
39use crate::span::tag_extraction::{extract_segment_name_from_event, extract_span_tags_from_event};
40use crate::utils::{self, MAX_DURATION_MOBILE_MS};
41use crate::{
42 BorrowedSpanOpDefaults, BreakdownsConfig, CombinedMeasurementsConfig, GeoIpLookup, MaxChars,
43 ModelMetadata, PerformanceScoreConfig, RawUserAgentInfo, SpanDescriptionRule,
44 TransactionNameConfig, breakdowns, event_error, legacy, mechanism, remove_other, schema, span,
45 stacktrace, transactions, trimming, user_agent,
46};
47
48#[derive(Clone, Debug)]
50pub struct NormalizationConfig<'a> {
51 pub project_id: Option<u64>,
53
54 pub client: Option<String>,
56
57 pub key_id: Option<String>,
61
62 pub protocol_version: Option<String>,
66
67 pub grouping_config: Option<serde_json::Value>,
72
73 pub client_ip: Option<&'a IpAddr>,
78
79 pub infer_ip_address: bool,
81
82 pub client_sample_rate: Option<f64>,
86
87 pub user_agent: RawUserAgentInfo<&'a str>,
93
94 pub max_name_and_unit_len: Option<usize>,
99
100 pub measurements: Option<CombinedMeasurementsConfig<'a>>,
106
107 pub breakdowns_config: Option<&'a BreakdownsConfig>,
109
110 pub normalize_user_agent: Option<bool>,
112
113 pub transaction_name_config: TransactionNameConfig<'a>,
115
116 pub is_renormalize: bool,
123
124 pub remove_other: bool,
126
127 pub emit_event_errors: bool,
129
130 pub enrich_spans: bool,
132
133 pub max_tag_value_length: usize, pub span_description_rules: Option<&'a Vec<SpanDescriptionRule>>,
140
141 pub performance_score: Option<&'a PerformanceScoreConfig>,
143
144 pub ai_model_metadata: Option<&'a ModelMetadata>,
146
147 pub geoip_lookup: Option<&'a GeoIpLookup>,
149
150 pub enable_trimming: bool,
154
155 pub normalize_spans: bool,
159
160 pub replay_id: Option<Uuid>,
164
165 pub span_allowed_hosts: &'a [String],
167
168 pub span_op_defaults: BorrowedSpanOpDefaults<'a>,
170
171 pub force_trace_context: bool,
182
183 pub dsc: Option<&'a DynamicSamplingContext>,
185}
186
187impl Default for NormalizationConfig<'_> {
188 fn default() -> Self {
189 Self {
190 project_id: Default::default(),
191 client: Default::default(),
192 key_id: Default::default(),
193 protocol_version: Default::default(),
194 grouping_config: Default::default(),
195 client_ip: Default::default(),
196 infer_ip_address: true,
197 client_sample_rate: Default::default(),
198 user_agent: Default::default(),
199 max_name_and_unit_len: Default::default(),
200 breakdowns_config: Default::default(),
201 normalize_user_agent: Default::default(),
202 transaction_name_config: Default::default(),
203 is_renormalize: Default::default(),
204 remove_other: Default::default(),
205 emit_event_errors: Default::default(),
206 enrich_spans: Default::default(),
207 max_tag_value_length: usize::MAX,
208 span_description_rules: Default::default(),
209 performance_score: Default::default(),
210 geoip_lookup: Default::default(),
211 ai_model_metadata: Default::default(),
212 enable_trimming: false,
213 measurements: None,
214 normalize_spans: true,
215 replay_id: Default::default(),
216 span_allowed_hosts: Default::default(),
217 span_op_defaults: Default::default(),
218 force_trace_context: Default::default(),
219 dsc: None,
220 }
221 }
222}
223
224pub fn normalize_event(event: &mut Annotated<Event>, config: &NormalizationConfig) {
229 let Annotated(Some(event), meta) = event else {
230 return;
231 };
232
233 let is_renormalize = config.is_renormalize;
234
235 let _ = legacy::LegacyProcessor.process_event(event, meta, ProcessingState::root());
237
238 if !is_renormalize {
239 let _ = schema::SchemaProcessor::new().process_event(event, meta, ProcessingState::root());
241
242 normalize(event, meta, config);
243 }
244
245 if config.enable_trimming {
246 let _ =
248 trimming::TrimmingProcessor::new().process_event(event, meta, ProcessingState::root());
249 }
250
251 if config.remove_other {
252 let _ =
254 remove_other::RemoveOtherProcessor.process_event(event, meta, ProcessingState::root());
255 }
256
257 if config.emit_event_errors {
258 let _ =
260 event_error::EmitEventErrors::new().process_event(event, meta, ProcessingState::root());
261 }
262}
263
264fn normalize(event: &mut Event, meta: &mut Meta, config: &NormalizationConfig) {
266 if config.normalize_spans && event.ty.value() == Some(&EventType::Transaction) {
269 span::normalize_conventions(event);
270 }
271
272 let mut transactions_processor = transactions::TransactionsProcessor::new(
277 config.transaction_name_config,
278 config.span_op_defaults,
279 );
280 let _ = transactions_processor.process_event(event, meta, ProcessingState::root());
281
282 let client_ip = config.client_ip.filter(|_| config.infer_ip_address);
283
284 normalize_security_report(event, client_ip, &config.user_agent);
286
287 normalize_ip_addresses(
289 &mut event.request,
290 &mut event.user,
291 event.platform.as_str(),
292 client_ip,
293 event.client_sdk.value(),
294 );
295
296 if let Some(geoip_lookup) = config.geoip_lookup {
297 normalize_user_geoinfo(geoip_lookup, &mut event.user, config.client_ip);
298 }
299
300 let _ = processor::apply(&mut event.release, |release, meta| {
302 if crate::validate_release(release).is_ok() {
303 Ok(())
304 } else {
305 meta.add_error(ErrorKind::InvalidData);
306 Err(ProcessingAction::DeleteValueSoft)
307 }
308 });
309 let _ = processor::apply(&mut event.environment, |environment, meta| {
310 if crate::validate_environment(environment).is_ok() {
311 Ok(())
312 } else {
313 meta.add_error(ErrorKind::InvalidData);
314 Err(ProcessingAction::DeleteValueSoft)
315 }
316 });
317
318 normalize_user(event);
320 normalize_logentry(&mut event.logentry, meta);
321 normalize_debug_meta(event);
322 normalize_breadcrumbs(event);
323 normalize_release_dist(event); normalize_event_tags(event); normalize_device_class(event);
328 normalize_stacktraces(event);
329 normalize_exceptions(event); normalize_user_agent(event, config.normalize_user_agent); normalize_event_measurements(event, config.measurements, config.max_name_and_unit_len); backfill_app_vitals_start(event);
333 if let Some(version) = normalize_performance_score(event, config.performance_score) {
334 event
335 .contexts
336 .get_or_insert_with(Contexts::new)
337 .get_or_default::<PerformanceScoreContext>()
338 .score_profile_version = Annotated::new(version);
339 }
340 enrich_ai_event_data(event, config.ai_model_metadata);
341 normalize_breakdowns(event, config.breakdowns_config); normalize_default_attributes(event, meta, config);
343 normalize_trace_context_tags(event);
344 normalize_replay_context(event, config.replay_id);
345
346 let _ = processor::apply(&mut event.request, |request, _| {
347 request::normalize_request(request);
348 Ok(())
349 });
350
351 if config.force_trace_context && event.ty.value() != Some(&EventType::Transaction) {
352 normalize_force_trace_context(event, config.dsc);
353 }
354
355 normalize_contexts(&mut event.contexts);
357
358 if config.normalize_spans && event.ty.value() == Some(&EventType::Transaction) {
359 span::normalize_dsc_for_event_spans(event, config);
360 span::normalize_app_start_spans(event);
361 span::exclusive_time::compute_span_exclusive_time(event);
362 }
363
364 if config.enrich_spans {
365 extract_span_tags_from_event(
366 event,
367 config.max_tag_value_length,
368 config.span_allowed_hosts,
369 );
370 extract_segment_name_from_event(event, config.max_tag_value_length);
371 }
372
373 if let Some(context) = event.context_mut::<TraceContext>() {
374 context.client_sample_rate = Annotated::from(config.client_sample_rate);
375 }
376}
377
378fn normalize_replay_context(event: &mut Event, replay_id: Option<Uuid>) {
379 if let Some(replay_id) = replay_id {
380 let contexts = event.contexts.get_or_insert_with(Contexts::default);
381 contexts.add(ReplayContext {
382 replay_id: Annotated::new(EventId(replay_id)),
383 other: Object::default(),
384 });
385 }
386}
387
388fn normalize_security_report(
390 event: &mut Event,
391 client_ip: Option<&IpAddr>,
392 user_agent: &RawUserAgentInfo<&str>,
393) {
394 if !is_security_report(event) {
395 return;
397 }
398
399 event.logger.get_or_insert_with(|| "csp".to_owned());
400
401 if let Some(client_ip) = client_ip {
402 let user = event.user.value_mut().get_or_insert_with(User::default);
403 user.ip_address = Annotated::new(client_ip.to_owned());
404 }
405
406 if !user_agent.is_empty() {
407 let headers = event
408 .request
409 .value_mut()
410 .get_or_insert_with(Request::default)
411 .headers
412 .value_mut()
413 .get_or_insert_with(Headers::default);
414
415 user_agent.populate_event_headers(headers);
416 }
417}
418
419fn is_security_report(event: &Event) -> bool {
420 event.csp.value().is_some()
421}
422
423pub fn normalize_ip_addresses(
425 request: &mut Annotated<Request>,
426 user: &mut Annotated<User>,
427 platform: Option<&str>,
428 client_ip: Option<&IpAddr>,
429 client_sdk_settings: Option<&ClientSdkInfo>,
430) {
431 let infer_ip = client_sdk_settings
432 .and_then(|c| c.settings.0.as_ref())
433 .map(|s| s.infer_ip())
434 .unwrap_or_default();
435
436 let client_ip = client_ip
437 .filter(|ip| infer_ip != AutoInferSetting::Never && !ip.is_auto() && ip.is_valid());
438 let remote_addr_ip = normalize_remote_addr(request, client_ip);
439
440 if infer_ip == AutoInferSetting::Never {
441 if let Some(user) = user.value_mut()
442 && user.ip_address.value().is_some_and(IpAddr::is_auto)
443 {
444 user.ip_address.set_value(None);
445 }
446 return;
447 }
448
449 let inferred_ip = remote_addr_ip.as_ref().or(client_ip);
452
453 if let Some(user) = user.value()
455 && user.ip_address.value().is_none()
456 && user
457 .ip_address
458 .meta()
459 .iter_remarks()
460 .any(|r| r.ty == RemarkType::Removed)
461 {
462 return;
463 }
464
465 let should_be_inferred = match user.value() {
469 Some(user) => match user.ip_address.value() {
470 Some(ip) => ip.is_auto(),
471 None => matches!(infer_ip, AutoInferSetting::Auto),
472 },
473 None => matches!(infer_ip, AutoInferSetting::Auto),
474 };
475
476 if should_be_inferred {
477 if let Some(ip) = inferred_ip {
478 let user = user.get_or_insert_with(User::default);
479 user.ip_address.set_value(Some(ip.to_owned()));
480 } else if let Some(user) = user.value_mut() {
481 user.ip_address.set_value(None);
482 }
483 }
484
485 if infer_ip == AutoInferSetting::Legacy {
489 if let Some(http_ip) = remote_addr_ip {
490 let user = user.get_or_insert_with(User::default);
491 user.ip_address.value_mut().get_or_insert(http_ip);
492 } else if let Some(client_ip) = inferred_ip {
493 let user = user.get_or_insert_with(User::default);
494 if user.ip_address.value().is_none()
497 && matches!(platform, Some("javascript" | "cocoa" | "objc"))
498 {
499 user.ip_address = Annotated::new(client_ip.to_owned());
500 }
501 }
502 }
503}
504
505fn normalize_remote_addr(
507 request: &mut Annotated<Request>,
508 client_ip: Option<&IpAddr>,
509) -> Option<IpAddr> {
510 let env = request.value_mut().as_mut()?.env.value_mut().as_mut()?;
511 let remote_addr = env.get_mut("REMOTE_ADDR")?;
512 let ip = IpAddr::parse(remote_addr.as_str()?).ok()?;
513 if !ip.is_auto() {
514 return Some(ip);
515 }
516
517 if let Some(ip) = client_ip {
518 remote_addr.set_value(Some(Value::String(ip.to_string())));
519 } else {
520 env.remove("REMOTE_ADDR");
521 }
522 client_ip.cloned()
523}
524
525pub fn normalize_user_geoinfo(
527 geoip_lookup: &GeoIpLookup,
528 user: &mut Annotated<User>,
529 ip_addr: Option<&IpAddr>,
530) {
531 let user = user.value_mut().get_or_insert_with(User::default);
532 if user.geo.value().is_some() {
534 return;
535 }
536 if let Some(ip_address) = user
537 .ip_address
538 .value()
539 .filter(|ip| !ip.is_auto())
540 .or(ip_addr)
541 .and_then(|ip| ip.as_str().parse().ok())
542 && let Some(geo) = geoip_lookup.lookup(ip_address)
543 {
544 user.geo.set_value(Some(geo));
545 }
546}
547
548fn normalize_user(event: &mut Event) {
549 let Annotated(Some(user), _) = &mut event.user else {
550 return;
551 };
552
553 if !user.other.is_empty() {
554 let data = user.data.value_mut().get_or_insert_with(Object::new);
555 data.extend(std::mem::take(&mut user.other));
556 }
557}
558
559fn normalize_logentry(logentry: &mut Annotated<LogEntry>, _meta: &mut Meta) {
560 let _ = processor::apply(logentry, |logentry, meta| {
561 crate::logentry::normalize_logentry(logentry, meta)
562 });
563}
564
565fn normalize_debug_meta(event: &mut Event) {
567 let Annotated(Some(debug_meta), _) = &mut event.debug_meta else {
568 return;
569 };
570 let Annotated(Some(debug_images), _) = &mut debug_meta.images else {
571 return;
572 };
573
574 for annotated_image in debug_images {
575 let _ = processor::apply(annotated_image, |image, meta| match image {
576 DebugImage::Other(_) => {
577 meta.add_error(Error::invalid("unsupported debug image type"));
578 Err(ProcessingAction::DeleteValueSoft)
579 }
580 _ => Ok(()),
581 });
582 }
583}
584
585fn normalize_breadcrumbs(event: &mut Event) {
586 let Annotated(Some(breadcrumbs), _) = &mut event.breadcrumbs else {
587 return;
588 };
589 let Some(breadcrumbs) = breadcrumbs.values.value_mut() else {
590 return;
591 };
592
593 for annotated_breadcrumb in breadcrumbs {
594 let Annotated(Some(breadcrumb), _) = annotated_breadcrumb else {
595 continue;
596 };
597
598 if breadcrumb.ty.value().is_empty() {
599 breadcrumb.ty.set_value(Some("default".to_owned()));
600 }
601 if breadcrumb.level.value().is_none() {
602 breadcrumb.level.set_value(Some(Level::Info));
603 }
604 }
605}
606
607fn normalize_release_dist(event: &mut Event) {
609 normalize_dist(&mut event.dist);
610}
611
612fn normalize_dist(distribution: &mut Annotated<String>) {
613 let _ = processor::apply(distribution, |dist, meta| {
614 let trimmed = dist.trim();
615 if trimmed.is_empty() {
616 return Err(ProcessingAction::DeleteValueHard);
617 } else if bytecount::num_chars(trimmed.as_bytes()) > MaxChars::Distribution.limit() {
618 meta.add_error(Error::new(ErrorKind::ValueTooLong));
619 return Err(ProcessingAction::DeleteValueSoft);
620 } else if trimmed != dist {
621 *dist = trimmed.to_owned();
622 }
623 Ok(())
624 });
625}
626
627struct DedupCache(SmallVec<[u64; 16]>);
628
629impl DedupCache {
630 pub fn new() -> Self {
631 Self(SmallVec::default())
632 }
633
634 pub fn probe<H: Hash>(&mut self, element: H) -> bool {
635 let mut hasher = DefaultHasher::new();
636 element.hash(&mut hasher);
637 let hash = hasher.finish();
638
639 if self.0.contains(&hash) {
640 false
641 } else {
642 self.0.push(hash);
643 true
644 }
645 }
646}
647
648fn normalize_event_tags(event: &mut Event) {
650 let tags = &mut event.tags.value_mut().get_or_insert_with(Tags::default).0;
651 let environment = &mut event.environment;
652 if environment.is_empty() {
653 *environment = Annotated::empty();
654 }
655
656 if let Some(tag) = tags.remove("environment").and_then(Annotated::into_value) {
658 environment.get_or_insert_with(|| tag);
659 }
660
661 let mut tag_cache = DedupCache::new();
664 tags.retain(|entry| {
665 match entry.value() {
666 Some(tag) => match tag.key() {
667 Some("release") | Some("dist") | Some("user") | Some("filename")
668 | Some("function") => false,
669 name => tag_cache.probe(name),
670 },
671 None => true,
673 }
674 });
675
676 for tag in tags.iter_mut() {
677 let _ = processor::apply(tag, |tag, _| {
678 if let Some(key) = tag.key()
679 && key.is_empty()
680 {
681 tag.0 = Annotated::from_error(Error::nonempty(), None);
682 }
683
684 if let Some(value) = tag.value()
685 && value.is_empty()
686 {
687 tag.1 = Annotated::from_error(Error::nonempty(), None);
688 }
689
690 Ok(())
691 });
692 }
693
694 let server_name = std::mem::take(&mut event.server_name);
695 if server_name.value().is_some() {
696 let tag_name = "server_name".to_owned();
697 tags.insert(tag_name, server_name);
698 }
699
700 let site = std::mem::take(&mut event.site);
701 if site.value().is_some() {
702 let tag_name = "site".to_owned();
703 tags.insert(tag_name, site);
704 }
705}
706
707fn normalize_device_class(event: &mut Event) {
710 let tags = &mut event.tags.value_mut().get_or_insert_with(Tags::default).0;
711 let tag_name = "device.class".to_owned();
712 tags.remove("device.class");
714 if let Some(contexts) = event.contexts.value()
715 && let Some(device_class) = DeviceClass::from_contexts(contexts)
716 {
717 tags.insert(tag_name, Annotated::new(device_class.to_string()));
718 }
719}
720
721fn normalize_stacktraces(event: &mut Event) {
726 normalize_event_stacktrace(event);
727 normalize_exception_stacktraces(event);
728 normalize_thread_stacktraces(event);
729}
730
731fn normalize_event_stacktrace(event: &mut Event) {
733 let Annotated(Some(stacktrace), meta) = &mut event.stacktrace else {
734 return;
735 };
736 stacktrace::normalize_stacktrace(&mut stacktrace.0, meta);
737}
738
739fn normalize_exception_stacktraces(event: &mut Event) {
743 let Some(event_exception) = event.exceptions.value_mut() else {
744 return;
745 };
746 let Some(exceptions) = event_exception.values.value_mut() else {
747 return;
748 };
749 for annotated_exception in exceptions {
750 let Some(exception) = annotated_exception.value_mut() else {
751 continue;
752 };
753 if let Annotated(Some(stacktrace), meta) = &mut exception.stacktrace {
754 stacktrace::normalize_stacktrace(&mut stacktrace.0, meta);
755 }
756 }
757}
758
759fn normalize_thread_stacktraces(event: &mut Event) {
763 let Some(event_threads) = event.threads.value_mut() else {
764 return;
765 };
766 let Some(threads) = event_threads.values.value_mut() else {
767 return;
768 };
769 for annotated_thread in threads {
770 let Some(thread) = annotated_thread.value_mut() else {
771 continue;
772 };
773 if let Annotated(Some(stacktrace), meta) = &mut thread.stacktrace {
774 stacktrace::normalize_stacktrace(&mut stacktrace.0, meta);
775 }
776 }
777}
778
779fn normalize_exceptions(event: &mut Event) {
780 let os_hint = mechanism::OsHint::from_event(event);
781
782 if let Some(exception_values) = event.exceptions.value_mut()
783 && let Some(exceptions) = exception_values.values.value_mut()
784 {
785 if exceptions.len() == 1
786 && event.stacktrace.value().is_some()
787 && let Some(exception) = exceptions.get_mut(0)
788 && let Some(exception) = exception.value_mut()
789 {
790 mem::swap(&mut exception.stacktrace, &mut event.stacktrace);
791 event.stacktrace = Annotated::empty();
792 }
793
794 for exception in exceptions {
802 normalize_exception(exception);
803 if let Some(exception) = exception.value_mut()
804 && let Some(mechanism) = exception.mechanism.value_mut()
805 {
806 mechanism::normalize_mechanism(mechanism, os_hint);
807 }
808 }
809 }
810}
811
812fn normalize_exception(exception: &mut Annotated<Exception>) {
813 static TYPE_VALUE_RE: OnceLock<Regex> = OnceLock::new();
814 let regex = TYPE_VALUE_RE.get_or_init(|| Regex::new(r"^(\w+):(.*)$").unwrap());
815
816 let _ = processor::apply(exception, |exception, meta| {
817 if exception.ty.value().is_empty()
818 && let Some(value_str) = exception.value.value_mut()
819 {
820 let new_values = regex
821 .captures(value_str)
822 .map(|cap| (cap[1].to_string(), cap[2].trim().to_owned().into()));
823
824 if let Some((new_type, new_value)) = new_values {
825 exception.ty.set_value(Some(new_type));
826 *value_str = new_value;
827 }
828 }
829
830 if exception.ty.value().is_empty() && exception.value.value().is_empty() {
831 meta.add_error(Error::with(ErrorKind::MissingAttribute, |error| {
832 error.insert("attribute", "type or value");
833 }));
834 return Err(ProcessingAction::DeleteValueSoft);
835 }
836
837 Ok(())
838 });
839}
840
841fn normalize_user_agent(_event: &mut Event, normalize_user_agent: Option<bool>) {
842 if normalize_user_agent.unwrap_or(false) {
843 user_agent::normalize_user_agent(_event);
844 }
845}
846
847fn normalize_event_measurements(
849 event: &mut Event,
850 measurements_config: Option<CombinedMeasurementsConfig>,
851 max_mri_len: Option<usize>,
852) {
853 if event.ty.value() != Some(&EventType::Transaction) {
854 event.measurements = Annotated::empty();
856 } else if let Annotated(Some(ref mut measurements), ref mut meta) = event.measurements {
857 normalize_measurements(
858 measurements,
859 meta,
860 measurements_config,
861 max_mri_len,
862 event.start_timestamp.0,
863 event.timestamp.0,
864 );
865 }
866}
867
868pub fn normalize_measurements(
870 measurements: &mut Measurements,
871 meta: &mut Meta,
872 measurements_config: Option<CombinedMeasurementsConfig>,
873 max_mri_len: Option<usize>,
874 start_timestamp: Option<Timestamp>,
875 end_timestamp: Option<Timestamp>,
876) {
877 normalize_mobile_measurements(measurements);
878 normalize_units(measurements);
879
880 let duration_millis = start_timestamp.zip(end_timestamp).and_then(|(start, end)| {
881 FiniteF64::new(relay_common::time::chrono_to_positive_millis(end - start))
882 });
883
884 compute_measurements(duration_millis, measurements);
885 if let Some(measurements_config) = measurements_config {
886 remove_invalid_measurements(measurements, meta, measurements_config, max_mri_len);
887 }
888}
889
890pub trait MeasurementsLike {
895 fn contains_measurement(&self, key: &str) -> bool;
897 fn get_measurement_value(&self, key: &str) -> Option<FiniteF64>;
899 fn insert_measurement(&mut self, key: String, value: Measurement);
901}
902
903impl MeasurementsLike for Measurements {
904 fn contains_measurement(&self, key: &str) -> bool {
905 self.contains_key(key)
906 }
907
908 fn get_measurement_value(&self, key: &str) -> Option<FiniteF64> {
909 self.get_value(key)
910 }
911
912 fn insert_measurement(&mut self, key: String, value: Measurement) {
913 self.insert(key, value.into());
914 }
915}
916
917impl MeasurementsLike for Attributes {
918 fn contains_measurement(&self, key: &str) -> bool {
919 self.0
920 .contains_key(relay_conventions::canonical(key).unwrap_or(key))
921 }
922
923 fn get_measurement_value(&self, key: &str) -> Option<FiniteF64> {
924 let value = self.get_value(relay_conventions::canonical(key).unwrap_or(key))?;
925 match value {
926 Value::F64(v) => FiniteF64::new(*v),
927 Value::U64(v) => FiniteF64::new(*v as f64),
928 Value::I64(v) => FiniteF64::new(*v as f64),
929 _ => None,
930 }
931 }
932
933 fn insert_measurement(&mut self, key: String, measurement: Measurement) {
934 self.0
935 .insert(key, measurement.value.map_value(|v| v.to_f64().into()));
936 }
937}
938
939pub trait MutMeasurements {
944 type MeasurementsContainer: MeasurementsLike;
945 fn measurements(&mut self) -> &mut Annotated<Self::MeasurementsContainer>;
946}
947
948impl MutMeasurements for Event {
949 type MeasurementsContainer = Measurements;
950 fn measurements(&mut self) -> &mut Annotated<Self::MeasurementsContainer> {
951 &mut self.measurements
952 }
953}
954
955impl MutMeasurements for Span {
956 type MeasurementsContainer = Measurements;
957 fn measurements(&mut self) -> &mut Annotated<Self::MeasurementsContainer> {
958 &mut self.measurements
959 }
960}
961
962impl MutMeasurements for SpanV2 {
963 type MeasurementsContainer = Attributes;
964
965 fn measurements(&mut self) -> &mut Annotated<Self::MeasurementsContainer> {
966 &mut self.attributes
967 }
968}
969
970pub fn normalize_performance_score(
975 event: &mut (impl Getter + MutMeasurements),
976 performance_score: Option<&PerformanceScoreConfig>,
977) -> Option<String> {
978 let mut version = None;
979 let Some(performance_score) = performance_score else {
980 return version;
981 };
982 for profile in &performance_score.profiles {
983 if let Some(condition) = &profile.condition {
984 if !condition.matches(event) {
985 continue;
986 }
987 if let Some(measurements) = event.measurements().value_mut() {
988 let mut should_add_total = false;
989 if profile.score_components.iter().any(|c| {
990 !measurements.contains_measurement(c.measurement.as_str())
991 && c.weight.abs() >= f64::EPSILON
992 && !c.optional
993 }) {
994 continue;
998 }
999 let mut score_total = FiniteF64::ZERO;
1000 let mut weight_total = FiniteF64::ZERO;
1001 for component in &profile.score_components {
1002 if component.optional
1004 && !measurements.contains_measurement(component.measurement.as_str())
1005 {
1006 continue;
1007 }
1008 weight_total += component.weight;
1009 }
1010 if weight_total.abs() < FiniteF64::EPSILON {
1011 continue;
1014 }
1015 for component in &profile.score_components {
1016 let mut normalized_component_weight = FiniteF64::ZERO;
1018
1019 if let Some(value) =
1020 measurements.get_measurement_value(component.measurement.as_str())
1021 {
1022 normalized_component_weight = component.weight.saturating_div(weight_total);
1023 let cdf = utils::calculate_cdf_score(
1024 value.to_f64().max(0.0), component.p10.to_f64(),
1026 component.p50.to_f64(),
1027 );
1028
1029 let cdf = Annotated::try_from(cdf);
1030
1031 measurements.insert_measurement(
1032 interpolate::score__ratio__key(&component.measurement),
1033 Measurement {
1034 value: cdf.clone(),
1035 unit: (MetricUnit::Fraction(FractionUnit::Ratio)).into(),
1036 },
1037 );
1038
1039 let component_score =
1040 cdf.and_then(|cdf| match cdf * normalized_component_weight {
1041 Some(v) => Annotated::new(v),
1042 None => Annotated::from_error(TryFromFloatError, None),
1043 });
1044
1045 if let Some(component_score) = component_score.value() {
1046 score_total += *component_score;
1047 should_add_total = true;
1048 }
1049
1050 measurements.insert_measurement(
1051 interpolate::score__key(&component.measurement),
1052 Measurement {
1053 value: component_score,
1054 unit: (MetricUnit::Fraction(FractionUnit::Ratio)).into(),
1055 },
1056 );
1057 }
1058
1059 measurements.insert_measurement(
1060 interpolate::score__weight__key(&component.measurement),
1061 Measurement {
1062 value: normalized_component_weight.into(),
1063 unit: (MetricUnit::Fraction(FractionUnit::Ratio)).into(),
1064 },
1065 );
1066 }
1067 if should_add_total {
1068 version.clone_from(&profile.version);
1069 measurements.insert_measurement(
1070 SCORE__TOTAL.to_owned(),
1071 Measurement {
1072 value: score_total.into(),
1073 unit: (MetricUnit::Fraction(FractionUnit::Ratio)).into(),
1074 },
1075 );
1076 }
1077 }
1078 break; }
1080 }
1081 version
1082}
1083
1084fn normalize_trace_context_tags(event: &mut Event) {
1086 let tags = &mut event.tags.value_mut().get_or_insert_with(Tags::default).0;
1087 if let Some(contexts) = event.contexts.value()
1088 && let Some(trace_context) = contexts.get::<TraceContext>()
1089 && let Some(data) = trace_context.data.value()
1090 {
1091 if let Some(lcp_element) = data.get_str(BROWSER__WEB_VITAL__LCP__ELEMENT)
1092 && !tags.contains("lcp.element")
1093 {
1094 let tag_name = "lcp.element".to_owned();
1095 tags.insert(tag_name, Annotated::new(lcp_element.to_owned()));
1096 }
1097 if let Some(lcp_size) = data
1098 .get_value(BROWSER__WEB_VITAL__LCP__SIZE)
1099 .and_then(|value| match value {
1100 Value::U64(value) => Some(*value),
1101 Value::I64(value) => u64::try_from(*value).ok(),
1102 _ => None,
1103 })
1104 && !tags.contains("lcp.size")
1105 {
1106 let tag_name = "lcp.size".to_owned();
1107 tags.insert(tag_name, Annotated::new(lcp_size.to_string()));
1108 }
1109 if let Some(lcp_id) = data.get_str(BROWSER__WEB_VITAL__LCP__ID) {
1110 let tag_name = "lcp.id".to_owned();
1111 if !tags.contains("lcp.id") {
1112 tags.insert(tag_name, Annotated::new(lcp_id.to_owned()));
1113 }
1114 }
1115 if let Some(lcp_url) = data.get_str(BROWSER__WEB_VITAL__LCP__URL) {
1116 let tag_name = "lcp.url".to_owned();
1117 if !tags.contains("lcp.url") {
1118 tags.insert(tag_name, Annotated::new(lcp_url.to_owned()));
1119 }
1120 }
1121 }
1122}
1123
1124fn compute_measurements(
1134 transaction_duration_ms: Option<FiniteF64>,
1135 measurements: &mut Measurements,
1136) {
1137 if let Some(frames_total) = measurements.get_value(FRAMES_TOTAL)
1138 && frames_total > 0.0
1139 {
1140 if let Some(frames_frozen) = measurements.get_value(FRAMES_FROZEN) {
1141 let frames_frozen_rate = Measurement {
1142 value: (frames_frozen / frames_total).into(),
1143 unit: (MetricUnit::Fraction(FractionUnit::Ratio)).into(),
1144 };
1145 measurements.insert(FRAMES_FROZEN_RATE.to_owned(), frames_frozen_rate.into());
1146 }
1147 if let Some(frames_slow) = measurements.get_value(FRAMES_SLOW) {
1148 let frames_slow_rate = Measurement {
1149 value: (frames_slow / frames_total).into(),
1150 unit: MetricUnit::Fraction(FractionUnit::Ratio).into(),
1151 };
1152 measurements.insert(FRAMES_SLOW_RATE.to_owned(), frames_slow_rate.into());
1153 }
1154 }
1155
1156 if let Some(transaction_duration_ms) = transaction_duration_ms
1158 && transaction_duration_ms > 0.0
1159 && let Some(stall_total_time) = measurements
1160 .get("stall_total_time")
1161 .and_then(Annotated::value)
1162 && matches!(
1163 stall_total_time.unit.value(),
1164 Some(&MetricUnit::Duration(DurationUnit::MilliSecond) | &MetricUnit::None) | None
1166 )
1167 && let Some(stall_total_time) = stall_total_time.value.0
1168 {
1169 let stall_percentage = Measurement {
1170 value: (stall_total_time / transaction_duration_ms).into(),
1171 unit: (MetricUnit::Fraction(FractionUnit::Ratio)).into(),
1172 };
1173 measurements.insert(STALL_PERCENTAGE.to_owned(), stall_percentage.into());
1174 }
1175}
1176
1177fn normalize_breakdowns(event: &mut Event, breakdowns_config: Option<&BreakdownsConfig>) {
1179 match breakdowns_config {
1180 None => {}
1181 Some(config) => breakdowns::normalize_breakdowns(event, config),
1182 }
1183}
1184
1185fn normalize_default_attributes(event: &mut Event, meta: &mut Meta, config: &NormalizationConfig) {
1186 let event_type = infer_event_type(event);
1187 event.ty = Annotated::from(event_type);
1188 event.project = Annotated::from(config.project_id);
1189 event.key_id = Annotated::from(config.key_id.clone());
1190 event.version = Annotated::from(config.protocol_version.clone());
1191 event.grouping_config = config
1192 .grouping_config
1193 .clone()
1194 .map_or(Annotated::empty(), |x| {
1195 FromValue::from_value(Annotated::<Value>::from(x))
1196 });
1197
1198 let _ = relay_event_schema::processor::apply(&mut event.platform, |platform, _| {
1199 if is_valid_platform(platform) {
1200 Ok(())
1201 } else {
1202 Err(ProcessingAction::DeleteValueSoft)
1203 }
1204 });
1205
1206 event.errors.get_or_insert_with(Vec::new);
1208 event.id.get_or_insert_with(EventId::new);
1209 event.platform.get_or_insert_with(|| "other".to_owned());
1210 event.logger.get_or_insert_with(String::new);
1211 event.extra.get_or_insert_with(Object::new);
1212 event.level.get_or_insert_with(|| match event_type {
1213 EventType::Transaction => Level::Info,
1214 _ => Level::Error,
1215 });
1216 if event.client_sdk.value().is_none() {
1217 event.client_sdk.set_value(get_sdk_info(config));
1218 }
1219
1220 if event.platform.as_str() == Some("java")
1221 && let Some(event_logger) = event.logger.value_mut().take()
1222 {
1223 let shortened = shorten_logger(event_logger, meta);
1224 event.logger.set_value(Some(shortened));
1225 }
1226}
1227
1228pub fn is_valid_platform(platform: &str) -> bool {
1232 VALID_PLATFORMS.contains(&platform)
1233}
1234
1235pub fn infer_event_type(event: &Event) -> EventType {
1240 if event.ty.value() == Some(&EventType::Transaction) {
1244 return EventType::Transaction;
1245 }
1246 if event.ty.value() == Some(&EventType::UserReportV2) {
1247 return EventType::UserReportV2;
1248 }
1249
1250 let has_exceptions = event
1252 .exceptions
1253 .value()
1254 .and_then(|exceptions| exceptions.values.value())
1255 .filter(|values| !values.is_empty())
1256 .is_some();
1257
1258 if has_exceptions {
1259 EventType::Error
1260 } else if event.csp.value().is_some() {
1261 EventType::Csp
1262 } else {
1263 EventType::Default
1264 }
1265}
1266
1267fn get_sdk_info(config: &NormalizationConfig) -> Option<ClientSdkInfo> {
1269 config.client.as_ref().and_then(|client| {
1270 client
1271 .splitn(2, '/')
1272 .collect_tuple()
1273 .or_else(|| client.splitn(2, ' ').collect_tuple())
1274 .map(|(name, version)| ClientSdkInfo {
1275 name: Annotated::new(name.to_owned()),
1276 version: Annotated::new(version.to_owned()),
1277 ..Default::default()
1278 })
1279 })
1280}
1281
1282fn shorten_logger(logger: String, meta: &mut Meta) -> String {
1294 let original_len = bytecount::num_chars(logger.as_bytes());
1295 let trimmed = logger.trim();
1296 let logger_len = bytecount::num_chars(trimmed.as_bytes());
1297 if logger_len <= MaxChars::Logger.limit() {
1298 if trimmed == logger {
1299 return logger;
1300 } else {
1301 if trimmed.is_empty() {
1302 meta.add_remark(Remark {
1303 ty: RemarkType::Removed,
1304 rule_id: "@logger:remove".to_owned(),
1305 range: Some((0, original_len)),
1306 });
1307 } else {
1308 meta.add_remark(Remark {
1309 ty: RemarkType::Substituted,
1310 rule_id: "@logger:trim".to_owned(),
1311 range: None,
1312 });
1313 }
1314 meta.set_original_length(Some(original_len));
1315 return trimmed.to_owned();
1316 };
1317 }
1318
1319 let mut tokens = trimmed.split("").collect_vec();
1320 tokens.pop();
1322 tokens.reverse(); tokens.pop();
1324
1325 let word_cut = remove_logger_extra_chars(&mut tokens);
1326 if word_cut {
1327 remove_logger_word(&mut tokens);
1328 }
1329
1330 tokens.reverse();
1331 meta.add_remark(Remark {
1332 ty: RemarkType::Substituted,
1333 rule_id: "@logger:replace".to_owned(),
1334 range: Some((0, logger_len - tokens.len())),
1335 });
1336 meta.set_original_length(Some(original_len));
1337
1338 format!("*{}", tokens.join(""))
1339}
1340
1341fn remove_logger_extra_chars(tokens: &mut Vec<&str>) -> bool {
1347 let mut remove_chars = tokens.len() - MaxChars::Logger.limit() + 1;
1349 let mut word_cut = false;
1350 while remove_chars > 0 {
1351 if let Some(c) = tokens.pop() {
1352 if !word_cut && c != "." {
1353 word_cut = true;
1354 } else if word_cut && c == "." {
1355 word_cut = false;
1356 }
1357 }
1358 remove_chars -= 1;
1359 }
1360 word_cut
1361}
1362
1363fn remove_logger_word(tokens: &mut Vec<&str>) {
1366 let mut delimiter_found = false;
1367 for token in tokens.iter() {
1368 if *token == "." {
1369 delimiter_found = true;
1370 break;
1371 }
1372 }
1373 if !delimiter_found {
1374 return;
1375 }
1376 while let Some(i) = tokens.last() {
1377 if *i == "." {
1378 break;
1379 }
1380 tokens.pop();
1381 }
1382}
1383
1384fn normalize_force_trace_context(event: &mut Event, dsc: Option<&DynamicSamplingContext>) {
1389 let contexts = event.contexts.get_or_insert_with(Contexts::new);
1390 let trace = contexts.get_or_default::<TraceContext>();
1391
1392 let trace_id = trace.trace_id.get_or_insert_with(|| {
1394 if let Some(dsc) = dsc {
1395 return dsc.trace_id;
1396 }
1397 TraceId::try_from(*event.id.get_or_insert_with(Default::default))
1398 .unwrap_or_else(|_| TraceId::random())
1399 });
1400 let _ = trace
1401 .span_id
1402 .get_or_insert_with(|| SpanId::derive_from_trace_id(trace_id));
1403}
1404
1405fn normalize_contexts(contexts: &mut Annotated<Contexts>) {
1407 let _ = processor::apply(contexts, |contexts, _meta| {
1408 contexts.0.remove("reprocessing");
1412
1413 for annotated in &mut contexts.0.values_mut() {
1414 if let Some(context_inner) = annotated.value_mut() {
1415 crate::normalize::contexts::normalize_context(&mut context_inner.0);
1416 }
1417 }
1418
1419 Ok(())
1420 });
1421}
1422
1423fn filter_mobile_outliers(measurements: &mut Measurements) {
1427 for key in [
1428 APP_START_COLD,
1429 APP_START_WARM,
1430 "time_to_initial_display",
1432 "time_to_full_display",
1433 ] {
1434 if let Some(value) = measurements.get_value(key)
1435 && value > MAX_DURATION_MOBILE_MS
1436 {
1437 measurements.remove(key);
1438 }
1439 }
1440}
1441
1442fn normalize_mobile_measurements(measurements: &mut Measurements) {
1443 normalize_app_start_measurements(measurements);
1444 filter_mobile_outliers(measurements);
1445}
1446
1447const APP_START_SOURCES: [(&str, Option<&str>); 5] = [
1448 (APP_START_COLD, Some("cold")),
1449 (APP_START_WARM, Some("warm")),
1450 (APP__VITALS__START__VALUE, None),
1451 (APP__VITALS__START__COLD__VALUE, None),
1452 (APP__VITALS__START__WARM__VALUE, None),
1453];
1454
1455fn backfill_app_vitals_start(event: &mut Event) {
1456 if event.ty.value() != Some(&EventType::Transaction) {
1457 return;
1458 }
1459
1460 backfill_app_vitals_start_screen(event);
1461
1462 let already_set = event
1463 .tags
1464 .value()
1465 .is_some_and(|tags| tags.get(APP__VITALS__START__TYPE).is_some())
1466 || event
1467 .measurements
1468 .value()
1469 .is_some_and(|m| m.contains_key(APP__VITALS__START__VALUE));
1470 if already_set {
1471 return;
1472 }
1473
1474 let Some((start_type, value)) =
1475 APP_START_SOURCES
1476 .iter()
1477 .find_map(|(measurement_name, start_type)| {
1478 let start_type = (*start_type)?;
1479 let measurement = event
1480 .measurements
1481 .value()?
1482 .get(*measurement_name)?
1483 .value()?;
1484 if measurement.unit.value()
1485 != Some(&MetricUnit::Duration(DurationUnit::MilliSecond))
1486 {
1487 return None;
1488 }
1489
1490 let value = *measurement.value.value()?;
1491 Some((start_type, value))
1492 })
1493 else {
1494 return;
1495 };
1496
1497 event
1498 .measurements
1499 .get_or_insert_with(Default::default)
1500 .insert(
1501 APP__VITALS__START__VALUE.to_owned(),
1502 Annotated::new(Measurement {
1503 value: Annotated::new(value),
1504 unit: Annotated::new(MetricUnit::Duration(DurationUnit::MilliSecond)),
1505 }),
1506 );
1507
1508 event
1509 .tags
1510 .value_mut()
1511 .get_or_insert_with(Tags::default)
1512 .0
1513 .insert(
1514 String::from(APP__VITALS__START__TYPE),
1515 Annotated::new(start_type.to_owned()),
1516 );
1517}
1518
1519fn backfill_app_vitals_start_screen(event: &mut Event) {
1527 let Some(screen) = event.transaction.value() else {
1528 return;
1529 };
1530 if screen.is_empty() || screen == "<unlabeled transaction>" {
1532 return;
1533 }
1534
1535 let has_app_start_measurement = event.measurements.value().is_some_and(|measurements| {
1536 APP_START_SOURCES
1537 .iter()
1538 .any(|(measurement_name, _)| measurements.contains_key(*measurement_name))
1539 });
1540 if !has_app_start_measurement {
1541 return;
1542 }
1543
1544 let screen = screen.to_owned();
1545 let Some(trace_context) = event.context_mut::<TraceContext>() else {
1546 return;
1547 };
1548 if trace_context.op.as_str() != Some("ui.load")
1549 || trace_context
1550 .data
1551 .value()
1552 .is_some_and(|data| data.contains(APP__VITALS__START__SCREEN))
1553 {
1554 return;
1555 }
1556
1557 let data = trace_context.data.get_or_insert_with(Default::default);
1558 data.insert_value(APP__VITALS__START__SCREEN, screen);
1559}
1560
1561fn normalize_units(measurements: &mut Measurements) {
1562 for (name, measurement) in measurements.iter_mut() {
1563 let measurement = match measurement.value_mut() {
1564 Some(m) => m,
1565 None => continue,
1566 };
1567
1568 let stated_unit = measurement.unit.value().copied();
1569 let default_unit = get_metric_measurement_unit(name);
1570 measurement
1571 .unit
1572 .set_value(Some(stated_unit.or(default_unit).unwrap_or_default()))
1573 }
1574}
1575
1576fn remove_invalid_measurements(
1585 measurements: &mut Measurements,
1586 meta: &mut Meta,
1587 measurements_config: CombinedMeasurementsConfig,
1588 max_name_and_unit_len: Option<usize>,
1589) {
1590 let max_custom_measurements = measurements_config
1592 .max_custom_measurements()
1593 .unwrap_or(usize::MAX);
1594
1595 let mut custom_measurements_count = 0;
1596 let mut removed_measurements = Object::new();
1597
1598 measurements.retain(|name, value| {
1599 let measurement = match value.value_mut() {
1600 Some(m) => m,
1601 None => return false,
1602 };
1603
1604 if !can_be_valid_metric_name(name) {
1605 meta.add_error(Error::invalid(format!(
1606 "Metric name contains invalid characters: \"{name}\""
1607 )));
1608 removed_measurements.insert(name.clone(), Annotated::new(std::mem::take(measurement)));
1609 return false;
1610 }
1611
1612 let unit = measurement.unit.value().unwrap_or(&MetricUnit::None);
1614
1615 if let Some(max_name_and_unit_len) = max_name_and_unit_len {
1616 let max_name_len = max_name_and_unit_len - unit.to_string().len();
1617
1618 if name.len() > max_name_len {
1619 meta.add_error(Error::invalid(format!(
1620 "Metric name too long {}/{max_name_len}: \"{name}\"",
1621 name.len(),
1622 )));
1623 removed_measurements
1624 .insert(name.clone(), Annotated::new(std::mem::take(measurement)));
1625 return false;
1626 }
1627 }
1628
1629 if let Some(builtin_measurement) = measurements_config
1631 .builtin_measurement_keys()
1632 .find(|builtin| builtin.name() == name)
1633 {
1634 let value = measurement.value.value().unwrap_or(&FiniteF64::ZERO);
1635 if !builtin_measurement.allow_negative() && *value < 0.0 {
1637 meta.add_error(Error::invalid(format!(
1638 "Negative value for measurement {name} not allowed: {value}",
1639 )));
1640 removed_measurements
1641 .insert(name.clone(), Annotated::new(std::mem::take(measurement)));
1642 return false;
1643 }
1644 return builtin_measurement.unit() == unit;
1648 }
1649
1650 if custom_measurements_count < max_custom_measurements {
1652 custom_measurements_count += 1;
1653 return true;
1654 }
1655
1656 meta.add_error(Error::invalid(format!("Too many measurements: {name}")));
1657 removed_measurements.insert(name.clone(), Annotated::new(std::mem::take(measurement)));
1658
1659 false
1660 });
1661
1662 if !removed_measurements.is_empty() {
1663 meta.set_original_value(Some(removed_measurements));
1664 }
1665}
1666
1667fn get_metric_measurement_unit(measurement_name: &str) -> Option<MetricUnit> {
1672 match measurement_name {
1675 "fcp" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
1677 "lcp" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
1678 "fid" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
1679 "fp" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
1680 "inp" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
1681 "ttfb" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
1682 "ttfb.requesttime" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
1683 "cls" => Some(MetricUnit::None),
1684
1685 "app_start_cold" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
1687 "app_start_warm" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
1688 "frames_total" => Some(MetricUnit::None),
1689 "frames_slow" => Some(MetricUnit::None),
1690 "frames_slow_rate" => Some(MetricUnit::Fraction(FractionUnit::Ratio)),
1691 "frames_frozen" => Some(MetricUnit::None),
1692 "frames_frozen_rate" => Some(MetricUnit::Fraction(FractionUnit::Ratio)),
1693 "time_to_initial_display" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
1694 "time_to_full_display" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
1695
1696 "stall_count" => Some(MetricUnit::None),
1698 "stall_total_time" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
1699 "stall_longest_time" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
1700 "stall_percentage" => Some(MetricUnit::Fraction(FractionUnit::Ratio)),
1701
1702 _ => None,
1704 }
1705}
1706
1707fn normalize_app_start_measurements(measurements: &mut Measurements) {
1712 use relay_conventions::measurements::{APP_START_COLD, APP_START_WARM};
1713 if let Some(app_start_cold_value) = measurements.remove("app.start.cold") {
1714 measurements.insert(APP_START_COLD.to_owned(), app_start_cold_value);
1715 }
1716 if let Some(app_start_warm_value) = measurements.remove("app.start.warm") {
1717 measurements.insert(APP_START_WARM.to_owned(), app_start_warm_value);
1718 }
1719}
1720
1721#[cfg(test)]
1722mod tests {
1723 use relay_event_schema::protocol::SpanData;
1724 use relay_protocol::assert_annotated_snapshot;
1725 use std::collections::BTreeMap;
1726 use std::collections::HashMap;
1727
1728 use insta::assert_debug_snapshot;
1729 use itertools::Itertools;
1730 use relay_event_schema::protocol::{Breadcrumb, Csp, DebugMeta, DeviceContext, Values};
1731 use relay_protocol::{SerializableAnnotated, get_value};
1732 use serde_json::json;
1733
1734 use super::*;
1735 use crate::eap;
1736 use crate::{ClientHints, MeasurementsConfig, ModelCostV2, ModelMetadataEntry};
1737
1738 const IOS_MOBILE_EVENT: &str = r#"
1739 {
1740 "sdk": {"name": "sentry.cocoa"},
1741 "contexts": {
1742 "trace": {
1743 "op": "ui.load"
1744 }
1745 },
1746 "measurements": {
1747 "app_start_warm": {
1748 "value": 8049.345970153808,
1749 "unit": "millisecond"
1750 },
1751 "time_to_full_display": {
1752 "value": 8240.571022033691,
1753 "unit": "millisecond"
1754 },
1755 "time_to_initial_display": {
1756 "value": 8049.345970153808,
1757 "unit": "millisecond"
1758 }
1759 }
1760 }
1761 "#;
1762
1763 const ANDROID_MOBILE_EVENT: &str = r#"
1764 {
1765 "sdk": {"name": "sentry.java.android"},
1766 "contexts": {
1767 "trace": {
1768 "op": "ui.load"
1769 }
1770 },
1771 "measurements": {
1772 "app_start_cold": {
1773 "value": 22648,
1774 "unit": "millisecond"
1775 },
1776 "time_to_full_display": {
1777 "value": 22647,
1778 "unit": "millisecond"
1779 },
1780 "time_to_initial_display": {
1781 "value": 22647,
1782 "unit": "millisecond"
1783 }
1784 }
1785 }
1786 "#;
1787
1788 fn collect_span_data<const N: usize>(event: Annotated<Event>) -> [Annotated<SpanData>; N] {
1789 get_value!(event.spans!)
1790 .iter()
1791 .map(|span| Annotated::new(get_value!(span.data!).clone()))
1792 .collect::<Vec<_>>()
1793 .try_into()
1794 .unwrap()
1795 }
1796
1797 fn trace_context_data(event: &Event) -> &Annotated<SpanData> {
1798 &event.context::<TraceContext>().unwrap().data
1799 }
1800
1801 fn app_vitals_start_screen_event(
1802 ty: &str,
1803 transaction: Option<&str>,
1804 trace_op: &str,
1805 measurement: Option<&str>,
1806 existing_screen: Option<&str>,
1807 ) -> Event {
1808 let mut payload = json!({
1809 "type": ty,
1810 "contexts": {"trace": {"op": trace_op}},
1811 "measurements": {},
1812 });
1813
1814 if let Some(transaction) = transaction {
1815 payload["transaction"] = json!(transaction);
1816 }
1817
1818 if let Some(measurement) = measurement {
1819 payload["measurements"] = json!({
1820 measurement: {"value": 1234.0, "unit": "millisecond"}
1821 });
1822 }
1823
1824 if let Some(screen) = existing_screen {
1825 payload["contexts"]["trace"]["data"] = json!({APP__VITALS__START__SCREEN: screen});
1826 }
1827
1828 Annotated::<Event>::from_json(&payload.to_string())
1829 .unwrap()
1830 .into_value()
1831 .unwrap()
1832 }
1833
1834 #[test]
1835 fn test_normalize_dist_none() {
1836 let mut dist = Annotated::default();
1837 normalize_dist(&mut dist);
1838 assert_eq!(dist.value(), None);
1839 }
1840
1841 #[test]
1842 fn test_normalize_dist_empty() {
1843 let mut dist = Annotated::new("".to_owned());
1844 normalize_dist(&mut dist);
1845 assert_eq!(dist.value(), None);
1846 }
1847
1848 #[test]
1849 fn test_normalize_dist_trim() {
1850 let mut dist = Annotated::new(" foo ".to_owned());
1851 normalize_dist(&mut dist);
1852 assert_eq!(dist.value(), Some(&"foo".to_owned()));
1853 }
1854
1855 #[test]
1856 fn test_normalize_dist_whitespace() {
1857 let mut dist = Annotated::new(" ".to_owned());
1858 normalize_dist(&mut dist);
1859 assert_eq!(dist.value(), None);
1860 }
1861
1862 #[test]
1863 fn test_normalize_platform_and_level_with_transaction_event() {
1864 let json = r#"
1865 {
1866 "type": "transaction"
1867 }
1868 "#;
1869
1870 let Annotated(Some(mut event), mut meta) = Annotated::<Event>::from_json(json).unwrap()
1871 else {
1872 panic!("Invalid transaction json");
1873 };
1874
1875 normalize_default_attributes(&mut event, &mut meta, &NormalizationConfig::default());
1876
1877 assert_eq!(event.level.value().unwrap().to_string(), "info");
1878 assert_eq!(event.ty.value().unwrap().to_string(), "transaction");
1879 assert_eq!(event.platform.as_str().unwrap(), "other");
1880 }
1881
1882 #[test]
1883 fn test_normalize_platform_and_level_with_error_event() {
1884 let json = r#"
1885 {
1886 "type": "error",
1887 "exception": {
1888 "values": [{"type": "ValueError", "value": "Should not happen"}]
1889 }
1890 }
1891 "#;
1892
1893 let Annotated(Some(mut event), mut meta) = Annotated::<Event>::from_json(json).unwrap()
1894 else {
1895 panic!("Invalid error json");
1896 };
1897
1898 normalize_default_attributes(&mut event, &mut meta, &NormalizationConfig::default());
1899
1900 assert_eq!(event.level.value().unwrap().to_string(), "error");
1901 assert_eq!(event.ty.value().unwrap().to_string(), "error");
1902 assert_eq!(event.platform.value().unwrap().to_owned(), "other");
1903 }
1904
1905 #[test]
1906 fn test_computed_measurements() {
1907 let json = r#"
1908 {
1909 "type": "transaction",
1910 "timestamp": "2021-04-26T08:00:05+0100",
1911 "start_timestamp": "2021-04-26T08:00:00+0100",
1912 "measurements": {
1913 "frames_slow": {"value": 1},
1914 "frames_frozen": {"value": 2},
1915 "frames_total": {"value": 4},
1916 "stall_total_time": {"value": 4000, "unit": "millisecond"}
1917 }
1918 }
1919 "#;
1920
1921 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
1922
1923 normalize_event_measurements(&mut event, None, None);
1924
1925 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
1926 {
1927 "type": "transaction",
1928 "timestamp": 1619420405.0,
1929 "start_timestamp": 1619420400.0,
1930 "measurements": {
1931 "frames_frozen": {
1932 "value": 2.0,
1933 "unit": "none",
1934 },
1935 "frames_frozen_rate": {
1936 "value": 0.5,
1937 "unit": "ratio",
1938 },
1939 "frames_slow": {
1940 "value": 1.0,
1941 "unit": "none",
1942 },
1943 "frames_slow_rate": {
1944 "value": 0.25,
1945 "unit": "ratio",
1946 },
1947 "frames_total": {
1948 "value": 4.0,
1949 "unit": "none",
1950 },
1951 "stall_percentage": {
1952 "value": 0.8,
1953 "unit": "ratio",
1954 },
1955 "stall_total_time": {
1956 "value": 4000.0,
1957 "unit": "millisecond",
1958 },
1959 },
1960 }
1961 "###);
1962 }
1963
1964 #[test]
1965 fn test_filter_custom_measurements() {
1966 let json = r#"
1967 {
1968 "type": "transaction",
1969 "timestamp": "2021-04-26T08:00:05+0100",
1970 "start_timestamp": "2021-04-26T08:00:00+0100",
1971 "measurements": {
1972 "my_custom_measurement_1": {"value": 123},
1973 "frames_frozen": {"value": 666, "unit": "invalid_unit"},
1974 "frames_slow": {"value": 1},
1975 "my_custom_measurement_3": {"value": 456},
1976 "my_custom_measurement_2": {"value": 789}
1977 }
1978 }
1979 "#;
1980 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
1981
1982 let project_measurement_config: MeasurementsConfig = serde_json::from_value(json!({
1983 "builtinMeasurements": [
1984 {"name": "frames_frozen", "unit": "none"},
1985 {"name": "frames_slow", "unit": "none"}
1986 ],
1987 "maxCustomMeasurements": 2,
1988 "stray_key": "zzz"
1989 }))
1990 .unwrap();
1991
1992 let dynamic_measurement_config =
1993 CombinedMeasurementsConfig::new(Some(&project_measurement_config), None);
1994
1995 normalize_event_measurements(&mut event, Some(dynamic_measurement_config), None);
1996
1997 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
1999 {
2000 "type": "transaction",
2001 "timestamp": 1619420405.0,
2002 "start_timestamp": 1619420400.0,
2003 "measurements": {
2004 "frames_slow": {
2005 "value": 1.0,
2006 "unit": "none",
2007 },
2008 "my_custom_measurement_1": {
2009 "value": 123.0,
2010 "unit": "none",
2011 },
2012 "my_custom_measurement_2": {
2013 "value": 789.0,
2014 "unit": "none",
2015 },
2016 },
2017 "_meta": {
2018 "measurements": {
2019 "": Meta(Some(MetaInner(
2020 err: [
2021 [
2022 "invalid_data",
2023 {
2024 "reason": "Too many measurements: my_custom_measurement_3",
2025 },
2026 ],
2027 ],
2028 val: Some({
2029 "my_custom_measurement_3": {
2030 "unit": "none",
2031 "value": 456.0,
2032 },
2033 }),
2034 ))),
2035 },
2036 },
2037 }
2038 "###);
2039 }
2040
2041 #[test]
2042 fn test_normalize_units() {
2043 let mut measurements = Annotated::<Measurements>::from_json(
2044 r#"{
2045 "fcp": {"value": 1.1},
2046 "stall_count": {"value": 3.3},
2047 "foo": {"value": 8.8}
2048 }"#,
2049 )
2050 .unwrap()
2051 .into_value()
2052 .unwrap();
2053 insta::assert_debug_snapshot!(measurements, @r###"
2054 Measurements(
2055 {
2056 "fcp": Measurement {
2057 value: 1.1,
2058 unit: ~,
2059 },
2060 "foo": Measurement {
2061 value: 8.8,
2062 unit: ~,
2063 },
2064 "stall_count": Measurement {
2065 value: 3.3,
2066 unit: ~,
2067 },
2068 },
2069 )
2070 "###);
2071 normalize_units(&mut measurements);
2072 insta::assert_debug_snapshot!(measurements, @r###"
2073 Measurements(
2074 {
2075 "fcp": Measurement {
2076 value: 1.1,
2077 unit: Duration(
2078 MilliSecond,
2079 ),
2080 },
2081 "foo": Measurement {
2082 value: 8.8,
2083 unit: None,
2084 },
2085 "stall_count": Measurement {
2086 value: 3.3,
2087 unit: None,
2088 },
2089 },
2090 )
2091 "###);
2092 }
2093
2094 #[test]
2095 fn test_normalize_security_report() {
2096 let mut event = Event {
2097 csp: Annotated::from(Csp::default()),
2098 ..Default::default()
2099 };
2100 let ipaddr = IpAddr("213.164.1.114".to_owned());
2101
2102 let client_ip = Some(&ipaddr);
2103
2104 let user_agent = RawUserAgentInfo {
2105 user_agent: Some(
2106 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/109.0",
2107 ),
2108 client_hints: ClientHints {
2109 sec_ch_ua_platform: Some("macOS"),
2110 sec_ch_ua_platform_version: Some("13.2.0"),
2111 sec_ch_ua: Some(
2112 r#""Chromium";v="110", "Not A(Brand";v="24", "Google Chrome";v="110""#,
2113 ),
2114 sec_ch_ua_model: Some("some model"),
2115 },
2116 };
2117
2118 normalize_security_report(&mut event, client_ip, &user_agent);
2121
2122 let headers = event
2123 .request
2124 .value_mut()
2125 .get_or_insert_with(Request::default)
2126 .headers
2127 .value_mut()
2128 .get_or_insert_with(Headers::default);
2129
2130 assert_eq!(
2131 event.user.value().unwrap().ip_address,
2132 Annotated::from(ipaddr)
2133 );
2134 assert_eq!(
2135 headers.get_header(RawUserAgentInfo::USER_AGENT),
2136 user_agent.user_agent
2137 );
2138 assert_eq!(
2139 headers.get_header(ClientHints::SEC_CH_UA),
2140 user_agent.client_hints.sec_ch_ua,
2141 );
2142 assert_eq!(
2143 headers.get_header(ClientHints::SEC_CH_UA_MODEL),
2144 user_agent.client_hints.sec_ch_ua_model,
2145 );
2146 assert_eq!(
2147 headers.get_header(ClientHints::SEC_CH_UA_PLATFORM),
2148 user_agent.client_hints.sec_ch_ua_platform,
2149 );
2150 assert_eq!(
2151 headers.get_header(ClientHints::SEC_CH_UA_PLATFORM_VERSION),
2152 user_agent.client_hints.sec_ch_ua_platform_version,
2153 );
2154
2155 assert!(
2156 std::mem::size_of_val(&ClientHints::<&str>::default()) == 64,
2157 "If you add new fields, update the test accordingly"
2158 );
2159 }
2160
2161 #[test]
2162 fn test_no_device_class() {
2163 let mut event = Event {
2164 ..Default::default()
2165 };
2166 normalize_device_class(&mut event);
2167 let tags = &event.tags.value_mut().get_or_insert_with(Tags::default).0;
2168 assert_eq!(None, tags.get("device_class"));
2169 }
2170
2171 #[test]
2172 fn test_apple_low_device_class() {
2173 let mut event = Event {
2174 contexts: {
2175 let mut contexts = Contexts::new();
2176 contexts.add(DeviceContext {
2177 family: "iPhone".to_owned().into(),
2178 model: "iPhone8,4".to_owned().into(),
2179 ..Default::default()
2180 });
2181 Annotated::new(contexts)
2182 },
2183 ..Default::default()
2184 };
2185 normalize_device_class(&mut event);
2186 assert_debug_snapshot!(event.tags, @r###"
2187 Tags(
2188 PairList(
2189 [
2190 TagEntry(
2191 "device.class",
2192 "1",
2193 ),
2194 ],
2195 ),
2196 )
2197 "###);
2198 }
2199
2200 #[test]
2201 fn test_apple_medium_device_class() {
2202 let mut event = Event {
2203 contexts: {
2204 let mut contexts = Contexts::new();
2205 contexts.add(DeviceContext {
2206 family: "iPhone".to_owned().into(),
2207 model: "iPhone12,8".to_owned().into(),
2208 ..Default::default()
2209 });
2210 Annotated::new(contexts)
2211 },
2212 ..Default::default()
2213 };
2214 normalize_device_class(&mut event);
2215 assert_debug_snapshot!(event.tags, @r###"
2216 Tags(
2217 PairList(
2218 [
2219 TagEntry(
2220 "device.class",
2221 "2",
2222 ),
2223 ],
2224 ),
2225 )
2226 "###);
2227 }
2228
2229 #[test]
2230 fn test_android_low_device_class() {
2231 let mut event = Event {
2232 contexts: {
2233 let mut contexts = Contexts::new();
2234 contexts.add(DeviceContext {
2235 family: "android".to_owned().into(),
2236 processor_frequency: 1000.into(),
2237 processor_count: 6.into(),
2238 memory_size: (2 * 1024 * 1024 * 1024).into(),
2239 ..Default::default()
2240 });
2241 Annotated::new(contexts)
2242 },
2243 ..Default::default()
2244 };
2245 normalize_device_class(&mut event);
2246 assert_debug_snapshot!(event.tags, @r###"
2247 Tags(
2248 PairList(
2249 [
2250 TagEntry(
2251 "device.class",
2252 "1",
2253 ),
2254 ],
2255 ),
2256 )
2257 "###);
2258 }
2259
2260 #[test]
2261 fn test_android_medium_device_class() {
2262 let mut event = Event {
2263 contexts: {
2264 let mut contexts = Contexts::new();
2265 contexts.add(DeviceContext {
2266 family: "android".to_owned().into(),
2267 processor_frequency: 2000.into(),
2268 processor_count: 8.into(),
2269 memory_size: (6 * 1024 * 1024 * 1024).into(),
2270 ..Default::default()
2271 });
2272 Annotated::new(contexts)
2273 },
2274 ..Default::default()
2275 };
2276 normalize_device_class(&mut event);
2277 assert_debug_snapshot!(event.tags, @r###"
2278 Tags(
2279 PairList(
2280 [
2281 TagEntry(
2282 "device.class",
2283 "2",
2284 ),
2285 ],
2286 ),
2287 )
2288 "###);
2289 }
2290
2291 #[test]
2292 fn test_android_high_device_class() {
2293 let mut event = Event {
2294 contexts: {
2295 let mut contexts = Contexts::new();
2296 contexts.add(DeviceContext {
2297 family: "android".to_owned().into(),
2298 processor_frequency: 2500.into(),
2299 processor_count: 8.into(),
2300 memory_size: (6 * 1024 * 1024 * 1024).into(),
2301 ..Default::default()
2302 });
2303 Annotated::new(contexts)
2304 },
2305 ..Default::default()
2306 };
2307 normalize_device_class(&mut event);
2308 assert_debug_snapshot!(event.tags, @r###"
2309 Tags(
2310 PairList(
2311 [
2312 TagEntry(
2313 "device.class",
2314 "3",
2315 ),
2316 ],
2317 ),
2318 )
2319 "###);
2320 }
2321
2322 #[test]
2323 fn test_keeps_valid_measurement() {
2324 let name = "lcp";
2325 let measurement = Measurement {
2326 value: Annotated::new(420.69.try_into().unwrap()),
2327 unit: Annotated::new(MetricUnit::Duration(DurationUnit::MilliSecond)),
2328 };
2329
2330 assert!(!is_measurement_dropped(name, measurement));
2331 }
2332
2333 #[test]
2334 fn test_drops_too_long_measurement_names() {
2335 let name = "lcpppppppppppppppppppppppppppp";
2336 let measurement = Measurement {
2337 value: Annotated::new(420.69.try_into().unwrap()),
2338 unit: Annotated::new(MetricUnit::Duration(DurationUnit::MilliSecond)),
2339 };
2340
2341 assert!(is_measurement_dropped(name, measurement));
2342 }
2343
2344 #[test]
2345 fn test_drops_measurements_with_invalid_characters() {
2346 let name = "i æm frøm nørwåy";
2347 let measurement = Measurement {
2348 value: Annotated::new(420.69.try_into().unwrap()),
2349 unit: Annotated::new(MetricUnit::Duration(DurationUnit::MilliSecond)),
2350 };
2351
2352 assert!(is_measurement_dropped(name, measurement));
2353 }
2354
2355 fn is_measurement_dropped(name: &str, measurement: Measurement) -> bool {
2356 let max_name_and_unit_len = Some(30);
2357
2358 let mut measurements: BTreeMap<String, Annotated<Measurement>> = Object::new();
2359 measurements.insert(name.to_owned(), Annotated::new(measurement));
2360
2361 let mut measurements = Measurements(measurements);
2362 let mut meta = Meta::default();
2363 let measurements_config = MeasurementsConfig {
2364 max_custom_measurements: 1,
2365 ..Default::default()
2366 };
2367
2368 let dynamic_config = CombinedMeasurementsConfig::new(Some(&measurements_config), None);
2369
2370 assert_eq!(measurements.len(), 1);
2373
2374 remove_invalid_measurements(
2375 &mut measurements,
2376 &mut meta,
2377 dynamic_config,
2378 max_name_and_unit_len,
2379 );
2380
2381 measurements.is_empty()
2383 }
2384
2385 #[test]
2386 fn test_custom_measurements_not_dropped() {
2387 let mut measurements = Measurements(BTreeMap::from([(
2388 "custom_measurement".to_owned(),
2389 Annotated::new(Measurement {
2390 value: Annotated::new(42.0.try_into().unwrap()),
2391 unit: Annotated::new(MetricUnit::Duration(DurationUnit::MilliSecond)),
2392 }),
2393 )]));
2394
2395 let original = measurements.clone();
2396 remove_invalid_measurements(
2397 &mut measurements,
2398 &mut Meta::default(),
2399 CombinedMeasurementsConfig::new(None, None),
2400 Some(30),
2401 );
2402
2403 assert_eq!(original, measurements);
2404 }
2405
2406 #[test]
2407 fn test_normalize_app_start_measurements_does_not_add_measurements() {
2408 let mut measurements = Annotated::<Measurements>::from_json(r###"{}"###)
2409 .unwrap()
2410 .into_value()
2411 .unwrap();
2412 insta::assert_debug_snapshot!(measurements, @r###"
2413 Measurements(
2414 {},
2415 )
2416 "###);
2417 normalize_app_start_measurements(&mut measurements);
2418 insta::assert_debug_snapshot!(measurements, @r###"
2419 Measurements(
2420 {},
2421 )
2422 "###);
2423 }
2424
2425 #[test]
2426 fn test_normalize_app_start_cold_measurements() {
2427 let mut measurements =
2428 Annotated::<Measurements>::from_json(r#"{"app.start.cold": {"value": 1.1}}"#)
2429 .unwrap()
2430 .into_value()
2431 .unwrap();
2432 insta::assert_debug_snapshot!(measurements, @r###"
2433 Measurements(
2434 {
2435 "app.start.cold": Measurement {
2436 value: 1.1,
2437 unit: ~,
2438 },
2439 },
2440 )
2441 "###);
2442 normalize_app_start_measurements(&mut measurements);
2443 insta::assert_debug_snapshot!(measurements, @r###"
2444 Measurements(
2445 {
2446 "app_start_cold": Measurement {
2447 value: 1.1,
2448 unit: ~,
2449 },
2450 },
2451 )
2452 "###);
2453 }
2454
2455 #[test]
2456 fn test_normalize_app_start_warm_measurements() {
2457 let mut measurements =
2458 Annotated::<Measurements>::from_json(r#"{"app.start.warm": {"value": 1.1}}"#)
2459 .unwrap()
2460 .into_value()
2461 .unwrap();
2462 insta::assert_debug_snapshot!(measurements, @r###"
2463 Measurements(
2464 {
2465 "app.start.warm": Measurement {
2466 value: 1.1,
2467 unit: ~,
2468 },
2469 },
2470 )
2471 "###);
2472 normalize_app_start_measurements(&mut measurements);
2473 insta::assert_debug_snapshot!(measurements, @r###"
2474 Measurements(
2475 {
2476 "app_start_warm": Measurement {
2477 value: 1.1,
2478 unit: ~,
2479 },
2480 },
2481 )
2482 "###);
2483 }
2484
2485 #[test]
2486 fn test_ai_legacy_measurements() {
2487 let json = r#"
2488 {
2489 "spans": [
2490 {
2491 "timestamp": 1702474613.0495,
2492 "start_timestamp": 1702474613.0175,
2493 "description": "OpenAI ",
2494 "op": "ai.chat_completions.openai",
2495 "span_id": "9c01bd820a083e63",
2496 "parent_span_id": "a1e13f3f06239d69",
2497 "trace_id": "922dda2462ea4ac2b6a4b339bee90863",
2498 "measurements": {
2499 "ai_prompt_tokens_used": {
2500 "value": 1000
2501 },
2502 "ai_completion_tokens_used": {
2503 "value": 2000
2504 }
2505 },
2506 "data": {
2507 "gen_ai.request.model": "claude-2.1"
2508 }
2509 },
2510 {
2511 "timestamp": 1702474613.0495,
2512 "start_timestamp": 1702474613.0175,
2513 "description": "OpenAI ",
2514 "op": "ai.chat_completions.openai",
2515 "span_id": "ac01bd820a083e63",
2516 "parent_span_id": "a1e13f3f06239d69",
2517 "trace_id": "922dda2462ea4ac2b6a4b339bee90863",
2518 "measurements": {
2519 "ai_prompt_tokens_used": {
2520 "value": 1000
2521 },
2522 "ai_completion_tokens_used": {
2523 "value": 2000
2524 }
2525 },
2526 "data": {
2527 "gen_ai.request.model": "gpt4-21-04"
2528 }
2529 }
2530 ]
2531 }
2532 "#;
2533
2534 let mut event = Annotated::<Event>::from_json(json).unwrap();
2535
2536 normalize_event(
2537 &mut event,
2538 &NormalizationConfig {
2539 ai_model_metadata: Some(&ModelMetadata {
2540 version: 1,
2541 models: HashMap::from([
2542 (
2543 "claude-2.1".parse().unwrap(),
2544 ModelMetadataEntry {
2545 costs: Some(ModelCostV2 {
2546 input_per_token: 0.01,
2547 output_per_token: 0.02,
2548 output_reasoning_per_token: 0.03,
2549 input_cached_per_token: 0.0,
2550 input_cache_write_per_token: 0.0,
2551 }),
2552 context_size: None,
2553 },
2554 ),
2555 (
2556 "gpt4-21-04".parse().unwrap(),
2557 ModelMetadataEntry {
2558 costs: Some(ModelCostV2 {
2559 input_per_token: 0.02,
2560 output_per_token: 0.03,
2561 output_reasoning_per_token: 0.04,
2562 input_cached_per_token: 0.0,
2563 input_cache_write_per_token: 0.0,
2564 }),
2565 context_size: None,
2566 },
2567 ),
2568 ]),
2569 }),
2570 ..NormalizationConfig::default()
2571 },
2572 );
2573
2574 let [span1, span2] = collect_span_data(event);
2575
2576 assert_annotated_snapshot!(span1, @r#"
2577 {
2578 "gen_ai.cost.cache_creation.input_tokens": 0.0,
2579 "gen_ai.cost.cache_read.input_tokens": 0.0,
2580 "gen_ai.cost.input_tokens": 10.0,
2581 "gen_ai.cost.output_tokens": 40.0,
2582 "gen_ai.cost.reasoning.output_tokens": 0.0,
2583 "gen_ai.cost.total_tokens": 50.0,
2584 "gen_ai.operation.type": "ai_client",
2585 "gen_ai.request.model": "claude-2.1",
2586 "gen_ai.response.model": "claude-2.1",
2587 "gen_ai.response.tokens_per_second": 62500.0,
2588 "gen_ai.usage.input_tokens": 1000.0,
2589 "gen_ai.usage.output_tokens": 2000.0,
2590 "gen_ai.usage.total_tokens": 3000.0
2591 }
2592 "#);
2593 assert_annotated_snapshot!(span2, @r#"
2594 {
2595 "gen_ai.cost.cache_creation.input_tokens": 0.0,
2596 "gen_ai.cost.cache_read.input_tokens": 0.0,
2597 "gen_ai.cost.input_tokens": 20.0,
2598 "gen_ai.cost.output_tokens": 60.0,
2599 "gen_ai.cost.reasoning.output_tokens": 0.0,
2600 "gen_ai.cost.total_tokens": 80.0,
2601 "gen_ai.operation.type": "ai_client",
2602 "gen_ai.request.model": "gpt4-21-04",
2603 "gen_ai.response.model": "gpt4-21-04",
2604 "gen_ai.response.tokens_per_second": 62500.0,
2605 "gen_ai.usage.input_tokens": 1000.0,
2606 "gen_ai.usage.output_tokens": 2000.0,
2607 "gen_ai.usage.total_tokens": 3000.0
2608 }
2609 "#);
2610 }
2611
2612 #[test]
2613 fn test_ai_data() {
2614 let json = r#"
2615 {
2616 "spans": [
2617 {
2618 "timestamp": 1702474614.0175,
2619 "start_timestamp": 1702474613.0175,
2620 "description": "OpenAI ",
2621 "op": "gen_ai.chat_completions.openai",
2622 "span_id": "9c01bd820a083e63",
2623 "parent_span_id": "a1e13f3f06239d69",
2624 "trace_id": "922dda2462ea4ac2b6a4b339bee90863",
2625 "data": {
2626 "gen_ai.usage.input_tokens": 1000,
2627 "gen_ai.usage.output_tokens": 2000,
2628 "gen_ai.usage.reasoning.output_tokens": 1000,
2629 "gen_ai.usage.cache_read.input_tokens": 500,
2630 "gen_ai.request.model": "claude-2.1"
2631 }
2632 },
2633 {
2634 "timestamp": 1702474614.0175,
2635 "start_timestamp": 1702474613.0175,
2636 "description": "OpenAI ",
2637 "op": "gen_ai.chat_completions.openai",
2638 "span_id": "ac01bd820a083e63",
2639 "parent_span_id": "a1e13f3f06239d69",
2640 "trace_id": "922dda2462ea4ac2b6a4b339bee90863",
2641 "data": {
2642 "gen_ai.usage.input_tokens": 1000,
2643 "gen_ai.usage.output_tokens": 2000,
2644 "gen_ai.request.model": "gpt4-21-04"
2645 }
2646 },
2647 {
2648 "timestamp": 1702474614.0175,
2649 "start_timestamp": 1702474613.0175,
2650 "description": "OpenAI ",
2651 "op": "gen_ai.chat_completions.openai",
2652 "span_id": "ac01bd820a083e63",
2653 "parent_span_id": "a1e13f3f06239d69",
2654 "trace_id": "922dda2462ea4ac2b6a4b339bee90863",
2655 "data": {
2656 "gen_ai.usage.input_tokens": 1000,
2657 "gen_ai.usage.output_tokens": 2000,
2658 "gen_ai.response.model": "gpt4-21-04"
2659 }
2660 }
2661 ]
2662 }
2663 "#;
2664
2665 let mut event = Annotated::<Event>::from_json(json).unwrap();
2666
2667 normalize_event(
2668 &mut event,
2669 &NormalizationConfig {
2670 ai_model_metadata: Some(&ModelMetadata {
2671 version: 1,
2672 models: HashMap::from([
2673 (
2674 "claude-2.1".parse().unwrap(),
2675 ModelMetadataEntry {
2676 costs: Some(ModelCostV2 {
2677 input_per_token: 0.01,
2678 output_per_token: 0.02,
2679 output_reasoning_per_token: 0.03,
2680 input_cached_per_token: 0.04,
2681 input_cache_write_per_token: 0.0,
2682 }),
2683 context_size: None,
2684 },
2685 ),
2686 (
2687 "gpt4-21-04".parse().unwrap(),
2688 ModelMetadataEntry {
2689 costs: Some(ModelCostV2 {
2690 input_per_token: 0.09,
2691 output_per_token: 0.05,
2692 output_reasoning_per_token: 0.0,
2693 input_cached_per_token: 0.0,
2694 input_cache_write_per_token: 0.0,
2695 }),
2696 context_size: None,
2697 },
2698 ),
2699 ]),
2700 }),
2701 ..NormalizationConfig::default()
2702 },
2703 );
2704
2705 let [span1, span2, span3] = collect_span_data(event);
2706
2707 assert_annotated_snapshot!(span1, @r#"
2708 {
2709 "gen_ai.cost.cache_creation.input_tokens": 0.0,
2710 "gen_ai.cost.cache_read.input_tokens": 20.0,
2711 "gen_ai.cost.input_tokens": 25.0,
2712 "gen_ai.cost.output_tokens": 50.0,
2713 "gen_ai.cost.reasoning.output_tokens": 30.0,
2714 "gen_ai.cost.total_tokens": 75.0,
2715 "gen_ai.operation.type": "ai_client",
2716 "gen_ai.request.model": "claude-2.1",
2717 "gen_ai.response.model": "claude-2.1",
2718 "gen_ai.response.tokens_per_second": 2000.0,
2719 "gen_ai.usage.cache_read.input_tokens": 500,
2720 "gen_ai.usage.input_tokens": 1000,
2721 "gen_ai.usage.output_tokens": 2000,
2722 "gen_ai.usage.reasoning.output_tokens": 1000,
2723 "gen_ai.usage.total_tokens": 3000.0
2724 }
2725 "#);
2726 assert_annotated_snapshot!(span2, @r#"
2727 {
2728 "gen_ai.cost.cache_creation.input_tokens": 0.0,
2729 "gen_ai.cost.cache_read.input_tokens": 0.0,
2730 "gen_ai.cost.input_tokens": 90.0,
2731 "gen_ai.cost.output_tokens": 100.0,
2732 "gen_ai.cost.reasoning.output_tokens": 0.0,
2733 "gen_ai.cost.total_tokens": 190.0,
2734 "gen_ai.operation.type": "ai_client",
2735 "gen_ai.request.model": "gpt4-21-04",
2736 "gen_ai.response.model": "gpt4-21-04",
2737 "gen_ai.response.tokens_per_second": 2000.0,
2738 "gen_ai.usage.input_tokens": 1000,
2739 "gen_ai.usage.output_tokens": 2000,
2740 "gen_ai.usage.total_tokens": 3000.0
2741 }
2742 "#);
2743 assert_annotated_snapshot!(span3, @r#"
2744 {
2745 "gen_ai.cost.cache_creation.input_tokens": 0.0,
2746 "gen_ai.cost.cache_read.input_tokens": 0.0,
2747 "gen_ai.cost.input_tokens": 90.0,
2748 "gen_ai.cost.output_tokens": 100.0,
2749 "gen_ai.cost.reasoning.output_tokens": 0.0,
2750 "gen_ai.cost.total_tokens": 190.0,
2751 "gen_ai.operation.type": "ai_client",
2752 "gen_ai.response.model": "gpt4-21-04",
2753 "gen_ai.response.tokens_per_second": 2000.0,
2754 "gen_ai.usage.input_tokens": 1000,
2755 "gen_ai.usage.output_tokens": 2000,
2756 "gen_ai.usage.total_tokens": 3000.0
2757 }
2758 "#);
2759 }
2760
2761 #[test]
2762 fn test_ai_data_with_no_tokens() {
2763 let json = r#"
2764 {
2765 "spans": [
2766 {
2767 "timestamp": 1702474613.0495,
2768 "start_timestamp": 1702474613.0175,
2769 "description": "OpenAI ",
2770 "op": "gen_ai.invoke_agent",
2771 "span_id": "9c01bd820a083e63",
2772 "parent_span_id": "a1e13f3f06239d69",
2773 "trace_id": "922dda2462ea4ac2b6a4b339bee90863",
2774 "data": {
2775 "gen_ai.request.model": "claude-2.1"
2776 }
2777 }
2778 ]
2779 }
2780 "#;
2781
2782 let mut event = Annotated::<Event>::from_json(json).unwrap();
2783
2784 normalize_event(
2785 &mut event,
2786 &NormalizationConfig {
2787 ai_model_metadata: Some(&ModelMetadata {
2788 version: 1,
2789 models: HashMap::from([(
2790 "claude-2.1".parse().unwrap(),
2791 ModelMetadataEntry {
2792 costs: Some(ModelCostV2 {
2793 input_per_token: 0.01,
2794 output_per_token: 0.02,
2795 output_reasoning_per_token: 0.03,
2796 input_cached_per_token: 0.0,
2797 input_cache_write_per_token: 0.0,
2798 }),
2799 context_size: None,
2800 },
2801 )]),
2802 }),
2803 ..NormalizationConfig::default()
2804 },
2805 );
2806
2807 let [span] = collect_span_data(event);
2808
2809 assert_annotated_snapshot!(span, @r#"
2810 {
2811 "gen_ai.operation.type": "agent",
2812 "gen_ai.request.model": "claude-2.1",
2813 "gen_ai.response.model": "claude-2.1"
2814 }
2815 "#);
2816 }
2817
2818 #[test]
2819 fn test_ai_data_with_ai_op_prefix() {
2820 let json = r#"
2821 {
2822 "spans": [
2823 {
2824 "timestamp": 1702474613.0495,
2825 "start_timestamp": 1702474613.0175,
2826 "description": "OpenAI ",
2827 "op": "ai.chat_completions.openai",
2828 "span_id": "9c01bd820a083e63",
2829 "parent_span_id": "a1e13f3f06239d69",
2830 "trace_id": "922dda2462ea4ac2b6a4b339bee90863",
2831 "data": {
2832 "gen_ai.usage.input_tokens": 1000,
2833 "gen_ai.usage.output_tokens": 2000,
2834 "gen_ai.usage.reasoning.output_tokens": 1000,
2835 "gen_ai.usage.cache_read.input_tokens": 500,
2836 "gen_ai.request.model": "claude-2.1"
2837 }
2838 },
2839 {
2840 "timestamp": 1702474613.0495,
2841 "start_timestamp": 1702474613.0175,
2842 "description": "OpenAI ",
2843 "op": "ai.chat_completions.openai",
2844 "span_id": "ac01bd820a083e63",
2845 "parent_span_id": "a1e13f3f06239d69",
2846 "trace_id": "922dda2462ea4ac2b6a4b339bee90863",
2847 "data": {
2848 "gen_ai.usage.input_tokens": 1000,
2849 "gen_ai.usage.output_tokens": 2000,
2850 "gen_ai.request.model": "gpt4-21-04"
2851 }
2852 }
2853 ]
2854 }
2855 "#;
2856
2857 let mut event = Annotated::<Event>::from_json(json).unwrap();
2858
2859 normalize_event(
2860 &mut event,
2861 &NormalizationConfig {
2862 ai_model_metadata: Some(&ModelMetadata {
2863 version: 1,
2864 models: HashMap::from([
2865 (
2866 "claude-2.1".parse().unwrap(),
2867 ModelMetadataEntry {
2868 costs: Some(ModelCostV2 {
2869 input_per_token: 0.01,
2870 output_per_token: 0.02,
2871 output_reasoning_per_token: 0.0,
2872 input_cached_per_token: 0.04,
2873 input_cache_write_per_token: 0.0,
2874 }),
2875 context_size: None,
2876 },
2877 ),
2878 (
2879 "gpt4-21-04".parse().unwrap(),
2880 ModelMetadataEntry {
2881 costs: Some(ModelCostV2 {
2882 input_per_token: 0.09,
2883 output_per_token: 0.05,
2884 output_reasoning_per_token: 0.06,
2885 input_cached_per_token: 0.0,
2886 input_cache_write_per_token: 0.0,
2887 }),
2888 context_size: None,
2889 },
2890 ),
2891 ]),
2892 }),
2893 ..NormalizationConfig::default()
2894 },
2895 );
2896
2897 let [span1, span2] = collect_span_data(event);
2898
2899 assert_annotated_snapshot!(span1, @r#"
2900 {
2901 "gen_ai.cost.cache_creation.input_tokens": 0.0,
2902 "gen_ai.cost.cache_read.input_tokens": 20.0,
2903 "gen_ai.cost.input_tokens": 25.0,
2904 "gen_ai.cost.output_tokens": 40.0,
2905 "gen_ai.cost.reasoning.output_tokens": 20.0,
2906 "gen_ai.cost.total_tokens": 65.0,
2907 "gen_ai.operation.type": "ai_client",
2908 "gen_ai.request.model": "claude-2.1",
2909 "gen_ai.response.model": "claude-2.1",
2910 "gen_ai.response.tokens_per_second": 62500.0,
2911 "gen_ai.usage.cache_read.input_tokens": 500,
2912 "gen_ai.usage.input_tokens": 1000,
2913 "gen_ai.usage.output_tokens": 2000,
2914 "gen_ai.usage.reasoning.output_tokens": 1000,
2915 "gen_ai.usage.total_tokens": 3000.0
2916 }
2917 "#);
2918 assert_annotated_snapshot!(span2, @r#"
2919 {
2920 "gen_ai.cost.cache_creation.input_tokens": 0.0,
2921 "gen_ai.cost.cache_read.input_tokens": 0.0,
2922 "gen_ai.cost.input_tokens": 90.0,
2923 "gen_ai.cost.output_tokens": 100.0,
2924 "gen_ai.cost.reasoning.output_tokens": 0.0,
2925 "gen_ai.cost.total_tokens": 190.0,
2926 "gen_ai.operation.type": "ai_client",
2927 "gen_ai.request.model": "gpt4-21-04",
2928 "gen_ai.response.model": "gpt4-21-04",
2929 "gen_ai.response.tokens_per_second": 62500.0,
2930 "gen_ai.usage.input_tokens": 1000,
2931 "gen_ai.usage.output_tokens": 2000,
2932 "gen_ai.usage.total_tokens": 3000.0
2933 }
2934 "#);
2935 }
2936
2937 #[test]
2938 fn test_ai_response_tokens_per_second_no_output_tokens() {
2939 let json = r#"
2940 {
2941 "spans": [
2942 {
2943 "timestamp": 1702474614.0175,
2944 "start_timestamp": 1702474613.0175,
2945 "op": "gen_ai.chat_completions",
2946 "span_id": "9c01bd820a083e63",
2947 "trace_id": "922dda2462ea4ac2b6a4b339bee90863",
2948 "data": {
2949 "gen_ai.usage.input_tokens": 500
2950 }
2951 }
2952 ]
2953 }
2954 "#;
2955
2956 let mut event = Annotated::<Event>::from_json(json).unwrap();
2957
2958 normalize_event(
2959 &mut event,
2960 &NormalizationConfig {
2961 ai_model_metadata: Some(&ModelMetadata {
2962 version: 1,
2963 models: HashMap::new(),
2964 }),
2965 ..NormalizationConfig::default()
2966 },
2967 );
2968
2969 let [span] = collect_span_data(event);
2970
2971 assert_annotated_snapshot!(span, @r#"
2973 {
2974 "gen_ai.operation.type": "other",
2975 "gen_ai.usage.input_tokens": 500,
2976 "gen_ai.usage.total_tokens": 500.0
2977 }
2978 "#);
2979 }
2980
2981 #[test]
2982 fn test_ai_response_tokens_per_second_zero_duration() {
2983 let json = r#"
2984 {
2985 "spans": [
2986 {
2987 "timestamp": 1702474613.0175,
2988 "start_timestamp": 1702474613.0175,
2989 "op": "gen_ai.chat_completions",
2990 "span_id": "9c01bd820a083e63",
2991 "trace_id": "922dda2462ea4ac2b6a4b339bee90863",
2992 "data": {
2993 "gen_ai.usage.output_tokens": 1000
2994 }
2995 }
2996 ]
2997 }
2998 "#;
2999
3000 let mut event = Annotated::<Event>::from_json(json).unwrap();
3001
3002 normalize_event(
3003 &mut event,
3004 &NormalizationConfig {
3005 ai_model_metadata: Some(&ModelMetadata {
3006 version: 1,
3007 models: HashMap::new(),
3008 }),
3009 ..NormalizationConfig::default()
3010 },
3011 );
3012
3013 let [span] = collect_span_data(event);
3014
3015 assert_annotated_snapshot!(span, @r#"
3017 {
3018 "gen_ai.operation.type": "other",
3019 "gen_ai.usage.output_tokens": 1000,
3020 "gen_ai.usage.total_tokens": 1000.0
3021 }
3022 "#);
3023 }
3024
3025 #[test]
3026 fn test_ai_operation_type_mapping() {
3027 let json = r#"
3028 {
3029 "type": "transaction",
3030 "transaction": "test-transaction",
3031 "spans": [
3032 {
3033 "op": "gen_ai.chat",
3034 "description": "AI chat completion",
3035 "data": {}
3036 },
3037 {
3038 "op": "gen_ai.handoff",
3039 "description": "AI agent handoff",
3040 "data": {}
3041 },
3042 {
3043 "op": "gen_ai.unknown",
3044 "description": "Unknown AI operation",
3045 "data": {}
3046 }
3047 ]
3048 }
3049 "#;
3050
3051 let mut event = Annotated::<Event>::from_json(json).unwrap();
3052
3053 normalize_event(&mut event, &NormalizationConfig::default());
3054
3055 let [span1, span2, span3] = collect_span_data(event);
3056
3057 assert_annotated_snapshot!(span1, @r#"
3058 {
3059 "gen_ai.operation.type": "other"
3060 }
3061 "#);
3062 assert_annotated_snapshot!(span2, @r#"
3063 {
3064 "gen_ai.operation.type": "handoff"
3065 }
3066 "#);
3067 assert_annotated_snapshot!(span3, @r#"
3068 {
3069 "gen_ai.operation.type": "other"
3070 }
3071 "#);
3072 }
3073
3074 #[test]
3075 fn test_apple_high_device_class() {
3076 let mut event = Event {
3077 contexts: {
3078 let mut contexts = Contexts::new();
3079 contexts.add(DeviceContext {
3080 family: "iPhone".to_owned().into(),
3081 model: "iPhone15,3".to_owned().into(),
3082 ..Default::default()
3083 });
3084 Annotated::new(contexts)
3085 },
3086 ..Default::default()
3087 };
3088 normalize_device_class(&mut event);
3089 assert_debug_snapshot!(event.tags, @r###"
3090 Tags(
3091 PairList(
3092 [
3093 TagEntry(
3094 "device.class",
3095 "3",
3096 ),
3097 ],
3098 ),
3099 )
3100 "###);
3101 }
3102
3103 #[test]
3104 fn test_filter_mobile_outliers() {
3105 let mut measurements =
3106 Annotated::<Measurements>::from_json(r#"{"app_start_warm": {"value": 180001}}"#)
3107 .unwrap()
3108 .into_value()
3109 .unwrap();
3110 assert_eq!(measurements.len(), 1);
3111 filter_mobile_outliers(&mut measurements);
3112 assert_eq!(measurements.len(), 0);
3113 }
3114
3115 #[test]
3116 fn test_backfill_app_vitals_start_cold() {
3117 let json = r#"{
3118 "type": "transaction",
3119 "timestamp": "2021-04-26T08:00:05+0100",
3120 "start_timestamp": "2021-04-26T08:00:00+0100",
3121 "measurements": {"app_start_cold": {"value": 1234.0, "unit": "millisecond"}}
3122 }"#;
3123 let mut event = Annotated::<Event>::from_json(json)
3124 .unwrap()
3125 .into_value()
3126 .unwrap();
3127 backfill_app_vitals_start(&mut event);
3128 assert_debug_snapshot!(event.measurements, @r#"
3129 Measurements(
3130 {
3131 "app.vitals.start.value": Measurement {
3132 value: 1234.0,
3133 unit: Duration(
3134 MilliSecond,
3135 ),
3136 },
3137 "app_start_cold": Measurement {
3138 value: 1234.0,
3139 unit: Duration(
3140 MilliSecond,
3141 ),
3142 },
3143 },
3144 )
3145 "#);
3146 assert_debug_snapshot!(event.tags, @r#"
3147 Tags(
3148 PairList(
3149 [
3150 TagEntry(
3151 "app.vitals.start.type",
3152 "cold",
3153 ),
3154 ],
3155 ),
3156 )
3157 "#);
3158 }
3159
3160 #[test]
3161 fn test_backfill_app_vitals_start_warm() {
3162 let json = r#"{
3163 "type": "transaction",
3164 "timestamp": "2021-04-26T08:00:05+0100",
3165 "start_timestamp": "2021-04-26T08:00:00+0100",
3166 "measurements": {"app_start_warm": {"value": 567.0, "unit": "millisecond"}}
3167 }"#;
3168 let mut event = Annotated::<Event>::from_json(json)
3169 .unwrap()
3170 .into_value()
3171 .unwrap();
3172 backfill_app_vitals_start(&mut event);
3173 assert_debug_snapshot!(event.measurements, @r#"
3174 Measurements(
3175 {
3176 "app.vitals.start.value": Measurement {
3177 value: 567.0,
3178 unit: Duration(
3179 MilliSecond,
3180 ),
3181 },
3182 "app_start_warm": Measurement {
3183 value: 567.0,
3184 unit: Duration(
3185 MilliSecond,
3186 ),
3187 },
3188 },
3189 )
3190 "#);
3191 assert_debug_snapshot!(event.tags, @r#"
3192 Tags(
3193 PairList(
3194 [
3195 TagEntry(
3196 "app.vitals.start.type",
3197 "warm",
3198 ),
3199 ],
3200 ),
3201 )
3202 "#);
3203 }
3204
3205 #[test]
3206 fn test_backfill_app_vitals_start_cold_preferred_over_warm() {
3207 let json = r#"{
3208 "type": "transaction",
3209 "timestamp": "2021-04-26T08:00:05+0100",
3210 "start_timestamp": "2021-04-26T08:00:00+0100",
3211 "measurements": {
3212 "app_start_cold": {"value": 100.0, "unit": "millisecond"},
3213 "app_start_warm": {"value": 200.0, "unit": "millisecond"}
3214 }
3215 }"#;
3216 let mut event = Annotated::<Event>::from_json(json)
3217 .unwrap()
3218 .into_value()
3219 .unwrap();
3220 backfill_app_vitals_start(&mut event);
3221 assert_debug_snapshot!(event.measurements, @r#"
3222 Measurements(
3223 {
3224 "app.vitals.start.value": Measurement {
3225 value: 100.0,
3226 unit: Duration(
3227 MilliSecond,
3228 ),
3229 },
3230 "app_start_cold": Measurement {
3231 value: 100.0,
3232 unit: Duration(
3233 MilliSecond,
3234 ),
3235 },
3236 "app_start_warm": Measurement {
3237 value: 200.0,
3238 unit: Duration(
3239 MilliSecond,
3240 ),
3241 },
3242 },
3243 )
3244 "#);
3245 assert_debug_snapshot!(event.tags, @r#"
3246 Tags(
3247 PairList(
3248 [
3249 TagEntry(
3250 "app.vitals.start.type",
3251 "cold",
3252 ),
3253 ],
3254 ),
3255 )
3256 "#);
3257 }
3258
3259 #[test]
3260 fn test_backfill_app_vitals_start_no_app_start_noop() {
3261 let json = r#"{
3262 "type": "transaction",
3263 "timestamp": "2021-04-26T08:00:05+0100",
3264 "start_timestamp": "2021-04-26T08:00:00+0100",
3265 "measurements": {"lcp": {"value": 100.0}}
3266 }"#;
3267 let mut event = Annotated::<Event>::from_json(json)
3268 .unwrap()
3269 .into_value()
3270 .unwrap();
3271 backfill_app_vitals_start(&mut event);
3272 assert_debug_snapshot!(event.measurements, @r#"
3273 Measurements(
3274 {
3275 "lcp": Measurement {
3276 value: 100.0,
3277 unit: ~,
3278 },
3279 },
3280 )
3281 "#);
3282 assert_debug_snapshot!(event.tags, @"~");
3283 }
3284
3285 #[test]
3286 fn test_backfill_app_vitals_start_respects_outlier_filter() {
3287 let json = r#"{
3288 "type": "transaction",
3289 "timestamp": "2021-04-26T08:00:05+0100",
3290 "start_timestamp": "2021-04-26T08:00:00+0100",
3291 "measurements": {"app_start_cold": {"value": 180001.0, "unit": "millisecond"}}
3292 }"#;
3293 let mut event = Annotated::<Event>::from_json(json)
3294 .unwrap()
3295 .into_value()
3296 .unwrap();
3297 normalize_event_measurements(&mut event, None, None);
3298 backfill_app_vitals_start(&mut event);
3299 assert_debug_snapshot!(event.measurements, @"
3300 Measurements(
3301 {},
3302 )
3303 ");
3304 assert_debug_snapshot!(event.tags, @"~");
3305 }
3306
3307 #[test]
3308 fn test_backfill_app_vitals_start_non_transaction_payload_noop() {
3309 let json = r#"{
3310 "type": "error",
3311 "measurements": {
3312 "app_start_cold": {"value": 1234.0, "unit": "millisecond"}
3313 }
3314 }"#;
3315 let mut event = Annotated::<Event>::from_json(json)
3316 .unwrap()
3317 .into_value()
3318 .unwrap();
3319 backfill_app_vitals_start(&mut event);
3320 assert_debug_snapshot!(event.measurements, @r#"
3321 Measurements(
3322 {
3323 "app_start_cold": Measurement {
3324 value: 1234.0,
3325 unit: Duration(
3326 MilliSecond,
3327 ),
3328 },
3329 },
3330 )
3331 "#);
3332 assert_debug_snapshot!(event.tags, @"~");
3333 }
3334
3335 #[test]
3336 fn test_backfill_app_vitals_start_does_not_overwrite_value() {
3337 let json = r#"{
3338 "type": "transaction",
3339 "timestamp": "2021-04-26T08:00:05+0100",
3340 "start_timestamp": "2021-04-26T08:00:00+0100",
3341 "measurements": {
3342 "app_start_cold": {"value": 100.0, "unit": "millisecond"},
3343 "app.vitals.start.value": {"value": 999.0, "unit": "millisecond"}
3344 }
3345 }"#;
3346 let mut event = Annotated::<Event>::from_json(json)
3347 .unwrap()
3348 .into_value()
3349 .unwrap();
3350 backfill_app_vitals_start(&mut event);
3351 assert_debug_snapshot!(event.measurements, @r#"
3352 Measurements(
3353 {
3354 "app.vitals.start.value": Measurement {
3355 value: 999.0,
3356 unit: Duration(
3357 MilliSecond,
3358 ),
3359 },
3360 "app_start_cold": Measurement {
3361 value: 100.0,
3362 unit: Duration(
3363 MilliSecond,
3364 ),
3365 },
3366 },
3367 )
3368 "#);
3369 assert_debug_snapshot!(event.tags, @"~");
3370 }
3371
3372 #[test]
3373 fn test_backfill_app_vitals_start_does_not_overwrite_type() {
3374 let json = r#"{
3375 "type": "transaction",
3376 "timestamp": "2021-04-26T08:00:05+0100",
3377 "start_timestamp": "2021-04-26T08:00:00+0100",
3378 "measurements": {"app_start_cold": {"value": 100.0, "unit": "millisecond"}}
3379 }"#;
3380 let mut event = Annotated::<Event>::from_json(json)
3381 .unwrap()
3382 .into_value()
3383 .unwrap();
3384 event
3385 .tags
3386 .value_mut()
3387 .get_or_insert_with(Tags::default)
3388 .0
3389 .insert(
3390 String::from(APP__VITALS__START__TYPE),
3391 Annotated::new("warm".to_owned()),
3392 );
3393
3394 backfill_app_vitals_start(&mut event);
3395
3396 assert_debug_snapshot!(event.measurements, @r#"
3397 Measurements(
3398 {
3399 "app_start_cold": Measurement {
3400 value: 100.0,
3401 unit: Duration(
3402 MilliSecond,
3403 ),
3404 },
3405 },
3406 )
3407 "#);
3408 assert_debug_snapshot!(event.tags, @r#"
3409 Tags(
3410 PairList(
3411 [
3412 TagEntry(
3413 "app.vitals.start.type",
3414 "warm",
3415 ),
3416 ],
3417 ),
3418 )
3419 "#);
3420 }
3421
3422 #[test]
3423 fn test_backfill_app_vitals_start_invalid_unit_noop() {
3424 let json = r#"{
3425 "type": "transaction",
3426 "timestamp": "2021-04-26T08:00:05+0100",
3427 "start_timestamp": "2021-04-26T08:00:00+0100",
3428 "measurements": {"app_start_cold": {"value": 1.5, "unit": "second"}}
3429 }"#;
3430 let mut event = Annotated::<Event>::from_json(json)
3431 .unwrap()
3432 .into_value()
3433 .unwrap();
3434 backfill_app_vitals_start(&mut event);
3435 assert_debug_snapshot!(event.measurements, @r#"
3436 Measurements(
3437 {
3438 "app_start_cold": Measurement {
3439 value: 1.5,
3440 unit: Duration(
3441 Second,
3442 ),
3443 },
3444 },
3445 )
3446 "#);
3447 assert_debug_snapshot!(event.tags, @"~");
3448 }
3449
3450 #[test]
3451 fn test_backfill_app_vitals_start_screen_from_legacy_measurement() {
3452 let json = r#"{
3453 "type": "transaction",
3454 "transaction": "MainActivity",
3455 "contexts": {
3456 "trace": {
3457 "op": "ui.load"
3458 }
3459 },
3460 "measurements": {
3461 "app_start_cold": {
3462 "value": 1234.0,
3463 "unit": "millisecond"
3464 }
3465 }
3466 }"#;
3467 let mut event = Annotated::<Event>::from_json(json)
3468 .unwrap()
3469 .into_value()
3470 .unwrap();
3471
3472 backfill_app_vitals_start(&mut event);
3473
3474 assert_annotated_snapshot!(trace_context_data(&event), @r#"
3475 {
3476 "app.vitals.start.screen": "MainActivity"
3477 }
3478 "#);
3479 }
3480
3481 #[test]
3482 fn test_backfill_app_vitals_start_screen_from_dotted_measurement() {
3483 let mut event = app_vitals_start_screen_event(
3484 "transaction",
3485 Some("SettingsActivity"),
3486 "ui.load",
3487 Some(APP__VITALS__START__WARM__VALUE),
3488 None,
3489 );
3490
3491 backfill_app_vitals_start(&mut event);
3492
3493 assert_annotated_snapshot!(trace_context_data(&event), @r#"
3494 {
3495 "app.vitals.start.screen": "SettingsActivity"
3496 }
3497 "#);
3498 }
3499
3500 #[test]
3501 fn test_backfill_app_vitals_start_screen_from_start_value_measurement() {
3502 let mut event = app_vitals_start_screen_event(
3503 "transaction",
3504 Some("ProfileActivity"),
3505 "ui.load",
3506 Some(APP__VITALS__START__VALUE),
3507 None,
3508 );
3509
3510 backfill_app_vitals_start(&mut event);
3511
3512 assert_annotated_snapshot!(trace_context_data(&event), @r#"
3513 {
3514 "app.vitals.start.screen": "ProfileActivity"
3515 }
3516 "#);
3517 }
3518
3519 #[test]
3520 fn test_backfill_app_vitals_start_screen_requires_ui_load() {
3521 let mut event = app_vitals_start_screen_event(
3522 "transaction",
3523 Some("MainActivity"),
3524 "navigation",
3525 Some("app_start_cold"),
3526 None,
3527 );
3528
3529 backfill_app_vitals_start(&mut event);
3530
3531 assert_annotated_snapshot!(trace_context_data(&event), @"{}");
3532 }
3533
3534 #[test]
3535 fn test_backfill_app_vitals_start_screen_requires_app_start_measurement() {
3536 let mut event = app_vitals_start_screen_event(
3537 "transaction",
3538 Some("MainActivity"),
3539 "ui.load",
3540 None,
3541 None,
3542 );
3543
3544 backfill_app_vitals_start(&mut event);
3545
3546 assert_annotated_snapshot!(trace_context_data(&event), @"{}");
3547 }
3548
3549 #[test]
3550 fn test_backfill_app_vitals_start_screen_only_requires_measurement_key() {
3551 let json = r#"{
3552 "type": "transaction",
3553 "transaction": "MainActivity",
3554 "contexts": {
3555 "trace": {
3556 "op": "ui.load"
3557 }
3558 },
3559 "measurements": {
3560 "app_start_cold": {
3561 "unit": "millisecond"
3562 }
3563 }
3564 }"#;
3565 let mut event = Annotated::<Event>::from_json(json)
3566 .unwrap()
3567 .into_value()
3568 .unwrap();
3569
3570 backfill_app_vitals_start(&mut event);
3571
3572 assert_annotated_snapshot!(trace_context_data(&event), @r#"
3573 {
3574 "app.vitals.start.screen": "MainActivity"
3575 }
3576 "#);
3577 }
3578
3579 #[test]
3580 fn test_backfill_app_vitals_start_screen_preserves_existing_value() {
3581 let mut event = app_vitals_start_screen_event(
3582 "transaction",
3583 Some("MainActivity"),
3584 "ui.load",
3585 Some("app_start_cold"),
3586 Some("SDKScreen"),
3587 );
3588
3589 backfill_app_vitals_start(&mut event);
3590
3591 assert_annotated_snapshot!(trace_context_data(&event), @r#"
3592 {
3593 "app.vitals.start.screen": "SDKScreen"
3594 }
3595 "#);
3596 }
3597
3598 #[test]
3599 fn test_backfill_app_vitals_start_screen_requires_transaction_name() {
3600 let mut event = app_vitals_start_screen_event(
3601 "transaction",
3602 Some("<unlabeled transaction>"),
3603 "ui.load",
3604 Some("app_start_cold"),
3605 None,
3606 );
3607
3608 backfill_app_vitals_start(&mut event);
3609
3610 assert_annotated_snapshot!(trace_context_data(&event), @"{}");
3611 }
3612
3613 #[test]
3614 fn test_computed_performance_score_transaction() {
3615 let json = r#"
3616 {
3617 "type": "transaction",
3618 "timestamp": "2021-04-26T08:00:05+0100",
3619 "start_timestamp": "2021-04-26T08:00:00+0100",
3620 "measurements": {
3621 "fid": {"value": 213, "unit": "millisecond"},
3622 "fcp": {"value": 1237, "unit": "millisecond"},
3623 "lcp": {"value": 6596, "unit": "millisecond"},
3624 "cls": {"value": 0.11}
3625 },
3626 "contexts": {
3627 "browser": {
3628 "name": "Chrome",
3629 "version": "120.1.1",
3630 "type": "browser"
3631 }
3632 }
3633 }
3634 "#;
3635
3636 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
3637
3638 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
3639 "profiles": [
3640 {
3641 "name": "Desktop",
3642 "scoreComponents": [
3643 {
3644 "measurement": "fcp",
3645 "weight": 0.15,
3646 "p10": 900,
3647 "p50": 1600
3648 },
3649 {
3650 "measurement": "lcp",
3651 "weight": 0.30,
3652 "p10": 1200,
3653 "p50": 2400
3654 },
3655 {
3656 "measurement": "fid",
3657 "weight": 0.30,
3658 "p10": 100,
3659 "p50": 300
3660 },
3661 {
3662 "measurement": "cls",
3663 "weight": 0.25,
3664 "p10": 0.1,
3665 "p50": 0.25
3666 },
3667 {
3668 "measurement": "ttfb",
3669 "weight": 0.0,
3670 "p10": 0.2,
3671 "p50": 0.4
3672 },
3673 ],
3674 "condition": {
3675 "op":"eq",
3676 "name": "event.contexts.browser.name",
3677 "value": "Chrome"
3678 }
3679 }
3680 ]
3681 }))
3682 .unwrap();
3683
3684 normalize_performance_score(&mut event, Some(&performance_score));
3685
3686 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
3687 {
3688 "type": "transaction",
3689 "timestamp": 1619420405.0,
3690 "start_timestamp": 1619420400.0,
3691 "contexts": {
3692 "browser": {
3693 "name": "Chrome",
3694 "version": "120.1.1",
3695 "type": "browser",
3696 },
3697 },
3698 "measurements": {
3699 "cls": {
3700 "value": 0.11,
3701 },
3702 "fcp": {
3703 "value": 1237.0,
3704 "unit": "millisecond",
3705 },
3706 "fid": {
3707 "value": 213.0,
3708 "unit": "millisecond",
3709 },
3710 "lcp": {
3711 "value": 6596.0,
3712 "unit": "millisecond",
3713 },
3714 "score.cls": {
3715 "value": 0.21864170607444863,
3716 "unit": "ratio",
3717 },
3718 "score.fcp": {
3719 "value": 0.10750855443790831,
3720 "unit": "ratio",
3721 },
3722 "score.fid": {
3723 "value": 0.19657361348282545,
3724 "unit": "ratio",
3725 },
3726 "score.lcp": {
3727 "value": 0.009238896571386584,
3728 "unit": "ratio",
3729 },
3730 "score.ratio.cls": {
3731 "value": 0.8745668242977945,
3732 "unit": "ratio",
3733 },
3734 "score.ratio.fcp": {
3735 "value": 0.7167236962527221,
3736 "unit": "ratio",
3737 },
3738 "score.ratio.fid": {
3739 "value": 0.6552453782760849,
3740 "unit": "ratio",
3741 },
3742 "score.ratio.lcp": {
3743 "value": 0.03079632190462195,
3744 "unit": "ratio",
3745 },
3746 "score.total": {
3747 "value": 0.531962770566569,
3748 "unit": "ratio",
3749 },
3750 "score.weight.cls": {
3751 "value": 0.25,
3752 "unit": "ratio",
3753 },
3754 "score.weight.fcp": {
3755 "value": 0.15,
3756 "unit": "ratio",
3757 },
3758 "score.weight.fid": {
3759 "value": 0.3,
3760 "unit": "ratio",
3761 },
3762 "score.weight.lcp": {
3763 "value": 0.3,
3764 "unit": "ratio",
3765 },
3766 "score.weight.ttfb": {
3767 "value": 0.0,
3768 "unit": "ratio",
3769 },
3770 },
3771 }
3772 "###);
3773 }
3774
3775 #[test]
3782 fn test_computed_performance_score_spanv2() {
3783 let json = r#"
3784 {
3785 "end_timestamp": "2021-04-26T08:00:05+0100",
3786 "start_timestamp": "2021-04-26T08:00:00+0100",
3787 "attributes": {
3788 "browser.name": {"value": "Chrome", "type": "string"},
3789 "browser.version": {"value": "120.1.1", "type": "string"},
3790 "fid": {"value": 213, "type": "double"},
3791 "browser.web_vital.fcp.value": {"value": 1237.0, "type": "double"},
3792 "lcp": {"value": 6596, "type": "double"},
3793 "browser.web_vital.cls.value": {"value": 0.11, "type": "double"}
3794 }
3795 }
3796 "#;
3797
3798 let mut span = Annotated::<SpanV2>::from_json(json).unwrap().0.unwrap();
3799
3800 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
3801 "profiles": [
3802 {
3803 "name": "Desktop",
3804 "scoreComponents": [
3805 {
3806 "measurement": "fcp",
3807 "weight": 0.15,
3808 "p10": 900,
3809 "p50": 1600
3810 },
3811 {
3812 "measurement": "lcp",
3813 "weight": 0.30,
3814 "p10": 1200,
3815 "p50": 2400
3816 },
3817 {
3818 "measurement": "fid",
3819 "weight": 0.30,
3820 "p10": 100,
3821 "p50": 300
3822 },
3823 {
3824 "measurement": "cls",
3825 "weight": 0.25,
3826 "p10": 0.1,
3827 "p50": 0.25
3828 },
3829 {
3830 "measurement": "ttfb",
3831 "weight": 0.0,
3832 "p10": 0.2,
3833 "p50": 0.4
3834 },
3835 ],
3836 "condition": {
3837 "op": "or",
3838 "inner": [{
3839 "op":"eq",
3840 "name": "event.context.browser.name",
3841 "value": "Chrome"
3842 }, {
3843 "op":"eq",
3844 "name": "span.attributes.browser.name.value",
3845 "value": "Chrome"
3846 }]
3847 }
3848 }
3849 ]
3850 }))
3851 .unwrap();
3852
3853 eap::normalize_attribute_names(&mut span.attributes);
3854 normalize_performance_score(&mut span, Some(&performance_score));
3855
3856 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(span)), {}, @r###"
3857 {
3858 "start_timestamp": 1619420400.0,
3859 "end_timestamp": 1619420405.0,
3860 "attributes": {
3861 "browser.name": {
3862 "type": "string",
3863 "value": "Chrome",
3864 },
3865 "browser.version": {
3866 "type": "string",
3867 "value": "120.1.1",
3868 },
3869 "browser.web_vital.cls.value": {
3870 "type": "double",
3871 "value": 0.11,
3872 },
3873 "browser.web_vital.fcp.value": {
3874 "type": "double",
3875 "value": 1237.0,
3876 },
3877 "browser.web_vital.lcp.value": {
3878 "type": "double",
3879 "value": 6596,
3880 },
3881 "fid": {
3882 "type": "double",
3883 "value": 213,
3884 },
3885 "lcp": {
3886 "type": "double",
3887 "value": 6596,
3888 },
3889 "score.cls": {
3890 "type": "double",
3891 "value": 0.21864170607444863,
3892 },
3893 "score.fcp": {
3894 "type": "double",
3895 "value": 0.10750855443790831,
3896 },
3897 "score.fid": {
3898 "type": "double",
3899 "value": 0.19657361348282545,
3900 },
3901 "score.lcp": {
3902 "type": "double",
3903 "value": 0.009238896571386584,
3904 },
3905 "score.ratio.cls": {
3906 "type": "double",
3907 "value": 0.8745668242977945,
3908 },
3909 "score.ratio.fcp": {
3910 "type": "double",
3911 "value": 0.7167236962527221,
3912 },
3913 "score.ratio.fid": {
3914 "type": "double",
3915 "value": 0.6552453782760849,
3916 },
3917 "score.ratio.lcp": {
3918 "type": "double",
3919 "value": 0.03079632190462195,
3920 },
3921 "score.total": {
3922 "type": "double",
3923 "value": 0.531962770566569,
3924 },
3925 "score.weight.cls": {
3926 "type": "double",
3927 "value": 0.25,
3928 },
3929 "score.weight.fcp": {
3930 "type": "double",
3931 "value": 0.15,
3932 },
3933 "score.weight.fid": {
3934 "type": "double",
3935 "value": 0.3,
3936 },
3937 "score.weight.lcp": {
3938 "type": "double",
3939 "value": 0.3,
3940 },
3941 "score.weight.ttfb": {
3942 "type": "double",
3943 "value": 0.0,
3944 },
3945 },
3946 }
3947 "###);
3948 }
3949
3950 #[test]
3953 fn test_computed_performance_score_with_under_normalized_weights() {
3954 let json = r#"
3955 {
3956 "type": "transaction",
3957 "timestamp": "2021-04-26T08:00:05+0100",
3958 "start_timestamp": "2021-04-26T08:00:00+0100",
3959 "measurements": {
3960 "fid": {"value": 213, "unit": "millisecond"},
3961 "fcp": {"value": 1237, "unit": "millisecond"},
3962 "lcp": {"value": 6596, "unit": "millisecond"},
3963 "cls": {"value": 0.11}
3964 },
3965 "contexts": {
3966 "browser": {
3967 "name": "Chrome",
3968 "version": "120.1.1",
3969 "type": "browser"
3970 }
3971 }
3972 }
3973 "#;
3974
3975 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
3976
3977 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
3978 "profiles": [
3979 {
3980 "name": "Desktop",
3981 "scoreComponents": [
3982 {
3983 "measurement": "fcp",
3984 "weight": 0.03,
3985 "p10": 900,
3986 "p50": 1600
3987 },
3988 {
3989 "measurement": "lcp",
3990 "weight": 0.06,
3991 "p10": 1200,
3992 "p50": 2400
3993 },
3994 {
3995 "measurement": "fid",
3996 "weight": 0.06,
3997 "p10": 100,
3998 "p50": 300
3999 },
4000 {
4001 "measurement": "cls",
4002 "weight": 0.05,
4003 "p10": 0.1,
4004 "p50": 0.25
4005 },
4006 {
4007 "measurement": "ttfb",
4008 "weight": 0.0,
4009 "p10": 0.2,
4010 "p50": 0.4
4011 },
4012 ],
4013 "condition": {
4014 "op":"eq",
4015 "name": "event.contexts.browser.name",
4016 "value": "Chrome"
4017 }
4018 }
4019 ]
4020 }))
4021 .unwrap();
4022
4023 normalize_performance_score(&mut event, Some(&performance_score));
4024
4025 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
4026 {
4027 "type": "transaction",
4028 "timestamp": 1619420405.0,
4029 "start_timestamp": 1619420400.0,
4030 "contexts": {
4031 "browser": {
4032 "name": "Chrome",
4033 "version": "120.1.1",
4034 "type": "browser",
4035 },
4036 },
4037 "measurements": {
4038 "cls": {
4039 "value": 0.11,
4040 },
4041 "fcp": {
4042 "value": 1237.0,
4043 "unit": "millisecond",
4044 },
4045 "fid": {
4046 "value": 213.0,
4047 "unit": "millisecond",
4048 },
4049 "lcp": {
4050 "value": 6596.0,
4051 "unit": "millisecond",
4052 },
4053 "score.cls": {
4054 "value": 0.21864170607444863,
4055 "unit": "ratio",
4056 },
4057 "score.fcp": {
4058 "value": 0.10750855443790831,
4059 "unit": "ratio",
4060 },
4061 "score.fid": {
4062 "value": 0.19657361348282545,
4063 "unit": "ratio",
4064 },
4065 "score.lcp": {
4066 "value": 0.009238896571386584,
4067 "unit": "ratio",
4068 },
4069 "score.ratio.cls": {
4070 "value": 0.8745668242977945,
4071 "unit": "ratio",
4072 },
4073 "score.ratio.fcp": {
4074 "value": 0.7167236962527221,
4075 "unit": "ratio",
4076 },
4077 "score.ratio.fid": {
4078 "value": 0.6552453782760849,
4079 "unit": "ratio",
4080 },
4081 "score.ratio.lcp": {
4082 "value": 0.03079632190462195,
4083 "unit": "ratio",
4084 },
4085 "score.total": {
4086 "value": 0.531962770566569,
4087 "unit": "ratio",
4088 },
4089 "score.weight.cls": {
4090 "value": 0.25,
4091 "unit": "ratio",
4092 },
4093 "score.weight.fcp": {
4094 "value": 0.15,
4095 "unit": "ratio",
4096 },
4097 "score.weight.fid": {
4098 "value": 0.3,
4099 "unit": "ratio",
4100 },
4101 "score.weight.lcp": {
4102 "value": 0.3,
4103 "unit": "ratio",
4104 },
4105 "score.weight.ttfb": {
4106 "value": 0.0,
4107 "unit": "ratio",
4108 },
4109 },
4110 }
4111 "###);
4112 }
4113
4114 #[test]
4117 fn test_computed_performance_score_with_over_normalized_weights() {
4118 let json = r#"
4119 {
4120 "type": "transaction",
4121 "timestamp": "2021-04-26T08:00:05+0100",
4122 "start_timestamp": "2021-04-26T08:00:00+0100",
4123 "measurements": {
4124 "fid": {"value": 213, "unit": "millisecond"},
4125 "fcp": {"value": 1237, "unit": "millisecond"},
4126 "lcp": {"value": 6596, "unit": "millisecond"},
4127 "cls": {"value": 0.11}
4128 },
4129 "contexts": {
4130 "browser": {
4131 "name": "Chrome",
4132 "version": "120.1.1",
4133 "type": "browser"
4134 }
4135 }
4136 }
4137 "#;
4138
4139 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
4140
4141 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
4142 "profiles": [
4143 {
4144 "name": "Desktop",
4145 "scoreComponents": [
4146 {
4147 "measurement": "fcp",
4148 "weight": 0.30,
4149 "p10": 900,
4150 "p50": 1600
4151 },
4152 {
4153 "measurement": "lcp",
4154 "weight": 0.60,
4155 "p10": 1200,
4156 "p50": 2400
4157 },
4158 {
4159 "measurement": "fid",
4160 "weight": 0.60,
4161 "p10": 100,
4162 "p50": 300
4163 },
4164 {
4165 "measurement": "cls",
4166 "weight": 0.50,
4167 "p10": 0.1,
4168 "p50": 0.25
4169 },
4170 {
4171 "measurement": "ttfb",
4172 "weight": 0.0,
4173 "p10": 0.2,
4174 "p50": 0.4
4175 },
4176 ],
4177 "condition": {
4178 "op":"eq",
4179 "name": "event.contexts.browser.name",
4180 "value": "Chrome"
4181 }
4182 }
4183 ]
4184 }))
4185 .unwrap();
4186
4187 normalize_performance_score(&mut event, Some(&performance_score));
4188
4189 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
4190 {
4191 "type": "transaction",
4192 "timestamp": 1619420405.0,
4193 "start_timestamp": 1619420400.0,
4194 "contexts": {
4195 "browser": {
4196 "name": "Chrome",
4197 "version": "120.1.1",
4198 "type": "browser",
4199 },
4200 },
4201 "measurements": {
4202 "cls": {
4203 "value": 0.11,
4204 },
4205 "fcp": {
4206 "value": 1237.0,
4207 "unit": "millisecond",
4208 },
4209 "fid": {
4210 "value": 213.0,
4211 "unit": "millisecond",
4212 },
4213 "lcp": {
4214 "value": 6596.0,
4215 "unit": "millisecond",
4216 },
4217 "score.cls": {
4218 "value": 0.21864170607444863,
4219 "unit": "ratio",
4220 },
4221 "score.fcp": {
4222 "value": 0.10750855443790831,
4223 "unit": "ratio",
4224 },
4225 "score.fid": {
4226 "value": 0.19657361348282545,
4227 "unit": "ratio",
4228 },
4229 "score.lcp": {
4230 "value": 0.009238896571386584,
4231 "unit": "ratio",
4232 },
4233 "score.ratio.cls": {
4234 "value": 0.8745668242977945,
4235 "unit": "ratio",
4236 },
4237 "score.ratio.fcp": {
4238 "value": 0.7167236962527221,
4239 "unit": "ratio",
4240 },
4241 "score.ratio.fid": {
4242 "value": 0.6552453782760849,
4243 "unit": "ratio",
4244 },
4245 "score.ratio.lcp": {
4246 "value": 0.03079632190462195,
4247 "unit": "ratio",
4248 },
4249 "score.total": {
4250 "value": 0.531962770566569,
4251 "unit": "ratio",
4252 },
4253 "score.weight.cls": {
4254 "value": 0.25,
4255 "unit": "ratio",
4256 },
4257 "score.weight.fcp": {
4258 "value": 0.15,
4259 "unit": "ratio",
4260 },
4261 "score.weight.fid": {
4262 "value": 0.3,
4263 "unit": "ratio",
4264 },
4265 "score.weight.lcp": {
4266 "value": 0.3,
4267 "unit": "ratio",
4268 },
4269 "score.weight.ttfb": {
4270 "value": 0.0,
4271 "unit": "ratio",
4272 },
4273 },
4274 }
4275 "###);
4276 }
4277
4278 #[test]
4279 fn test_computed_performance_score_missing_measurement() {
4280 let json = r#"
4281 {
4282 "type": "transaction",
4283 "timestamp": "2021-04-26T08:00:05+0100",
4284 "start_timestamp": "2021-04-26T08:00:00+0100",
4285 "measurements": {
4286 "a": {"value": 213, "unit": "millisecond"}
4287 },
4288 "contexts": {
4289 "browser": {
4290 "name": "Chrome",
4291 "version": "120.1.1",
4292 "type": "browser"
4293 }
4294 }
4295 }
4296 "#;
4297
4298 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
4299
4300 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
4301 "profiles": [
4302 {
4303 "name": "Desktop",
4304 "scoreComponents": [
4305 {
4306 "measurement": "a",
4307 "weight": 0.15,
4308 "p10": 900,
4309 "p50": 1600
4310 },
4311 {
4312 "measurement": "b",
4313 "weight": 0.30,
4314 "p10": 1200,
4315 "p50": 2400
4316 },
4317 ],
4318 "condition": {
4319 "op":"eq",
4320 "name": "event.contexts.browser.name",
4321 "value": "Chrome"
4322 }
4323 }
4324 ]
4325 }))
4326 .unwrap();
4327
4328 normalize_performance_score(&mut event, Some(&performance_score));
4329
4330 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
4331 {
4332 "type": "transaction",
4333 "timestamp": 1619420405.0,
4334 "start_timestamp": 1619420400.0,
4335 "contexts": {
4336 "browser": {
4337 "name": "Chrome",
4338 "version": "120.1.1",
4339 "type": "browser",
4340 },
4341 },
4342 "measurements": {
4343 "a": {
4344 "value": 213.0,
4345 "unit": "millisecond",
4346 },
4347 },
4348 }
4349 "###);
4350 }
4351
4352 #[test]
4353 fn test_computed_performance_score_optional_measurement() {
4354 let json = r#"
4355 {
4356 "type": "transaction",
4357 "timestamp": "2021-04-26T08:00:05+0100",
4358 "start_timestamp": "2021-04-26T08:00:00+0100",
4359 "measurements": {
4360 "a": {"value": 213, "unit": "millisecond"},
4361 "b": {"value": 213, "unit": "millisecond"}
4362 },
4363 "contexts": {
4364 "browser": {
4365 "name": "Chrome",
4366 "version": "120.1.1",
4367 "type": "browser"
4368 }
4369 }
4370 }
4371 "#;
4372
4373 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
4374
4375 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
4376 "profiles": [
4377 {
4378 "name": "Desktop",
4379 "scoreComponents": [
4380 {
4381 "measurement": "a",
4382 "weight": 0.15,
4383 "p10": 900,
4384 "p50": 1600,
4385 },
4386 {
4387 "measurement": "b",
4388 "weight": 0.30,
4389 "p10": 1200,
4390 "p50": 2400,
4391 "optional": true
4392 },
4393 {
4394 "measurement": "c",
4395 "weight": 0.55,
4396 "p10": 1200,
4397 "p50": 2400,
4398 "optional": true
4399 },
4400 ],
4401 "condition": {
4402 "op":"eq",
4403 "name": "event.contexts.browser.name",
4404 "value": "Chrome"
4405 }
4406 }
4407 ]
4408 }))
4409 .unwrap();
4410
4411 normalize_performance_score(&mut event, Some(&performance_score));
4412
4413 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
4414 {
4415 "type": "transaction",
4416 "timestamp": 1619420405.0,
4417 "start_timestamp": 1619420400.0,
4418 "contexts": {
4419 "browser": {
4420 "name": "Chrome",
4421 "version": "120.1.1",
4422 "type": "browser",
4423 },
4424 },
4425 "measurements": {
4426 "a": {
4427 "value": 213.0,
4428 "unit": "millisecond",
4429 },
4430 "b": {
4431 "value": 213.0,
4432 "unit": "millisecond",
4433 },
4434 "score.a": {
4435 "value": 0.33333215313291975,
4436 "unit": "ratio",
4437 },
4438 "score.b": {
4439 "value": 0.66666415149198,
4440 "unit": "ratio",
4441 },
4442 "score.ratio.a": {
4443 "value": 0.9999964593987591,
4444 "unit": "ratio",
4445 },
4446 "score.ratio.b": {
4447 "value": 0.9999962272379699,
4448 "unit": "ratio",
4449 },
4450 "score.total": {
4451 "value": 0.9999963046248997,
4452 "unit": "ratio",
4453 },
4454 "score.weight.a": {
4455 "value": 0.33333333333333337,
4456 "unit": "ratio",
4457 },
4458 "score.weight.b": {
4459 "value": 0.6666666666666667,
4460 "unit": "ratio",
4461 },
4462 "score.weight.c": {
4463 "value": 0.0,
4464 "unit": "ratio",
4465 },
4466 },
4467 }
4468 "###);
4469 }
4470
4471 #[test]
4472 fn test_computed_performance_score_weight_0() {
4473 let json = r#"
4474 {
4475 "type": "transaction",
4476 "timestamp": "2021-04-26T08:00:05+0100",
4477 "start_timestamp": "2021-04-26T08:00:00+0100",
4478 "measurements": {
4479 "cls": {"value": 0.11}
4480 }
4481 }
4482 "#;
4483
4484 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
4485
4486 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
4487 "profiles": [
4488 {
4489 "name": "Desktop",
4490 "scoreComponents": [
4491 {
4492 "measurement": "cls",
4493 "weight": 0,
4494 "p10": 0.1,
4495 "p50": 0.25
4496 },
4497 ],
4498 "condition": {
4499 "op":"and",
4500 "inner": []
4501 }
4502 }
4503 ]
4504 }))
4505 .unwrap();
4506
4507 normalize_performance_score(&mut event, Some(&performance_score));
4508
4509 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
4510 {
4511 "type": "transaction",
4512 "timestamp": 1619420405.0,
4513 "start_timestamp": 1619420400.0,
4514 "measurements": {
4515 "cls": {
4516 "value": 0.11,
4517 },
4518 },
4519 }
4520 "###);
4521 }
4522
4523 #[test]
4524 fn test_computed_performance_score_negative_value() {
4525 let json = r#"
4526 {
4527 "type": "transaction",
4528 "timestamp": "2021-04-26T08:00:05+0100",
4529 "start_timestamp": "2021-04-26T08:00:00+0100",
4530 "measurements": {
4531 "ttfb": {"value": -100, "unit": "millisecond"}
4532 }
4533 }
4534 "#;
4535
4536 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
4537
4538 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
4539 "profiles": [
4540 {
4541 "name": "Desktop",
4542 "scoreComponents": [
4543 {
4544 "measurement": "ttfb",
4545 "weight": 1.0,
4546 "p10": 100.0,
4547 "p50": 250.0
4548 },
4549 ],
4550 "condition": {
4551 "op":"and",
4552 "inner": []
4553 }
4554 }
4555 ]
4556 }))
4557 .unwrap();
4558
4559 normalize_performance_score(&mut event, Some(&performance_score));
4560
4561 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
4562 {
4563 "type": "transaction",
4564 "timestamp": 1619420405.0,
4565 "start_timestamp": 1619420400.0,
4566 "measurements": {
4567 "score.ratio.ttfb": {
4568 "value": 1.0,
4569 "unit": "ratio",
4570 },
4571 "score.total": {
4572 "value": 1.0,
4573 "unit": "ratio",
4574 },
4575 "score.ttfb": {
4576 "value": 1.0,
4577 "unit": "ratio",
4578 },
4579 "score.weight.ttfb": {
4580 "value": 1.0,
4581 "unit": "ratio",
4582 },
4583 "ttfb": {
4584 "value": -100.0,
4585 "unit": "millisecond",
4586 },
4587 },
4588 }
4589 "###);
4590 }
4591
4592 #[test]
4593 fn test_filter_negative_web_vital_measurements() {
4594 let json = r#"
4595 {
4596 "type": "transaction",
4597 "timestamp": "2021-04-26T08:00:05+0100",
4598 "start_timestamp": "2021-04-26T08:00:00+0100",
4599 "measurements": {
4600 "ttfb": {"value": -100, "unit": "millisecond"}
4601 }
4602 }
4603 "#;
4604 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
4605
4606 let project_measurement_config: MeasurementsConfig = serde_json::from_value(json!({
4608 "builtinMeasurements": [
4609 {"name": "ttfb", "unit": "millisecond"},
4610 ],
4611 }))
4612 .unwrap();
4613
4614 let dynamic_measurement_config =
4615 CombinedMeasurementsConfig::new(Some(&project_measurement_config), None);
4616
4617 normalize_event_measurements(&mut event, Some(dynamic_measurement_config), None);
4618
4619 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
4620 {
4621 "type": "transaction",
4622 "timestamp": 1619420405.0,
4623 "start_timestamp": 1619420400.0,
4624 "measurements": {},
4625 "_meta": {
4626 "measurements": {
4627 "": Meta(Some(MetaInner(
4628 err: [
4629 [
4630 "invalid_data",
4631 {
4632 "reason": "Negative value for measurement ttfb not allowed: -100",
4633 },
4634 ],
4635 ],
4636 val: Some({
4637 "ttfb": {
4638 "unit": "millisecond",
4639 "value": -100.0,
4640 },
4641 }),
4642 ))),
4643 },
4644 },
4645 }
4646 "###);
4647 }
4648
4649 #[test]
4650 fn test_computed_performance_score_multiple_profiles() {
4651 let json = r#"
4652 {
4653 "type": "transaction",
4654 "timestamp": "2021-04-26T08:00:05+0100",
4655 "start_timestamp": "2021-04-26T08:00:00+0100",
4656 "measurements": {
4657 "cls": {"value": 0.11},
4658 "inp": {"value": 120.0}
4659 }
4660 }
4661 "#;
4662
4663 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
4664
4665 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
4666 "profiles": [
4667 {
4668 "name": "Desktop",
4669 "scoreComponents": [
4670 {
4671 "measurement": "cls",
4672 "weight": 0,
4673 "p10": 0.1,
4674 "p50": 0.25
4675 },
4676 ],
4677 "condition": {
4678 "op":"and",
4679 "inner": []
4680 }
4681 },
4682 {
4683 "name": "Desktop",
4684 "scoreComponents": [
4685 {
4686 "measurement": "inp",
4687 "weight": 1.0,
4688 "p10": 0.1,
4689 "p50": 0.25
4690 },
4691 ],
4692 "condition": {
4693 "op":"and",
4694 "inner": []
4695 }
4696 }
4697 ]
4698 }))
4699 .unwrap();
4700
4701 normalize_performance_score(&mut event, Some(&performance_score));
4702
4703 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
4704 {
4705 "type": "transaction",
4706 "timestamp": 1619420405.0,
4707 "start_timestamp": 1619420400.0,
4708 "measurements": {
4709 "cls": {
4710 "value": 0.11,
4711 },
4712 "inp": {
4713 "value": 120.0,
4714 },
4715 "score.inp": {
4716 "value": 0.0,
4717 "unit": "ratio",
4718 },
4719 "score.ratio.inp": {
4720 "value": 0.0,
4721 "unit": "ratio",
4722 },
4723 "score.total": {
4724 "value": 0.0,
4725 "unit": "ratio",
4726 },
4727 "score.weight.inp": {
4728 "value": 1.0,
4729 "unit": "ratio",
4730 },
4731 },
4732 }
4733 "###);
4734 }
4735
4736 #[test]
4737 fn test_compute_performance_score_for_mobile_ios_profile() {
4738 let mut event = Annotated::<Event>::from_json(IOS_MOBILE_EVENT)
4739 .unwrap()
4740 .0
4741 .unwrap();
4742
4743 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
4744 "profiles": [
4745 {
4746 "name": "Mobile",
4747 "scoreComponents": [
4748 {
4749 "measurement": "time_to_initial_display",
4750 "weight": 0.25,
4751 "p10": 1800.0,
4752 "p50": 3000.0,
4753 "optional": true
4754 },
4755 {
4756 "measurement": "time_to_full_display",
4757 "weight": 0.25,
4758 "p10": 2500.0,
4759 "p50": 4000.0,
4760 "optional": true
4761 },
4762 {
4763 "measurement": "app_start_warm",
4764 "weight": 0.25,
4765 "p10": 200.0,
4766 "p50": 500.0,
4767 "optional": true
4768 },
4769 {
4770 "measurement": "app_start_cold",
4771 "weight": 0.25,
4772 "p10": 200.0,
4773 "p50": 500.0,
4774 "optional": true
4775 }
4776 ],
4777 "condition": {
4778 "op": "and",
4779 "inner": [
4780 {
4781 "op": "or",
4782 "inner": [
4783 {
4784 "op": "eq",
4785 "name": "event.sdk.name",
4786 "value": "sentry.cocoa"
4787 },
4788 {
4789 "op": "eq",
4790 "name": "event.sdk.name",
4791 "value": "sentry.java.android"
4792 }
4793 ]
4794 },
4795 {
4796 "op": "eq",
4797 "name": "event.contexts.trace.op",
4798 "value": "ui.load"
4799 }
4800 ]
4801 }
4802 }
4803 ]
4804 }))
4805 .unwrap();
4806
4807 normalize_performance_score(&mut event, Some(&performance_score));
4808
4809 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {});
4810 }
4811
4812 #[test]
4813 fn test_compute_performance_score_for_mobile_android_profile() {
4814 let mut event = Annotated::<Event>::from_json(ANDROID_MOBILE_EVENT)
4815 .unwrap()
4816 .0
4817 .unwrap();
4818
4819 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
4820 "profiles": [
4821 {
4822 "name": "Mobile",
4823 "scoreComponents": [
4824 {
4825 "measurement": "time_to_initial_display",
4826 "weight": 0.25,
4827 "p10": 1800.0,
4828 "p50": 3000.0,
4829 "optional": true
4830 },
4831 {
4832 "measurement": "time_to_full_display",
4833 "weight": 0.25,
4834 "p10": 2500.0,
4835 "p50": 4000.0,
4836 "optional": true
4837 },
4838 {
4839 "measurement": "app_start_warm",
4840 "weight": 0.25,
4841 "p10": 200.0,
4842 "p50": 500.0,
4843 "optional": true
4844 },
4845 {
4846 "measurement": "app_start_cold",
4847 "weight": 0.25,
4848 "p10": 200.0,
4849 "p50": 500.0,
4850 "optional": true
4851 }
4852 ],
4853 "condition": {
4854 "op": "and",
4855 "inner": [
4856 {
4857 "op": "or",
4858 "inner": [
4859 {
4860 "op": "eq",
4861 "name": "event.sdk.name",
4862 "value": "sentry.cocoa"
4863 },
4864 {
4865 "op": "eq",
4866 "name": "event.sdk.name",
4867 "value": "sentry.java.android"
4868 }
4869 ]
4870 },
4871 {
4872 "op": "eq",
4873 "name": "event.contexts.trace.op",
4874 "value": "ui.load"
4875 }
4876 ]
4877 }
4878 }
4879 ]
4880 }))
4881 .unwrap();
4882
4883 normalize_performance_score(&mut event, Some(&performance_score));
4884
4885 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {});
4886 }
4887
4888 #[test]
4889 fn test_computes_performance_score_and_tags_with_profile_version() {
4890 let json = r#"
4891 {
4892 "type": "transaction",
4893 "timestamp": "2021-04-26T08:00:05+0100",
4894 "start_timestamp": "2021-04-26T08:00:00+0100",
4895 "measurements": {
4896 "inp": {"value": 120.0}
4897 }
4898 }
4899 "#;
4900
4901 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
4902
4903 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
4904 "profiles": [
4905 {
4906 "name": "Desktop",
4907 "scoreComponents": [
4908 {
4909 "measurement": "inp",
4910 "weight": 1.0,
4911 "p10": 0.1,
4912 "p50": 0.25
4913 },
4914 ],
4915 "condition": {
4916 "op":"and",
4917 "inner": []
4918 },
4919 "version": "beta"
4920 }
4921 ]
4922 }))
4923 .unwrap();
4924
4925 normalize(
4926 &mut event,
4927 &mut Meta::default(),
4928 &NormalizationConfig {
4929 performance_score: Some(&performance_score),
4930 ..Default::default()
4931 },
4932 );
4933
4934 insta::assert_ron_snapshot!(SerializableAnnotated(&event.contexts), {}, @r###"
4935 {
4936 "performance_score": {
4937 "score_profile_version": "beta",
4938 "type": "performancescore",
4939 },
4940 }
4941 "###);
4942 insta::assert_ron_snapshot!(SerializableAnnotated(&event.measurements), {}, @r###"
4943 {
4944 "inp": {
4945 "value": 120.0,
4946 "unit": "millisecond",
4947 },
4948 "score.inp": {
4949 "value": 0.0,
4950 "unit": "ratio",
4951 },
4952 "score.ratio.inp": {
4953 "value": 0.0,
4954 "unit": "ratio",
4955 },
4956 "score.total": {
4957 "value": 0.0,
4958 "unit": "ratio",
4959 },
4960 "score.weight.inp": {
4961 "value": 1.0,
4962 "unit": "ratio",
4963 },
4964 }
4965 "###);
4966 }
4967
4968 #[test]
4969 fn test_normalize_adds_trace_context() {
4970 let json = r#"
4971 {
4972 "type": "error",
4973 "exception": {
4974 "values": [{"type": "ValueError", "value": "Should not happen"}]
4975 }
4976 }
4977 "#;
4978
4979 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
4980
4981 normalize(
4982 &mut event,
4983 &mut Meta::default(),
4984 &NormalizationConfig {
4985 force_trace_context: true,
4986 ..Default::default()
4987 },
4988 );
4989
4990 insta::assert_ron_snapshot!(SerializableAnnotated(&event.contexts), {
4991 ".event_id" => "[event-id]",
4992 ".trace.trace_id" => "[trace-id]",
4993 ".trace.span_id" => "[span-id]"
4994 }, @r#"
4995 {
4996 "trace": {
4997 "trace_id": "[trace-id]",
4998 "span_id": "[span-id]",
4999 "status": "unknown",
5000 "type": "trace",
5001 },
5002 }
5003 "#);
5004 }
5005
5006 #[test]
5007 fn test_normalize_adds_trace_context_prefers_dsc_trace_id() {
5008 let json = r#"
5009 {
5010 "event_id": "11111111111111111111111111111111",
5011 "type": "error",
5012 "exception": {
5013 "values": [{"type": "ValueError", "value": "Should not happen"}]
5014 }
5015 }
5016 "#;
5017
5018 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
5019
5020 let dsc: DynamicSamplingContext = serde_json::from_value(json!({
5021 "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
5022 "public_key": "e12d836b15bb49d7bbf99e64295d995b"
5023 }))
5024 .unwrap();
5025
5026 normalize(
5027 &mut event,
5028 &mut Meta::default(),
5029 &NormalizationConfig {
5030 force_trace_context: true,
5031 dsc: Some(&dsc),
5032 ..Default::default()
5033 },
5034 );
5035
5036 insta::assert_ron_snapshot!(SerializableAnnotated(&event.contexts), {}, @r#"
5037 {
5038 "trace": {
5039 "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
5040 "span_id": "4c79f60c11214eb3",
5041 "status": "unknown",
5042 "type": "trace",
5043 },
5044 }
5045 "#);
5046 }
5047
5048 #[test]
5049 fn test_normalize_adds_trace_context_without_dsc_falls_back_to_event_id() {
5050 let json = r#"
5051 {
5052 "event_id": "11111111111111111111111111111111",
5053 "type": "error",
5054 "exception": {
5055 "values": [{"type": "ValueError", "value": "Should not happen"}]
5056 }
5057 }
5058 "#;
5059
5060 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
5061
5062 normalize(
5063 &mut event,
5064 &mut Meta::default(),
5065 &NormalizationConfig {
5066 force_trace_context: true,
5067 ..Default::default()
5068 },
5069 );
5070
5071 insta::assert_ron_snapshot!(SerializableAnnotated(&event.contexts), {}, @r#"
5072 {
5073 "trace": {
5074 "trace_id": "11111111111111111111111111111111",
5075 "span_id": "1111111111111111",
5076 "status": "unknown",
5077 "type": "trace",
5078 },
5079 }
5080 "#);
5081 }
5082
5083 #[test]
5084 fn test_normalize_fills_empty_trace_context_from_dsc() {
5085 let json = r#"
5086 {
5087 "event_id": "11111111111111111111111111111111",
5088 "type": "error",
5089 "exception": {
5090 "values": [{"type": "ValueError", "value": "Should not happen"}]
5091 },
5092 "contexts": {
5093 "trace": {}
5094 }
5095 }
5096 "#;
5097
5098 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
5099
5100 let dsc: DynamicSamplingContext = serde_json::from_value(json!({
5101 "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
5102 "public_key": "e12d836b15bb49d7bbf99e64295d995b"
5103 }))
5104 .unwrap();
5105
5106 normalize(
5107 &mut event,
5108 &mut Meta::default(),
5109 &NormalizationConfig {
5110 force_trace_context: true,
5111 dsc: Some(&dsc),
5112 ..Default::default()
5113 },
5114 );
5115
5116 insta::assert_ron_snapshot!(SerializableAnnotated(&event.contexts), {}, @r#"
5117 {
5118 "trace": {
5119 "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
5120 "span_id": "4c79f60c11214eb3",
5121 "status": "unknown",
5122 "type": "trace",
5123 },
5124 }
5125 "#);
5126 }
5127
5128 #[test]
5129 fn test_normalize_preserves_span_id_when_using_dsc_trace_id() {
5130 let json = r#"
5131 {
5132 "event_id": "11111111111111111111111111111111",
5133 "type": "error",
5134 "exception": {
5135 "values": [{"type": "ValueError", "value": "Should not happen"}]
5136 },
5137 "contexts": {
5138 "trace": {
5139 "span_id": "aaaaaaaaaaaaaaaa"
5140 }
5141 }
5142 }
5143 "#;
5144
5145 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
5146
5147 let dsc: DynamicSamplingContext = serde_json::from_value(json!({
5148 "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
5149 "public_key": "e12d836b15bb49d7bbf99e64295d995b"
5150 }))
5151 .unwrap();
5152
5153 normalize(
5154 &mut event,
5155 &mut Meta::default(),
5156 &NormalizationConfig {
5157 force_trace_context: true,
5158 dsc: Some(&dsc),
5159 ..Default::default()
5160 },
5161 );
5162
5163 insta::assert_ron_snapshot!(SerializableAnnotated(&event.contexts), {}, @r#"
5164 {
5165 "trace": {
5166 "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
5167 "span_id": "aaaaaaaaaaaaaaaa",
5168 "status": "unknown",
5169 "type": "trace",
5170 },
5171 }
5172 "#);
5173 }
5174
5175 #[test]
5176 fn test_normalize_derives_span_id_from_existing_trace_id() {
5177 let json = r#"
5178 {
5179 "event_id": "11111111111111111111111111111111",
5180 "type": "error",
5181 "exception": {
5182 "values": [{"type": "ValueError", "value": "Should not happen"}]
5183 },
5184 "contexts": {
5185 "trace": {
5186 "trace_id": "22222222222222222222222222222222"
5187 }
5188 }
5189 }
5190 "#;
5191
5192 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
5193
5194 let dsc: DynamicSamplingContext = serde_json::from_value(json!({
5195 "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
5196 "public_key": "e12d836b15bb49d7bbf99e64295d995b"
5197 }))
5198 .unwrap();
5199
5200 normalize(
5201 &mut event,
5202 &mut Meta::default(),
5203 &NormalizationConfig {
5204 force_trace_context: true,
5205 dsc: Some(&dsc),
5206 ..Default::default()
5207 },
5208 );
5209
5210 insta::assert_ron_snapshot!(SerializableAnnotated(&event.contexts), {}, @r#"
5211 {
5212 "trace": {
5213 "trace_id": "22222222222222222222222222222222",
5214 "span_id": "2222222222222222",
5215 "status": "unknown",
5216 "type": "trace",
5217 },
5218 }
5219 "#);
5220 }
5221
5222 #[test]
5223 fn test_normalize_preserves_trace_context_with_conflicting_dsc() {
5224 let json = r#"
5225 {
5226 "event_id": "11111111111111111111111111111111",
5227 "type": "error",
5228 "exception": {
5229 "values": [{"type": "ValueError", "value": "Should not happen"}]
5230 },
5231 "contexts": {
5232 "trace": {
5233 "trace_id": "22222222222222222222222222222222",
5234 "span_id": "aaaaaaaaaaaaaaaa"
5235 }
5236 }
5237 }
5238 "#;
5239
5240 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
5241
5242 let dsc: DynamicSamplingContext = serde_json::from_value(json!({
5243 "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
5244 "public_key": "e12d836b15bb49d7bbf99e64295d995b"
5245 }))
5246 .unwrap();
5247
5248 normalize(
5249 &mut event,
5250 &mut Meta::default(),
5251 &NormalizationConfig {
5252 force_trace_context: true,
5253 dsc: Some(&dsc),
5254 ..Default::default()
5255 },
5256 );
5257
5258 insta::assert_ron_snapshot!(SerializableAnnotated(&event.contexts), {}, @r#"
5259 {
5260 "trace": {
5261 "trace_id": "22222222222222222222222222222222",
5262 "span_id": "aaaaaaaaaaaaaaaa",
5263 "status": "unknown",
5264 "type": "trace",
5265 },
5266 }
5267 "#);
5268 }
5269
5270 #[test]
5271 fn test_computes_standalone_cls_performance_score() {
5272 let json = r#"
5273 {
5274 "type": "transaction",
5275 "timestamp": "2021-04-26T08:00:05+0100",
5276 "start_timestamp": "2021-04-26T08:00:00+0100",
5277 "measurements": {
5278 "cls": {"value": 0.5}
5279 }
5280 }
5281 "#;
5282
5283 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
5284
5285 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
5286 "profiles": [
5287 {
5288 "name": "Default",
5289 "scoreComponents": [
5290 {
5291 "measurement": "fcp",
5292 "weight": 0.15,
5293 "p10": 900.0,
5294 "p50": 1600.0,
5295 "optional": true,
5296 },
5297 {
5298 "measurement": "lcp",
5299 "weight": 0.30,
5300 "p10": 1200.0,
5301 "p50": 2400.0,
5302 "optional": true,
5303 },
5304 {
5305 "measurement": "cls",
5306 "weight": 0.15,
5307 "p10": 0.1,
5308 "p50": 0.25,
5309 "optional": true,
5310 },
5311 {
5312 "measurement": "ttfb",
5313 "weight": 0.10,
5314 "p10": 200.0,
5315 "p50": 400.0,
5316 "optional": true,
5317 },
5318 ],
5319 "condition": {
5320 "op": "and",
5321 "inner": [],
5322 },
5323 }
5324 ]
5325 }))
5326 .unwrap();
5327
5328 normalize(
5329 &mut event,
5330 &mut Meta::default(),
5331 &NormalizationConfig {
5332 performance_score: Some(&performance_score),
5333 ..Default::default()
5334 },
5335 );
5336
5337 insta::assert_ron_snapshot!(SerializableAnnotated(&event.measurements), {}, @r###"
5338 {
5339 "cls": {
5340 "value": 0.5,
5341 "unit": "none",
5342 },
5343 "score.cls": {
5344 "value": 0.16615877613713903,
5345 "unit": "ratio",
5346 },
5347 "score.ratio.cls": {
5348 "value": 0.16615877613713903,
5349 "unit": "ratio",
5350 },
5351 "score.total": {
5352 "value": 0.16615877613713903,
5353 "unit": "ratio",
5354 },
5355 "score.weight.cls": {
5356 "value": 1.0,
5357 "unit": "ratio",
5358 },
5359 "score.weight.fcp": {
5360 "value": 0.0,
5361 "unit": "ratio",
5362 },
5363 "score.weight.lcp": {
5364 "value": 0.0,
5365 "unit": "ratio",
5366 },
5367 "score.weight.ttfb": {
5368 "value": 0.0,
5369 "unit": "ratio",
5370 },
5371 }
5372 "###);
5373 }
5374
5375 #[test]
5376 fn test_computes_standalone_lcp_performance_score() {
5377 let json = r#"
5378 {
5379 "type": "transaction",
5380 "timestamp": "2021-04-26T08:00:05+0100",
5381 "start_timestamp": "2021-04-26T08:00:00+0100",
5382 "measurements": {
5383 "lcp": {"value": 1200.0}
5384 }
5385 }
5386 "#;
5387
5388 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
5389
5390 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
5391 "profiles": [
5392 {
5393 "name": "Default",
5394 "scoreComponents": [
5395 {
5396 "measurement": "fcp",
5397 "weight": 0.15,
5398 "p10": 900.0,
5399 "p50": 1600.0,
5400 "optional": true,
5401 },
5402 {
5403 "measurement": "lcp",
5404 "weight": 0.30,
5405 "p10": 1200.0,
5406 "p50": 2400.0,
5407 "optional": true,
5408 },
5409 {
5410 "measurement": "cls",
5411 "weight": 0.15,
5412 "p10": 0.1,
5413 "p50": 0.25,
5414 "optional": true,
5415 },
5416 {
5417 "measurement": "ttfb",
5418 "weight": 0.10,
5419 "p10": 200.0,
5420 "p50": 400.0,
5421 "optional": true,
5422 },
5423 ],
5424 "condition": {
5425 "op": "and",
5426 "inner": [],
5427 },
5428 }
5429 ]
5430 }))
5431 .unwrap();
5432
5433 normalize(
5434 &mut event,
5435 &mut Meta::default(),
5436 &NormalizationConfig {
5437 performance_score: Some(&performance_score),
5438 ..Default::default()
5439 },
5440 );
5441
5442 insta::assert_ron_snapshot!(SerializableAnnotated(&event.measurements), {}, @r###"
5443 {
5444 "lcp": {
5445 "value": 1200.0,
5446 "unit": "millisecond",
5447 },
5448 "score.lcp": {
5449 "value": 0.8999999314038525,
5450 "unit": "ratio",
5451 },
5452 "score.ratio.lcp": {
5453 "value": 0.8999999314038525,
5454 "unit": "ratio",
5455 },
5456 "score.total": {
5457 "value": 0.8999999314038525,
5458 "unit": "ratio",
5459 },
5460 "score.weight.cls": {
5461 "value": 0.0,
5462 "unit": "ratio",
5463 },
5464 "score.weight.fcp": {
5465 "value": 0.0,
5466 "unit": "ratio",
5467 },
5468 "score.weight.lcp": {
5469 "value": 1.0,
5470 "unit": "ratio",
5471 },
5472 "score.weight.ttfb": {
5473 "value": 0.0,
5474 "unit": "ratio",
5475 },
5476 }
5477 "###);
5478 }
5479
5480 #[test]
5481 fn test_computed_performance_score_uses_first_matching_profile() {
5482 let json = r#"
5483 {
5484 "type": "transaction",
5485 "timestamp": "2021-04-26T08:00:05+0100",
5486 "start_timestamp": "2021-04-26T08:00:00+0100",
5487 "measurements": {
5488 "a": {"value": 213, "unit": "millisecond"},
5489 "b": {"value": 213, "unit": "millisecond"}
5490 },
5491 "contexts": {
5492 "browser": {
5493 "name": "Chrome",
5494 "version": "120.1.1",
5495 "type": "browser"
5496 }
5497 }
5498 }
5499 "#;
5500
5501 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
5502
5503 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
5504 "profiles": [
5505 {
5506 "name": "Mobile",
5507 "scoreComponents": [
5508 {
5509 "measurement": "a",
5510 "weight": 0.15,
5511 "p10": 100,
5512 "p50": 200,
5513 },
5514 {
5515 "measurement": "b",
5516 "weight": 0.30,
5517 "p10": 100,
5518 "p50": 200,
5519 "optional": true
5520 },
5521 {
5522 "measurement": "c",
5523 "weight": 0.55,
5524 "p10": 100,
5525 "p50": 200,
5526 "optional": true
5527 },
5528 ],
5529 "condition": {
5530 "op":"eq",
5531 "name": "event.contexts.browser.name",
5532 "value": "Chrome Mobile"
5533 }
5534 },
5535 {
5536 "name": "Desktop",
5537 "scoreComponents": [
5538 {
5539 "measurement": "a",
5540 "weight": 0.15,
5541 "p10": 900,
5542 "p50": 1600,
5543 },
5544 {
5545 "measurement": "b",
5546 "weight": 0.30,
5547 "p10": 1200,
5548 "p50": 2400,
5549 "optional": true
5550 },
5551 {
5552 "measurement": "c",
5553 "weight": 0.55,
5554 "p10": 1200,
5555 "p50": 2400,
5556 "optional": true
5557 },
5558 ],
5559 "condition": {
5560 "op":"eq",
5561 "name": "event.contexts.browser.name",
5562 "value": "Chrome"
5563 }
5564 },
5565 {
5566 "name": "Default",
5567 "scoreComponents": [
5568 {
5569 "measurement": "a",
5570 "weight": 0.15,
5571 "p10": 100,
5572 "p50": 200,
5573 },
5574 {
5575 "measurement": "b",
5576 "weight": 0.30,
5577 "p10": 100,
5578 "p50": 200,
5579 "optional": true
5580 },
5581 {
5582 "measurement": "c",
5583 "weight": 0.55,
5584 "p10": 100,
5585 "p50": 200,
5586 "optional": true
5587 },
5588 ],
5589 "condition": {
5590 "op": "and",
5591 "inner": [],
5592 }
5593 }
5594 ]
5595 }))
5596 .unwrap();
5597
5598 normalize_performance_score(&mut event, Some(&performance_score));
5599
5600 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
5601 {
5602 "type": "transaction",
5603 "timestamp": 1619420405.0,
5604 "start_timestamp": 1619420400.0,
5605 "contexts": {
5606 "browser": {
5607 "name": "Chrome",
5608 "version": "120.1.1",
5609 "type": "browser",
5610 },
5611 },
5612 "measurements": {
5613 "a": {
5614 "value": 213.0,
5615 "unit": "millisecond",
5616 },
5617 "b": {
5618 "value": 213.0,
5619 "unit": "millisecond",
5620 },
5621 "score.a": {
5622 "value": 0.33333215313291975,
5623 "unit": "ratio",
5624 },
5625 "score.b": {
5626 "value": 0.66666415149198,
5627 "unit": "ratio",
5628 },
5629 "score.ratio.a": {
5630 "value": 0.9999964593987591,
5631 "unit": "ratio",
5632 },
5633 "score.ratio.b": {
5634 "value": 0.9999962272379699,
5635 "unit": "ratio",
5636 },
5637 "score.total": {
5638 "value": 0.9999963046248997,
5639 "unit": "ratio",
5640 },
5641 "score.weight.a": {
5642 "value": 0.33333333333333337,
5643 "unit": "ratio",
5644 },
5645 "score.weight.b": {
5646 "value": 0.6666666666666667,
5647 "unit": "ratio",
5648 },
5649 "score.weight.c": {
5650 "value": 0.0,
5651 "unit": "ratio",
5652 },
5653 },
5654 }
5655 "###);
5656 }
5657
5658 #[test]
5659 fn test_computed_performance_score_falls_back_to_default_profile() {
5660 let json = r#"
5661 {
5662 "type": "transaction",
5663 "timestamp": "2021-04-26T08:00:05+0100",
5664 "start_timestamp": "2021-04-26T08:00:00+0100",
5665 "measurements": {
5666 "a": {"value": 213, "unit": "millisecond"},
5667 "b": {"value": 213, "unit": "millisecond"}
5668 },
5669 "contexts": {}
5670 }
5671 "#;
5672
5673 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
5674
5675 let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
5676 "profiles": [
5677 {
5678 "name": "Mobile",
5679 "scoreComponents": [
5680 {
5681 "measurement": "a",
5682 "weight": 0.15,
5683 "p10": 900,
5684 "p50": 1600,
5685 "optional": true
5686 },
5687 {
5688 "measurement": "b",
5689 "weight": 0.30,
5690 "p10": 1200,
5691 "p50": 2400,
5692 "optional": true
5693 },
5694 {
5695 "measurement": "c",
5696 "weight": 0.55,
5697 "p10": 1200,
5698 "p50": 2400,
5699 "optional": true
5700 },
5701 ],
5702 "condition": {
5703 "op":"eq",
5704 "name": "event.contexts.browser.name",
5705 "value": "Chrome Mobile"
5706 }
5707 },
5708 {
5709 "name": "Desktop",
5710 "scoreComponents": [
5711 {
5712 "measurement": "a",
5713 "weight": 0.15,
5714 "p10": 900,
5715 "p50": 1600,
5716 "optional": true
5717 },
5718 {
5719 "measurement": "b",
5720 "weight": 0.30,
5721 "p10": 1200,
5722 "p50": 2400,
5723 "optional": true
5724 },
5725 {
5726 "measurement": "c",
5727 "weight": 0.55,
5728 "p10": 1200,
5729 "p50": 2400,
5730 "optional": true
5731 },
5732 ],
5733 "condition": {
5734 "op":"eq",
5735 "name": "event.contexts.browser.name",
5736 "value": "Chrome"
5737 }
5738 },
5739 {
5740 "name": "Default",
5741 "scoreComponents": [
5742 {
5743 "measurement": "a",
5744 "weight": 0.15,
5745 "p10": 100,
5746 "p50": 200,
5747 "optional": true
5748 },
5749 {
5750 "measurement": "b",
5751 "weight": 0.30,
5752 "p10": 100,
5753 "p50": 200,
5754 "optional": true
5755 },
5756 {
5757 "measurement": "c",
5758 "weight": 0.55,
5759 "p10": 100,
5760 "p50": 200,
5761 "optional": true
5762 },
5763 ],
5764 "condition": {
5765 "op": "and",
5766 "inner": [],
5767 }
5768 }
5769 ]
5770 }))
5771 .unwrap();
5772
5773 normalize_performance_score(&mut event, Some(&performance_score));
5774
5775 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
5776 {
5777 "type": "transaction",
5778 "timestamp": 1619420405.0,
5779 "start_timestamp": 1619420400.0,
5780 "contexts": {},
5781 "measurements": {
5782 "a": {
5783 "value": 213.0,
5784 "unit": "millisecond",
5785 },
5786 "b": {
5787 "value": 213.0,
5788 "unit": "millisecond",
5789 },
5790 "score.a": {
5791 "value": 0.15121816827413334,
5792 "unit": "ratio",
5793 },
5794 "score.b": {
5795 "value": 0.3024363365482667,
5796 "unit": "ratio",
5797 },
5798 "score.ratio.a": {
5799 "value": 0.45365450482239994,
5800 "unit": "ratio",
5801 },
5802 "score.ratio.b": {
5803 "value": 0.45365450482239994,
5804 "unit": "ratio",
5805 },
5806 "score.total": {
5807 "value": 0.4536545048224,
5808 "unit": "ratio",
5809 },
5810 "score.weight.a": {
5811 "value": 0.33333333333333337,
5812 "unit": "ratio",
5813 },
5814 "score.weight.b": {
5815 "value": 0.6666666666666667,
5816 "unit": "ratio",
5817 },
5818 "score.weight.c": {
5819 "value": 0.0,
5820 "unit": "ratio",
5821 },
5822 },
5823 }
5824 "###);
5825 }
5826
5827 #[test]
5828 fn test_normalization_removes_reprocessing_context() {
5829 let json = r#"{
5830 "contexts": {
5831 "reprocessing": {}
5832 }
5833 }"#;
5834 let mut event = Annotated::<Event>::from_json(json).unwrap();
5835 assert!(get_value!(event.contexts!).contains_key("reprocessing"));
5836 normalize_event(&mut event, &NormalizationConfig::default());
5837 assert!(!get_value!(event.contexts!).contains_key("reprocessing"));
5838 }
5839
5840 #[test]
5841 fn test_renormalization_does_not_remove_reprocessing_context() {
5842 let json = r#"{
5843 "contexts": {
5844 "reprocessing": {}
5845 }
5846 }"#;
5847 let mut event = Annotated::<Event>::from_json(json).unwrap();
5848 assert!(get_value!(event.contexts!).contains_key("reprocessing"));
5849 normalize_event(
5850 &mut event,
5851 &NormalizationConfig {
5852 is_renormalize: true,
5853 ..Default::default()
5854 },
5855 );
5856 assert!(get_value!(event.contexts!).contains_key("reprocessing"));
5857 }
5858
5859 #[test]
5860 fn test_normalize_user() {
5861 let json = r#"{
5862 "user": {
5863 "id": "123456",
5864 "username": "john",
5865 "other": "value"
5866 }
5867 }"#;
5868 let mut event = Annotated::<Event>::from_json(json).unwrap();
5869 normalize_user(event.value_mut().as_mut().unwrap());
5870
5871 let user = event.value().unwrap().user.value().unwrap();
5872 assert_eq!(user.data, {
5873 let mut map = Object::new();
5874 map.insert(
5875 "other".to_owned(),
5876 Annotated::new(Value::String("value".to_owned())),
5877 );
5878 Annotated::new(map)
5879 });
5880 assert_eq!(user.other, Object::new());
5881 assert_eq!(user.username, Annotated::new("john".to_owned().into()));
5882 }
5883
5884 #[test]
5885 fn test_handle_types_in_spaced_exception_values() {
5886 let mut exception = Annotated::new(Exception {
5887 value: Annotated::new("ValueError: unauthorized".to_owned().into()),
5888 ..Exception::default()
5889 });
5890 normalize_exception(&mut exception);
5891
5892 let exception = exception.value().unwrap();
5893 assert_eq!(exception.value.as_str(), Some("unauthorized"));
5894 assert_eq!(exception.ty.as_str(), Some("ValueError"));
5895 }
5896
5897 #[test]
5898 fn test_handle_types_in_non_spaced_excepton_values() {
5899 let mut exception = Annotated::new(Exception {
5900 value: Annotated::new("ValueError:unauthorized".to_owned().into()),
5901 ..Exception::default()
5902 });
5903 normalize_exception(&mut exception);
5904
5905 let exception = exception.value().unwrap();
5906 assert_eq!(exception.value.as_str(), Some("unauthorized"));
5907 assert_eq!(exception.ty.as_str(), Some("ValueError"));
5908 }
5909
5910 #[test]
5911 fn test_rejects_empty_exception_fields() {
5912 let mut exception = Annotated::new(Exception {
5913 value: Annotated::new("".to_owned().into()),
5914 ty: Annotated::new("".to_owned()),
5915 ..Default::default()
5916 });
5917
5918 normalize_exception(&mut exception);
5919
5920 assert!(exception.value().is_none());
5921 assert!(exception.meta().has_errors());
5922 }
5923
5924 #[test]
5925 fn test_json_value() {
5926 let mut exception = Annotated::new(Exception {
5927 value: Annotated::new(r#"{"unauthorized":true}"#.to_owned().into()),
5928 ..Exception::default()
5929 });
5930
5931 normalize_exception(&mut exception);
5932
5933 let exception = exception.value().unwrap();
5934
5935 assert_eq!(exception.value.as_str(), Some(r#"{"unauthorized":true}"#));
5937 assert_eq!(exception.ty.value(), None);
5938 }
5939
5940 #[test]
5941 fn test_exception_invalid() {
5942 let mut exception = Annotated::new(Exception::default());
5943
5944 normalize_exception(&mut exception);
5945
5946 let expected = Error::with(ErrorKind::MissingAttribute, |error| {
5947 error.insert("attribute", "type or value");
5948 });
5949 assert_eq!(
5950 exception.meta().iter_errors().collect_tuple(),
5951 Some((&expected,))
5952 );
5953 }
5954
5955 #[test]
5956 fn test_normalize_exception() {
5957 let mut event = Annotated::new(Event {
5958 exceptions: Annotated::new(Values::new(vec![Annotated::new(Exception {
5959 ty: Annotated::empty(),
5961 value: Annotated::empty(),
5962 ..Default::default()
5963 })])),
5964 ..Default::default()
5965 });
5966
5967 normalize_event(&mut event, &NormalizationConfig::default());
5968
5969 let exception = event
5970 .value()
5971 .unwrap()
5972 .exceptions
5973 .value()
5974 .unwrap()
5975 .values
5976 .value()
5977 .unwrap()
5978 .first()
5979 .unwrap();
5980
5981 assert_debug_snapshot!(exception.meta(), @r###"
5982 Meta {
5983 remarks: [],
5984 errors: [
5985 Error {
5986 kind: MissingAttribute,
5987 data: {
5988 "attribute": String(
5989 "type or value",
5990 ),
5991 },
5992 },
5993 ],
5994 original_length: None,
5995 original_value: Some(
5996 Object(
5997 {
5998 "mechanism": ~,
5999 "module": ~,
6000 "raw_stacktrace": ~,
6001 "stacktrace": ~,
6002 "thread_id": ~,
6003 "type": ~,
6004 "value": ~,
6005 },
6006 ),
6007 ),
6008 }
6009 "###);
6010 }
6011
6012 #[test]
6013 fn test_normalize_breadcrumbs() {
6014 let mut event = Event {
6015 breadcrumbs: Annotated::new(Values {
6016 values: Annotated::new(vec![Annotated::new(Breadcrumb::default())]),
6017 ..Default::default()
6018 }),
6019 ..Default::default()
6020 };
6021 normalize_breadcrumbs(&mut event);
6022
6023 let breadcrumb = event
6024 .breadcrumbs
6025 .value()
6026 .unwrap()
6027 .values
6028 .value()
6029 .unwrap()
6030 .first()
6031 .unwrap()
6032 .value()
6033 .unwrap();
6034 assert_eq!(breadcrumb.ty.value().unwrap(), "default");
6035 assert_eq!(&breadcrumb.level.value().unwrap().to_string(), "info");
6036 }
6037
6038 #[test]
6039 fn test_other_debug_images_have_meta_errors() {
6040 let mut event = Event {
6041 debug_meta: Annotated::new(DebugMeta {
6042 images: Annotated::new(vec![Annotated::new(
6043 DebugImage::Other(BTreeMap::default()),
6044 )]),
6045 ..Default::default()
6046 }),
6047 ..Default::default()
6048 };
6049 normalize_debug_meta(&mut event);
6050
6051 let debug_image_meta = event
6052 .debug_meta
6053 .value()
6054 .unwrap()
6055 .images
6056 .value()
6057 .unwrap()
6058 .first()
6059 .unwrap()
6060 .meta();
6061 assert_debug_snapshot!(debug_image_meta, @r###"
6062 Meta {
6063 remarks: [],
6064 errors: [
6065 Error {
6066 kind: InvalidData,
6067 data: {
6068 "reason": String(
6069 "unsupported debug image type",
6070 ),
6071 },
6072 },
6073 ],
6074 original_length: None,
6075 original_value: Some(
6076 Object(
6077 {},
6078 ),
6079 ),
6080 }
6081 "###);
6082 }
6083
6084 #[test]
6085 fn test_skip_span_normalization_when_configured() {
6086 let json = r#"{
6087 "type": "transaction",
6088 "start_timestamp": 1,
6089 "timestamp": 2,
6090 "contexts": {
6091 "trace": {
6092 "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
6093 "span_id": "aaaaaaaaaaaaaaaa"
6094 }
6095 },
6096 "spans": [
6097 {
6098 "op": "db",
6099 "description": "SELECT * FROM table;",
6100 "start_timestamp": 1,
6101 "timestamp": 2,
6102 "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
6103 "span_id": "bbbbbbbbbbbbbbbb",
6104 "parent_span_id": "aaaaaaaaaaaaaaaa"
6105 }
6106 ]
6107 }"#;
6108
6109 let mut event = Annotated::<Event>::from_json(json).unwrap();
6110 assert!(get_value!(event.spans[0].exclusive_time).is_none());
6111 normalize_event(
6112 &mut event,
6113 &NormalizationConfig {
6114 is_renormalize: true,
6115 ..Default::default()
6116 },
6117 );
6118 assert!(get_value!(event.spans[0].exclusive_time).is_none());
6119 normalize_event(
6120 &mut event,
6121 &NormalizationConfig {
6122 is_renormalize: false,
6123 ..Default::default()
6124 },
6125 );
6126 assert!(get_value!(event.spans[0].exclusive_time).is_some());
6127 }
6128
6129 #[test]
6130 fn test_normalize_trace_context_tags_extracts_lcp_info() {
6131 let json = r#"{
6132 "type": "transaction",
6133 "start_timestamp": 1,
6134 "timestamp": 2,
6135 "contexts": {
6136 "trace": {
6137 "data": {
6138 "browser.web_vital.lcp.element": "body > div#app > div > h1#header",
6139 "browser.web_vital.lcp.size": 24827,
6140 "browser.web_vital.lcp.id": "header",
6141 "browser.web_vital.lcp.url": "http://example.com/image.jpg"
6142 }
6143 }
6144 },
6145 "measurements": {
6146 "lcp": { "value": 146.20000000298023, "unit": "millisecond" }
6147 }
6148 }"#;
6149 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
6150 normalize_trace_context_tags(&mut event);
6151 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
6152 {
6153 "type": "transaction",
6154 "timestamp": 2.0,
6155 "start_timestamp": 1.0,
6156 "contexts": {
6157 "trace": {
6158 "data": {
6159 "browser.web_vital.lcp.element": "body > div#app > div > h1#header",
6160 "browser.web_vital.lcp.id": "header",
6161 "browser.web_vital.lcp.size": 24827,
6162 "browser.web_vital.lcp.url": "http://example.com/image.jpg",
6163 },
6164 "type": "trace",
6165 },
6166 },
6167 "tags": [
6168 [
6169 "lcp.element",
6170 "body > div#app > div > h1#header",
6171 ],
6172 [
6173 "lcp.size",
6174 "24827",
6175 ],
6176 [
6177 "lcp.id",
6178 "header",
6179 ],
6180 [
6181 "lcp.url",
6182 "http://example.com/image.jpg",
6183 ],
6184 ],
6185 "measurements": {
6186 "lcp": {
6187 "value": 146.20000000298023,
6188 "unit": "millisecond",
6189 },
6190 },
6191 }
6192 "###);
6193 }
6194
6195 #[test]
6196 fn test_normalize_trace_context_tags_does_not_overwrite_lcp_tags() {
6197 let json = r#"{
6198 "type": "transaction",
6199 "start_timestamp": 1,
6200 "timestamp": 2,
6201 "contexts": {
6202 "trace": {
6203 "data": {
6204 "browser.web_vital.lcp.element": "body > div#app > div > h1#id",
6205 "browser.web_vital.lcp.size": 33333,
6206 "browser.web_vital.lcp.id": "id",
6207 "browser.web_vital.lcp.url": "http://example.com/another-image.jpg"
6208 }
6209 }
6210 },
6211 "tags": {
6212 "lcp.element": "body > div#app > div > h1#header",
6213 "lcp.size": 24827,
6214 "lcp.id": "header",
6215 "lcp.url": "http://example.com/image.jpg"
6216 },
6217 "measurements": {
6218 "lcp": { "value": 146.20000000298023, "unit": "millisecond" }
6219 }
6220 }"#;
6221 let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
6222 normalize_trace_context_tags(&mut event);
6223 insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
6224 {
6225 "type": "transaction",
6226 "timestamp": 2.0,
6227 "start_timestamp": 1.0,
6228 "contexts": {
6229 "trace": {
6230 "data": {
6231 "browser.web_vital.lcp.element": "body > div#app > div > h1#id",
6232 "browser.web_vital.lcp.id": "id",
6233 "browser.web_vital.lcp.size": 33333,
6234 "browser.web_vital.lcp.url": "http://example.com/another-image.jpg",
6235 },
6236 "type": "trace",
6237 },
6238 },
6239 "tags": [
6240 [
6241 "lcp.element",
6242 "body > div#app > div > h1#header",
6243 ],
6244 [
6245 "lcp.id",
6246 "header",
6247 ],
6248 [
6249 "lcp.size",
6250 "24827",
6251 ],
6252 [
6253 "lcp.url",
6254 "http://example.com/image.jpg",
6255 ],
6256 ],
6257 "measurements": {
6258 "lcp": {
6259 "value": 146.20000000298023,
6260 "unit": "millisecond",
6261 },
6262 },
6263 }
6264 "###);
6265 }
6266
6267 #[test]
6268 fn test_tags_are_trimmed() {
6269 let json = r#"
6270 {
6271 "tags": {
6272 "key": "too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_",
6273 "too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_": "value"
6274 }
6275 }
6276 "#;
6277
6278 let mut event = Annotated::<Event>::from_json(json).unwrap();
6279
6280 normalize_event(
6281 &mut event,
6282 &NormalizationConfig {
6283 enable_trimming: true,
6284 ..NormalizationConfig::default()
6285 },
6286 );
6287
6288 insta::assert_debug_snapshot!(get_value!(event.tags!), @r###"
6289 Tags(
6290 PairList(
6291 [
6292 TagEntry(
6293 "key",
6294 Annotated(
6295 "too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__lo...",
6296 Meta {
6297 remarks: [
6298 Remark {
6299 ty: Substituted,
6300 rule_id: "!limit",
6301 range: Some(
6302 (
6303 197,
6304 200,
6305 ),
6306 ),
6307 },
6308 ],
6309 errors: [],
6310 original_length: Some(
6311 210,
6312 ),
6313 original_value: None,
6314 },
6315 ),
6316 ),
6317 TagEntry(
6318 Annotated(
6319 "too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__long_too__lo...",
6320 Meta {
6321 remarks: [
6322 Remark {
6323 ty: Substituted,
6324 rule_id: "!limit",
6325 range: Some(
6326 (
6327 197,
6328 200,
6329 ),
6330 ),
6331 },
6332 ],
6333 errors: [],
6334 original_length: Some(
6335 210,
6336 ),
6337 original_value: None,
6338 },
6339 ),
6340 "value",
6341 ),
6342 ],
6343 ),
6344 )
6345 "###);
6346 }
6347}