opentelemetry_sdk 0.32.0

The SDK for the OpenTelemetry metrics collection and distributed tracing framework
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
681
682
683
684
//! Types for delivery of pre-aggregated metric time series data.

use std::{borrow::Cow, time::SystemTime};

use opentelemetry::{InstrumentationScope, KeyValue};

use crate::Resource;

use super::Temporality;

/// A collection of [ScopeMetrics] and the associated [Resource] that created them.
#[derive(Debug)]
pub struct ResourceMetrics {
    /// The entity that collected the metrics.
    pub(crate) resource: Resource,
    /// The collection of metrics with unique [InstrumentationScope]s.
    pub(crate) scope_metrics: Vec<ScopeMetrics>,
}

impl Default for ResourceMetrics {
    fn default() -> Self {
        Self {
            resource: Resource::empty(),
            scope_metrics: Vec::new(),
        }
    }
}

impl ResourceMetrics {
    /// Returns a reference to the [Resource] in [ResourceMetrics].
    pub fn resource(&self) -> &Resource {
        &self.resource
    }

    /// Returns an iterator over the [ScopeMetrics] in [ResourceMetrics].
    pub fn scope_metrics(&self) -> impl Iterator<Item = &ScopeMetrics> {
        self.scope_metrics.iter()
    }
}

/// A collection of metrics produced by a meter.
#[derive(Default, Debug)]
pub struct ScopeMetrics {
    /// The [InstrumentationScope] that the meter was created with.
    pub(crate) scope: InstrumentationScope,
    /// The list of aggregations created by the meter.
    pub(crate) metrics: Vec<Metric>,
}

impl ScopeMetrics {
    /// Returns a reference to the [InstrumentationScope] in [ScopeMetrics].
    pub fn scope(&self) -> &InstrumentationScope {
        &self.scope
    }

    /// Returns an iterator over the [Metric]s in [ScopeMetrics].
    pub fn metrics(&self) -> impl Iterator<Item = &Metric> {
        self.metrics.iter()
    }
}

/// A collection of one or more aggregated time series from an [Instrument].
///
/// [Instrument]: crate::metrics::Instrument
#[derive(Debug)]
pub struct Metric {
    /// The name of the instrument that created this data.
    pub(crate) name: Cow<'static, str>,
    /// The description of the instrument, which can be used in documentation.
    pub(crate) description: Cow<'static, str>,
    /// The unit in which the instrument reports.
    pub(crate) unit: Cow<'static, str>,
    /// The aggregated data from an instrument.
    pub(crate) data: AggregatedMetrics,
}

impl Metric {
    /// Returns the name of the instrument that created this data.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the description of the instrument.
    pub fn description(&self) -> &str {
        &self.description
    }

    /// Returns the unit in which the instrument reports.
    pub fn unit(&self) -> &str {
        &self.unit
    }

    /// Returns the aggregated data from the instrument.
    pub fn data(&self) -> &AggregatedMetrics {
        &self.data
    }
}

/// Aggregated metrics data from an instrument
#[derive(Debug)]
pub enum AggregatedMetrics {
    /// All metric data with `f64` value type
    F64(MetricData<f64>),
    /// All metric data with `u64` value type
    U64(MetricData<u64>),
    /// All metric data with `i64` value type
    I64(MetricData<i64>),
}

/// Metric data for all types
#[derive(Debug)]
pub enum MetricData<T> {
    /// Metric data for Gauge
    Gauge(Gauge<T>),
    /// Metric data for Sum
    Sum(Sum<T>),
    /// Metric data for Histogram
    Histogram(Histogram<T>),
    /// Metric data for ExponentialHistogram
    ExponentialHistogram(ExponentialHistogram<T>),
}

impl From<MetricData<f64>> for AggregatedMetrics {
    fn from(value: MetricData<f64>) -> Self {
        AggregatedMetrics::F64(value)
    }
}

impl From<MetricData<i64>> for AggregatedMetrics {
    fn from(value: MetricData<i64>) -> Self {
        AggregatedMetrics::I64(value)
    }
}

impl From<MetricData<u64>> for AggregatedMetrics {
    fn from(value: MetricData<u64>) -> Self {
        AggregatedMetrics::U64(value)
    }
}

impl<T> From<Gauge<T>> for MetricData<T> {
    fn from(value: Gauge<T>) -> Self {
        MetricData::Gauge(value)
    }
}

