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::CommonMetricData;
15use crate::Glean;
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 {
87 let uuid = Uuid::new_v4();
88
89 let value = uuid.to_string();
90 let metric = self.clone();
91 crate::launch_with_glean(move |glean| metric.set_sync(glean, value));
92
93 uuid.to_string()
94 }
95
96 #[doc(hidden)]
98 pub fn generate_and_set_sync(&self, storage: &Glean) -> Uuid {
99 let uuid = Uuid::new_v4();
100 self.set_sync(storage, uuid.to_string());
101 uuid
102 }
103
104 #[doc(hidden)]
106 pub fn get_value<'a, S: Into<Option<&'a str>>>(
107 &self,
108 glean: &Glean,
109 ping_name: S,
110 ) -> Option<Uuid> {
111 let queried_ping_name = ping_name
112 .into()
113 .unwrap_or_else(|| &self.meta().inner.send_in_pings[0]);
114
115 match StorageManager.snapshot_metric_for_test(
116 glean.storage(),
117 queried_ping_name,
118 &self.meta.identifier(glean),
119 self.meta.inner.lifetime,
120 ) {
121 Some(Metric::Uuid(uuid)) => Uuid::parse_str(&uuid).ok(),
122 _ => None,
123 }
124 }
125
126 pub fn test_get_value(&self, ping_name: Option<String>) -> Option<String> {
141 crate::block_on_dispatcher();
142 crate::core::with_glean(|glean| {
143 self.get_value(glean, ping_name.as_deref())
144 .map(|uuid| uuid.to_string())
145 })
146 }
147
148 pub fn test_get_num_recorded_errors(&self, error: ErrorType) -> i32 {
160 crate::block_on_dispatcher();
161
162 crate::core::with_glean(|glean| {
163 test_get_num_recorded_errors(glean, self.meta(), error).unwrap_or(0)
164 })
165 }
166}