Debian Codegraph @

third_party/rust/glean-core/src/metrics/experiment.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::cmp;
6 use std::collections::HashMap;
7 use std::sync::atomic::AtomicU8;
8
9 use crate::common_metric_data::CommonMetricDataInternal;
10 use crate::error_recording::{record_error, ErrorType};
11 use crate::metrics::{Metric, MetricType, RecordedExperiment};
12 use crate::storage::{StorageManager, INTERNAL_STORAGE};
13 use crate::util::{truncate_string_at_boundary, truncate_string_at_boundary_with_error};
14 use crate::Lifetime;
15 use crate::{CommonMetricData, Glean};
16
17 /// The maximum length of the experiment id, the branch id, and the keys of the
18 /// `extra` map. Identifiers longer than this number of characters are truncated.
19 const MAX_EXPERIMENTS_IDS_LEN: usize = 100;
20 /// The maximum length of the experiment `extra` values. Values longer than this
21 /// limit will be truncated.
22 const MAX_EXPERIMENT_VALUE_LEN: usize = MAX_EXPERIMENTS_IDS_LEN;
23 /// The maximum number of extras allowed in the `extra` hash map. Any items added
24 /// beyond this limit will be dropped. Note that truncation of a hash map is
25 /// nondeterministic in which items are truncated.
26 const MAX_EXPERIMENTS_EXTRAS_SIZE: usize = 20;
27
28 /// An experiment metric.
29 ///
30 /// Used to store active experiments.
31 /// This is used through the `set_experiment_active`/`set_experiment_inactive` Glean SDK API.
32 #[derive(Clone, Debug)]
33 pub struct ExperimentMetric {
34 meta: CommonMetricDataInternal,
35 }
36
37 impl MetricType for ExperimentMetric {
38 fn meta(&self) -> &CommonMetricDataInternal {
39 &self.meta
40 }
41 }
42
43 impl ExperimentMetric {
44 /// Creates a new experiment metric.
45 ///
46 /// # Arguments
47 ///
48 /// * `id` - the id of the experiment. Please note that this will be
49 /// truncated to `MAX_EXPERIMENTS_IDS_LEN`, if needed.
50 ///
51 /// # Implementation note
52 ///
53 /// This runs synchronously and queries the database to record potential errors.
54 pub fn new(glean: &Glean, id: String) -> Self {
55 let mut error = None;
56
57 // Make sure that experiment id is within the expected limit.
58 let truncated_id = if id.len() > MAX_EXPERIMENTS_IDS_LEN {
59 let msg = format!(
60 "Value length {} for experiment id exceeds maximum of {}",
61 id.len(),
62 MAX_EXPERIMENTS_IDS_LEN
63 );
64 error = Some(msg);
65 truncate_string_at_boundary(id, MAX_EXPERIMENTS_IDS_LEN)
66 } else {
67 id
68 };
69
70 let new_experiment = Self {
71 meta: CommonMetricDataInternal {
72 inner: CommonMetricData {
73 name: format!("{}#experiment", truncated_id),
74 // We don't need a category, the name is already unique
75 category: "".into(),
76 send_in_pings: vec![INTERNAL_STORAGE.into()],
77 lifetime: Lifetime::Application,
78 ..Default::default()
79 },
80 disabled: AtomicU8::new(0),
81 },
82 };
83
84 // Check for a truncation error to record
85 if let Some(msg) = error {
86 record_error(
87 glean,
88 &new_experiment.meta,
89 ErrorType::InvalidValue,
90 msg,
91 None,
92 );
93 }
94
95 new_experiment
96 }
97
98 /// Records an experiment as active.
99 ///
100 /// # Arguments
101 ///
102 /// * `glean` - The Glean instance this metric belongs to.
103 /// * `branch` - the active branch of the experiment. Please note that this will be
104 /// truncated to `MAX_EXPERIMENTS_IDS_LEN`, if needed.
105 /// * `extra` - an optional, user defined String to String map used to provide richer
106 /// experiment context if needed.
107 pub fn set_active_sync(&self, glean: &Glean, branch: String, extra: HashMap<String, String>) {
108 if !self.should_record(glean) {
109 return;
110 }
111
112 // Make sure that branch id is within the expected limit.
113 let truncated_branch = if branch.len() > MAX_EXPERIMENTS_IDS_LEN {
114 truncate_string_at_boundary_with_error(
115 glean,
116 &self.meta,
117 branch,
118 MAX_EXPERIMENTS_IDS_LEN,
119 )
120 } else {
121 branch
122 };
123
124 // Apply limits to extras
125 if extra.len() > MAX_EXPERIMENTS_EXTRAS_SIZE {
126 let msg = format!(
127 "Extra hash map length {} exceeds maximum of {}",
128 extra.len(),
129 MAX_EXPERIMENTS_EXTRAS_SIZE
130 );
131 record_error(glean, &self.meta, ErrorType::InvalidValue, msg, None);
132 }
133
134 let mut truncated_extras =
135 HashMap::with_capacity(cmp::min(extra.len(), MAX_EXPERIMENTS_EXTRAS_SIZE));
136 for (key, value) in extra.into_iter().take(MAX_EXPERIMENTS_EXTRAS_SIZE) {
137 let truncated_key = if key.len() > MAX_EXPERIMENTS_IDS_LEN {
138 truncate_string_at_boundary_with_error(
139 glean,
140 &self.meta,
141 key,
142 MAX_EXPERIMENTS_IDS_LEN,
143 )
144 } else {
145 key
146 };
147 let truncated_value = if value.len() > MAX_EXPERIMENT_VALUE_LEN {
148 truncate_string_at_boundary_with_error(
149 glean,
150 &self.meta,
151 value,
152 MAX_EXPERIMENT_VALUE_LEN,
153 )
154 } else {
155 value
156 };
157
158 truncated_extras.insert(truncated_key, truncated_value);
159 }
160 let truncated_extras = if truncated_extras.is_empty() {
161 None
162 } else {
163 Some(truncated_extras)
164 };
165
166 let value = Metric::Experiment(RecordedExperiment {
167 branch: truncated_branch,
168 extra: truncated_extras,
169 });
170 glean.storage().record(glean, &self.meta, &value)
171 }
172
173 /// Records an experiment as inactive.
174 ///
175 /// # Arguments
176 ///
177 /// * `glean` - The Glean instance this metric belongs to.
178 pub fn set_inactive_sync(&self, glean: &Glean) {
179 if !self.should_record(glean) {
180 return;
181 }
182
183 if let Err(e) = glean.storage().remove_single_metric(
184 Lifetime::Application,
185 INTERNAL_STORAGE,
186 &self.meta.inner.name,
187 ) {
188 log::error!("Failed to set experiment as inactive: {:?}", e);
189 }
190 }
191
192 /// **Test-only API (exported for FFI purposes).**
193 ///
194 /// Gets the currently stored experiment data as a JSON representation of
195 /// the RecordedExperiment.
196 ///
197 /// This doesn't clear the stored value.
198 ///
199 /// # Arguments
200 ///
201 /// * `ping_name` - the optional name of the ping to retrieve the metric
202 /// for. Defaults to the first value in `send_in_pings`.
203 ///
204 /// # Returns
205 ///
206 /// The stored value or `None` if nothing stored.
207 pub fn test_get_value(&self, glean: &Glean) -> Option<RecordedExperiment> {
208 match StorageManager.snapshot_metric_for_test(
209 glean.storage(),
210 INTERNAL_STORAGE,
211 &self.meta.identifier(glean),
212 self.meta.inner.lifetime,
213 ) {
214 Some(Metric::Experiment(e)) => Some(e),
215 _ => None,
216 }
217 }
218 }
219
220 #[cfg(test)]
221 mod test {
222 use super::*;
223
224 #[test]
225 fn stable_serialization() {
226 let experiment_empty = RecordedExperiment {
227 branch: "branch".into(),
228 extra: Default::default(),
229 };
230
231 let mut data = HashMap::new();
232 data.insert("a key".to_string(), "a value".to_string());
233 let experiment_data = RecordedExperiment {
234 branch: "branch".into(),
235 extra: Some(data),
236 };
237
238 let experiment_empty_bin = bincode::serialize(&experiment_empty).unwrap();
239 let experiment_data_bin = bincode::serialize(&experiment_data).unwrap();
240
241 assert_eq!(
242 experiment_empty,
243 bincode::deserialize(&experiment_empty_bin).unwrap()
244 );
245 assert_eq!(
246 experiment_data,
247 bincode::deserialize(&experiment_data_bin).unwrap()
248 );
249 }
250
251 #[test]
252 #[rustfmt::skip] // Let's not add newlines unnecessary
253 fn deserialize_old_encoding() {
254 // generated by `bincode::serialize` as of Glean commit ac27fceb7c0d5a7288d7d569e8c5c5399a53afb2
255 // empty was generated from: `RecordedExperiment { branch: "branch".into(), extra: None, }`
256 let empty_bin = vec![6, 0, 0, 0, 0, 0, 0, 0, 98, 114, 97, 110, 99, 104];
257 // data was generated from: RecordedExperiment { branch: "branch".into(), extra: Some({"a key": "a value"}), };
258 let data_bin = vec![6, 0, 0, 0, 0, 0, 0, 0, 98, 114, 97, 110, 99, 104,
259 1, 1, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0,
260 97, 32, 107, 101, 121, 7, 0, 0, 0, 0, 0, 0, 0, 97,
261 32, 118, 97, 108, 117, 101];
262
263
264 let mut data = HashMap::new();
265 data.insert("a key".to_string(), "a value".to_string());
266 let experiment_data = RecordedExperiment { branch: "branch".into(), extra: Some(data), };
267
268 // We can't actually decode old experiment data.
269 // Luckily Glean did store experiments in the database before commit ac27fceb7c0d5a7288d7d569e8c5c5399a53afb2.
270 let experiment_empty: Result<RecordedExperiment, _> = bincode::deserialize(&empty_bin);
271 assert!(experiment_empty.is_err());
272
273 assert_eq!(experiment_data, bincode::deserialize(&data_bin).unwrap());
274 }
275 }