-
Notifications
You must be signed in to change notification settings - Fork 91
/
transactions.rs
1288 lines (1148 loc) · 41.4 KB
/
transactions.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::metrics_extraction::conditional_tagging::run_conditional_tagging;
use crate::metrics_extraction::utils;
use crate::metrics_extraction::TaggingRule;
use relay_common::{SpanStatus, UnixTimestamp};
use relay_general::protocol::TraceContext;
use relay_general::protocol::{AsPair, Timestamp, TransactionSource};
use relay_general::protocol::{Context, ContextInner};
use relay_general::protocol::{Event, EventType};
use relay_general::store;
use relay_general::types::Annotated;
use relay_metrics::{DurationUnit, Metric, MetricNamespace, MetricUnit, MetricValue};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
/// The metric on which the user satisfaction threshold is applied.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum SatisfactionMetric {
Duration,
Lcp,
#[serde(other)]
Unknown,
}
/// Configuration for a single threshold.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct SatisfactionThreshold {
metric: SatisfactionMetric,
threshold: f64,
}
/// Configuration for applying the user satisfaction threshold.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SatisfactionConfig {
/// The project-wide threshold to apply.
project_threshold: SatisfactionThreshold,
/// Transaction-specific overrides of the project-wide threshold.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
transaction_thresholds: BTreeMap<String, SatisfactionThreshold>,
}
/// Configuration for extracting custom measurements from transaction payloads.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct CustomMeasurementConfig {
/// The maximum number of custom measurements to extract. Defaults to zero.
limit: usize,
}
/// Maximum supported version of metrics extraction from transactions.
///
/// The version is an integer scalar, incremented by one on each new version.
const EXTRACT_MAX_VERSION: u16 = 1;
/// Configuration for extracting metrics from transaction payloads.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct TransactionMetricsConfig {
/// The required version to extract transaction metrics.
version: u16,
extract_metrics: BTreeSet<String>,
extract_custom_tags: BTreeSet<String>,
satisfaction_thresholds: Option<SatisfactionConfig>,
custom_measurements: CustomMeasurementConfig,
}
impl TransactionMetricsConfig {
pub fn is_enabled(&self) -> bool {
self.version > 0 && self.version <= EXTRACT_MAX_VERSION
}
}
const METRIC_NAMESPACE: MetricNamespace = MetricNamespace::Transactions;
fn get_trace_context(event: &Event) -> Option<&TraceContext> {
let contexts = event.contexts.value()?;
let trace = contexts.get("trace").map(Annotated::value);
if let Some(Some(ContextInner(Context::Trace(trace_context)))) = trace {
return Some(trace_context.as_ref());
}
None
}
/// Extract transaction status, defaulting to [`SpanStatus::Unknown`].
/// Must be consistent with `process_trace_context` in [`relay_general::store`].
fn extract_transaction_status(trace_context: &TraceContext) -> SpanStatus {
*trace_context.status.value().unwrap_or(&SpanStatus::Unknown)
}
fn extract_transaction_op(trace_context: &TraceContext) -> Option<String> {
let op = trace_context.op.value()?;
Some(op.to_string())
}
fn extract_dist(transaction: &Event) -> Option<String> {
let mut dist = transaction.dist.0.clone();
store::normalize_dist(&mut dist);
dist
}
/// Extract HTTP method
/// See <https://github.com/getsentry/snuba/blob/2e038c13a50735d58cc9397a29155ab5422a62e5/snuba/datasets/errors_processor.py#L64-L67>.
fn extract_http_method(transaction: &Event) -> Option<String> {
let request = transaction.request.value()?;
let method = request.method.value()?;
Some(method.to_owned())
}
/// Satisfaction value used for Apdex and User Misery
/// <https://docs.sentry.io/product/performance/metrics/#apdex>
enum UserSatisfaction {
Satisfied,
Tolerated,
Frustrated,
}
impl fmt::Display for UserSatisfaction {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
UserSatisfaction::Satisfied => write!(f, "satisfied"),
UserSatisfaction::Tolerated => write!(f, "tolerated"),
UserSatisfaction::Frustrated => write!(f, "frustrated"),
}
}
}
impl UserSatisfaction {
/// The frustration threshold is always four times the threshold
/// (see <https://docs.sentry.io/product/performance/metrics/#apdex>)
const FRUSTRATION_FACTOR: f64 = 4.0;
fn from_value(value: f64, threshold: f64) -> Self {
if value <= threshold {
Self::Satisfied
} else if value <= Self::FRUSTRATION_FACTOR * threshold {
Self::Tolerated
} else {
Self::Frustrated
}
}
}
/// Extract the the satisfaction value depending on the actual measurement/duration value
/// and the configured threshold.
fn extract_user_satisfaction(
config: &Option<SatisfactionConfig>,
transaction: &Event,
start_timestamp: Timestamp,
end_timestamp: Timestamp,
) -> Option<UserSatisfaction> {
if let Some(config) = config {
let threshold = transaction
.transaction
.value()
.and_then(|name| config.transaction_thresholds.get(name))
.unwrap_or(&config.project_threshold);
if let Some(value) = match threshold.metric {
SatisfactionMetric::Duration => Some(relay_common::chrono_to_positive_millis(
end_timestamp - start_timestamp,
)),
SatisfactionMetric::Lcp => store::get_measurement(transaction, "lcp"),
SatisfactionMetric::Unknown => None,
} {
return Some(UserSatisfaction::from_value(value, threshold.threshold));
}
}
None
}
/// Decide whether we want to keep the transaction name.
/// High-cardinality sources are excluded to protect our metrics infrastructure.
/// Note that this will produce a discrepancy between metrics and raw transaction data.
fn keep_transaction_name(source: &TransactionSource) -> bool {
match source {
// For now, we hope that custom transaction names set by users are low-cardinality.
TransactionSource::Custom => true,
// "url" are raw URLs, potentially containing identifiers.
TransactionSource::Url => false,
// These four are names of software components, which we assume to be low-cardinality.
TransactionSource::Route => true,
TransactionSource::View => true,
TransactionSource::Component => true,
TransactionSource::Task => true,
// "unknown" is the value for old SDKs that do not send a transaction source yet.
// Assume high-cardinality and drop.
TransactionSource::Unknown => false,
// Any other value would be an SDK bug, assume high-cardinality and drop.
TransactionSource::Other(source) => {
relay_log::error!("Invalid transaction source: '{}'", source);
false
}
}
}
/// These are the tags that are added to all extracted metrics.
fn extract_universal_tags(
event: &Event,
custom_tags: &BTreeSet<String>,
) -> BTreeMap<String, String> {
let mut tags = BTreeMap::new();
if let Some(release) = event.release.as_str() {
tags.insert("release".to_owned(), release.to_owned());
}
if let Some(dist) = extract_dist(event) {
tags.insert("dist".to_owned(), dist);
}
if let Some(environment) = event.environment.as_str() {
tags.insert("environment".to_owned(), environment.to_owned());
}
if let Some(transaction) = event.transaction.as_str() {
if keep_transaction_name(event.get_transaction_source()) {
tags.insert("transaction".to_owned(), transaction.to_owned());
}
}
// The platform tag should not increase dimensionality in most cases, because most
// transactions are specific to one platform
let platform = match event.platform.as_str() {
Some(platform) if store::is_valid_platform(platform) => platform,
_ => "other",
};
tags.insert("platform".to_owned(), platform.to_owned());
if let Some(trace_context) = get_trace_context(event) {
let status = extract_transaction_status(trace_context);
tags.insert("transaction.status".to_owned(), status.to_string());
if let Some(op) = extract_transaction_op(trace_context) {
tags.insert("transaction.op".to_owned(), op);
}
}
if let Some(http_method) = extract_http_method(event) {
tags.insert("http.method".to_owned(), http_method);
}
if !custom_tags.is_empty() {
// XXX(slow): event tags are a flat array
if let Some(event_tags) = event.tags.value() {
for tag_entry in &**event_tags {
if let Some(entry) = tag_entry.value() {
let (key, value) = entry.as_pair();
if let (Some(key), Some(value)) = (key.as_str(), value.as_str()) {
if custom_tags.contains(key) {
tags.insert(key.to_owned(), value.to_owned());
}
}
}
}
}
}
tags
}
/// Returns the unit of the provided metric.
///
/// For known measurements, this returns `Some(MetricUnit)`, which can also include
/// `Some(MetricUnit::None)`. For unknown measurement names, this returns `None`.
fn get_metric_measurement_unit(metric: &str) -> Option<MetricUnit> {
match metric {
// Web
"fcp" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
"lcp" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
"fid" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
"fp" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
"ttfb" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
"ttfb.requesttime" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
"cls" => Some(MetricUnit::None),
// Mobile
"app_start_cold" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
"app_start_warm" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
"frames_total" => Some(MetricUnit::None),
"frames_slow" => Some(MetricUnit::None),
"frames_frozen" => Some(MetricUnit::None),
// React-Native
"stall_count" => Some(MetricUnit::None),
"stall_total_time" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
"stall_longest_time" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
// Default
_ => None,
}
}
pub fn extract_transaction_metrics(
config: &TransactionMetricsConfig,
breakdowns_config: Option<&store::BreakdownsConfig>,
conditional_tagging_config: &[TaggingRule],
event: &Event,
target: &mut Vec<Metric>,
) -> bool {
if config.extract_metrics.is_empty() {
relay_log::trace!("dropping all transaction metrics because of empty allow-list");
return false;
}
let before_len = target.len();
let mut custom_measurement_budget = config.custom_measurements.limit;
let push_metric = |metric: Metric| {
if config.extract_metrics.contains(&metric.name) {
// Anything in config.extract_metrics is considered a known / builtin metric,
// as opposed to custom measurements.
target.push(metric);
} else if custom_measurement_budget > 0
&& metric.name.starts_with("d:transactions/measurements.")
{
// We allow a fixed amount of custom measurements in addition to
// the known / builtin metrics.
target.push(metric);
custom_measurement_budget -= 1;
} else {
relay_log::trace!("dropping metric {} because of allow-list", metric.name);
}
};
extract_transaction_metrics_inner(config, breakdowns_config, event, push_metric);
let added_slice = &mut target[before_len..];
run_conditional_tagging(event, conditional_tagging_config, added_slice);
!added_slice.is_empty()
}
fn extract_transaction_metrics_inner(
config: &TransactionMetricsConfig,
breakdowns_config: Option<&store::BreakdownsConfig>,
event: &Event,
mut push_metric: impl FnMut(Metric),
) {
if event.ty.value() != Some(&EventType::Transaction) {
return;
}
let (start_timestamp, end_timestamp) = match store::validate_timestamps(event) {
Ok(pair) => pair,
Err(_) => {
return; // invalid transaction
}
};
let unix_timestamp = match UnixTimestamp::from_datetime(end_timestamp.into_inner()) {
Some(ts) => ts,
None => return,
};
let tags = extract_universal_tags(event, &config.extract_custom_tags);
// Measurements
if let Some(measurements) = event.measurements.value() {
for (name, annotated) in measurements.iter() {
let measurement = match annotated.value() {
Some(m) => m,
None => continue,
};
let value = match measurement.value.value() {
Some(value) => *value,
None => continue,
};
let mut tags_for_measurement = tags.clone();
if let Some(rating) = get_measurement_rating(name, value) {
tags_for_measurement.insert("measurement_rating".to_owned(), rating);
}
let stated_unit = measurement.unit.value().copied();
let default_unit = get_metric_measurement_unit(name);
if let (Some(default), Some(stated)) = (default_unit, stated_unit) {
if default != stated {
relay_log::error!("unit mismatch on measurements.{}: {}", name, stated);
}
}
push_metric(Metric::new_mri(
METRIC_NAMESPACE,
format!("measurements.{}", name),
stated_unit.or(default_unit).unwrap_or_default(),
MetricValue::Distribution(value),
unix_timestamp,
tags_for_measurement,
));
}
}
// Breakdowns
if let Some(breakdowns_config) = breakdowns_config {
for (breakdown, measurements) in store::get_breakdown_measurements(event, breakdowns_config)
{
for (measurement_name, annotated) in measurements.iter() {
let measurement = match annotated.value() {
Some(m) => m,
None => continue,
};
let value = match measurement.value.value() {
Some(value) => *value,
None => continue,
};
let unit = measurement.unit.value();
push_metric(Metric::new_mri(
METRIC_NAMESPACE,
format!("breakdowns.{}.{}", breakdown, measurement_name),
unit.copied().unwrap_or(MetricUnit::None),
MetricValue::Distribution(value),
unix_timestamp,
tags.clone(),
));
}
}
}
let user_satisfaction = extract_user_satisfaction(
&config.satisfaction_thresholds,
event,
start_timestamp,
end_timestamp,
);
let tags_with_satisfaction = match user_satisfaction {
Some(satisfaction) => utils::with_tag(&tags, "satisfaction", satisfaction),
None => tags,
};
// Duration
let duration_millis = relay_common::chrono_to_positive_millis(end_timestamp - start_timestamp);
push_metric(Metric::new_mri(
METRIC_NAMESPACE,
"duration",
MetricUnit::Duration(DurationUnit::MilliSecond),
MetricValue::Distribution(duration_millis),
unix_timestamp,
tags_with_satisfaction.clone(),
));
// User
if let Some(user) = event.user.value() {
if let Some(user_id) = user.id.as_str() {
push_metric(Metric::new_mri(
METRIC_NAMESPACE,
"user",
MetricUnit::None,
MetricValue::set_from_str(user_id),
unix_timestamp,
// A single user might end up in multiple satisfaction buckets when they have
// some satisfying transactions and some frustrating transactions.
// This is OK as long as we do not add these numbers *after* aggregation:
// <WRONG>total_users = uniqIf(user, satisfied) + uniqIf(user, tolerated) + uniqIf(user, frustrated)</WRONG>
// <RIGHT>total_users = uniq(user)</RIGHT>
tags_with_satisfaction,
));
}
}
}
fn get_measurement_rating(name: &str, value: f64) -> Option<String> {
let rate_range = |meh_ceiling: f64, poor_ceiling: f64| {
debug_assert!(meh_ceiling < poor_ceiling);
if value < meh_ceiling {
Some("good".to_owned())
} else if value < poor_ceiling {
Some("meh".to_owned())
} else {
Some("poor".to_owned())
}
};
match name {
"lcp" => rate_range(2500.0, 4000.0),
"fcp" => rate_range(1000.0, 3000.0),
"fid" => rate_range(100.0, 300.0),
"cls" => rate_range(0.1, 0.25),
_ => None,
}
}
#[cfg(test)]
#[cfg(feature = "processing")]
mod tests {
use super::*;
use crate::metrics_extraction::TaggingRule;
use insta::assert_debug_snapshot;
use relay_general::protocol::TransactionInfo;
use relay_general::store::BreakdownsConfig;
use relay_general::types::Annotated;
use relay_metrics::DurationUnit;
#[test]
fn test_extract_transaction_metrics() {
let json = r#"
{
"type": "transaction",
"platform": "javascript",
"timestamp": "2021-04-26T08:00:00+0100",
"start_timestamp": "2021-04-26T07:59:01+0100",
"release": "1.2.3",
"dist": "foo ",
"environment": "fake_environment",
"transaction": "mytransaction",
"transaction_info": {"source": "custom"},
"user": {
"id": "user123"
},
"tags": {
"fOO": "bar",
"bogus": "absolutely"
},
"measurements": {
"foo": {"value": 420.69},
"lcp": {"value": 3000.0}
},
"contexts": {
"trace": {
"op": "myop",
"status": "ok"
}
},
"spans": [
{
"description": "<OrganizationContext>",
"op": "react.mount",
"parent_span_id": "8f5a2b8768cafb4e",
"span_id": "bd429c44b67a3eb4",
"start_timestamp": 1597976393.4619668,
"timestamp": 1597976393.4718769,
"trace_id": "ff62a8b040f340bda5d830223def1d81"
}
],
"request": {
"method": "POST"
}
}
"#;
let breakdowns_config: BreakdownsConfig = serde_json::from_str(
r#"
{
"span_ops": {
"type": "spanOperations",
"matches": ["react.mount"]
}
}
"#,
)
.unwrap();
let event = Annotated::from_json(json).unwrap();
let mut metrics = vec![];
extract_transaction_metrics(
&TransactionMetricsConfig::default(),
Some(&breakdowns_config),
&[],
event.value().unwrap(),
&mut metrics,
);
assert_eq!(metrics, &[]);
let config: TransactionMetricsConfig = serde_json::from_str(
r#"
{
"extractMetrics": [
"d:transactions/measurements.foo@none",
"d:transactions/measurements.lcp@millisecond",
"d:transactions/breakdowns.span_ops.ops.react.mount@millisecond",
"d:transactions/duration@millisecond",
"s:transactions/user@none"
],
"extractCustomTags": ["fOO"]
}
"#,
)
.unwrap();
let mut metrics = vec![];
extract_transaction_metrics(
&config,
Some(&breakdowns_config),
&[],
event.value().unwrap(),
&mut metrics,
);
assert_eq!(metrics.len(), 5, "{:?}", metrics);
assert_eq!(metrics[0].name, "d:transactions/measurements.foo@none");
assert_eq!(
metrics[1].name,
"d:transactions/measurements.lcp@millisecond"
);
assert_eq!(
metrics[2].name,
"d:transactions/breakdowns.span_ops.ops.react.mount@millisecond"
);
let duration_metric = &metrics[3];
assert_eq!(duration_metric.name, "d:transactions/duration@millisecond");
if let MetricValue::Distribution(value) = duration_metric.value {
assert_eq!(value, 59000.0);
} else {
panic!(); // Duration must be set
}
let user_metric = &metrics[4];
assert_eq!(user_metric.name, "s:transactions/user@none");
assert!(matches!(user_metric.value, MetricValue::Set(_)));
assert_eq!(metrics[1].tags["measurement_rating"], "meh");
for metric in &metrics[0..4] {
assert!(matches!(metric.value, MetricValue::Distribution(_)));
}
for metric in metrics {
assert_eq!(metric.tags["release"], "1.2.3");
assert_eq!(metric.tags["dist"], "foo");
assert_eq!(metric.tags["environment"], "fake_environment");
assert_eq!(metric.tags["transaction"], "mytransaction");
assert_eq!(metric.tags["fOO"], "bar");
assert_eq!(metric.tags["http.method"], "POST");
assert_eq!(metric.tags["transaction.status"], "ok");
assert_eq!(metric.tags["transaction.op"], "myop");
assert_eq!(metric.tags["platform"], "javascript");
assert!(!metric.tags.contains_key("bogus"));
}
}
#[test]
fn test_metric_measurement_units() {
let json = r#"
{
"type": "transaction",
"timestamp": "2021-04-26T08:00:00+0100",
"start_timestamp": "2021-04-26T07:59:01+0100",
"measurements": {
"fcp": {"value": 1.1},
"stall_count": {"value": 3.3},
"foo": {"value": 8.8}
}
}
"#;
let config: TransactionMetricsConfig = serde_json::from_str(
r#"
{
"extractMetrics": [
"d:transactions/measurements.fcp@millisecond",
"d:transactions/measurements.stall_count@none",
"d:transactions/measurements.foo@none"
]
}
"#,
)
.unwrap();
let event = Annotated::from_json(json).unwrap();
let mut metrics = vec![];
extract_transaction_metrics(&config, None, &[], event.value().unwrap(), &mut metrics);
assert_eq!(metrics.len(), 3, "{:?}", metrics);
assert_eq!(
metrics[0].name, "d:transactions/measurements.fcp@millisecond",
"{:?}",
metrics[0]
);
assert_eq!(
metrics[1].name, "d:transactions/measurements.foo@none",
"{:?}",
metrics[1]
);
assert_eq!(
metrics[2].name, "d:transactions/measurements.stall_count@none",
"{:?}",
metrics[2]
);
}
#[test]
fn test_metric_measurement_unit_overrides() {
let json = r#"{
"type": "transaction",
"timestamp": "2021-04-26T08:00:00+0100",
"start_timestamp": "2021-04-26T07:59:01+0100",
"measurements": {
"fcp": {"value": 1.1, "unit": "second"},
"lcp": {"value": 2.2, "unit": "none"}
}
}"#;
let config: TransactionMetricsConfig = serde_json::from_str(
r#"{
"extractMetrics": [
"d:transactions/measurements.fcp@second",
"d:transactions/measurements.lcp@none"
]
}"#,
)
.unwrap();
let event = Annotated::from_json(json).unwrap();
let mut metrics = vec![];
extract_transaction_metrics(&config, None, &[], event.value().unwrap(), &mut metrics);
assert_eq!(metrics.len(), 2);
assert_eq!(metrics[0].name, "d:transactions/measurements.fcp@second");
// None is an override, too.
assert_eq!(metrics[1].name, "d:transactions/measurements.lcp@none");
}
#[test]
fn test_transaction_duration() {
let json = r#"
{
"type": "transaction",
"platform": "bogus",
"timestamp": "2021-04-26T08:00:00+0100",
"start_timestamp": "2021-04-26T07:59:01+0100",
"release": "1.2.3",
"environment": "fake_environment",
"transaction": "mytransaction",
"contexts": {
"trace": {
"status": "ok"
}
}
}
"#;
let event = Annotated::from_json(json).unwrap();
let config: TransactionMetricsConfig = serde_json::from_str(
r#"
{
"extractMetrics": [
"d:transactions/duration@millisecond"
]
}
"#,
)
.unwrap();
let mut metrics = vec![];
extract_transaction_metrics(&config, None, &[], event.value().unwrap(), &mut metrics);
assert_eq!(metrics.len(), 1);
let duration_metric = &metrics[0];
assert_eq!(duration_metric.name, "d:transactions/duration@millisecond");
if let MetricValue::Distribution(value) = duration_metric.value {
assert_eq!(value, 59000.0); // millis
} else {
panic!(); // Duration must be set
}
assert_eq!(duration_metric.tags.len(), 4);
assert_eq!(duration_metric.tags["release"], "1.2.3");
assert_eq!(duration_metric.tags["transaction.status"], "ok");
assert_eq!(duration_metric.tags["environment"], "fake_environment");
assert_eq!(duration_metric.tags["platform"], "other");
}
#[test]
fn test_user_satisfaction() {
let json = r#"
{
"type": "transaction",
"transaction": "foo",
"start_timestamp": "2021-04-26T08:00:00+0100",
"timestamp": "2021-04-26T08:00:01+0100",
"user": {
"id": "user123"
},
"contexts": {
"trace": {
"status": "ok"
}
}
}
"#;
let event = Annotated::from_json(json).unwrap();
let config: TransactionMetricsConfig = serde_json::from_str(
r#"
{
"extractMetrics": [
"d:transactions/duration@millisecond",
"s:transactions/user@none"
],
"satisfactionThresholds": {
"projectThreshold": {
"metric": "duration",
"threshold": 300
},
"extra_key": "should_be_ignored"
}
}
"#,
)
.unwrap();
let mut metrics = vec![];
extract_transaction_metrics(&config, None, &[], event.value().unwrap(), &mut metrics);
assert_eq!(metrics.len(), 2);
let duration_metric = &metrics[0];
assert_eq!(duration_metric.tags.len(), 3);
assert_eq!(duration_metric.tags["satisfaction"], "tolerated");
assert_eq!(duration_metric.tags["transaction.status"], "ok");
let user_metric = &metrics[1];
assert_eq!(user_metric.tags.len(), 3);
assert_eq!(user_metric.tags["satisfaction"], "tolerated");
}
#[test]
fn test_user_satisfaction_override() {
let json = r#"
{
"type": "transaction",
"transaction": "foo",
"start_timestamp": "2021-04-26T08:00:00+0100",
"timestamp": "2021-04-26T08:00:02+0100",
"measurements": {
"lcp": {"value": 41}
}
}
"#;
let event = Annotated::from_json(json).unwrap();
let config: TransactionMetricsConfig = serde_json::from_str(
r#"
{
"extractMetrics": [
"d:transactions/duration@millisecond"
],
"satisfactionThresholds": {
"projectThreshold": {
"metric": "duration",
"threshold": 300
},
"transactionThresholds": {
"foo": {
"metric": "lcp",
"threshold": 42
}
}
}
}
"#,
)
.unwrap();
let mut metrics = vec![];
extract_transaction_metrics(&config, None, &[], event.value().unwrap(), &mut metrics);
assert_eq!(metrics.len(), 1);
for metric in metrics {
assert_eq!(metric.tags.len(), 2);
assert_eq!(metric.tags["satisfaction"], "satisfied");
}
}
#[test]
fn test_user_satisfaction_catch_new_metric() {
let json = r#"
{
"type": "transaction",
"transaction": "foo",
"start_timestamp": "2021-04-26T08:00:00+0100",
"timestamp": "2021-04-26T08:00:02+0100",
"measurements": {
"lcp": {"value": 41}
}
}
"#;
let event = Annotated::from_json(json).unwrap();
let config: TransactionMetricsConfig = serde_json::from_str(
r#"
{
"extractMetrics": [
"d:transactions/duration@millisecond"
],
"satisfactionThresholds": {
"projectThreshold": {
"metric": "unknown_metric",
"threshold": 300
}
}
}
"#,
)
.unwrap();
let mut metrics = vec![];
extract_transaction_metrics(&config, None, &[], event.value().unwrap(), &mut metrics);
assert_eq!(metrics.len(), 1);
for metric in metrics {
assert_eq!(metric.tags.len(), 1);
assert!(!metric.tags.contains_key("satisfaction"));
}
}
#[test]
fn test_custom_measurements() {
let json = r#"
{
"type": "transaction",
"transaction": "foo",
"start_timestamp": "2021-04-26T08:00:00+0100",
"timestamp": "2021-04-26T08:00:02+0100",
"measurements": {
"a_custom1": {"value": 41},
"fcp": {"value": 0.123},
"g_custom2": {"value": 42, "unit": "second"},
"h_custom3": {"value": 43}
}
}
"#;
let event = Annotated::from_json(json).unwrap();
let config: TransactionMetricsConfig = serde_json::from_str(
r#"
{
"extractMetrics": [
"d:transactions/measurements.fcp@millisecond"
],
"customMeasurements": {
"limit": 2
}
}
"#,
)
.unwrap();
let mut metrics = vec![];
extract_transaction_metrics(&config, None, &[], event.value().unwrap(), &mut metrics);
assert_debug_snapshot!(metrics, @r###"
[
Metric {
name: "d:transactions/measurements.a_custom1@none",
value: Distribution(
41.0,
),
timestamp: UnixTimestamp(1619420402),
tags: {
"platform": "other",
},
},
Metric {
name: "d:transactions/measurements.fcp@millisecond",
value: Distribution(
0.123,
),
timestamp: UnixTimestamp(1619420402),
tags: {
"measurement_rating": "good",
"platform": "other",
},
},
Metric {
name: "d:transactions/measurements.g_custom2@second",
value: Distribution(
42.0,
),
timestamp: UnixTimestamp(1619420402),
tags: {
"platform": "other",
},
},
]
"###);
}
#[test]
fn test_conditional_tagging() {
let json = r#"
{
"type": "transaction",