impl<T> From<Sum<T>> for MetricData<T> {
    fn from(value: Sum<T>) -> Self {
        MetricData::Sum(value)
    }
}

impl<T> From<Histogram<T>> for MetricData<T> {
    fn from(value: Histogram<T>) -> Self {
        MetricData::Histogram(value)
    }
}

impl<T> From<ExponentialHistogram<T>> for MetricData<T> {
    fn from(value: ExponentialHistogram<T>) -> Self {
        MetricData::ExponentialHistogram(value)
    }
}

/// DataPoint is a single data point in a time series.
#[derive(Debug, Clone, PartialEq)]
pub struct GaugeDataPoint<T> {
    /// Attributes is the set of key value pairs that uniquely identify the
    /// time series.
    pub(crate) attributes: Vec<KeyValue>,
    /// The value of this data point.
    pub(crate) value: T,
    /// The sampled [Exemplar]s collected during the time series.
    pub(crate) exemplars: Vec<Exemplar<T>>,
}

impl<T> GaugeDataPoint<T> {
    /// Returns an iterator over the attributes in [GaugeDataPoint].
    pub fn attributes(&self) -> impl Iterator<Item = &KeyValue> {
        self.attributes.iter()
    }

    /// Returns an iterator over the [Exemplar]s in [GaugeDataPoint].
    pub fn exemplars(&self) -> impl Iterator<Item = &Exemplar<T>> {
        self.exemplars.iter()
    }
}

impl<T: Copy> GaugeDataPoint<T> {
    /// Returns the value of this data point.
    pub fn value(&self) -> T {
        self.value
    }
}

/// A measurement of the current value of an instrument.
#[derive(Debug, Clone)]
pub struct Gauge<T> {
    /// Represents individual aggregated measurements with unique attributes.
    pub(crate) data_points: Vec<GaugeDataPoint<T>>,
    /// The time when the time series was started.
    pub(crate) start_time: Option<SystemTime>,
    /// The time when the time series was recorded.
    pub(crate) time: SystemTime,
}

impl<T> Gauge<T> {
    /// Returns an iterator over the [GaugeDataPoint]s in [Gauge].
    pub fn data_points(&self) -> impl Iterator<Item = &GaugeDataPoint<T>> {
        self.data_points.iter()
    }

    /// Returns the time when the time series was started.
    pub fn start_time(&self) -> Option<SystemTime> {
        self.start_time
    }

    /// Returns the time when the time series was recorded.
    pub fn time(&self) -> SystemTime {
        self.time
    }
}

/// DataPoint is a single data point in a time series.
#[derive(Debug, Clone, PartialEq)]
pub struct SumDataPoint<T> {
    /// Attributes is the set of key value pairs that uniquely identify the
    /// time series.
    pub(crate) attributes: Vec<KeyValue>,
    /// The value of this data point.
    pub(crate) value: T,
    /// The sampled [Exemplar]s collected during the time series.
    pub(crate) exemplars: Vec<Exemplar<T>>,
}

impl<T> SumDataPoint<T> {
    /// Returns an iterator over the attributes in [SumDataPoint].
    pub fn attributes(&self) -> impl Iterator<Item = &KeyValue> {
        self.attributes.iter()
    }

    /// Returns an iterator over the [Exemplar]s in [SumDataPoint].
    pub fn exemplars(&self) -> impl Iterator<Item = &Exemplar<T>> {
        self.exemplars.iter()
    }
}

impl<T: Copy> SumDataPoint<T> {
    /// Returns the value of this data point.
    pub fn value(&self) -> T {
        self.value
    }
}

/// Represents the sum of all measurements of values from an instrument.
#[derive(Debug, Clone)]
pub struct Sum<T> {
    /// Represents individual aggregated measurements with unique attributes.
    pub(crate) data_points: Vec<SumDataPoint<T>>,
    /// The time when the time series was started.
    pub(crate) start_time: SystemTime,
    /// The time when the time series was recorded.
    pub(crate) time: SystemTime,
    /// Describes if the aggregation is reported as the change from the last report
    /// time, or the cumulative changes since a fixed start time.
    pub(crate) temporality: Temporality,
    /// Whether this aggregation only increases or decreases.
    pub(crate) is_monotonic: bool,
}

impl<T> Sum<T> {
    /// Returns an iterator over the [SumDataPoint]s in [Sum].
    pub fn data_points(&self) -> impl Iterator<Item = &SumDataPoint<T>> {
        self.data_points.iter()
    }

