1use std::cmp::Ordering;
5use std::collections::{HashMap, HashSet};
6use std::fmt::{Display, Formatter};
7use std::sync::{Arc, Mutex, MutexGuard};
8
9use serde_derive::{Deserialize, Serialize};
10use serde_json::Value;
11
12use crate::enrollment::{EnrollmentStatus, ExperimentEnrollment, PreviousGeckoPrefState};
13use crate::error::Result;
14use crate::json::PrefValue;
15use crate::{EnrolledExperiment, Experiment, NimbusError};
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#[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 fn get_prefs_with_state(&self) -> MapOfFeatureIdToPropertyNameToGeckoPrefState;
131
132 fn set_gecko_prefs_state(&self, new_prefs_state: Vec<GeckoPrefState>);
134
135 fn set_gecko_prefs_original_values(&self, original_gecko_prefs: Vec<OriginalGeckoPref>);
137}
138
139#[derive(Default)]
140pub struct GeckoPrefStoreState {
141 pub gecko_prefs_with_state: MapOfFeatureIdToPropertyNameToGeckoPrefState,
142}
143
144impl GeckoPrefStoreState {
145 pub fn update_pref_state(&mut self, new_pref_state: &GeckoPrefState) -> bool {
146 self.gecko_prefs_with_state
147 .iter_mut()
148 .find_map(|(_, props)| {
149 props.iter_mut().find_map(|(_, pref_state)| {
150 if pref_state.gecko_pref.pref == new_pref_state.gecko_pref.pref {
151 *pref_state = new_pref_state.clone();
152 Some(true)
153 } else {
154 None
155 }
156 })
157 })
158 .is_some()
159 }
160}
161
162pub struct GeckoPrefStore {
163 pub handler: Arc<Box<dyn GeckoPrefHandler>>,
165 pub state: Mutex<GeckoPrefStoreState>,
166}
167
168impl GeckoPrefStore {
169 pub fn new(handler: Arc<Box<dyn GeckoPrefHandler>>) -> Self {
170 Self {
171 handler,
172 state: Mutex::new(GeckoPrefStoreState::default()),
173 }
174 }
175
176 pub fn initialize(&self) -> Result<()> {
177 let prefs = self.handler.get_prefs_with_state();
178 let mut state = self
179 .state
180 .lock()
181 .expect("Unable to lock GeckoPrefStore state");
182 state.gecko_prefs_with_state = prefs;
183
184 Ok(())
185 }
186
187 pub fn get_mutable_pref_state(&self) -> MutexGuard<'_, GeckoPrefStoreState> {
188 self.state
189 .lock()
190 .expect("Unable to lock GeckoPrefStore state")
191 }
192
193 pub fn pref_is_user_set(&self, pref: &str) -> bool {
194 let state = self.get_mutable_pref_state();
195 state
196 .gecko_prefs_with_state
197 .iter()
198 .find_map(|(_, props)| {
199 props.iter().find_map(|(_, gecko_pref_state)| {
200 if gecko_pref_state.gecko_pref.pref == pref {
201 Some(gecko_pref_state.is_user_set)
202 } else {
203 None
204 }
205 })
206 })
207 .unwrap_or(false)
208 }
209
210 pub fn map_gecko_prefs_to_enrollment_slugs_and_update_store(
217 &self,
218 experiments: &[Experiment],
220 enrollments: &[ExperimentEnrollment],
222 experiments_by_slug: &HashMap<String, EnrolledExperiment>,
224 update_gecko_prefs: bool,
226 ) -> HashMap<String, HashSet<String>> {
227 struct RecipeData<'a> {
228 experiment: &'a Experiment,
229 experiment_enrollment: &'a ExperimentEnrollment,
230 branch_slug: &'a str,
231 }
232
233 let mut state = self.get_mutable_pref_state();
234
235 let mut recipe_data: Vec<RecipeData> = vec![];
239
240 for experiment_enrollment in enrollments {
241 let experiment = match experiments
242 .iter()
243 .find(|experiment| experiment.slug == experiment_enrollment.slug)
244 {
245 Some(exp) => exp,
246 None => continue,
247 };
248 recipe_data.push(RecipeData {
249 experiment,
250 experiment_enrollment,
251 branch_slug: match experiments_by_slug.get(&experiment.slug) {
252 Some(ee) => &ee.branch_slug,
253 None => continue,
254 },
255 });
256 }
257 recipe_data.sort_by(
259 |a, b| match (a.experiment.is_rollout, b.experiment.is_rollout) {
260 (true, false) => Ordering::Less,
261 (false, true) => Ordering::Greater,
262 _ => Ordering::Equal,
263 },
264 );
265
266 let mut results: HashMap<String, HashSet<String>> = HashMap::new();
273
274 for (feature_name, props) in state.gecko_prefs_with_state.iter_mut() {
275 let mut has_matching_recipes = false;
276 for RecipeData {
277 experiment:
278 Experiment {
279 slug,
280 feature_ids,
281 branches,
282 ..
283 },
284 experiment_enrollment,
285 branch_slug,
286 } in &recipe_data
287 {
288 if feature_ids.contains(feature_name)
289 && matches!(
290 experiment_enrollment.status,
291 EnrollmentStatus::Enrolled { .. }
292 )
293 {
294 let branch = match branches.iter().find(|branch| &branch.slug == branch_slug) {
295 Some(b) => b,
296 None => continue,
297 };
298 has_matching_recipes = true;
299 for (feature, prop_name, prop_value) in branch.get_feature_props_and_values() {
300 if feature == *feature_name && props.contains_key(&prop_name) {
301 props.entry(prop_name.clone()).and_modify(|pref_state| {
307 pref_state.enrollment_value = Some(PrefEnrollmentData {
308 experiment_slug: slug.clone(),
309 pref_value: prop_value.clone(),
310 feature_id: feature,
311 variable: prop_name,
312 });
313 results
314 .entry(pref_state.gecko_pref.pref.clone())
315 .or_default()
316 .insert(slug.clone());
317 });
318 }
319 }
320 }
321 }
322
323 if !has_matching_recipes {
324 for (_, pref_state) in props.iter_mut() {
325 pref_state.enrollment_value = None;
326 }
327 }
328 }
329
330 if update_gecko_prefs {
332 let mut set_state_list = Vec::new();
334 state.gecko_prefs_with_state.iter().for_each(|(_, props)| {
335 props.iter().for_each(|(_, pref_state)| {
336 if pref_state.enrollment_value.is_some() {
337 set_state_list.push(pref_state.clone());
338 }
339 });
340 });
341 self.handler.set_gecko_prefs_state(set_state_list);
343 }
344
345 results
346 }
347}
348
349pub fn query_gecko_pref_store(
350 gecko_pref_store: Option<Arc<GeckoPrefStore>>,
351 args: &[Value],
352) -> Result<Value> {
353 if args.len() != 1 {
354 return Err(NimbusError::TransformParameterError(
355 "gecko_pref transform preferenceIsUserSet requires exactly 1 parameter".into(),
356 ));
357 }
358
359 let gecko_pref = match serde_json::from_value::<String>(args.first().unwrap().clone()) {
360 Ok(v) => v,
361 Err(e) => return Err(NimbusError::JSONError("gecko_pref = nimbus::stateful::gecko_prefs::query_gecko_prefs_store::serde_json::from_value".into(), e.to_string()))
362 };
363
364 Ok(gecko_pref_store
365 .map(|store| Value::Bool(store.pref_is_user_set(&gecko_pref)))
366 .unwrap_or(Value::Bool(false)))
367}
368
369pub(crate) type MapOfExperimentSlugToPreviousState = HashMap<String, Vec<PreviousGeckoPrefState>>;
370pub(crate) fn build_prev_gecko_pref_states(
371 states: &[GeckoPrefState],
372) -> MapOfExperimentSlugToPreviousState {
373 let mut original_gecko_states = MapOfExperimentSlugToPreviousState::new();
374 for state in states {
375 let Some(enrollment_value) = &state.enrollment_value else {
376 continue;
377 };
378 original_gecko_states
379 .entry(enrollment_value.experiment_slug.clone())
380 .or_default()
381 .push(PreviousGeckoPrefState {
382 original_value: state.into(),
383 feature_id: enrollment_value.feature_id.clone(),
384 variable: enrollment_value.variable.clone(),
385 });
386 }
387 original_gecko_states
388}