glean_core/metrics/
quantity.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5use std::sync::Arc;
6
7use crate::common_metric_data::{CommonMetricDataInternal, DynamicLabelType};
8use crate::error_recording::{record_error, test_get_num_recorded_errors, ErrorType};
9use crate::metrics::Metric;
10use crate::metrics::MetricType;
11use crate::storage::StorageManager;
12use crate::Glean;
13use crate::{CommonMetricData, TestGetValue};
14
15/// A quantity metric.
16///
17/// Used to store explicit non-negative integers.
18#[derive(Clone, Debug)]
19pub struct QuantityMetric {
20    meta: Arc<CommonMetricDataInternal>,
21}
22
23impl MetricType for QuantityMetric {
24    fn meta(&self) -> &CommonMetricDataInternal {
25        &self.meta
26    }
27
28    fn with_name(&self, name: String) -> Self {
29        let mut meta = (*self.meta).clone();
30        meta.inner.name = name;
31        Self {
32            meta: Arc::new(meta),
33        }
34    }
35
36    fn with_dynamic_label(&self, label: DynamicLabelType) -> Self {
37        let mut meta = (*self.meta).clone();
38        meta.inner.dynamic_label = Some(label);
39        Self {
40            meta: Arc::new(meta),
41        }
42    }
43}
44
45// IMPORTANT:
46//
47// When changing this implementation, make sure all the operations are
48// also declared in the related trait in `../traits/`.
49impl QuantityMetric {
50    /// Creates a new quantity metric.
51    pub fn new(meta: CommonMetricData) -> Self {
52        Self {
53            meta: Arc::new(meta.into()),
54        }
55    }
56
57    /// Sets the value. Must be non-negative.
58    ///
59    /// # Arguments
60    ///
61    /// * `value` - The value. Must be non-negative.
62    ///
63    /// ## Notes
64    ///
65    /// Logs an error if the `value` is negative.
66    pub fn set(&self, value: i64) {
67        let metric = self.clone();
68        crate::launch_with_glean(move |glean| metric.set_sync(glean, value))
69    }
70
71    /// Sets the value synchronously. Must be non-negative.
72    #[doc(hidden)]
73    pub fn set_sync(&self, glean: &Glean, value: i64) {
74        if !self.should_record(glean) {
75            return;
76        }
77
78        if value < 0 {
79            record_error(
80                glean,
81                &self.meta,
82                ErrorType::InvalidValue,
83                format!("Set negative value {}", value),
84                None,
85            );
86            return;
87        }
88
89        glean
90            .storage()
91            .record(glean, &self.meta, &Metric::Quantity(value))
92    }
93
94    /// Get current value.
95    #[doc(hidden)]
96    pub fn get_value<'a, S: Into<Option<&'a str>>>(
97        &self,
98        glean: &Glean,
99        ping_name: S,
100    ) -> Option<i64> {
101        let queried_ping_name = ping_name
102            .into()
103            .unwrap_or_else(|| &self.meta().inner.send_in_pings[0]);
104
105        match StorageManager.snapshot_metric_for_test(
106            glean.storage(),
107            queried_ping_name,
108            &self.meta.identifier(glean),
109            self.meta.inner.lifetime,
110        ) {
111            Some(Metric::Quantity(i)) => Some(i),
112            _ => None,
113        }
114    }
115
116    /// **Test-only API (exported for FFI purposes).**
117    ///
118    /// Gets the currently stored value as an integer.
119    ///
120    /// This doesn't clear the stored value.
121    ///
122    /// # Arguments
123    ///
124    /// * `ping_name` - the optional name of the ping to retrieve the metric
125    ///                 for. Defaults to the first value in `send_in_pings`.
126    ///
127    /// # Returns
128    ///
129    /// The stored value or `None` if nothing stored.
130    pub fn test_get_value(&self, ping_name: Option<String>) -> Option<i64> {
131        crate::block_on_dispatcher();
132        crate::core::with_glean(|glean| self.get_value(glean, ping_name.as_deref()))
133    }
134
135    /// **Exported for test purposes.**
136    ///
137    /// Gets the number of recorded errors for the given metric and error type.
138    ///
139    /// # Arguments
140    ///
141    /// * `error` - The type of error
142    ///
143    /// # Returns
144    ///
145    /// The number of errors reported.
146    pub fn test_get_num_recorded_errors(&self, error: ErrorType) -> i32 {
147        crate::block_on_dispatcher();
148
149        crate::core::with_glean(|glean| {
150            test_get_num_recorded_errors(glean, self.meta(), error).unwrap_or(0)
151        })
152    }
153}
154
155impl TestGetValue<i64> for QuantityMetric {
156    /// **Test-only API (exported for FFI purposes).**
157    ///
158    /// Gets the currently stored value as an integer.
159    ///
160    /// This doesn't clear the stored value.
161    ///
162    /// # Arguments
163    ///
164    /// * `ping_name` - the optional name of the ping to retrieve the metric
165    ///                 for. Defaults to the first value in `send_in_pings`.
166    ///
167    /// # Returns
168    ///
169    /// The stored value or `None` if nothing stored.
170    fn test_get_value(&self, ping_name: Option<String>) -> Option<i64> {
171        crate::block_on_dispatcher();
172        crate::core::with_glean(|glean| self.get_value(glean, ping_name.as_deref()))
173    }
174}