    /// Returns the time when the time series was started.
    pub fn start_time(&self) -> SystemTime {
        self.start_time
    }

    /// Returns the time when the time series was recorded.
    pub fn time(&self) -> SystemTime {
        self.time
    }

    /// Returns the temporality describing if the aggregation is reported as the change
    /// from the last report time, or the cumulative changes since a fixed start time.
    pub fn temporality(&self) -> Temporality {
        self.temporality
    }

    /// Returns whether this aggregation only increases or decreases.
    pub fn is_monotonic(&self) -> bool {
        self.is_monotonic
    }
}

/// Represents the histogram of all measurements of values from an instrument.
#[derive(Debug, Clone)]
pub struct Histogram<T> {
    /// Individual aggregated measurements with unique attributes.
    pub(crate) data_points: Vec<HistogramDataPoint<T>>,
    /// The time when the time series was started.
    pub(crate) start_time: SystemTime,
    /// The time when the time series was recorded.
    pub(crate) time: SystemTime,
    /// Describes if the aggregation is reported as the change from the last report
    /// time, or the cumulative changes since a fixed start time.
    pub(crate) temporality: Temporality,
}

impl<T> Histogram<T> {
    /// Returns an iterator over the [HistogramDataPoint]s in [Histogram].
    pub fn data_points(&self) -> impl Iterator<Item = &HistogramDataPoint<T>> {
        self.data_points.iter()
    }

    /// Returns the time when the time series was started.
    pub fn start_time(&self) -> SystemTime {
        self.start_time
    }

    /// Returns the time when the time series was recorded.
    pub fn time(&self) -> SystemTime {
        self.time
    }

    /// Returns the temporality describing if the aggregation is reported as the change
    /// from the last report time, or the cumulative changes since a fixed start time.
    pub fn temporality(&self) -> Temporality {
        self.temporality
    }
}

/// A single histogram data point in a time series.
#[derive(Debug, Clone, PartialEq)]
pub struct HistogramDataPoint<T> {
    /// The set of key value pairs that uniquely identify the time series.
    pub(crate) attributes: Vec<KeyValue>,
    /// The number of updates this histogram has been calculated with.
    pub(crate) count: u64,
    /// The upper bounds of the buckets of the histogram.
    ///
    /// Because the last boundary is +infinity this one is implied.
    pub(crate) bounds: Vec<f64>,
    /// The count of each of the buckets.
    pub(crate) bucket_counts: Vec<u64>,

    /// The minimum value recorded.
    pub(crate) min: Option<T>,
    /// The maximum value recorded.
    pub(crate) max: Option<T>,
    /// The sum of the values recorded.
    pub(crate) sum: T,

    /// The sampled [Exemplar]s collected during the time series.
    pub(crate) exemplars: Vec<Exemplar<T>>,
}

impl<T> HistogramDataPoint<T> {
    /// Returns an iterator over the attributes in [HistogramDataPoint].
    pub fn attributes(&self) -> impl Iterator<Item = &KeyValue> {
        self.attributes.iter()
    }

    /// Returns an iterator over the exemplars in [HistogramDataPoint].
    pub fn exemplars(&self) -> impl Iterator<Item = &Exemplar<T>> {
        self.exemplars.iter()
    }

    /// Returns an iterator over the bucket boundaries in [HistogramDataPoint].
    pub fn bounds(&self) -> impl Iterator<Item = f64> + '_ {
        self.bounds.iter().copied()
    }

    /// Returns an iterator over the bucket counts in [HistogramDataPoint].
    pub fn bucket_counts(&self) -> impl Iterator<Item = u64> + '_ {
        self.bucket_counts.iter().copied()
    }

    /// Returns the number of updates this histogram has been calculated with.
    pub fn count(&self) -> u64 {
        self.count
    }
}

impl<T: Copy> HistogramDataPoint<T> {
    /// Returns the minimum value recorded.
    pub fn min(&self) -> Option<T> {
        self.min
    }

    /// Returns the maximum value recorded.
    pub fn max(&self) -> Option<T> {
        self.max
    }

    /// Returns the sum of the values recorded.
    pub fn sum(&self) -> T {
        self.sum
    }
}

