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(self.meta(), queried_ping_name) {
105            Some(Metric::Quantity(i)) => Some(i),
106            _ => None,
107        }
108    }
109
110    /// **Test-only API (exported for FFI purposes).**
111    ///
112    /// Gets the currently stored value as an integer.
113    ///
114    /// This doesn't clear the stored value.
115    ///
116    /// # Arguments
117    ///
118    /// * `ping_name` - the optional name of the ping to retrieve the metric
119    ///                 for. Defaults to the first value in `send_in_pings`.
120    ///
121    /// # Returns
122    ///
123    /// The stored value or `None` if nothing stored.
124    pub fn test_get_value(&self, ping_name: Option<String>) -> Option<i64> {
125        crate::block_on_dispatcher();
126        crate::core::with_glean(|glean| self.get_value(glean, ping_name.as_deref()))
127    }
128
129    /// **Exported for test purposes.**
130    ///
131    /// Gets the number of recorded errors for the given metric and error type.
132    ///
133    /// # Arguments
134    ///
135    /// * `error` - The type of error
136    ///
137    /// # Returns
138    ///
139    /// The number of errors reported.
140    pub fn test_get_num_recorded_errors(&self, error: ErrorType) -> i32 {
141        crate::block_on_dispatcher();
142
143        crate::core::with_glean(|glean| {
144            test_get_num_recorded_errors(glean, self.meta(), error).unwrap_or(0)
145        })
146    }
147}
148
149impl TestGetValue for QuantityMetric {
150    type Output = i64;
151
152    /// **Test-only API (exported for FFI purposes).**
153    ///
154    /// Gets the currently stored value as an integer.
155    ///
156    /// This doesn't clear the stored value.
157    ///
158    /// # Arguments
159    ///
160    /// * `ping_name` - the optional name of the ping to retrieve the metric
161    ///                 for. Defaults to the first value in `send_in_pings`.
162    ///
163    /// # Returns
164    ///
165    /// The stored value or `None` if nothing stored.
166    fn test_get_value(&self, ping_name: Option<String>) -> Option<i64> {
167        crate::block_on_dispatcher();
168        crate::core::with_glean(|glean| self.get_value(glean, ping_name.as_deref()))
169    }
170}