Skip to main content

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