/// The histogram of all measurements of values from an instrument.
#[derive(Debug, Clone)]
pub struct ExponentialHistogram<T> {
    /// The individual aggregated measurements with unique attributes.
    pub(crate) data_points: Vec<ExponentialHistogramDataPoint<T>>,
    /// When the time series was started.
    pub(crate) start_time: SystemTime,
    /// The time when the time series was recorded.
    pub(crate) time: SystemTime,
    /// Describes if the aggregation is reported as the change from the last report
    /// time, or the cumulative changes since a fixed start time.
    pub(crate) temporality: Temporality,
}

impl<T> ExponentialHistogram<T> {
    /// Returns an iterator over the [ExponentialHistogramDataPoint]s in [ExponentialHistogram].
    pub fn data_points(&self) -> impl Iterator<Item = &ExponentialHistogramDataPoint<T>> {
        self.data_points.iter()
    }

    /// Returns the time when the time series was started.
    pub fn start_time(&self) -> SystemTime {
        self.start_time
    }

    /// Returns the time when the time series was recorded.
    pub fn time(&self) -> SystemTime {
        self.time
    }

    /// Returns the temporality describing if the aggregation is reported as the change
    /// from the last report time, or the cumulative changes since a fixed start time.
    pub fn temporality(&self) -> Temporality {
        self.temporality
    }
}

/// A single exponential histogram data point in a time series.
#[derive(Debug, Clone, PartialEq)]
pub struct ExponentialHistogramDataPoint<T> {
    /// The set of key value pairs that uniquely identify the time series.
    pub(crate) attributes: Vec<KeyValue>,

    /// The number of updates this histogram has been calculated with.
    pub(crate) count: usize,
    /// The minimum value recorded.
    pub(crate) min: Option<T>,
    /// The maximum value recorded.
    pub(crate) max: Option<T>,
    /// The sum of the values recorded.
    pub(crate) sum: T,

    /// Describes the resolution of the histogram.
    ///
    /// Boundaries are located at powers of the base, where:
    ///
    ///   base = 2 ^ (2 ^ -scale)
    pub(crate) scale: i8,

    /// The number of values whose absolute value is less than or equal to
    /// `zero_threshold`.
    ///
    /// When `zero_threshold` is `0`, this is the number of values that cannot be
    /// expressed using the standard exponential formula as well as values that have
    /// been rounded to zero.
    pub(crate) zero_count: u64,

    /// The range of positive value bucket counts.
    pub(crate) positive_bucket: ExponentialBucket,
    /// The range of negative value bucket counts.
    pub(crate) negative_bucket: ExponentialBucket,

    /// The width of the zero region.
    ///
    /// Where the zero region is defined as the closed interval
    /// [-zero_threshold, zero_threshold].
    pub(crate) zero_threshold: f64,

    /// The sampled exemplars collected during the time series.
    pub(crate) exemplars: Vec<Exemplar<T>>,
}

impl<T> ExponentialHistogramDataPoint<T> {
    /// Returns an iterator over the attributes in [ExponentialHistogramDataPoint].
    pub fn attributes(&self) -> impl Iterator<Item = &KeyValue> {
        self.attributes.iter()
    }

    /// Returns an iterator over the exemplars in [ExponentialHistogramDataPoint].
    pub fn exemplars(&self) -> impl Iterator<Item = &Exemplar<T>> {
        self.exemplars.iter()
    }

    /// Returns the number of updates this histogram has been calculated with.
    pub fn count(&self) -> usize {
        self.count
    }

    /// Returns the resolution of the histogram.
    pub fn scale(&self) -> i8 {
        self.scale
    }

    /// Returns the number of values whose absolute value is less than or equal to zero_threshold.
    pub fn zero_count(&self) -> u64 {
        self.zero_count
    }

    /// Returns the range of positive value bucket counts.
    pub fn positive_bucket(&self) -> &ExponentialBucket {
        &self.positive_bucket
    }

    /// Returns the range of negative value bucket counts.
    pub fn negative_bucket(&self) -> &ExponentialBucket {
        &self.negative_bucket
    }

    /// Returns the width of the zero region.
    pub fn zero_threshold(&self) -> f64 {
        self.zero_threshold
    }
}

impl<T: Copy> ExponentialHistogramDataPoint<T> {
    /// Returns the minimum value recorded.
    pub fn min(&self) -> Option<T> {
        self.min
    }

    /// Returns the maximum value recorded.
    pub fn max(&self) -> Option<T> {
        self.max
    }

