1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use std::{fmt::Display, path::Path};

use anyhow::Result;
use console::Term;
use serde_json::Value;

use crate::{
    sources::{ExperimentListSource, ExperimentSource},
    value_utils::{self, CliUtils},
};

#[derive(serde::Serialize, Debug, Default)]
pub(crate) struct ExperimentInfo<'a> {
    pub(crate) slug: &'a str,
    pub(crate) app_name: &'a str,
    pub(crate) channel: &'a str,
    pub(crate) branches: Vec<&'a str>,
    pub(crate) features: Vec<&'a str>,
    pub(crate) targeting: &'a str,
    pub(crate) bucketing: u64,
    pub(crate) is_rollout: bool,
    pub(crate) user_facing_name: &'a str,
    pub(crate) user_facing_description: &'a str,
    pub(crate) enrollment: DateRange<'a>,
    pub(crate) is_enrollment_paused: bool,
    pub(crate) duration: DateRange<'a>,
}

impl<'a> ExperimentInfo<'a> {
    pub(crate) fn enrollment(&self) -> &DateRange<'a> {
        &self.enrollment
    }

    pub(crate) fn active(&self) -> &DateRange<'a> {
        &self.duration
    }

    fn bucketing_percent(&self) -> String {
        format!("{: >3.0} %", self.bucketing / 100)
    }
}

#[derive(serde::Serialize, Debug, Default)]
pub(crate) struct DateRange<'a> {
    start: Option<&'a str>,
    end: Option<&'a str>,
    proposed: Option<i64>,
}

impl<'a> DateRange<'a> {
    fn new(start: Option<&'a Value>, end: Option<&'a Value>, duration: Option<&'a Value>) -> Self {
        let start = start.map(Value::as_str).unwrap_or_default();
        let end = end.map(Value::as_str).unwrap_or_default();
        let proposed = duration.map(Value::as_i64).unwrap_or_default();
        Self {
            start,
            end,
            proposed,
        }
    }

    pub(crate) fn contains(&self, date: &str) -> bool {
        let start = self.start.unwrap_or("9999-99-99");
        let end = self.end.unwrap_or("9999-99-99");

        start <= date && date <= end
    }
}

impl Display for DateRange<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match (self.start, self.end, self.proposed) {
            (Some(s), Some(e), _) => f.write_str(&format!("{s} ➞ {e}")),
            (Some(s), _, Some(d)) => f.write_str(&format!("{s}, proposed ending after {d} days")),
            (Some(s), _, _) => f.write_str(&format!("{s} ➞ ?")),
            (None, Some(e), Some(d)) => {
                f.write_str(&format!("ending {e}, started {d} days before"))
            }
            (None, Some(e), _) => f.write_str(&format!("ending {e}")),
            _ => f.write_str("unknown"),
        }
    }
}

impl<'a> TryFrom<&'a Value> for ExperimentInfo<'a> {
    type Error = anyhow::Error;

    fn try_from(exp: &'a Value) -> Result<Self> {
        let features: Vec<_> = exp
            .get_array("featureIds")?
            .iter()
            .flat_map(|f| f.as_str())
            .collect();
        let branches: Vec<_> = exp
            .get_array("branches")?
            .iter()
            .flat_map(|b| {
                b.get("slug")
                    .expect("Expecting a branch with a slug")
                    .as_str()
            })
            .collect();

        let config = exp.get_object("bucketConfig")?;

        Ok(Self {
            slug: exp.get_str("slug")?,
            app_name: exp.get_str("appName")?,
            channel: exp.get_str("channel")?,
            branches,
            features,
            targeting: exp.get_str("targeting")?,
            bucketing: config.get_u64("count")?,
            is_rollout: exp.get_bool("isRollout")?,
            user_facing_name: exp.get_str("userFacingName")?,
            user_facing_description: exp.get_str("userFacingDescription")?,
            enrollment: DateRange::new(
                exp.get("startDate"),
                exp.get("enrollmentEndDate"),
                exp.get("proposedEnrollment"),
            ),
            is_enrollment_paused: exp.get_bool("isEnrollmentPaused")?,
            duration: DateRange::new(
                exp.get("startDate"),
                exp.get("endDate"),
                exp.get("proposedDuration"),
            ),
        })
    }
}

