glean_core/metrics/
uuid.rs1use std::sync::Arc;
6
7use uuid::Uuid;
8
9use crate::common_metric_data::CommonMetricDataInternal;
10use crate::error_recording::{record_error, test_get_num_recorded_errors, ErrorType};
11use crate::metrics::Metric;
12use crate::metrics::MetricType;
13use crate::storage::StorageManager;
14use crate::Glean;
15use crate::{CommonMetricData, TestGetValue};
16
17#[derive(Clone, Debug)]
21pub struct UuidMetric {
22 meta: Arc<CommonMetricDataInternal>,
23}
24
25impl MetricType for UuidMetric {
26 fn meta(&self) -> &CommonMetricDataInternal {
27 &self.meta
28 }
29}
30
31impl UuidMetric {
36 pub fn new(meta: CommonMetricData) -> Self {
38 Self {
39 meta: Arc::new(meta.into()),
40 }
41 }
42
43 pub fn set(&self, value: String) {
49 let metric = self.clone();
50 crate::launch_with_glean(move |glean| metric.set_sync(glean, &value))
51 }
52
53 #[doc(hidden)]
55 pub fn set_sync<S: Into<String>>(&self, glean: &Glean, value: S) {
56 if !self.should_record(glean) {
57 return;
58 }
59
60 let value = value.into();
61
62 if let Ok(uuid) = uuid::Uuid::parse_str(&value) {
63 let value = Metric::Uuid(uuid.as_hyphenated().to_string());
64 glean.storage().record(glean, &self.meta, &value)
65 } else {
66 let msg = format!("Unexpected UUID value '{}'", value);
67 record_error(glean, &self.meta, ErrorType::InvalidValue, msg, None);
68 }
69 }
70
71 #[doc(hidden)]
81 pub fn set_from_uuid_sync(&self, glean: &Glean, value: Uuid) {
82 self.set_sync(glean, value.to_string())
83 }
84
85 pub fn generate_and_set(&self) -> String {
89 let uuid = Uuid::new_v4();
90
91 let value = uuid.to_string();
92 let metric = self.clone();
93 crate::launch_with_glean(move |glean| metric.set_sync(glean, value));
94
95 uuid.to_string()
96 }
97
98 #[doc(hidden)]
100 pub fn generate_and_set_sync(&self, storage: &Glean) -> Uuid {
101 let uuid = Uuid::new_v4();
102 self.set_sync(storage, uuid.to_string());
103 uuid
104 }
105
106 #[doc(hidden)]
108 pub fn get_value<'a, S: Into<Option<&'a str>>>(
109 &self,
110 glean: &Glean,
111 ping_name: S,
112 ) -> Option<Uuid> {
113 let queried_ping_name = ping_name
114 .into()
115 .unwrap_or_else(|| &self.meta().inner.send_in_pings[0]);
116
117 match StorageManager.snapshot_metric_for_test(
118 glean.storage(),
119 queried_ping_name,
120 &self.meta.identifier(glean),
121 self.meta.inner.lifetime,
122 ) {
123 Some(Metric::Uuid(uuid)) => Uuid::parse_str(&uuid).ok(),
124 _ => None,
125 }
126 }
127
128 pub fn test_get_num_recorded_errors(&self, error: ErrorType) -> i32 {
140 crate::block_on_dispatcher();
141
142 crate::core::with_glean(|glean| {
143 test_get_num_recorded_errors(glean, self.meta(), error).unwrap_or(0)
144 })
145 }
146}
147
148impl TestGetValue<String> for UuidMetric {
149 fn test_get_value(&self, ping_name: Option<String>) -> Option<String> {
164 crate::block_on_dispatcher();
165 crate::core::with_glean(|glean| {
166 self.get_value(glean, ping_name.as_deref())
167 .map(|uuid| uuid.to_string())
168 })
169 }
170}