    /// Returns the sum of the values recorded.
    pub fn sum(&self) -> T {
        self.sum
    }
}

/// A set of bucket counts, encoded in a contiguous array of counts.
#[derive(Debug, Clone, PartialEq)]
pub struct ExponentialBucket {
    /// The bucket index of the first entry in the `counts` vec.
    pub(crate) offset: i32,

    /// A vec where `counts[i]` carries the count of the bucket at index `offset + i`.
    ///
    /// `counts[i]` is the count of values greater than base^(offset+i) and less than
    /// or equal to base^(offset+i+1).
    pub(crate) counts: Vec<u64>,
}

impl ExponentialBucket {
    /// Returns the bucket index of the first entry in the counts vec.
    pub fn offset(&self) -> i32 {
        self.offset
    }

    /// Returns an iterator over the counts.
    pub fn counts(&self) -> impl Iterator<Item = u64> + '_ {
        self.counts.iter().copied()
    }
}

/// A measurement sampled from a time series providing a typical example.
#[derive(Debug, Clone, PartialEq)]
pub struct Exemplar<T> {
    /// The attributes recorded with the measurement but filtered out of the
    /// time series' aggregated data.
    pub(crate) filtered_attributes: Vec<KeyValue>,
    /// The time when the measurement was recorded.
    pub(crate) time: SystemTime,
    /// The measured value.
    pub value: T,
    /// The ID of the span that was active during the measurement.
    ///
    /// If no span was active or the span was not sampled this will be empty.
    pub(crate) span_id: [u8; 8],
    /// The ID of the trace the active span belonged to during the measurement.
    ///
    /// If no span was active or the span was not sampled this will be empty.
    pub(crate) trace_id: [u8; 16],
}

impl<T> Exemplar<T> {
    /// Returns an iterator over the filtered attributes in [Exemplar].
    pub fn filtered_attributes(&self) -> impl Iterator<Item = &KeyValue> {
        self.filtered_attributes.iter()
    }

    /// Returns the time when the measurement was recorded.
    pub fn time(&self) -> SystemTime {
        self.time
    }

    /// Returns the ID of the span that was active during the measurement.
    pub fn span_id(&self) -> &[u8; 8] {
        &self.span_id
    }

    /// Returns the ID of the trace the active span belonged to during the measurement.
    pub fn trace_id(&self) -> &[u8; 16] {
        &self.trace_id
    }
}

#[cfg(test)]
mod tests {

    use super::{Exemplar, ExponentialHistogramDataPoint, HistogramDataPoint, SumDataPoint};

    use opentelemetry::time::now;
    use opentelemetry::KeyValue;

    #[test]
    fn validate_cloning_data_points() {
        let data_type = SumDataPoint {
            attributes: vec![KeyValue::new("key", "value")],
            value: 0u32,
            exemplars: vec![Exemplar {
                filtered_attributes: vec![],
                time: now(),
                value: 0u32,
                span_id: [0; 8],
                trace_id: [0; 16],
            }],
        };
        assert_eq!(data_type.clone(), data_type);

        let histogram_data_point = HistogramDataPoint {
            attributes: vec![KeyValue::new("key", "value")],
            count: 0,
            bounds: vec![],
            bucket_counts: vec![],
            min: None,
            max: None,
            sum: 0u32,
            exemplars: vec![Exemplar {
                filtered_attributes: vec![],
                time: now(),
                value: 0u32,
                span_id: [0; 8],
                trace_id: [0; 16],
            }],
        };
        assert_eq!(histogram_data_point.clone(), histogram_data_point);

        let exponential_histogram_data_point = ExponentialHistogramDataPoint {
            attributes: vec![KeyValue::new("key", "value")],
            count: 0,
            min: None,
            max: None,
            sum: 0u32,
            scale: 0,
            zero_count: 0,
            positive_bucket: super::ExponentialBucket {
                offset: 0,
                counts: vec![],
            },
            negative_bucket: super::ExponentialBucket {
                offset: 0,
                counts: vec![],
            },
            zero_threshold: 0.0,
            exemplars: vec![Exemplar {
                filtered_attributes: vec![],
                time: now(),
                value: 0u32,
                span_id: [0; 8],
                trace_id: [0; 16],
            }],
        };
        assert_eq!(
            exponential_histogram_data_point.clone(),
            exponential_histogram_data_point
        );
    }
}