Skip to main content

glean_core/metrics/
object.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 crate::common_metric_data::CommonMetricDataInternal;
8use crate::error_recording::{record_error, test_get_num_recorded_errors, ErrorType};
9use crate::metrics::JsonValue;
10use crate::metrics::Metric;
11use crate::metrics::MetricType;
12use crate::Glean;
13use crate::{CommonMetricData, TestGetValue};
14
15/// An object metric.
16///
17/// Record structured data.
18/// The value must adhere to a predefined structure and is serialized into JSON.
19#[derive(Clone, Debug)]
20pub struct ObjectMetric {
21    meta: Arc<CommonMetricDataInternal>,
22}
23
24impl MetricType for ObjectMetric {
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 ObjectMetric {
35    /// Creates a new object metric.
36    pub fn new(meta: CommonMetricData) -> Self {
37        Self {
38            meta: Arc::new(meta.into()),
39        }
40    }
41
42    /// Sets to the specified structure.
43    ///
44    /// # Arguments
45    ///
46    /// * `glean` - the Glean instance this metric belongs to.
47    /// * `value` - the value to set.
48    #[doc(hidden)]
49    pub fn set_sync(&self, glean: &Glean, value: JsonValue) {
50        if !self.should_record(glean) {
51            return;
52        }
53
54        let value = Metric::Object(serde_json::to_string(&value).unwrap());
55        glean.storage().record(glean, &self.meta, &value)
56    }
57
58    /// Sets to the specified structure.
59    ///
60    /// No additional verification is done.
61    /// The shape needs to be externally verified.
62    ///
63    /// # Arguments
64    ///
65    /// * `value` - the value to set.
66    pub fn set(&self, value: JsonValue) {
67        let metric = self.clone();
68        crate::launch_with_glean(move |glean| metric.set_sync(glean, value))
69    }
70
71    /// Sets to the specified structure.
72    ///
73    /// Parses the passed JSON string.
74    /// If it can't be parsed into a valid object it records an invalid value error.
75    ///
76    /// Note: This does not check the structure. This needs to be done by the wrapper.
77    ///
78    /// # Arguments
79    ///
80    /// * `object` - JSON representation of the object to set.
81    pub fn set_string(&self, object: String) {
82        let metric = self.clone();
83        crate::launch_with_glean(move |glean| {
84            let object = match serde_json::from_str(&object) {
85                Ok(object) => object,
86                Err(_) => {
87                    let msg = "Value did not match predefined schema";
88                    record_error(glean, &metric.meta, ErrorType::InvalidValue, msg, None);
89                    return;
90                }
91            };
92            metric.set_sync(glean, object)
93        })
94    }
95
96    /// Record an `InvalidValue` error for this metric.
97    ///
98    /// Only to be used by the RLB.
99    // TODO(bug 1691073): This can probably go once we have a more generic mechanism to record
100    // errors
101    pub fn record_schema_error(&self) {
102        let metric = self.clone();
103        crate::launch_with_glean(move |glean| {
104            let msg = "Value did not match predefined schema";
105            record_error(glean, &metric.meta, ErrorType::InvalidValue, msg, None);
106        });
107    }
108
109    /// Get current value
110    #[doc(hidden)]
111    pub fn get_value<'a, S: Into<Option<&'a str>>>(
112        &self,
113        glean: &Glean,
114        ping_name: S,
115    ) -> Option<String> {
116        let queried_ping_name = ping_name
117            .into()
118            .unwrap_or_else(|| &self.meta().inner.send_in_pings[0]);
119
120        match glean.storage().get_metric(self.meta(), queried_ping_name) {
121            Some(Metric::Object(o)) => Some(o),
122            _ => None,
123        }
124    }
125
126    /// **Exported for test purposes.**
127    ///
128    /// Gets the number of recorded errors for the given metric and error type.
129    ///
130    /// # Arguments
131    ///
132    /// * `error` - The type of error
133    /// * `ping_name` - represents the optional name of the ping to retrieve the
134    ///   metric for. inner to the first value in `send_in_pings`.
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 for ObjectMetric {
149    type Output = JsonValue;
150
151    /// **Test-only API (exported for FFI purposes).**
152    ///
153    /// Gets the currently stored value as JSON.
154    ///
155    /// This doesn't clear the stored value.
156    fn test_get_value(&self, ping_name: Option<String>) -> Option<JsonValue> {
157        crate::block_on_dispatcher();
158        let value = crate::core::with_glean(|glean| self.get_value(glean, ping_name.as_deref()));
159        // We only store valid JSON
160        value.map(|val| serde_json::from_str(&val).unwrap())
161    }
162}