sentry-core 0.48.2

Core Sentry library used for instrumentation and integration development.
Documentation
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
#![cfg(all(feature = "test", feature = "metrics"))]

use std::collections::HashSet;
use std::sync::Arc;

use anyhow::{Context, Result};

use sentry::protocol::{MetricType, Unit, Value};
use sentry_core::protocol::{EnvelopeItem, ItemContainer};
use sentry_core::{metrics, test};
use sentry_core::{ClientOptions, TransactionContext};
use sentry_types::protocol::v7::{Envelope, LogAttribute, Metric, User};

/// Test that metrics are sent when metrics are enabled.
#[test]
fn sent_when_enabled() {
    let options = ClientOptions {
        enable_metrics: true,
        ..Default::default()
    };

    let mut envelopes =
        test::with_captured_envelopes_options(|| metrics::counter("test", 1).capture(), options);

    assert_eq!(envelopes.len(), 1, "expected exactly one envelope");

    let envelope = envelopes.pop().unwrap();

    let mut items = envelope.into_items();
    let Some(item) = items.next() else {
        panic!("Expected at least one item");
    };

    assert!(items.next().is_none(), "Expected only one item");

    let EnvelopeItem::ItemContainer(ItemContainer::Metrics(mut metrics)) = item else {
        panic!("Envelope item has unexpected structure");
    };

    assert_eq!(metrics.len(), 1, "Expected exactly one metric");

    let metric = metrics.pop().unwrap();
    assert!(matches!(metric, Metric {
        r#type: MetricType::Counter,
        name,
        value: 1.0,
        ..
    } if name == "test"));
}

/// Test that metrics are sent by default.
#[test]
fn metrics_enabled_by_default() {
    let options = ClientOptions::default();

    let envelopes =
        test::with_captured_envelopes_options(|| metrics::counter("test", 1).capture(), options);
    assert_eq!(
        envelopes.len(),
        1,
        "expected exactly one envelope when metrics are enabled by default"
    )
}

/// Test that metrics are disabled (not sent) when disabled in the
/// [`ClientOptions`].
#[test]
fn metrics_disabled_when_configured() {
    let options = ClientOptions {
        enable_metrics: false,
        ..Default::default()
    };

    let envelopes =
        test::with_captured_envelopes_options(|| metrics::counter("test", 1).capture(), options);
    assert!(
        envelopes.is_empty(),
        "no envelopes should be captured when metrics disabled"
    )
}

/// Test that no metrics are captured by a no-op call with
/// metrics enabled
#[test]
fn noop_sends_nothing() {
    let options = ClientOptions::default();

    let envelopes = test::with_captured_envelopes_options(|| (), options);

    assert!(envelopes.is_empty(), "no-op should not capture metrics");
}

/// Test that 100 metrics are sent in a single envelope.
#[test]
fn test_metrics_batching_at_limit() {
    let options = ClientOptions::default();

    let envelopes = test::with_captured_envelopes_options(
        || {
            (0..100)
                .map(|i| format!("metric.{i}"))
                .for_each(|name| metrics::counter(name, 1).capture());
        },
        options,
    );

    let envelope = envelopes
        .try_into_only_item()
        .expect("expected exactly one envelope");
    let item = envelope
        .into_items()
        .try_into_only_item()
        .expect("expected exactly one item");
    let metrics = item
        .into_metrics()
        .expect("the envelope item is not a metrics item");

    assert_eq!(metrics.len(), 100, "expected 100 metrics");

    let metric_names: HashSet<_> = metrics
        .into_iter()
        .inspect(|metric| assert_eq!(metric.value, 1.0, "metric had unexpected value"))
        .inspect(|metric| {
            assert_eq!(
                metric.r#type,
                MetricType::Counter,
                "metric had unexpected type"
            )
        })
        .map(|metric| metric.name)
        .collect();

    (0..100)
        .map(|i| format!("metric.{i}"))
        .for_each(|metric_name| {
            assert!(
                metric_names.contains(metric_name.as_str()),
                "expected metric {metric_name} was not captured"
            )
        });
}

