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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! This is the Rust client library for Vexilla, a static file-based VCS-native feature flag system.
//!
//! If you would like to know more about Vexilla head on over to our website. [https://vexilla.dev](https://vexilla.dev)
//!

use convert_case::{Case, Casing};
use serde_json::Result;
use std::collections::HashMap;

mod example;
mod hashing;
mod scheduling;
mod types;

use crate::hashing::*;
use crate::scheduling::*;
use crate::types::*;

type VexillaResult<T, E = VexillaError> = std::result::Result<T, E>;
type Callback = fn(url: &str) -> VexillaResult<String>;

/// VexillaClient is the core struct of this SDK. Most interaction with Vexilla and your feature flags will be through this struct.
#[derive(Clone, Debug, Default)]
pub struct VexillaClient {
    environment: &'static str,
    base_url: &'static str,
    instance_id: &'static str,

    show_logs: bool,

    manifest: Manifest,
    flag_groups: HashMap<String, FlagGroup>,

    group_lookup_table: HashMap<String, String>,
    flag_lookup_table: HashMap<String, HashMap<String, String>>,
    environment_lookup_table: HashMap<String, HashMap<String, String>>,
}

impl VexillaClient {
    /// Create a new client for consuming feature flags.
    pub fn new(
        environment: impl Into<&'static str>,
        base_url: impl Into<&'static str>,
        instance_id: impl Into<&'static str>,
    ) -> VexillaClient {
        VexillaClient {
            manifest: Manifest::default(),
            show_logs: false,
            environment: environment.into(),
            base_url: base_url.into(),
            instance_id: instance_id.into(),
            flag_groups: HashMap::new(),
            group_lookup_table: HashMap::new(),
            flag_lookup_table: HashMap::new(),
            environment_lookup_table: HashMap::new(),
        }
    }

    /// Fetches the manifest file for facilitating name->id lookups. Does not set the value on the client. You would need to call `set_manifest` after. Alternatively, you can use `sync_manifest` to do both steps with less code.
    pub fn get_manifest(&self, fetch: Callback) -> VexillaResult<Manifest> {
        let url = format!("{}/manifest.json", self.base_url);
        let response_text = fetch(&url);
        let manifest: Manifest =
            serde_json::from_str(response_text?.as_ref()).map_err(|_| VexillaError::Unknown)?;

        Ok(manifest)
    }

    /// Sets a fetched manifest within the VexillaClient instance. It can also be useful for mocking flags for testing.
    pub fn set_manifest(&mut self, manifest: Manifest) {
        self.group_lookup_table = create_group_lookup_table(manifest);
    }

    /// Fetches and sets the manifest within the client to facilitate name->Id lookups.
    pub fn sync_manifest(&mut self, fetch: Callback) -> VexillaResult<bool> {
        let manifest = self.get_manifest(fetch)?;
        let lookup_table = create_group_lookup_table(manifest.clone());
        self.manifest = manifest;
        self.group_lookup_table = lookup_table;
        Ok(true)
    }

    /// Fetches the flags for a specific flag group. Can use the ID or the name of the group for the lookup.
    pub fn get_flags(&self, group_name_or_id: &str, fetch: Callback) -> VexillaResult<FlagGroup> {
        let coerced_group_id = &self
            .group_lookup_table
            .get(group_name_or_id)
            .ok_or(VexillaError::GroupLookupKeyNotFound)?;
        let url = format!("{}/{}.json", self.base_url, coerced_group_id);
        let response_text = fetch(&url)?;

        let flags: Result<FlagGroup> = serde_json::from_str(response_text.as_str());

        if let Ok(..) = flags {
            Ok(flags.unwrap())
        } else {
            VexillaResult::Err(VexillaError::Unknown)
        }
    }

    /// Sets a fetched flag group within the Client instance.
    pub fn set_flags(&mut self, flags: FlagGroup) -> VexillaResult<bool> {
        let coerced_group_name_or_id = &self
            .group_lookup_table
            .get(&flags.group_id)
            .ok_or("group not found")
            .map_err(|_| VexillaError::Unknown)?;
        self.flag_groups
            .insert(coerced_group_name_or_id.to_string(), flags.clone());

        let group_flag_table = create_feature_lookup_table(flags.clone());
        self.flag_lookup_table
            .insert(coerced_group_name_or_id.to_string(), group_flag_table);

        let environment_table = create_environment_lookup_table(flags);
        self.environment_lookup_table
            .insert(coerced_group_name_or_id.to_string(), environment_table);
        Ok(true)
    }

