Debian Codegraph @

third_party/rust/glean/src/private/object.rs

raw
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
5 use std::marker::PhantomData;
6
7 use malloc_size_of::MallocSizeOf;
8
9 use glean_core::metrics::{JsonValue, MetricIdentifier};
10 use glean_core::traits;
11
12 use crate::ErrorType;
13
14 // We need to wrap the glean-core type: otherwise if we try to implement
15 // the trait for the metric in `glean_core::metrics` we hit error[E0117]:
16 // only traits defined in the current crate can be implemented for arbitrary
17 // types.
18
19 /// Developer-facing API for recording object metrics.
20 ///
21 /// Instances of this class type are automatically generated by the parsers
22 /// at build time, allowing developers to record values that were previously
23 /// registered in the metrics.yaml file.
24 #[derive(Clone)]
25 pub struct ObjectMetric<K> {
26 pub(crate) inner: glean_core::metrics::ObjectMetric,
27 object_type: PhantomData<K>,
28 }
29
30 impl<K> MallocSizeOf for ObjectMetric<K> {
31 fn size_of(&self, ops: &mut malloc_size_of::MallocSizeOfOps) -> usize {
32 self.inner.size_of(ops)
33 }
34 }
35
36 impl<'a, K> MetricIdentifier<'a> for ObjectMetric<K> {
37 fn get_identifiers(&'a self) -> (&'a str, &'a str, Option<&'a str>) {
38 self.inner.get_identifiers()
39 }
40 }
41
42 impl<K: traits::ObjectSerialize> ObjectMetric<K> {
43 /// The public constructor used by automatically generated metrics.
44 pub fn new(meta: glean_core::CommonMetricData) -> Self {
45 let inner = glean_core::metrics::ObjectMetric::new(meta);
46 Self {
47 inner,
48 object_type: PhantomData,
49 }
50 }
51
52 /// Sets to the specified structure.
53 ///
54 /// # Arguments
55 ///
56 /// * `object` - the object to set.
57 pub fn set(&self, object: K) {
58 let obj = object
59 .into_serialized_object()
60 .expect("failed to serialize object. This should be impossible.");
61 self.inner.set(obj);
62 }
63
64 /// Sets to the specified structure.
65 ///
66 /// Parses the passed JSON string.
67 /// If it can't be parsed into a valid object it records an invalid value error.
68 ///
69 /// # Arguments
70 ///
71 /// * `object` - JSON representation of the object to set.
72 pub fn set_string(&self, object: String) {
73 let data = match K::from_str(&object) {
74 Ok(data) => data,
75 Err(_) => {
76 self.inner.record_schema_error();
77 return;
78 }
79 };
80 self.set(data)
81 }
82
83 /// **Test-only API (exported for FFI purposes).**
84 ///
85 /// Gets the currently stored value as JSON-encoded string.
86 ///
87 /// This doesn't clear the stored value.
88 pub fn test_get_value<'a, S: Into<Option<&'a str>>>(&self, ping_name: S) -> Option<JsonValue> {
89 let ping_name = ping_name.into().map(|s| s.to_string());
90 self.inner.test_get_value(ping_name)
91 }
92
93 /// **Exported for test purposes.**
94 ///
95 /// Gets the number of recorded errors for the given metric and error type.
96 ///
97 /// # Arguments
98 ///
99 /// * `error` - The type of error
100 ///
101 /// # Returns
102 ///
103 /// The number of errors reported.
104 pub fn test_get_num_recorded_errors(&self, error: ErrorType) -> i32 {
105 self.inner.test_get_num_recorded_errors(error)
106 }
107 }
108
109 #[cfg(test)]
110 mod test {
111 use super::*;
112 use crate::common_test::{lock_test, new_glean};
113 use crate::CommonMetricData;
114
115 use serde_json::json;
116
117 #[test]
118 fn simple_array() {
119 let _lock = lock_test();
120 let _t = new_glean(None, true);
121
122 type SimpleArray = Vec<i64>;
123
124 let metric: ObjectMetric<SimpleArray> = ObjectMetric::new(CommonMetricData {
125 name: "object".into(),
126 category: "test".into(),
127 send_in_pings: vec!["store1".into()],
128 ..Default::default()
129 });
130
131 let arr = SimpleArray::from([1, 2, 3]);
132 metric.set(arr);
133
134 let data = metric.test_get_value(None).expect("no object recorded");
135 let expected = json!([1, 2, 3]);
136 assert_eq!(expected, data);
137 }
138
139 #[test]
140 fn complex_nested_object() {
141 let _lock = lock_test();
142 let _t = new_glean(None, true);
143
144 type BalloonsObject = Vec<BalloonsObjectItem>;
145
146 #[derive(
147 Debug, Hash, Eq, PartialEq, traits::__serde::Deserialize, traits::__serde::Serialize,
148 )]
149 #[serde(crate = "traits::__serde")]
150 #[serde(deny_unknown_fields)]
151 struct BalloonsObjectItem {
152 #[serde(skip_serializing_if = "Option::is_none")]
153 colour: Option<String>,
154 #[serde(skip_serializing_if = "Option::is_none")]
155 diameter: Option<i64>,
156 }
157
158 let metric: ObjectMetric<BalloonsObject> = ObjectMetric::new(CommonMetricData {
159 name: "object".into(),
160 category: "test".into(),
161 send_in_pings: vec!["store1".into()],
162 ..Default::default()
163 });
164
165 let balloons = BalloonsObject::from([
166 BalloonsObjectItem {
167 colour: Some("red".to_string()),
168 diameter: Some(5),
169 },
170 BalloonsObjectItem {
171 colour: Some("green".to_string()),
172 diameter: None,
173 },
174 ]);
175 metric.set(balloons);
176
177 let data = metric.test_get_value(None).expect("no object recorded");
178 let expected = json!([
179 { "colour": "red", "diameter": 5 },
180 { "colour": "green" },
181 ]);
182 assert_eq!(expected, data);
183 }
184
185 #[test]
186 fn set_string_api() {
187 let _lock = lock_test();
188 let _t = new_glean(None, true);
189
190 type SimpleArray = Vec<i64>;
191
192 let metric: ObjectMetric<SimpleArray> = ObjectMetric::new(CommonMetricData {
193 name: "object".into(),
194 category: "test".into(),
195 send_in_pings: vec!["store1".into()],
196 ..Default::default()
197 });
198
199 let arr_str = String::from("[1, 2, 3]");
200 metric.set_string(arr_str);
201
202 let data = metric.test_get_value(None).expect("no object recorded");
203 let expected = json!([1, 2, 3]);
204 assert_eq!(expected, data);
205 }
206
207 #[test]
208 fn set_string_api_complex() {
209 let _lock = lock_test();
210 let _t = new_glean(None, true);
211
212 #[derive(
213 Debug, Hash, Eq, PartialEq, traits::__serde::Deserialize, traits::__serde::Serialize,
214 )]
215 #[serde(crate = "traits::__serde")]
216 #[serde(deny_unknown_fields)]
217 struct StackTrace {
218 #[serde(skip_serializing_if = "Option::is_none")]
219 error: Option<String>,
220 #[serde(
221 skip_serializing_if = "Vec::is_empty",
222 default = "Vec::new",
223 deserialize_with = "traits::__serde_helper::vec_null"
224 )]
225 modules: Vec<String>,
226 #[serde(skip_serializing_if = "Option::is_none")]
227 thread_info: Option<StackTraceThreadInfo>,
228 }
229
230 #[derive(
231 Debug, Hash, Eq, PartialEq, traits::__serde::Serialize, traits::__serde::Deserialize,
232 )]
233 #[serde(crate = "traits::__serde")]
234 #[serde(deny_unknown_fields)]
235 struct StackTraceThreadInfo {
236 base_address: Option<String>,
237 }
238
239 let metric: ObjectMetric<StackTrace> = ObjectMetric::new(CommonMetricData {
240 name: "object".into(),
241 category: "test".into(),
242 send_in_pings: vec!["store1".into()],
243 ..Default::default()
244 });
245
246 let arr_str = json!({
247 "error": "error",
248 "modules": null,
249 "thread_info": null,
250 })
251 .to_string();
252 metric.set_string(arr_str);
253
254 let data = metric.test_get_value(None).expect("no object recorded");
255 let expected = json!({
256 "error": "error"
257 });
258 assert_eq!(expected, data);
259 assert_eq!(
260 0,
261 metric.test_get_num_recorded_errors(ErrorType::InvalidValue)
262 );
263 }
264 }