impl ExperimentListSource {
    pub(crate) fn print_list(&self) -> Result<bool> {
        let value: Value = self.try_into()?;
        let array = value_utils::try_extract_data_list(&value)?;

        let term = Term::stdout();
        let style = term.style().italic().underlined();
        term.write_line(&format!(
            "{slug: <66}|{channel: <9}|{bucketing: >7}|{features: <31}|{is_rollout}|{branches: <20}",
            slug = style.apply_to("Experiment slug"),
            channel = style.apply_to(" Channel"),
            bucketing = style.apply_to(" % "),
            features = style.apply_to(" Features"),
            is_rollout = style.apply_to("   "),
            branches = style.apply_to(" Branches"),
        ))?;
        for exp in array {
            let info = match ExperimentInfo::try_from(&exp) {
                Ok(e) => e,
                _ => continue,
            };

            let is_rollout = if info.is_rollout { "R" } else { "" };

            term.write_line(&format!(
                " {slug: <65}| {channel: <8}| {bucketing: >5} | {features: <30}| {is_rollout: <1} | {branches}",
                slug = info.slug,
                channel = info.channel,
                bucketing = info.bucketing_percent(),
                features = info.features.join(", "),
                branches = info.branches.join(", ")
            ))?;
        }
        Ok(true)
    }
}

impl ExperimentSource {
    pub(crate) fn print_info<P>(&self, output: Option<P>) -> Result<bool>
    where
        P: AsRef<Path>,
    {
        let value = self.try_into()?;
        let info: ExperimentInfo = ExperimentInfo::try_from(&value)?;
        if output.is_some() {
            value_utils::write_to_file_or_print(output, &info)?;
            return Ok(true);
        }
        let url = match self {
            Self::FromApiV6 { slug, endpoint } => Some(format!("{endpoint}/nimbus/{slug}/summary")),
            _ => None,
        };
        let term = Term::stdout();
        let t_style = term.style().italic();
        let d_style = term.style().bold().cyan();
        let line = |title: &str, detail: &str| {
            _ = term.write_line(&format!(
                "{: <11} {}",
                t_style.apply_to(title),
                d_style.apply_to(detail)
            ));
        };

        let enrollment = format!(
            "{} ({})",
            info.enrollment,
            if info.is_enrollment_paused {
                "paused"
            } else {
                "enrolling"
            }
        );

        let is_rollout = if info.is_rollout {
            "Rollout".to_string()
        } else {
            let n = info.branches.len();
            let b = if n == 1 {
                "1 branch".to_string()
            } else {
                format!("{n} branches")
            };
            format!("Experiment with {b}")
        };

        line("Slug", info.slug);
        line("Name", info.user_facing_name);
        line("Description", info.user_facing_description);
        if let Some(url) = url {
            line("URL", &url);
        }
        line("App", info.app_name);
        line("Channel", info.channel);
        line("E/R", &is_rollout);
        line("Enrollment", &enrollment);
        line("Observing", &info.duration.to_string());
        line("Targeting", &format!("\"{}\"", info.targeting));
        line("Bucketing", &info.bucketing_percent());
        line("Branches", &info.branches.join(", "));
        line("Features", &info.features.join(", "));

        Ok(true)
    }
}

#[cfg(test)]
mod unit_tests {
    use serde_json::json;

    use super::*;

    impl<'a> DateRange<'a> {
        pub(crate) fn from_str(start: &'a str, end: &'a str, duration: i64) -> Self {
            Self {
                start: Some(start),
                end: Some(end),
                proposed: Some(duration),
            }
        }
    }

