Skip to main content

glean_core/metrics/
boolean.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::{test_get_num_recorded_errors, ErrorType};
9use crate::metrics::MetricType;
10use crate::metrics::{Metric, TestGetValue};
11use crate::CommonMetricData;
12use crate::Glean;
13
14/// A boolean metric.
15///
16/// Records a simple flag.
17#[derive(Clone, Debug)]
18pub struct BooleanMetric {
19    meta: Arc<CommonMetricDataInternal>,
20}
21
22impl MetricType for BooleanMetric {
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 BooleanMetric {
49    /// Creates a new boolean metric.
50    pub fn new(meta: CommonMetricData) -> Self {
51        Self {
52            meta: Arc::new(meta.into()),
53        }
54    }
55
56    /// Sets to the specified boolean value.
57    ///
58    /// # Arguments
59    ///
60    /// * `glean` - the Glean instance this metric belongs to.
61    /// * `value` - the value to set.
62    #[doc(hidden)]
63    pub fn set_sync(&self, glean: &Glean, value: bool) {
64        if !self.should_record(glean) {
65            return;
66        }
67
68        let value = Metric::Boolean(value);
69        glean.storage().record(glean, &self.meta, &value)
70    }
71
72    /// Sets to the specified boolean value.
73    ///
74    /// # Arguments
75    ///
76    /// * `value` - the value to set.
77    pub fn set(&self, value: bool) {
78        let metric = self.clone();
79        crate::launch_with_glean(move |glean| metric.set_sync(glean, value))
80    }
81
82    /// **Test-only API (exported for FFI purposes).**
83    ///
84    /// Gets the currently stored value as a boolean.
85    ///
86    /// This doesn't clear the stored value.
87    #[doc(hidden)]
88    pub fn get_value(&self, glean: &Glean, ping_name: Option<&str>) -> Option<bool> {
89        let queried_ping_name = ping_name.unwrap_or_else(|| &self.meta().inner.send_in_pings[0]);
90
91        match glean.storage().get_metric(
92            #[cfg(not(feature = "sqlite"))]
93            glean,
94            self.meta(),
95            queried_ping_name,
96        ) {
97            Some(Metric::Boolean(b)) => Some(b),
98            _ => None,
99        }
100    }
101
102    /// **Exported for test purposes.**
103    ///
104    /// Gets the number of recorded errors for the given metric and error type.
105    ///
106    /// # Arguments
107    ///
108    /// * `error` - The type of error
109    ///
110    /// # Returns
111    ///
112    /// The number of errors reported.
113    pub fn test_get_num_recorded_errors(&self, error: ErrorType) -> i32 {
114        crate::block_on_dispatcher();
115
116        crate::core::with_glean(|glean| {
117            test_get_num_recorded_errors(glean, self.meta(), error).unwrap_or(0)
118        })
119    }
120}
121
122impl TestGetValue for BooleanMetric {
123    type Output = bool;
124    /// **Test-only API (exported for FFI purposes).**
125    ///
126    /// Gets the currently stored value as a boolean.
127    ///
128    /// This doesn't clear the stored value.
129    ///
130    /// # Arguments
131    ///
132    /// * `ping_name` - the optional name of the ping to retrieve the metric
133    ///                 for. Defaults to the first value in `send_in_pings`.
134    ///
135    /// # Returns
136    ///
137    /// The stored value or `None` if nothing stored.
138    fn test_get_value(&self, ping_name: Option<String>) -> Option<bool> {
139        crate::block_on_dispatcher();
140        crate::core::with_glean(|glean| self.get_value(glean, ping_name.as_deref()))
141    }
142}