glean_core/metrics/
object.rs1use std::sync::Arc;
6
7use crate::common_metric_data::CommonMetricDataInternal;
8use crate::error_recording::{record_error, test_get_num_recorded_errors, ErrorType};
9use crate::metrics::JsonValue;
10use crate::metrics::Metric;
11use crate::metrics::MetricType;
12use crate::storage::StorageManager;
13use crate::Glean;
14use crate::{CommonMetricData, TestGetValue};
15
16#[derive(Clone, Debug)]
21pub struct ObjectMetric {
22 meta: Arc<CommonMetricDataInternal>,
23}
24
25impl MetricType for ObjectMetric {
26 fn meta(&self) -> &CommonMetricDataInternal {
27 &self.meta
28 }
29}
30
31impl ObjectMetric {
36 pub fn new(meta: CommonMetricData) -> Self {
38 Self {
39 meta: Arc::new(meta.into()),
40 }
41 }
42
43 #[doc(hidden)]
50 pub fn set_sync(&self, glean: &Glean, value: JsonValue) {
51 if !self.should_record(glean) {
52 return;
53 }
54
55 let value = Metric::Object(serde_json::to_string(&value).unwrap());
56 glean.storage().record(glean, &self.meta, &value)
57 }
58
59 pub fn set(&self, value: JsonValue) {
68 let metric = self.clone();
69 crate::launch_with_glean(move |glean| metric.set_sync(glean, value))
70 }
71
72 pub fn set_string(&self, object: String) {
83 let metric = self.clone();
84 crate::launch_with_glean(move |glean| {
85 let object = match serde_json::from_str(&object) {
86 Ok(object) => object,
87 Err(_) => {
88 let msg = "Value did not match predefined schema";
89 record_error(glean, &metric.meta, ErrorType::InvalidValue, msg, None);
90 return;
91 }
92 };
93 metric.set_sync(glean, object)
94 })
95 }
96
97 pub fn record_schema_error(&self) {
103 let metric = self.clone();
104 crate::launch_with_glean(move |glean| {
105 let msg = "Value did not match predefined schema";
106 record_error(glean, &metric.meta, ErrorType::InvalidValue, msg, None);
107 });
108 }
109
110 #[doc(hidden)]
112 pub fn get_value<'a, S: Into<Option<&'a str>>>(
113 &self,
114 glean: &Glean,
115 ping_name: S,
116 ) -> Option<String> {
117 let queried_ping_name = ping_name
118 .into()
119 .unwrap_or_else(|| &self.meta().inner.send_in_pings[0]);
120
121 match StorageManager.snapshot_metric_for_test(
122 glean.storage(),
123 queried_ping_name,
124 &self.meta.identifier(glean),
125 self.meta.inner.lifetime,
126 ) {
127 Some(Metric::Object(o)) => Some(o),
128 _ => None,
129 }
130 }
131
132 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<JsonValue> for ObjectMetric {
155 fn test_get_value(&self, ping_name: Option<String>) -> Option<JsonValue> {
161 crate::block_on_dispatcher();
162 let value = crate::core::with_glean(|glean| self.get_value(glean, ping_name.as_deref()));
163 value.map(|val| serde_json::from_str(&val).unwrap())
165 }
166}