    /// Fetches and sets the flag group within the client to facilitate name->Id lookups.
    pub fn sync_flags(
        &mut self,
        group_name_or_id: &str,
        fetch: Callback,
    ) -> VexillaResult<(), VexillaError> {
        let cloned_self = self.clone();
        let coerced_group_id = cloned_self
            .group_lookup_table
            .get(group_name_or_id)
            .ok_or(VexillaError::GroupLookupKeyNotFound)?;
        let flag_group = self.get_flags(coerced_group_id.as_str(), fetch)?;
        let _ = self.set_flags(flag_group)?;
        Ok(())
    }

    /// Checks if a toggle, gradual, or selective flag should be enabled. Other methods exist for other flag types, such as value.
    pub fn should(
        &self,
        group_name_or_id: &'static str,
        feature_name_or_id: impl Into<&'static str>,
    ) -> VexillaResult<bool> {
        let feature = self.get_feature(group_name_or_id, feature_name_or_id.into())?;

        let is_within_schedule = is_scheduled_feature_active(feature.to_owned());

        match (feature.clone(), is_within_schedule) {
            (Feature::Toggle(feature), true) => Ok(feature.value),
            (Feature::Gradual(feature), true) => {
                Ok(self.hash_instance_id(feature.seed) < feature.value)
            }
            (Feature::Selective(feature), true) => match feature {
                SelectiveFeature::String { value, .. } => {
                    Ok(value.contains(&self.instance_id.to_owned()))
                }
                SelectiveFeature::Number(feature) => match feature {
                    SelectiveFeatureNumber::Float { value, .. } => Ok(value.contains(
                        &self
                            .instance_id
                            .to_owned()
                            .parse()
                            .map_err(|_| VexillaError::Unknown)?,
                    )),
                    SelectiveFeatureNumber::Int { value, .. } => Ok(value.contains(
                        &self
                            .instance_id
                            .to_owned()
                            .parse()
                            .map_err(|_| VexillaError::Unknown)?,
                    )),
                },
                _ => Err(VexillaError::InvalidShouldFeatureType(feature.value_type())),
            },

            (_, false) => Ok(false),

            (_, _) => Err(VexillaError::InvalidShouldFeatureType(
                feature.feature_type(),
            )),
        }
    }

    /// Checks if a toggle, gradual, or selective flag should be enabled. Uses a custom instance ID rather than the one set in the Client. Other methods exist for other flag types, such as value.
    pub fn should_custom_str(
        &self,
        group_name_or_id: &str,
        feature_name_or_id: impl Into<&'static str>,
        custom_id: &str,
    ) -> VexillaResult<bool> {
        let feature = self.get_feature(group_name_or_id, feature_name_or_id.into())?;

        let is_within_schedule = is_scheduled_feature_active(feature.to_owned());

        match (feature.clone(), is_within_schedule) {
            (Feature::Toggle(feature), true) => Ok(feature.value),
            (Feature::Gradual(feature), true) => {
                Ok(hash_value(custom_id, feature.seed) < feature.value)
            }
            (Feature::Selective(feature), true) => match feature {
                SelectiveFeature::String { value, .. } => Ok(value.contains(&custom_id.to_owned())),
                _ => Err(VexillaError::InvalidShouldCustomStr(feature.value_type())),
            },

            (_, false) => Ok(false),

            (_, _) => Err(VexillaError::InvalidShouldFeatureType(
                feature.feature_type(),
            )),
        }
    }