/// Test that 101 envelopes are sent in two separate envelopes
#[test]
fn test_metrics_batching_over_limit() {
    let options = ClientOptions::default();

    let mut envelopes = test::with_captured_envelopes_options(
        || {
            (0..101)
                .map(|i| format!("metric.{i}"))
                .for_each(|name| metrics::counter(name, 1).capture());
        },
        options,
    )
    .into_iter();
    let envelope1 = envelopes.next().expect("expected a first envelope");
    let envelope2 = envelopes.next().expect("expected a second envelope");
    assert!(envelopes.next().is_none(), "expected exactly two envelopes");

    let item1 = envelope1
        .into_items()
        .try_into_only_item()
        .expect("expected exactly one item in the first envelope");
    let metrics1 = item1
        .into_metrics()
        .expect("the first envelope item is not a metrics item");

    assert_eq!(metrics1.len(), 100, "expected 100 metrics");

    let first_metric_names: HashSet<_> = metrics1
        .into_iter()
        .inspect(|metric| assert_eq!(metric.value, 1.0, "metric had unexpected value"))
        .inspect(|metric| {
            assert_eq!(
                metric.r#type,
                MetricType::Counter,
                "metric had unexpected type"
            )
        })
        .map(|metric| metric.name)
        .collect();

    (0..100)
        .map(|i| format!("metric.{i}"))
        .for_each(|metric_name| {
            assert!(
                first_metric_names.contains(metric_name.as_str()),
                "expected metric {metric_name} was not captured in the first envelope"
            )
        });

    let item2 = envelope2
        .into_items()
        .try_into_only_item()
        .expect("expected exactly one item in the second envelope");
    let metrics2 = item2
        .into_metrics()
        .expect("the second envelope item is not a metrics item");
    let metric2 = metrics2
        .try_into_only_item()
        .expect("expected exactly one metric in the second envelope");

    assert!(
        matches!(metric2, Metric {
            r#type: MetricType::Counter,
            name,
            value: 1.0,
            ..
        } if name == "metric.100"),
        "unexpected metric captured"
    )
}

