glean_core/metrics/
quantity.rs1use 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#[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
44impl QuantityMetric {
49 pub fn new(meta: CommonMetricData) -> Self {
51 Self {
52 meta: Arc::new(meta.into()),
53 }
54 }
55
56 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 #[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 #[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 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 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 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}