    #[test]
    fn test_date_range_to_string() -> Result<()> {
        let from = json!("2023-06-01");
        let to = json!("2023-06-19");
        let null = json!(null);
        let days28 = json!(28);

        let dr = DateRange::new(Some(&null), Some(&null), Some(&null));
        let expected = "unknown".to_string();
        let observed = dr.to_string();
        assert_eq!(expected, observed);

        let dr = DateRange::new(Some(&null), Some(&null), Some(&days28));
        let expected = "unknown".to_string();
        let observed = dr.to_string();
        assert_eq!(expected, observed);

        let dr = DateRange::new(Some(&null), Some(&to), Some(&null));
        let expected = "ending 2023-06-19".to_string();
        let observed = dr.to_string();
        assert_eq!(expected, observed);

        let dr = DateRange::new(Some(&null), Some(&to), Some(&days28));
        let expected = "ending 2023-06-19, started 28 days before".to_string();
        let observed = dr.to_string();
        assert_eq!(expected, observed);

        let dr = DateRange::new(Some(&from), Some(&null), Some(&null));
        let expected = "2023-06-01 ➞ ?".to_string();
        let observed = dr.to_string();
        assert_eq!(expected, observed);

        let dr = DateRange::new(Some(&from), Some(&null), Some(&days28));
        let expected = "2023-06-01, proposed ending after 28 days".to_string();
        let observed = dr.to_string();
        assert_eq!(expected, observed);

        let dr = DateRange::new(Some(&from), Some(&to), Some(&null));
        let expected = "2023-06-01 ➞ 2023-06-19".to_string();
        let observed = dr.to_string();
        assert_eq!(expected, observed);

        let dr = DateRange::new(Some(&from), Some(&to), Some(&days28));
        let expected = "2023-06-01 ➞ 2023-06-19".to_string();
        let observed = dr.to_string();
        assert_eq!(expected, observed);
        Ok(())
    }

    #[test]
    fn test_date_range_contains() -> Result<()> {
        let from = json!("2023-06-01");
        let to = json!("2023-06-19");
        let null = json!(null);

        let before = "2023-05-01";
        let during = "2023-06-03";
        let after = "2023-06-20";

        let dr = DateRange::new(Some(&null), Some(&null), Some(&null));
        assert!(!dr.contains(before));
        assert!(!dr.contains(during));
        assert!(!dr.contains(after));

        let dr = DateRange::new(Some(&null), Some(&to), Some(&null));
        assert!(!dr.contains(before));
        assert!(!dr.contains(during));
        assert!(!dr.contains(after));

        let dr = DateRange::new(Some(&from), Some(&null), Some(&null));
        assert!(!dr.contains(before));
        assert!(dr.contains(during));
        assert!(dr.contains(after));

        let dr = DateRange::new(Some(&from), Some(&to), Some(&null));
        assert!(!dr.contains(before));
        assert!(dr.contains(during));
        assert!(!dr.contains(after));

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_experiment_info() -> Result<()> {
        let exp = ExperimentSource::from_fixture("fenix-nimbus-validation-v3.json");
        let value: Value = Value::try_from(&exp)?;

        let info = ExperimentInfo::try_from(&value)?;

        assert_eq!("fenix-nimbus-validation-v3", info.slug);
        assert_eq!("Fenix Nimbus Validation v3", info.user_facing_name);
        assert_eq!(
            "Verify we can run A/A experiments and bucket.",
            info.user_facing_description
        );
        assert_eq!("fenix", info.app_name);
        assert_eq!("nightly", info.channel);
        assert!(!info.is_rollout);
        assert!(!info.is_enrollment_paused);
        assert_eq!("true", info.targeting);
        assert_eq!(8000, info.bucketing);
        assert_eq!(" 80 %", info.bucketing_percent());
        assert_eq!(vec!["a1", "a2"], info.branches);
        assert_eq!(vec!["no-feature-fenix"], info.features);

        Ok(())
    }
}