    /// Checks if a toggle, gradual, or selective flag should be enabled. Uses a custom instance ID rather than the one set in the Client. Other methods exist for other flag types, such as value.
    pub fn should_custom_int(
        &self,
        group_name_or_id: &str,
        feature_name_or_id: impl Into<&'static str>,
        custom_id: i64,
    ) -> VexillaResult<bool> {
        let feature = self.get_feature(group_name_or_id, feature_name_or_id.into())?;

        let is_within_schedule = is_scheduled_feature_active(feature.to_owned());

        match (feature.clone(), is_within_schedule) {
            (Feature::Toggle(feature), true) => Ok(feature.value),
            (Feature::Gradual(_feature), true) => Err(VexillaError::Unknown),
            (Feature::Selective(feature), true) => match feature {
                SelectiveFeature::Number(SelectiveFeatureNumber::Int { value, .. }) => {
                    Ok(value.contains(&custom_id))
                }
                _ => Err(VexillaError::InvalidShouldCustomInt(feature.value_type())),
            },

            (_, false) => Ok(false),

            (_, _) => Err(VexillaError::InvalidShouldFeatureType(
                feature.feature_type(),
            )),
        }
    }

    /// Checks if a toggle, gradual, or selective flag should be enabled. Uses a custom instance ID rather than the one set in the Client. Other methods exist for other flag types, such as value.
    pub fn should_custom_float(
        &self,
        group_name_or_id: &str,
        feature_name_or_id: impl Into<&'static str>,
        custom_id: f64,
    ) -> VexillaResult<bool> {
        let feature = self.get_feature(group_name_or_id, feature_name_or_id.into())?;

        let is_within_schedule = is_scheduled_feature_active(feature.to_owned());

        match (feature.clone(), is_within_schedule) {
            (Feature::Toggle(feature), true) => Ok(feature.value),
            (Feature::Gradual(_feature), true) => Err(VexillaError::Unknown),
            (Feature::Selective(feature), true) => match feature {
                SelectiveFeature::Number(SelectiveFeatureNumber::Float { value, .. }) => {
                    Ok(value.contains(&custom_id))
                }
                _ => Err(VexillaError::InvalidShouldCustomInt(feature.value_type())),
            },

            (_, false) => Ok(false),

            (_, _) => Err(VexillaError::InvalidShouldFeatureType(
                feature.feature_type(),
            )),
        }
    }

    /// Gets an environment specific string value and falls back to a default if the feature is outside of its schedule.
    pub fn value_str(
        &self,
        group_name_or_id: &str,
        feature_name_or_id: impl Into<&'static str>,
        default: &'static str,
    ) -> VexillaResult<String> {
        let feature = self.get_feature(group_name_or_id, feature_name_or_id.into())?;
        let is_within_schedule = is_scheduled_feature_active(feature.to_owned());

        match (feature.clone(), is_within_schedule) {
            (Feature::Value(feature), true) => match feature {
                ValueFeature::String { value, .. } => Ok(value),
                _ => Err(VexillaError::InvalidValueStringType(feature.value_type())),
            },

            (_, false) => Ok(default.to_string()),

            (_, _) => Err(VexillaError::InvalidValueFeatureType(
                feature.feature_type(),
            )),
        }
    }

    /// Gets an environment specific int value and falls back to a default if the feature is outside of its schedule.
    pub fn value_int(
        &self,
        group_name_or_id: &str,
        feature_name_or_id: impl Into<&'static str>,
        default: i64,
    ) -> VexillaResult<i64> {
        let feature = self.get_feature(group_name_or_id, feature_name_or_id.into())?;

        let is_within_schedule = is_scheduled_feature_active(feature.to_owned());

        match (feature.clone(), is_within_schedule) {
            (Feature::Value(feature), true) => match feature {
                ValueFeature::Number(ValueFeatureNumber::Int { value, .. }) => Ok(value.to_owned()),
                _ => Err(VexillaError::InvalidValueI64Type(feature.value_type())),
            },

            (_, false) => Ok(default),

            (_, _) => Err(VexillaError::InvalidValueFeatureType(
                feature.feature_type(),
            )),
        }
    }

    /// Gets an environment specific float value and falls back to a default if the feature is outside of its schedule.
    pub fn value_float(
        &self,
        group_name_or_id: &str,
        feature_name_or_id: impl Into<&'static str>,
        default: f64,
    ) -> VexillaResult<f64> {
        let feature = self.get_feature(group_name_or_id, feature_name_or_id.into())?;

        let is_within_schedule = is_scheduled_feature_active(feature.to_owned());

        match (feature.clone(), is_within_schedule) {
            (Feature::Value(feature), true) => match feature {
                ValueFeature::Number(ValueFeatureNumber::Float { value, .. }) => {
                    Ok(value.to_owned())
                }
                _ => Err(VexillaError::InvalidValueF64Type(feature.value_type())),
            },

            (_, false) => Ok(default),

            (_, _) => Err(VexillaError::InvalidValueFeatureType(
                feature.feature_type(),
            )),
        }
    }

