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