opentelemetry_sdk/metrics/internal/
last_value.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
use std::{
    collections::{hash_map::Entry, HashMap},
    sync::Mutex,
    time::SystemTime,
};

use crate::{metrics::data::DataPoint, metrics::AttributeSet};
use opentelemetry::{global, metrics::MetricsError, KeyValue};

use super::{
    aggregate::{is_under_cardinality_limit, STREAM_OVERFLOW_ATTRIBUTE_SET},
    Number,
};

/// Timestamped measurement data.
struct DataPointValue<T> {
    timestamp: SystemTime,
    value: T,
}

/// Summarizes a set of measurements as the last one made.
#[derive(Default)]
pub(crate) struct LastValue<T> {
    values: Mutex<HashMap<AttributeSet, DataPointValue<T>>>,
}

impl<T: Number<T>> LastValue<T> {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    pub(crate) fn measure(&self, measurement: T, attrs: AttributeSet) {
        let d: DataPointValue<T> = DataPointValue {
            timestamp: SystemTime::now(),
            value: measurement,
        };
        if let Ok(mut values) = self.values.lock() {
            let size = values.len();
            match values.entry(attrs) {
                Entry::Occupied(mut occupied_entry) => {
                    occupied_entry.insert(d);
                }
                Entry::Vacant(vacant_entry) => {
                    if is_under_cardinality_limit(size) {
                        vacant_entry.insert(d);
                    } else {
                        values.insert(STREAM_OVERFLOW_ATTRIBUTE_SET.clone(), d);
                        global::handle_error(MetricsError::Other("Warning: Maximum data points for metric stream exceeded. Entry added to overflow.".into()));
                    }
                }
            }
        }
    }

    pub(crate) fn compute_aggregation(&self, dest: &mut Vec<DataPoint<T>>) {
        dest.clear();
        let mut values = match self.values.lock() {
            Ok(guard) if !guard.is_empty() => guard,
            _ => return,
        };

        let n = values.len();
        if n > dest.capacity() {
            dest.reserve_exact(n - dest.capacity());
        }

        for (attrs, value) in values.drain() {
            dest.push(DataPoint {
                attributes: attrs
                    .iter()
                    .map(|(k, v)| KeyValue::new(k.clone(), v.clone()))
                    .collect(),
                time: Some(value.timestamp),
                value: value.value,
                start_time: None,
                exemplars: vec![],
            });
        }
    }
}