    fn hash_instance_id(&self, seed: f64) -> f64 {
        hash_value(self.instance_id, seed)
    }

    fn get_feature(
        &self,
        group_name_or_id: &str,
        feature_name_or_id: impl Into<&'static str>,
    ) -> VexillaResult<Feature> {
        let ids = self.get_real_ids(group_name_or_id, feature_name_or_id.into())?;

        let group = &self
            .flag_groups
            .get(&ids.real_group_id)
            .ok_or(VexillaError::FlagGroupKeyNotFound)?;

        let environment = group
            .environments
            .get(&ids.real_environment_id)
            .ok_or(VexillaError::EnvironmentLookupKeyNotFound)?;

        let feature = environment
            .features
            .get(&ids.real_feature_id)
            .ok_or(VexillaError::EnvironmentFeatureKeyNotFound)?;

        Ok(feature.clone())
    }

    fn get_real_ids(
        &self,
        group_name_or_id: &str,
        feature_name_or_id: &str,
    ) -> VexillaResult<RealIds> {
        let real_group_id = self
            .group_lookup_table
            .get(group_name_or_id)
            .ok_or(VexillaError::GroupLookupKeyNotFound)?
            .to_string();

        let real_feature_id = self
            .flag_lookup_table
            .get(&real_group_id)
            .ok_or(VexillaError::GroupLookupKeyNotFound)?
            .get(feature_name_or_id)
            .ok_or(VexillaError::FlagLookupKeyNotFound)?
            .to_string();

        let real_environment_id = self
            .environment_lookup_table
            .get(&real_group_id)
            .ok_or(VexillaError::GroupLookupKeyNotFound)?
            .get(self.environment)
            .ok_or(VexillaError::FlagLookupKeyNotFound)?
            .to_string();

        Ok(RealIds {
            real_group_id,
            real_feature_id,
            real_environment_id,
        })
    }
}

fn create_group_lookup_table(manifest: Manifest) -> HashMap<String, String> {
    let mut new_lookup_table: HashMap<String, String> = HashMap::new();

    manifest.groups.iter().for_each(|group| {
        new_lookup_table.insert(group.group_id.clone(), group.group_id.clone());
        new_lookup_table.insert(group.name.clone(), group.group_id.clone());
        new_lookup_table.insert(group.group_id.to_case(Case::Kebab), group.group_id.clone());
    });

    new_lookup_table
}

fn create_feature_lookup_table(flag_group: FlagGroup) -> HashMap<String, String> {
    let mut new_lookup_table: HashMap<String, String> = HashMap::new();

    flag_group
        .features
        .iter()
        .for_each(|(feature_id, feature)| {
            new_lookup_table.insert(feature_id.clone(), feature_id.clone());
            new_lookup_table.insert(feature.name.clone(), feature_id.clone());
            new_lookup_table.insert(feature.name.to_case(Case::Kebab), feature_id.clone());
        });

    new_lookup_table
}