#[test]
fn metric_attributes_are_captured() {
    let options = ClientOptions::default();

    let envelopes = test::with_captured_envelopes_options(
        || {
            metrics::counter("test", 1)
                .attribute("http.route", "/health")
                .attribute("http.response.status_code", 200)
                .capture();
        },
        options,
    );

    let envelope = envelopes
        .try_into_only_item()
        .expect("expected exactly one envelope");
    let item = envelope
        .into_items()
        .try_into_only_item()
        .expect("expected exactly one item");
    let metric = item
        .into_metrics()
        .expect("expected metrics item")
        .try_into_only_item()
        .expect("expected exactly one metric in the envelope");

    let Metric {
        r#type,
        name,
        value,
        timestamp: _,
        trace_id: _,
        span_id,
        unit,
        attributes,
    } = metric;

    assert_eq!(r#type, MetricType::Counter);
    assert_eq!(name, "test");
    assert_eq!(value, 1.0);
    assert!(span_id.is_none());
    assert!(unit.is_none());
    assert_eq!(
        attributes.get("http.route").map(|value| &value.0),
        Some(&Value::from("/health")),
    );
    assert_eq!(
        attributes
            .get("http.response.status_code")
            .map(|value| &value.0),
        Some(&Value::from(200)),
    );
}

#[test]
fn metric_unit_is_captured() {
    let options = ClientOptions::default();

    let envelopes = test::with_captured_envelopes_options(
        || metrics::gauge("test", 42).unit(Unit::Millisecond).capture(),
        options,
    );

    let envelope = envelopes
        .try_into_only_item()
        .expect("expected exactly one envelope");
    let item = envelope
        .into_items()
        .try_into_only_item()
        .expect("expected exactly one item");
    let metric = item
        .into_metrics()
        .expect("expected metrics item")
        .try_into_only_item()
        .expect("expected exactly one metric in the envelope");

    let Metric {
        r#type,
        name,
        value,
        timestamp: _,
        trace_id: _,
        span_id,
        unit,
        attributes: _,
    } = metric;

    assert_eq!(r#type, MetricType::Gauge);
    assert_eq!(name, "test");
    assert_eq!(value, 42.0);
    assert!(span_id.is_none());
    assert_eq!(unit, Some(Unit::Millisecond));
}

/// Test that metrics in the same scope share the same trace_id when no span is active.
///
/// This tests that trace ID is set from the propagation context when there is no active span.
#[test]
fn metrics_share_trace_id_without_active_span() {
    let options = ClientOptions::default();

    let envelopes = test::with_captured_envelopes_options(
        || {
            metrics::counter("test-2", 1).capture();
            metrics::counter("test-2", 1).capture();
        },
        options,
    );
    let envelope = envelopes
        .try_into_only_item()
        .expect("expected one envelope");
    let item = envelope
        .into_items()
        .try_into_only_item()
        .expect("expected one item");
    let metrics = item.into_metrics().expect("expected metrics item");

    let [metric1, metric2] = metrics.as_slice() else {
        panic!("expected exactly two metrics");
    };

    assert_eq!(
        metric1.trace_id, metric2.trace_id,
        "metrics in the same scope should share the same trace_id"
    );

    assert!(metric1.span_id.is_none());
    assert!(metric2.span_id.is_none());
}

/// Test that span_id is set from the active span when one is present.
#[test]
fn metrics_span_id_from_active_span() {
    let options = ClientOptions::default();

    let mut expected_span_id = None;
    let envelopes = test::with_captured_envelopes_options(
        || {
            let transaction_ctx = TransactionContext::new("test transaction", "test");
            expected_span_id = Some(transaction_ctx.span_id());
            let transaction = sentry_core::start_transaction(transaction_ctx);
            sentry_core::configure_scope(|scope| scope.set_span(Some(transaction.clone().into())));
            metrics::counter("test", 1).capture();
            transaction.finish();
        },
        options,
    );

    let expected_span_id = expected_span_id.expect("expected_span_id did not get set");

    let envelope = envelopes
        .try_into_only_item()
        .expect("expected one envelope");
    let item = envelope
        .into_items()
        .try_into_only_item()
        .expect("expected one item");
    let mut metrics = item.into_metrics().expect("expected metrics item");
    let metric = metrics.pop().expect("expected one metric");

    assert_eq!(
        metric.span_id,
        Some(expected_span_id),
        "span_id should be set from the active span"
    );
}

/// Test that default SDK attributes are attached to metrics.
#[test]
fn default_attributes_attached() {
    let options = ClientOptions {
        environment: Some("test-env".into()),
        release: Some("1.0.0".into()),
        server_name: Some("test-server".into()),
        ..Default::default()
    };

    let envelopes =
        test::with_captured_envelopes_options(|| metrics::counter("test", 1).capture(), options);
    let metric = extract_single_metric(envelopes).expect("expected a single-metric envelope");

    let expected_attributes = [
        ("sentry.environment", "test-env"),
        ("sentry.release", "1.0.0"),
        ("sentry.sdk.name", "sentry.rust"),
        ("sentry.sdk.version", env!("CARGO_PKG_VERSION")),
        ("server.address", "test-server"),
    ]
    .into_iter()
    .map(|(attribute, value)| (attribute.into(), value.into()))
    .collect();

    assert_eq!(metric.attributes, expected_attributes);
}

/// Test that optional default attributes are omitted when not configured.
#[test]
fn optional_default_attributes_omitted_when_not_configured() {
    let options = ClientOptions::default();

    let envelopes =
        test::with_captured_envelopes_options(|| metrics::counter("test", 1).capture(), options);
    let metric = extract_single_metric(envelopes).expect("expected a single-metric envelope");

    let expected_attributes = [
        // Importantly, no other attributes should be set.
        ("sentry.sdk.name", "sentry.rust"),
        ("sentry.sdk.version", env!("CARGO_PKG_VERSION")),
    ]
    .into_iter()
    .map(|(attribute, value)| (attribute.into(), value.into()))
    .collect();

    assert_eq!(metric.attributes, expected_attributes);
}

/// Test that explicitly set metric attributes are not overwritten by defaults.
#[test]
fn default_attributes_do_not_overwrite_explicit() {
    let options = ClientOptions {
        environment: Some("default-env".into()),
        ..Default::default()
    };

    let envelopes = test::with_captured_envelopes_options(
        || {
            metrics::counter("test", 1)
                .attribute("sentry.environment", "custom-env")
                .capture();
        },
        options,
    );
    let metric = extract_single_metric(envelopes).expect("expected a single-metric envelope");

    let expected_attributes = [
        // Check the environment is the one set directly on the metric
        ("sentry.environment", "custom-env"),
        // The other default attributes also stay
        ("sentry.sdk.name", "sentry.rust"),
        ("sentry.sdk.version", env!("CARGO_PKG_VERSION")),
    ]
    .into_iter()
    .map(|(attribute, value)| (attribute.into(), value.into()))
    .collect();

    assert_eq!(metric.attributes, expected_attributes);
}

/// Test that user attributes are NOT attached when `send_default_pii` is false.
#[test]
fn user_attributes_absent_without_send_default_pii() {
    let options = ClientOptions {
        send_default_pii: false,
        ..Default::default()
    };

    let envelopes = test::with_captured_envelopes_options(
        || {
            sentry_core::configure_scope(|scope| {
                scope.set_user(Some(User {
                    id: Some("uid-123".into()),
                    username: Some("testuser".into()),
                    email: Some("test@example.com".into()),
                    ..Default::default()
                }));
            });
            metrics::counter("test", 1).capture();
        },
        options,
    );
    let metric = extract_single_metric(envelopes).expect("expected a single-metric envelope");

    let expected_attributes = [
        // Note the lack of user attributes, despite setting them on the scope.
        ("sentry.sdk.name", "sentry.rust"),
        ("sentry.sdk.version", env!("CARGO_PKG_VERSION")),
    ]
    .into_iter()
    .map(|(attribute, value)| (attribute.into(), value.into()))
    .collect();

    assert_eq!(metric.attributes, expected_attributes);
}

/// Test that scope user attributes are attached to metrics when
/// `send_default_pii` is true.
#[test]
fn metric_user_attributes_from_scope_are_applied_with_send_default_pii() {
    let options = ClientOptions {
        send_default_pii: true,
        ..Default::default()
    };

    let envelopes = test::with_captured_envelopes_options(
        || {
            sentry_core::configure_scope(|scope| {
                scope.set_user(Some(User {
                    id: Some("uid-123".into()),
                    username: Some("testuser".into()),
                    email: Some("test@example.com".into()),
                    ..Default::default()
                }));
            });
            metrics::counter("test", 1).capture()
        },
        options,
    );
    let metric = extract_single_metric(envelopes).expect("expected a single-metric envelope");

    let expected_attributes = [
        ("sentry.sdk.name", "sentry.rust"),
        ("sentry.sdk.version", env!("CARGO_PKG_VERSION")),
        ("user.id", "uid-123"),
        ("user.name", "testuser"),
        ("user.email", "test@example.com"),
    ]
    .into_iter()
    .map(|(attribute, value)| (attribute.into(), value.into()))
    .collect();

    assert_eq!(metric.attributes, expected_attributes);
}

/// Test that if a metric already has any user attribute set, scope user
/// attributes are not merged in.
#[test]
fn metric_user_attributes_do_not_overwrite_explicit() {
    let options = ClientOptions {
        send_default_pii: true,
        ..Default::default()
    };

    let envelopes = test::with_captured_envelopes_options(
        || {
            sentry_core::configure_scope(|scope| {
                scope.set_user(Some(User {
                    id: Some("scope-uid".into()),
                    username: Some("scope-user".into()),
                    email: Some("scope@example.com".into()),
                    ..Default::default()
                }));
            });
            metrics::counter("test", 1)
                .attribute("user.id", "explicit-uid")
                .attribute("user.name", "explicit-user")
                .capture();
        },
        options,
    );
    let metric = extract_single_metric(envelopes).expect("expected a single-metric envelope");

    let expected_attributes = [
        ("sentry.sdk.name", "sentry.rust"),
        ("sentry.sdk.version", env!("CARGO_PKG_VERSION")),
        ("user.id", "explicit-uid"),
        ("user.name", "explicit-user"),
    ]
    .into_iter()
    .map(|(attribute, value)| (attribute.into(), value.into()))
    .collect();

    assert_eq!(metric.attributes, expected_attributes);
}

/// Test that `before_send_metric` can filter out metrics.
#[test]
fn before_send_metric_can_drop() {
    let options = ClientOptions {
        before_send_metric: Some(Arc::new(|_| None)),
        ..Default::default()
    };

    let envelopes =
        test::with_captured_envelopes_options(|| metrics::counter("test", 1).capture(), options);
    assert!(
        envelopes.is_empty(),
        "metric should be dropped by before_send_metric"
    );
}

/// Test that `before_send_metric` can modify metrics.
#[test]
fn before_send_metric_can_modify() {
    let options = ClientOptions {
        before_send_metric: Some(Arc::new(|mut metric| {
            metric
                .attributes
                .insert("added_by_callback".into(), LogAttribute(Value::from("yes")));
            Some(metric)
        })),
        ..Default::default()
    };

    let envelopes =
        test::with_captured_envelopes_options(|| metrics::counter("test", 1).capture(), options);
    let metric = extract_single_metric(envelopes).expect("expected a single-metric envelope");

    assert_eq!(
        metric.attributes.get("added_by_callback"),
        Some(&LogAttribute(Value::from("yes"))),
    );
}

/// Returns a [`Metric`] with [type `Counter`](MetricType),
/// the provided name, and a value of `1.0`.
/// Helper to extract the single metric from a list of captured envelopes.
///
/// Asserts that the envelope contains only a single item, which contains only
/// a single metrics item, and returns that metrics item, or an error if failed.
fn extract_single_metric<I>(envelopes: I) -> Result<Metric>
where
    I: IntoIterator<Item = Envelope>,
{
    envelopes
        .try_into_only_item()
        .context("expected exactly one envelope")?
        .into_items()
        .try_into_only_item()
        .context("expected exactly one item")?
        .into_metrics()
        .context("expected a metrics item")?
        .try_into_only_item()
        .context("expected exactly one metric")
}

/// Extension trait for iterators allowing conversion to only item.
trait TryIntoOnlyElementExt<I> {
    type Item;

    /// Convert the iterator to the only item, erroring if the
    /// iterator does not contain exactly one item.
    fn try_into_only_item(self) -> Result<Self::Item>;
}

impl<I> TryIntoOnlyElementExt<I> for I
where
    I: IntoIterator,
{
    type Item = I::Item;

    fn try_into_only_item(self) -> Result<Self::Item> {
        let mut iter = self.into_iter();
        let rv = iter.next().context("iterator was empty")?;

        match iter.next() {
            Some(_) => anyhow::bail!("iterator had more than one item"),
            None => Ok(rv),
        }
    }
}

trait IntoMetricsExt {
    /// Attempt to convert the provided value to a trace metric,
    /// returning None if the conversion is not possible.
    fn into_metrics(self) -> Option<Vec<Metric>>;
}

impl IntoMetricsExt for EnvelopeItem {
    fn into_metrics(self) -> Option<Vec<Metric>> {
        match self {
            EnvelopeItem::ItemContainer(ItemContainer::Metrics(metrics)) => Some(metrics),
            _ => None,
        }
    }
}