zenmanage 1.0.0

Official Zenmanage feature flags SDK for Rust
Documentation
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
use crate::{
    context::Context,
    types::{Rule, RuleCondition, RuleContextTarget},
};

/// Evaluates flag rules against a context.
///
/// Comparison semantics follow the Zenmanage API and the other SDKs: an
/// attribute condition compares against the first rule value (`in` and `notin`
/// use the whole list) and matches when any of the attribute's values does.
#[derive(Clone, Debug, Default)]
pub struct RuleEngine;

impl RuleEngine {
    /// Returns the first rule that matches `context`. Rules are tried in the
    /// order given.
    pub fn evaluate<'a>(&self, rules: &'a [Rule], context: &Context) -> Option<&'a Rule> {
        rules.iter().find(|rule| self.evaluate_rule(rule, context))
    }

    fn evaluate_rule(&self, rule: &Rule, context: &Context) -> bool {
        if let Some(clauses) = &rule.clauses
            && !clauses.is_empty()
        {
            return clauses
                .iter()
                .all(|clause| self.evaluate_clause(clause, context));
        }

        if let Some(criteria) = &rule.criteria {
            return self.evaluate_clause(criteria, context);
        }

        true
    }

    fn evaluate_clause(&self, clause: &RuleCondition, context: &Context) -> bool {
        let operator = normalize_operator(&clause.operator);

        match clause.attribute.as_str() {
            selector @ ("context" | "segment") => {
                let value = clause.value.as_ref();
                let targets = context_targets(value);
                // A missing or unreadable member list isn't an empty segment: nothing
                // matches it.
                if selector == "segment" && !is_member_list(value, targets.len()) {
                    return false;
                }

                evaluate_membership(selector, &operator, &targets, context)
            }
            _ => self.evaluate_attribute_clause(clause, &operator, context),
        }
    }

    fn evaluate_attribute_clause(
        &self,
        clause: &RuleCondition,
        operator: &str,
        context: &Context,
    ) -> bool {
        let values = context
            .get_attribute(&clause.attribute)
            .map(|attribute| attribute.get_values())
            .unwrap_or_default();

        match operator {
            "isnull" => return values.iter().all(|value| value.is_empty()),
            "notnull" => return values.iter().any(|value| !value.is_empty()),
            _ => {}
        }

        // A context without the attribute satisfies every negated comparison.
        if values.is_empty() {
            return matches!(
                operator,
                "notequal" | "notin" | "notcontains" | "notstartswith" | "notendswith"
            );
        }

        let targets = attribute_targets(clause.value.as_ref());
        let targets: Vec<&str> = targets.iter().map(String::as_str).collect();

        compare(operator, &values, &targets)
    }
}

/// Compares `values` with the rule's `targets`. `in` and `notin` use every
/// target and the other operators the first. Without a target nothing matches.
fn compare(operator: &str, values: &[&str], targets: &[&str]) -> bool {
    let Some(&first) = targets.first() else {
        return false;
    };
    let any = |matches: &dyn Fn(&str) -> bool| values.iter().any(|value| matches(value));
    let listed = |value: &str| targets.contains(&value);

    match operator {
        "equal" => any(&|value| value == first),
        "notequal" => !any(&|value| value == first),
        "in" => any(&listed),
        "notin" => !any(&listed),
        "contains" => any(&|value| value.contains(first)),
        "notcontains" => !any(&|value| value.contains(first)),
        "startswith" => any(&|value| value.starts_with(first)),
        "notstartswith" => !any(&|value| value.starts_with(first)),
        "endswith" => any(&|value| value.ends_with(first)),
        "notendswith" => !any(&|value| value.ends_with(first)),
        "gt" => compare_numbers(values, first, |value, target| value > target),
        "gte" => compare_numbers(values, first, |value, target| value >= target),
        "lt" => compare_numbers(values, first, |value, target| value < target),
        "lte" => compare_numbers(values, first, |value, target| value <= target),
        _ => false,
    }
}