fn create_environment_lookup_table(flag_group: FlagGroup) -> HashMap<String, String> {
    let mut new_lookup_table: HashMap<String, String> = HashMap::new();

    flag_group
        .environments
        .iter()
        .for_each(|(environment_id, environment)| {
            new_lookup_table.insert(environment_id.clone(), environment_id.clone());
            new_lookup_table.insert(environment.name.clone(), environment_id.clone());
            new_lookup_table.insert(
                environment.name.to_case(Case::Kebab),
                environment_id.clone(),
            );
        });

    new_lookup_table
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn end_to_end() {
        let mut client = VexillaClient::new(
            "dev",
            "http://localhost:3000",
            "b7e91cc5-ec76-4ec3-9c1c-075032a13a1a",
        );

        /*
            Manifest
        */

        let manifest = client
            .get_manifest(|url| Ok(reqwest::blocking::get(url).unwrap().text().unwrap()))
            .unwrap();

        assert!(!manifest.version.is_empty());

        client
            .sync_manifest(|url| Ok(reqwest::blocking::get(url).unwrap().text().unwrap()))
            .unwrap();

        /*
            Get Flags
        */

        let flags = client
            .get_flags("Gradual", |url| {
                Ok(reqwest::blocking::get(url).unwrap().text().unwrap())
            })
            .unwrap();

        assert_eq!(flags.name, "Gradual");

        /*
            Gradual
        */

        client
            .sync_flags("Gradual", |url| {
                Ok(reqwest::blocking::get(url).unwrap().text().unwrap())
            })
            .unwrap();

        let working_gradual_by_id = client.should("Gradual", "oIVHzosp0ao3HN0fmFwwr").unwrap();
        assert!(working_gradual_by_id);

        let working_gradual_by_name = client.should("Gradual", "testingWorkingGradual").unwrap();
        assert!(working_gradual_by_name);

        let non_working_gradual_by_id = client.should("Gradual", "-T2se1u9jyj1HNkbJ9Cdr").unwrap();
        assert!(!non_working_gradual_by_id);

        let non_working_gradual_by_name = client
            .should("Gradual", "testingNonWorkingGradual")
            .unwrap();
        assert!(!non_working_gradual_by_name);

        /*
           Scheduled
        */

        client
            .sync_flags("Scheduled", |url| {
                Ok(reqwest::blocking::get(url).unwrap().text().unwrap())
            })
            .unwrap();

        /*
           Scheduled (Global timeless)
        */

        let before_global_scheduled = client.should("Scheduled", "beforeGlobal").unwrap();
        assert!(!before_global_scheduled);

        let during_global_scheduled = client.should("Scheduled", "duringGlobal").unwrap();
        assert!(during_global_scheduled);

        let after_global_scheduled = client.should("Scheduled", "afterGlobal").unwrap();
        assert!(!after_global_scheduled);

        /*
           Scheduled (Global Start/End)
        */

        let before_global_startend_scheduled =
            client.should("Scheduled", "beforeGlobalStartEnd").unwrap();
        assert!(!before_global_startend_scheduled);

        let during_global_startend_scheduled =
            client.should("Scheduled", "duringGlobalStartEnd").unwrap();
        assert!(during_global_startend_scheduled);

        let after_global_startend_scheduled =
            client.should("Scheduled", "afterGlobalStartEnd").unwrap();
        assert!(!after_global_startend_scheduled);

        /*
           Scheduled (Global Daily)
        */

        let before_global_daily_scheduled =
            client.should("Scheduled", "beforeGlobalDaily").unwrap();
        assert!(!before_global_daily_scheduled);

        let during_global_daily_scheduled =
            client.should("Scheduled", "duringGlobalDaily").unwrap();
        assert!(during_global_daily_scheduled);

        let after_global_daily_scheduled = client.should("Scheduled", "afterGlobalDaily").unwrap();
        assert!(!after_global_daily_scheduled);

        /*
           Selective
        */

        client
            .sync_flags("Selective", |url| {
                Ok(reqwest::blocking::get(url).unwrap().text().unwrap())
            })
            .unwrap();

        let selective_string_default = client.should("Selective", "String").unwrap();
        assert!(selective_string_default);

        let selective_string_custom = client
            .should_custom_str("Selective", "String", "shouldBeInList")
            .unwrap();
        assert!(selective_string_custom);

        let selective_string_custom_fail = client
            .should_custom_str("Selective", "String", "shouldNotBeInList")
            .unwrap();
        assert!(!selective_string_custom_fail);

        let selective_number_custom = client.should_custom_int("Selective", "Number", 42).unwrap();
        assert!(selective_number_custom);

        let selective_number_custom_fail =
            client.should_custom_int("Selective", "Number", 43).unwrap();
        assert!(!selective_number_custom_fail);

        /*
           Value
        */

        client
            .sync_flags("Value", |url| {
                Ok(reqwest::blocking::get(url).unwrap().text().unwrap())
            })
            .unwrap();

        let value_str = client.value_str("Value", "String", "bar").unwrap();
        assert!(value_str == "foo");

        let value_int = client
            .value_int(
                example::ValueGroup::NAME,
                example::ValueGroup::Features::Integer,
                21,
            )
            .unwrap();
        assert!(value_int == 42);

        let value_float = client.value_float("Value", "Float", 21.21).unwrap();
        assert!(value_float == 42.42);
    }
}