glean_core/metrics/
uuid.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5use 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/// An UUID metric.
18///
19/// Stores UUID v4 (randomly generated) values.
20#[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
31// IMPORTANT:
32//
33// When changing this implementation, make sure all the operations are
34// also declared in the related trait in `../traits/`.
35impl UuidMetric {
36    /// Creates a new UUID metric
37    pub fn new(meta: CommonMetricData) -> Self {
38        Self {
39            meta: Arc::new(meta.into()),
40        }
41    }
42
43    /// Sets to the specified value.
44    ///
45    /// # Arguments
46    ///
47    /// * `value` - The [`Uuid`] to set the metric to.
48    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    /// Sets to the specified value synchronously.
54    #[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    /// Sets to the specified value, from a string.
72    ///
73    /// This should only be used from FFI. When calling directly from Rust, it
74    /// is better to use [`set`](UuidMetric::set).
75    ///
76    /// # Arguments
77    ///
78    /// * `glean` - The Glean instance this metric belongs to.
79    /// * `value` - The [`Uuid`] to set the metric to.
80    #[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    /// Generates a new random [`Uuid`] and sets the metric to it.
86    ///
87    /// Returns the generated UUID formatted as a hex string.
88    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    /// Generates a new random [`Uuid`'] and sets the metric to it synchronously.
99    #[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    /// Gets the current-stored value as a string, or None if there is no value.
107    #[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    /// **Exported for test purposes.**
129    ///
130    /// Gets the number of recorded errors for the given metric and error type.
131    ///
132    /// # Arguments
133    ///
134    /// * `error` - The type of error
135    ///
136    /// # Returns
137    ///
138    /// The number of errors reported.
139    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    /// **Test-only API (exported for FFI purposes).**
150    ///
151    /// Gets the currently stored value as a string.
152    ///
153    /// This doesn't clear the stored value.
154    ///
155    /// # Arguments
156    ///
157    /// * `ping_name` - the optional name of the ping to retrieve the metric
158    ///                 for. Defaults to the first value in `send_in_pings`.
159    ///
160    /// # Returns
161    ///
162    /// The stored value or `None` if nothing stored.
163    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}