/// `not_equal`, `Not-Equal` and `notequal` are the same operator.
fn normalize_operator(operator: &str) -> String {
    operator
        .trim()
        .chars()
        .filter(|ch| !matches!(ch, '_' | '-'))
        .map(|ch| ch.to_ascii_lowercase())
        .collect()
}

/// Compares the context's identifier with the targets of its own type (a target
/// without a type applies to every type). A context without an identifier never
/// matches, negated or not.
///
/// A segment's targets are its member list, so `equal` and `in` match any member
/// and `notequal` and `notin` match everyone else, including when no member is of
/// the context's type. Otherwise a rule without a target of the context's type
/// never matches.
fn evaluate_membership(
    selector: &str,
    operator: &str,
    targets: &[RuleContextTarget],
    context: &Context,
) -> bool {
    let Some(identifier) = context
        .identifier
        .as_deref()
        .filter(|identifier| !identifier.is_empty())
    else {
        return false;
    };

    let applicable: Vec<&str> = targets
        .iter()
        .filter(|target| {
            target
                .r#type
                .as_deref()
                .is_none_or(|kind| kind.is_empty() || kind == context.context_type)
        })
        .map(|target| target.identifier.as_str())
        .collect();

    if selector == "segment" {
        match operator {
            "equal" | "in" => return applicable.contains(&identifier),
            "notequal" | "notin" => return !applicable.contains(&identifier),
            _ => {}
        }
    }

    compare(operator, &[identifier], &applicable)
}

fn compare_numbers(values: &[&str], target: &str, compare: fn(f64, f64) -> bool) -> bool {
    let Ok(target) = target.trim().parse::<f64>() else {
        return false;
    };

    values
        .iter()
        .filter_map(|value| value.trim().parse::<f64>().ok())
        .any(|value| compare(value, target))
}

fn attribute_targets(value: Option<&serde_json::Value>) -> Vec<String> {
    fn scalar(value: &serde_json::Value) -> Option<String> {
        match value {
            serde_json::Value::String(text) => Some(text.clone()),
            serde_json::Value::Number(number) => Some(number.to_string()),
            serde_json::Value::Bool(flag) => Some(flag.to_string()),
            _ => None,
        }
    }

    match value {
        Some(serde_json::Value::Array(items)) => items.iter().filter_map(scalar).collect(),
        Some(other) => scalar(other).into_iter().collect(),
        None => Vec::new(),
    }
}

/// Whether every entry of a segment condition's value was read as a member.
fn is_member_list(value: Option<&serde_json::Value>, read: usize) -> bool {
    match value {
        Some(serde_json::Value::Array(items)) => items.len() == read,
        Some(_) => read == 1,
        None => false,
    }
}

