glean_core/metrics/
recorded_experiment.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::collections::HashMap;
6
7use malloc_size_of_derive::MallocSizeOf;
8use serde::{Deserialize, Serialize};
9use serde_json::{json, Map as JsonMap, Value as JsonValue};
10
11/// Deserialized experiment data.
12#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, MallocSizeOf)]
13pub struct RecordedExperiment {
14    /// The experiment's branch as set through [`set_experiment_active`](crate::glean_set_experiment_active).
15    pub branch: String,
16    /// Any extra data associated with this experiment through [`set_experiment_active`](crate::glean_set_experiment_active).
17    /// Note: `Option` required to keep backwards-compatibility.
18    pub extra: Option<HashMap<String, String>>,
19}
20
21impl RecordedExperiment {
22    /// Gets the recorded experiment data as a JSON value.
23    ///
24    /// For JSON, we don't want to include `{"extra": null}` -- we just want to skip
25    /// `extra` entirely. Unfortunately, we can't use a serde field annotation for this,
26    /// since that would break bincode serialization, which doesn't support skipping
27    /// fields. Therefore, we use a custom serialization function just for JSON here.
28    pub fn as_json(&self) -> JsonValue {
29        let mut value = JsonMap::new();
30        value.insert("branch".to_string(), json!(self.branch));
31        if self.extra.is_some() {
32            value.insert("extra".to_string(), json!(self.extra));
33        }
34        JsonValue::Object(value)
35    }
36}