Skip to main content

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::Glean;
14use crate::{CommonMetricData, TestGetValue};
15
16/// An UUID metric.
17///
18/// Stores UUID v4 (randomly generated) values.
19#[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
30// IMPORTANT:
31//
32// When changing this implementation, make sure all the operations are
33// also declared in the related trait in `../traits/`.
34impl UuidMetric {
35    /// Creates a new UUID metric
36    pub fn new(meta: CommonMetricData) -> Self {
37        Self {
38            meta: Arc::new(meta.into()),
39        }
40    }
41
42    /// Sets to the specified value.
43    ///
44    /// # Arguments
45    ///
46    /// * `value` - The [`Uuid`] to set the metric to.
47    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    /// Sets to the specified value synchronously.
53    #[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    /// Sets to the specified value, from a string.
71    ///
72    /// This should only be used from FFI. When calling directly from Rust, it
73    /// is better to use [`set`](UuidMetric::set).
74    ///
75    /// # Arguments
76    ///
77    /// * `glean` - The Glean instance this metric belongs to.
78    /// * `value` - The [`Uuid`] to set the metric to.
79    #[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    /// Generates a new random [`Uuid`] and sets the metric to it.
85    ///
86    /// Returns the generated UUID formatted as a hex string.
87    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    /// Generates a new random [`Uuid`'] and sets the metric to it synchronously.
98    #[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    /// Gets the current-stored value as a string, or None if there is no value.
106    #[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    /// **Exported for test purposes.**
123    ///
124    /// Gets the number of recorded errors for the given metric and error type.
125    ///
126    /// # Arguments
127    ///
128    /// * `error` - The type of error
129    ///
130    /// # Returns
131    ///
132    /// The number of errors reported.
133    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    /// **Test-only API (exported for FFI purposes).**
146    ///
147    /// Gets the currently stored value as a string.
148    ///
149    /// This doesn't clear the stored value.
150    ///
151    /// # Arguments
152    ///
153    /// * `ping_name` - the optional name of the ping to retrieve the metric
154    ///                 for. Defaults to the first value in `send_in_pings`.
155    ///
156    /// # Returns
157    ///
158    /// The stored value or `None` if nothing stored.
159    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}