fn context_targets(value: Option<&serde_json::Value>) -> Vec<RuleContextTarget> {
    fn target(value: &serde_json::Value) -> Option<RuleContextTarget> {
        match value {
            serde_json::Value::String(identifier) => Some(RuleContextTarget {
                identifier: identifier.clone(),
                r#type: None,
            }),
            serde_json::Value::Object(_) => serde_json::from_value(value.clone()).ok(),
            _ => None,
        }
    }

    match value {
        Some(serde_json::Value::Array(items)) => items.iter().filter_map(target).collect(),
        Some(other) => target(other).into_iter().collect(),
        None => Vec::new(),
    }
}

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

    use crate::{
        context::{Attribute, Context},
        types::{PrimitiveValue, RuleCondition, RuleValue},
    };

    use super::*;

    fn rule_with_clause(attribute: &str, operator: &str, value: serde_json::Value) -> Rule {
        Rule {
            version: None,
            description: None,
            criteria: None,
            clauses: Some(vec![RuleCondition {
                attribute: attribute.to_owned(),
                operator: operator.to_owned(),
                value: Some(value),
            }]),
            position: None,
            value: RuleValue {
                version: None,
                value: PrimitiveValue {
                    boolean: Some(true),
                    string: None,
                    number: None,
                    json: None,
                },
            },
        }
    }

    fn matches(
        context: &Context,
        attribute: &str,
        operator: &str,
        value: serde_json::Value,
    ) -> bool {
        RuleEngine
            .evaluate(&[rule_with_clause(attribute, operator, value)], context)
            .is_some()
    }

    fn user() -> Context {
        Context::single("user", "user-1", None::<String>)
    }

    fn user_with(key: &str, values: Vec<&str>) -> Context {
        user().add_attribute(Attribute::new(key, values))
    }

    #[test]
    fn equal_and_notequal_use_the_first_rule_value() {
        let context = user_with("plan", vec!["pro"]);

        assert!(matches(&context, "plan", "equal", json!("pro")));
        assert!(matches(&context, "plan", "equal", json!(["pro", "free"])));
        assert!(!matches(&context, "plan", "equal", json!(["free", "pro"])));
        assert!(!matches(&context, "plan", "notequal", json!("pro")));
        assert!(matches(&context, "plan", "notequal", json!("free")));
    }

    #[test]
    fn any_attribute_value_can_match() {
        let context = user_with("tags", vec!["alpha", "beta"]);

        assert!(matches(&context, "tags", "equal", json!(["beta"])));
        assert!(matches(&context, "tags", "contains", json!(["bet"])));
        assert!(!matches(&context, "tags", "notcontains", json!(["alpha"])));
        assert!(matches(&context, "tags", "in", json!(["gamma", "beta"])));
        assert!(!matches(
            &context,
            "tags",
            "notin",
            json!(["gamma", "beta"])
        ));
        assert!(matches(&context, "tags", "notin", json!(["gamma"])));
    }

    #[test]
    fn string_prefix_and_suffix_operators() {
        let context = user_with("email", vec!["alice@example.com"]);

        assert!(matches(&context, "email", "startswith", json!("alice")));
        assert!(!matches(&context, "email", "notstartswith", json!("alice")));
        assert!(matches(&context, "email", "notstartswith", json!("admin")));
        assert!(matches(&context, "email", "endswith", json!(".com")));
        assert!(!matches(&context, "email", "notendswith", json!(".com")));
        assert!(matches(&context, "email", "notendswith", json!(".org")));
        assert!(matches(&context, "email", "contains", json!("@example")));
        assert!(matches(&context, "email", "notcontains", json!("other")));
    }

    #[test]
    fn numeric_operators_compare_numbers_not_text() {
        let context = user_with("age", vec!["21"]);

        assert!(matches(&context, "age", "gt", json!("3")));
        assert!(matches(&context, "age", "gte", json!("21")));
        assert!(matches(&context, "age", "gte", json!(18)));
        assert!(matches(&context, "age", "lt", json!(["100"])));
        assert!(matches(&context, "age", "lte", json!(21.0)));
        assert!(!matches(&context, "age", "gt", json!("21")));
        assert!(!matches(&context, "age", "gt", json!("not-a-number")));
        assert!(!matches(
            &user_with("age", vec!["old"]),
            "age",
            "gt",
            json!("1")
        ));
    }

    #[test]
    fn operator_spelling_is_normalized() {
        let context = user_with("email", vec!["alice@example.com"]);

        assert!(matches(&context, "email", "starts_with", json!("alice")));
        assert!(matches(&context, "email", "Ends-With", json!(".com")));
        assert!(matches(&context, "email", "NOT_EQUAL", json!("bob")));
    }

    #[test]
    fn unknown_operator_never_matches() {
        let context = user_with("plan", vec!["pro"]);

        assert!(!matches(&context, "plan", "matches-regex", json!("p.*")));
        assert!(!matches(&user(), "context", "gt", json!(["user-1"])));
    }

    #[test]
    fn comparison_without_a_rule_value_never_matches() {
        let context = user_with("plan", vec!["pro"]);

        assert!(!matches(&context, "plan", "equal", json!([])));
        assert!(!matches(&context, "plan", "notequal", json!([])));
        assert!(!matches(&context, "plan", "notin", json!(null)));
    }

    #[test]
    fn isnull_matches_when_attribute_is_absent_or_empty() {
        assert!(matches(&user(), "tag", "isnull", json!(null)));
        assert!(matches(
            &user_with("tag", vec![""]),
            "tag",
            "isnull",
            json!(null)
        ));
        assert!(matches(
            &user_with("tag", vec![]),
            "tag",
            "isnull",
            json!([])
        ));
        assert!(!matches(
            &user_with("tag", vec!["active"]),
            "tag",
            "isnull",
            json!(null)
        ));
    }

    #[test]
    fn notnull_needs_a_value() {
        assert!(matches(
            &user_with("tag", vec!["active"]),
            "tag",
            "notnull",
            json!(null)
        ));
        assert!(!matches(&user(), "tag", "notnull", json!(null)));
        assert!(!matches(
            &user_with("tag", vec![""]),
            "tag",
            "notnull",
            json!(null)
        ));
    }

    #[test]
    fn missing_attribute_satisfies_only_negated_operators() {
        for operator in [
            "notequal",
            "notin",
            "notcontains",
            "notstartswith",
            "notendswith",
        ] {
            assert!(
                matches(&user(), "missing", operator, json!("x")),
                "{operator} should match an absent attribute"
            );
        }

        for operator in [
            "equal",
            "in",
            "contains",
            "startswith",
            "endswith",
            "gt",
            "gte",
            "lt",
            "lte",
        ] {
            assert!(
                !matches(&user(), "missing", operator, json!("1")),
                "{operator} should not match an absent attribute"
            );
        }
    }

    #[test]
    fn context_condition_checks_identifier_and_type() {
        let targets = json!([{"identifier": "user-1", "type": "user"}]);

        assert!(matches(&user(), "context", "in", targets.clone()));
        assert!(matches(&user(), "context", "equal", targets.clone()));
        assert!(!matches(&user(), "context", "notin", targets.clone()));
        assert!(!matches(&user(), "context", "notequal", targets.clone()));

        let other = Context::single("user", "user-2", None::<String>);
        assert!(!matches(&other, "context", "in", targets.clone()));
        assert!(matches(&other, "context", "notin", targets.clone()));
        assert!(matches(&other, "context", "notequal", targets));
    }

    #[test]
    fn context_equal_uses_the_first_target_and_in_uses_all() {
        let targets = json!(["user-9", "user-1"]);

        assert!(!matches(&user(), "context", "equal", targets.clone()));
        assert!(matches(&user(), "context", "notequal", targets.clone()));
        assert!(matches(&user(), "context", "in", targets.clone()));
        assert!(!matches(&user(), "context", "notin", targets));
    }

    #[test]
    fn context_identifier_supports_string_comparisons() {
        let targets = json!([{"identifier": "user", "type": "user"}]);
        let suffix = json!(["-1"]);

        for selector in ["context", "segment"] {
            assert!(matches(&user(), selector, "contains", targets.clone()));
            assert!(!matches(&user(), selector, "notcontains", targets.clone()));
            assert!(matches(&user(), selector, "startswith", targets.clone()));
            assert!(!matches(
                &user(),
                selector,
                "notstartswith",
                targets.clone()
            ));
            assert!(matches(&user(), selector, "endswith", suffix.clone()));
            assert!(!matches(&user(), selector, "notendswith", suffix.clone()));
            assert!(!matches(
                &Context::default(),
                selector,
                "notcontains",
                targets.clone()
            ));
        }
    }

    #[test]
    fn context_target_of_another_type_never_matches() {
        let targets = json!([{"identifier": "user-1", "type": "user"}]);
        let organization = Context::single("organization", "user-1", None::<String>);

        for operator in ["equal", "notequal", "in", "notin"] {
            assert!(
                !matches(&organization, "context", operator, targets.clone()),
                "{operator}"
            );
        }
    }

    #[test]
    fn context_target_without_a_type_matches_any_type() {
        let organization = Context::single("organization", "user-1", None::<String>);

        assert!(matches(
            &organization,
            "context",
            "in",
            json!([{"identifier": "user-1", "type": null}])
        ));
        assert!(matches(&organization, "context", "in", json!(["user-1"])));
        assert!(matches(
            &organization,
            "context",
            "equal",
            json!({"identifier": "user-1"})
        ));
    }

    #[test]
    fn context_without_identifier_never_matches() {
        let targets = json!([{"identifier": "user-1", "type": null}]);

        for selector in ["context", "segment"] {
            for operator in ["equal", "notequal", "in", "notin"] {
                assert!(
                    !matches(&Context::default(), selector, operator, targets.clone()),
                    "{selector} {operator}"
                );
            }
        }
    }

    #[test]
    fn empty_context_target_list_never_matches() {
        for operator in ["equal", "notequal", "in", "notin"] {
            assert!(
                !matches(&user(), "context", operator, json!([])),
                "{operator}"
            );
        }
    }

    #[test]
    fn segment_counts_every_member() {
        let members = json!([
            {"identifier": "a", "type": "user"},
            {"identifier": "b", "type": "user"},
            {"identifier": "c", "type": null}
        ]);

        for identifier in ["a", "b", "c", "z"] {
            let context = Context::single("user", identifier, None::<String>);
            let member = identifier != "z";

            for operator in ["equal", "in"] {
                assert_eq!(
                    matches(&context, "segment", operator, members.clone()),
                    member,
                    "{operator} {identifier}"
                );
            }
            for operator in ["notequal", "notin"] {
                assert_eq!(
                    matches(&context, "segment", operator, members.clone()),
                    !member,
                    "{operator} {identifier}"
                );
            }
        }
    }

    #[test]
    fn segment_without_a_readable_member_list_never_matches() {
        let unreadable = [
            json!(null),
            json!(7),
            json!([7]),
            json!([null]),
            json!([{"id": "user-1"}]),
            json!([{"identifier": "z", "type": "user"}, {}]),
        ];

        for operator in ["equal", "notequal", "in", "notin"] {
            for members in &unreadable {
                assert!(
                    !matches(&user(), "segment", operator, members.clone()),
                    "{operator} {members}"
                );
            }

            let mut missing = rule_with_clause("segment", operator, json!([]));
            missing.clauses.as_mut().unwrap()[0].value = None;
            assert!(
                RuleEngine.evaluate(&[missing], &user()).is_none(),
                "{operator} missing"
            );
        }
    }

    #[test]
    fn segment_without_an_applicable_member_contains_nobody() {
        let organization = Context::single("organization", "user-1", None::<String>);
        let user_only = json!([{"identifier": "user-1", "type": "user"}]);

        for (context, members) in [(user(), json!([])), (organization, user_only)] {
            for operator in ["equal", "in"] {
                assert!(
                    !matches(&context, "segment", operator, members.clone()),
                    "{operator}"
                );
            }
            for operator in ["notequal", "notin"] {
                assert!(
                    matches(&context, "segment", operator, members.clone()),
                    "{operator}"
                );
            }
        }
    }

    #[test]
    fn segment_condition_matches_members() {
        let members = json!([
            {"identifier": "user-9", "type": null},
            {"identifier": "user-1", "type": "user"}
        ]);

        assert!(matches(&user(), "segment", "in", members.clone()));
        assert!(!matches(&user(), "segment", "notin", members));
    }

    #[test]
    fn every_clause_must_match_and_the_first_matching_rule_wins() {
        let context = user_with("country", vec!["US"]);
        let mut both = rule_with_clause("country", "equal", json!("US"));
        both.clauses.as_mut().unwrap().push(RuleCondition {
            attribute: "plan".to_owned(),
            operator: "equal".to_owned(),
            value: Some(json!("pro")),
        });
        let mut country = rule_with_clause("country", "equal", json!("US"));
        country.description = Some("country".to_owned());
        let mut also_country = country.clone();
        also_country.description = Some("second".to_owned());

        let rules = [both, country, also_country];
        let matched = RuleEngine.evaluate(&rules, &context).expect("a match");

        assert_eq!(matched.description.as_deref(), Some("country"));
    }
}