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::Glean;
14use crate::{CommonMetricData, TestGetValue};
15
16#[derive(Clone, Debug)]
20pub struct UuidMetric {
21 meta: Arc<CommonMetricDataInternal>,
22}
23
24impl MetricType for UuidMetric {
25 fn meta(&self) -> &CommonMetricDataInternal {
26 &self.meta
27 }
28}
29
30impl UuidMetric {
35 pub fn new(meta: CommonMetricData) -> Self {
37 Self {
38 meta: Arc::new(meta.into()),
39 }
40 }
41
42 pub fn set(&self, value: String) {
48 let metric = self.clone();
49 crate::launch_with_glean(move |glean| metric.set_sync(glean, &value))
50 }
51
52 #[doc(hidden)]
54 pub fn set_sync<S: Into<String>>(&self, glean: &Glean, value: S) {
55 if !self.should_record(glean) {
56 return;
57 }
58
59 let value = value.into();
60
61 if let Ok(uuid) = uuid::Uuid::parse_str(&value) {
62 let value = Metric::Uuid(uuid.as_hyphenated().to_string());
63 glean.storage().record(glean, &self.meta, &value)
64 } else {
65 let msg = format!("Unexpected UUID value '{}'", value);
66 record_error(glean, &self.meta, ErrorType::InvalidValue, msg, None);
67 }
68 }
69
70 #[doc(hidden)]
80 pub fn set_from_uuid_sync(&self, glean: &Glean, value: Uuid) {
81 self.set_sync(glean, value.to_string())
82 }
83
84 pub fn generate_and_set(&self) -> String {
88 let uuid = Uuid::new_v4();
89
90 let value = uuid.to_string();
91 let metric = self.clone();
92 crate::launch_with_glean(move |glean| metric.set_sync(glean, value));
93
94 uuid.to_string()
95 }
96
97 #[doc(hidden)]
99 pub fn generate_and_set_sync(&self, storage: &Glean) -> Uuid {
100 let uuid = Uuid::new_v4();
101 self.set_sync(storage, uuid.to_string());
102 uuid
103 }
104
105 #[doc(hidden)]
107 pub fn get_value<'a, S: Into<Option<&'a str>>>(
108 &self,
109 glean: &Glean,
110 ping_name: S,
111 ) -> Option<Uuid> {
112 let queried_ping_name = ping_name
113 .into()
114 .unwrap_or_else(|| &self.meta().inner.send_in_pings[0]);
115
116 match glean.storage().get_metric(self.meta(), queried_ping_name) {
117 Some(Metric::Uuid(uuid)) => Uuid::parse_str(&uuid).ok(),
118 _ => None,
119 }
120 }
121
122 pub fn test_get_num_recorded_errors(&self, error: ErrorType) -> i32 {
134 crate::block_on_dispatcher();
135
136 crate::core::with_glean(|glean| {
137 test_get_num_recorded_errors(glean, self.meta(), error).unwrap_or(0)
138 })
139 }
140}
141
142impl TestGetValue for UuidMetric {
143 type Output = String;
144
145 fn test_get_value(&self, ping_name: Option<String>) -> Option<String> {
160 crate::block_on_dispatcher();
161 crate::core::with_glean(|glean| {
162 self.get_value(glean, ping_name.as_deref())
163 .map(|uuid| uuid.to_string())
164 })
165 }
166}