nimbus/stateful/
gecko_prefs.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/. */
4use crate::{
5    enrollment::{EnrollmentStatus, ExperimentEnrollment, PreviousGeckoPrefState},
6    error::Result,
7    json::PrefValue,
8    EnrolledExperiment, Experiment, NimbusError,
9};
10use serde_derive::{Deserialize, Serialize};
11use serde_json::Value;
12use std::cmp::Ordering;
13use std::collections::{HashMap, HashSet};
14use std::fmt::{Display, Formatter};
15use std::sync::{Arc, Mutex, MutexGuard};
16
17#[derive(Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq, Copy)]
18#[serde(rename_all = "lowercase")]
19pub enum PrefBranch {
20    Default,
21    User,
22}
23
24impl Display for PrefBranch {
25    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
26        match self {
27            PrefBranch::Default => f.write_str("default"),
28            PrefBranch::User => f.write_str("user"),
29        }
30    }
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct GeckoPref {
35    pub pref: String,
36    pub branch: PrefBranch,
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct PrefEnrollmentData {
41    pub experiment_slug: String,
42    pub pref_value: PrefValue,
43    pub feature_id: String,
44    pub variable: String,
45}
46
47#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct GeckoPrefState {
49    pub gecko_pref: GeckoPref,
50    pub gecko_value: Option<PrefValue>,
51    pub enrollment_value: Option<PrefEnrollmentData>,
52    pub is_user_set: bool,
53}
54
55impl GeckoPrefState {
56    pub fn new(pref: &str, branch: Option<PrefBranch>) -> Self {
57        Self {
58            gecko_pref: GeckoPref {
59                pref: pref.into(),
60                branch: branch.unwrap_or(PrefBranch::Default),
61            },
62            gecko_value: None,
63            enrollment_value: None,
64            is_user_set: false,
65        }
66    }
67
68    pub fn with_gecko_value(mut self, value: PrefValue) -> Self {
69        self.gecko_value = Some(value);
70        self
71    }
72
73    pub fn with_enrollment_value(mut self, pref_enrollment_data: PrefEnrollmentData) -> Self {
74        self.enrollment_value = Some(pref_enrollment_data);
75        self
76    }
77
78    pub fn set_by_user(mut self) -> Self {
79        self.is_user_set = true;
80        self
81    }
82}
83
84#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq, Copy)]
85pub enum PrefUnenrollReason {
86    Changed,
87    FailedToSet,
88}
89
90// The pre-experiment original state of a Gecko pref. Values may be used to set on Gecko to restore the pref to the original state.
91// ⚠️ Attention : Changes to this type should be accompanied by a new test  ⚠️
92// ⚠️ in `src/stateful/tests/test_enrollment_bw_compat.rs` below, and may require a DB migration. ⚠️
93#[derive(Deserialize, Serialize, Debug, Clone, Hash, Eq, PartialEq)]
94pub struct OriginalGeckoPref {
95    pub pref: String,
96    pub branch: PrefBranch,
97    pub value: Option<PrefValue>,
98}
99
100impl<'a> From<&'a GeckoPrefState> for OriginalGeckoPref {
101    fn from(state: &'a GeckoPrefState) -> Self {
102        Self {
103            pref: state.gecko_pref.pref.clone(),
104            branch: state.gecko_pref.branch,
105            value: state.gecko_value.clone(),
106        }
107    }
108}
109
110pub type MapOfFeatureIdToPropertyNameToGeckoPrefState =
111    HashMap<String, HashMap<String, GeckoPrefState>>;
112
113pub fn create_feature_prop_pref_map(
114    list: Vec<(&str, &str, GeckoPrefState)>,
115) -> MapOfFeatureIdToPropertyNameToGeckoPrefState {
116    list.iter().fold(
117        HashMap::new(),
118        |mut feature_map, (feature_id, prop_name, pref_state)| {
119            feature_map
120                .entry(feature_id.to_string())
121                .or_default()
122                .insert(prop_name.to_string(), pref_state.clone());
123            feature_map
124        },
125    )
126}
127
128pub trait GeckoPrefHandler: Send + Sync {
129    /// Used to obtain the prefs values from Gecko
130    fn get_prefs_with_state(&self) -> MapOfFeatureIdToPropertyNameToGeckoPrefState;
131
132    /// Used to set the state for each pref based on enrollments
133    fn set_gecko_prefs_state(&self, new_prefs_state: Vec<GeckoPrefState>);
134}
135
136#[derive(Default)]
137pub struct GeckoPrefStoreState {
138    pub gecko_prefs_with_state: MapOfFeatureIdToPropertyNameToGeckoPrefState,
139}
140
141impl GeckoPrefStoreState {
142    pub fn update_pref_state(&mut self, new_pref_state: &GeckoPrefState) -> bool {
143        self.gecko_prefs_with_state
144            .iter_mut()
145            .find_map(|(_, props)| {
146                props.iter_mut().find_map(|(_, pref_state)| {
147                    if pref_state.gecko_pref.pref == new_pref_state.gecko_pref.pref {
148                        *pref_state = new_pref_state.clone();
149                        Some(true)
150                    } else {
151                        None
152                    }
153                })
154            })
155            .is_some()
156    }
157}
158
159pub struct GeckoPrefStore {
160    // This is Arc<Box<_>> because of FFI
161    pub handler: Arc<Box<dyn GeckoPrefHandler>>,
162    pub state: Mutex<GeckoPrefStoreState>,
163}
164
165impl GeckoPrefStore {
166    pub fn new(handler: Arc<Box<dyn GeckoPrefHandler>>) -> Self {
167        Self {
168            handler,
169            state: Mutex::new(GeckoPrefStoreState::default()),
170        }
171    }
172
173    pub fn initialize(&self) -> Result<()> {
174        let prefs = self.handler.get_prefs_with_state();
175        let mut state = self
176            .state
177            .lock()
178            .expect("Unable to lock GeckoPrefStore state");
179        state.gecko_prefs_with_state = prefs;
180
181        Ok(())
182    }
183
184    pub fn get_mutable_pref_state(&self) -> MutexGuard<'_, GeckoPrefStoreState> {
185        self.state
186            .lock()
187            .expect("Unable to lock GeckoPrefStore state")
188    }
189
190    pub fn pref_is_user_set(&self, pref: &str) -> bool {
191        let state = self.get_mutable_pref_state();
192        state
193            .gecko_prefs_with_state
194            .iter()
195            .find_map(|(_, props)| {
196                props.iter().find_map(|(_, gecko_pref_state)| {
197                    if gecko_pref_state.gecko_pref.pref == pref {
198                        Some(gecko_pref_state.is_user_set)
199                    } else {
200                        None
201                    }
202                })
203            })
204            .unwrap_or(false)
205    }
206
207    /// This method accomplishes a number of tasks important to the Gecko pref enrollment workflow.
208    /// 1. It returns a map of pref string to a vector of enrolled recipes in which the value for
209    ///    the enrolled branch's feature values includes the property of that feature that sets the
210    ///    aforementioned pref.
211    /// 2. It updates the GeckoPrefStore state, such that the appropriate GeckoPrefState's
212    ///    `enrollment_value` reflects the appropriate value.
213    pub fn map_gecko_prefs_to_enrollment_slugs_and_update_store(
214        &self,
215        // contains full experiment metadata
216        experiments: &[Experiment],
217        // contains enrollment status for a given experiment
218        enrollments: &[ExperimentEnrollment],
219        // contains slug of enrolled branch
220        experiments_by_slug: &HashMap<String, EnrolledExperiment>,
221    ) -> HashMap<String, HashSet<String>> {
222        struct RecipeData<'a> {
223            experiment: &'a Experiment,
224            experiment_enrollment: &'a ExperimentEnrollment,
225            branch_slug: &'a str,
226        }
227
228        let mut state = self.get_mutable_pref_state();
229
230        /* List of tuples that contain recipe slug, rollout bool, list of feature ids, and
231         * branch, in that order.
232         */
233        let mut recipe_data: Vec<RecipeData> = vec![];
234
235        for experiment_enrollment in enrollments {
236            let experiment = match experiments
237                .iter()
238                .find(|experiment| experiment.slug == experiment_enrollment.slug)
239            {
240                Some(exp) => exp,
241                None => continue,
242            };
243            recipe_data.push(RecipeData {
244                experiment,
245                experiment_enrollment,
246                branch_slug: match experiments_by_slug.get(&experiment.slug) {
247                    Some(ee) => &ee.branch_slug,
248                    None => continue,
249                },
250            });
251        }
252        // sort `recipe_data` such that rollouts are applied before experiments
253        recipe_data.sort_by(
254            |a, b| match (a.experiment.is_rollout, b.experiment.is_rollout) {
255                (true, false) => Ordering::Less,
256                (false, true) => Ordering::Greater,
257                _ => Ordering::Equal,
258            },
259        );
260
261        /* This map will ultimately be returned from the function, as a map of pref strings to
262         * relevant enrolled recipe slugs, 'relevant' meaning experiments whose enrolled branch
263         * values apply a value to a prop for which there is a Gecko pref.
264         *
265         * We start by iterating mutably over the map of features to props to gecko prefs.
266         */
267        let mut results: HashMap<String, HashSet<String>> = HashMap::new();
268
269        for (feature_name, props) in state.gecko_prefs_with_state.iter_mut() {
270            let mut has_matching_recipes = false;
271            for RecipeData {
272                experiment:
273                    Experiment {
274                        slug,
275                        feature_ids,
276                        branches,
277                        ..
278                    },
279                experiment_enrollment,
280                branch_slug,
281            } in &recipe_data
282            {
283                if feature_ids.contains(feature_name)
284                    && matches!(
285                        experiment_enrollment.status,
286                        EnrollmentStatus::Enrolled { .. }
287                    )
288                {
289                    let branch = match branches.iter().find(|branch| &branch.slug == branch_slug) {
290                        Some(b) => b,
291                        None => continue,
292                    };
293                    has_matching_recipes = true;
294                    for (feature, prop_name, prop_value) in branch.get_feature_props_and_values() {
295                        if feature == *feature_name && props.contains_key(&prop_name) {
296                            // set the enrollment_value for this gecko pref.
297                            // rollouts and experiments on the same feature will
298                            // both set the value here, but rollouts will happen
299                            // first, and will therefore be overridden by
300                            // experiments.
301                            props.entry(prop_name.clone()).and_modify(|pref_state| {
302                                pref_state.enrollment_value = Some(PrefEnrollmentData {
303                                    experiment_slug: slug.clone(),
304                                    pref_value: prop_value.clone(),
305                                    feature_id: feature,
306                                    variable: prop_name,
307                                });
308                                results
309                                    .entry(pref_state.gecko_pref.pref.clone())
310                                    .or_default()
311                                    .insert(slug.clone());
312                            });
313                        }
314                    }
315                }
316            }
317
318            if !has_matching_recipes {
319                for (_, pref_state) in props.iter_mut() {
320                    pref_state.enrollment_value = None;
321                }
322            }
323        }
324
325        // obtain a list of all Gecko pref states for which there is an enrollment value
326        let mut set_state_list = Vec::new();
327        state.gecko_prefs_with_state.iter().for_each(|(_, props)| {
328            props.iter().for_each(|(_, pref_state)| {
329                if pref_state.enrollment_value.is_some() {
330                    set_state_list.push(pref_state.clone());
331                }
332            });
333        });
334        // tell the handler to set the aforementioned Gecko prefs
335        self.handler.set_gecko_prefs_state(set_state_list);
336
337        results
338    }
339}
340
341pub fn query_gecko_pref_store(
342    gecko_pref_store: Option<Arc<GeckoPrefStore>>,
343    args: &[Value],
344) -> Result<Value> {
345    if args.len() != 1 {
346        return Err(NimbusError::TransformParameterError(
347            "gecko_pref transform preferenceIsUserSet requires exactly 1 parameter".into(),
348        ));
349    }
350
351    let gecko_pref = match serde_json::from_value::<String>(args.first().unwrap().clone()) {
352        Ok(v) => v,
353        Err(e) => return Err(NimbusError::JSONError("gecko_pref = nimbus::stateful::gecko_prefs::query_gecko_prefs_store::serde_json::from_value".into(), e.to_string()))
354    };
355
356    Ok(gecko_pref_store
357        .map(|store| Value::Bool(store.pref_is_user_set(&gecko_pref)))
358        .unwrap_or(Value::Bool(false)))
359}
360
361pub(crate) type MapOfExperimentSlugToPreviousState = HashMap<String, Vec<PreviousGeckoPrefState>>;
362pub(crate) fn build_prev_gecko_pref_states(
363    states: &[GeckoPrefState],
364) -> MapOfExperimentSlugToPreviousState {
365    let mut original_gecko_states = MapOfExperimentSlugToPreviousState::new();
366    for state in states {
367        let Some(enrollment_value) = &state.enrollment_value else {
368            continue;
369        };
370        original_gecko_states
371            .entry(enrollment_value.experiment_slug.clone())
372            .or_default()
373            .push(PreviousGeckoPrefState {
374                original_value: state.into(),
375                feature_id: enrollment_value.feature_id.clone(),
376                variable: enrollment_value.variable.clone(),
377            });
378    }
379    original_gecko_states
380}