use crate::{
context::Context,
types::{Rule, RuleCondition, RuleContextTarget},
};
#[derive(Clone, Debug, Default)]
pub struct RuleEngine;
impl RuleEngine {
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);
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()),
_ => {}
}
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)
}
}
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,
}
}
fn normalize_operator(operator: &str) -> String {
operator
.trim()
.chars()
.filter(|ch| !matches!(ch, '_' | '-'))
.map(|ch| ch.to_ascii_lowercase())
.collect()
}
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(),
}
}
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"));
}
}