flagd-evaluation-engine 0.0.4

Evaluation engine for flagd - JSONLogic-based targeting rules
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
use crate::error::FlagdEvaluationError;
use datalogic_rs::Engine;
use datalogic_rs::bumpalo::Bump;
use datalogic_rs::operator::EvalContext;
use datalogic_rs::{ArenaExt, CustomOperator, DataValue};
use open_feature::{EvaluationContext, EvaluationContextFieldValue};
use serde_json::Value;
use std::sync::Arc;

mod fractional;
mod semver;

use fractional::FractionalOperator;
use semver::SemVerOperator;

/// JSONLogic-based targeting rule evaluator for flag evaluation
///
/// Supports custom operators for flagd-specific targeting:
/// - `fractional`: Consistent hashing for percentage-based rollouts
/// - `sem_ver`: Semantic version comparison
pub struct Operator {
    logic: Arc<Engine>,
}

impl Default for Operator {
    fn default() -> Self {
        Self::new()
    }
}

impl Operator {
    pub fn new() -> Self {
        let logic = Engine::builder()
            .add_operator("fractional", FractionalOperator)
            .add_operator("sem_ver", SemVerOperator)
            .add_operator("starts_with", StartsWithOperator)
            .add_operator("ends_with", EndsWithOperator)
            .build();

        Operator {
            logic: Arc::new(logic),
        }
    }

    pub fn apply(
        &self,
        flag_key: &str,
        targeting_rule: &str,
        ctx: &EvaluationContext,
    ) -> Result<Option<String>, FlagdEvaluationError> {
        let targeting_rule = Self::normalize_targeting_rule(targeting_rule)?;
        let compiled = self.logic.compile(&targeting_rule).map_err(|e| {
            FlagdEvaluationError::Parse(format!("Failed to compile targeting rule: {:?}", e))
        })?;

        // Build context data as serde_json::Value
        let context_data = self.build_context(flag_key, ctx);

        // Evaluate using datalogic-rs
        let mut session = self.logic.session();
        match session.eval_str(&compiled, &context_data.to_string()) {
            Ok(result) => {
                // Convert result to Option<String>
                match serde_json::from_str::<Value>(&result)? {
                    Value::String(s) => Ok(Some(s)),
                    Value::Null => Ok(None),
                    _ => Ok(Some(result.to_string())),
                }
            }
            Err(e) => {
                tracing::debug!("DataLogic evaluation error: {:?}", e);
                Err(FlagdEvaluationError::Parse(format!(
                    "Failed to evaluate targeting rule: {:?}",
                    e
                )))
            }
        }
    }

    fn normalize_targeting_rule(targeting_rule: &str) -> Result<String, FlagdEvaluationError> {
        let value: Value = serde_json::from_str(targeting_rule)?;
        serde_json::to_string(&value).map_err(FlagdEvaluationError::from)
    }

    fn build_context(&self, flag_key: &str, ctx: &EvaluationContext) -> Value {
        // Create a JSON object for our context
        let mut root = serde_json::Map::new();

        // Add targeting key if present
        if let Some(targeting_key) = &ctx.targeting_key {
            root.insert(
                "targetingKey".to_string(),
                Value::String(targeting_key.clone()),
            );
        }

        // Add flagd metadata
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Create flagd object
        let mut flagd_props = serde_json::Map::new();
        flagd_props.insert("flagKey".to_string(), Value::String(flag_key.to_string()));
        flagd_props.insert(
            "timestamp".to_string(),
            Value::Number(serde_json::Number::from(timestamp)),
        );

        // Add flagd object to main object
        root.insert("$flagd".to_string(), Value::Object(flagd_props));

        // Add custom fields
        for (key, value) in &ctx.custom_fields {
            root.insert(key.clone(), self.evaluation_context_value_to_json(value));
        }

        // Return the JSON object
        Value::Object(root)
    }

    /// Convert EvaluationContextFieldValue to serde_json::Value
    fn evaluation_context_value_to_json(&self, value: &EvaluationContextFieldValue) -> Value {
        match value {
            EvaluationContextFieldValue::String(s) => Value::String(s.clone()),
            EvaluationContextFieldValue::Bool(b) => Value::Bool(*b),
            EvaluationContextFieldValue::Int(i) => Value::Number(serde_json::Number::from(*i)),
            EvaluationContextFieldValue::Float(f) => {
                if let Some(num) = serde_json::Number::from_f64(*f) {
                    Value::Number(num)
                } else {
                    Value::Null
                }
            }
            EvaluationContextFieldValue::DateTime(dt) => Value::String(dt.to_string()),
            EvaluationContextFieldValue::Struct(s) => {
                // Try to downcast to StructValue for proper serialization
                if let Some(struct_value) = s.downcast_ref::<open_feature::StructValue>() {
                    self.struct_value_to_json(struct_value)
                } else {
                    // Fallback for other types - serialize as string representation
                    Value::Object(serde_json::Map::new())
                }
            }
        }
    }

    /// Convert StructValue to serde_json::Value with proper nested serialization
    fn struct_value_to_json(&self, struct_value: &open_feature::StructValue) -> Value {
        let mut map = serde_json::Map::new();
        for (key, value) in &struct_value.fields {
            map.insert(key.clone(), self.open_feature_value_to_json(value));
        }
        Value::Object(map)
    }

    /// Convert OpenFeature Value to serde_json::Value
    fn open_feature_value_to_json(&self, value: &open_feature::Value) -> Value {
        match value {
            open_feature::Value::String(s) => Value::String(s.clone()),
            open_feature::Value::Bool(b) => Value::Bool(*b),
            open_feature::Value::Int(i) => Value::Number(serde_json::Number::from(*i)),
            open_feature::Value::Float(f) => {
                if let Some(num) = serde_json::Number::from_f64(*f) {
                    Value::Number(num)
                } else {
                    Value::Null
                }
            }
            open_feature::Value::Struct(s) => self.struct_value_to_json(s),
            open_feature::Value::Array(arr) => Value::Array(
                arr.iter()
                    .map(|v| self.open_feature_value_to_json(v))
                    .collect(),
            ),
        }
    }
}

struct StartsWithOperator;
struct EndsWithOperator;

impl CustomOperator for StartsWithOperator {
    fn evaluate<'a>(
        &self,
        args: &[&'a DataValue<'a>],
        _context: &mut EvalContext<'_, 'a>,
        arena: &'a Bump,
    ) -> datalogic_rs::Result<&'a DataValue<'a>> {
        Ok(arena.bool(string_op(args, |text, pattern| text.starts_with(pattern))))
    }
}

impl CustomOperator for EndsWithOperator {
    fn evaluate<'a>(
        &self,
        args: &[&'a DataValue<'a>],
        _context: &mut EvalContext<'_, 'a>,
        arena: &'a Bump,
    ) -> datalogic_rs::Result<&'a DataValue<'a>> {
        Ok(arena.bool(string_op(args, |text, pattern| text.ends_with(pattern))))
    }
}

fn string_op(args: &[&DataValue<'_>], op: impl Fn(&str, &str) -> bool) -> bool {
    let [text, pattern, ..] = args else {
        return false;
    };

    match (text.as_str(), pattern.as_str()) {
        (Some(text), Some(pattern)) => op(text, pattern),
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use open_feature::{EvaluationContext, StructValue, Value as OFValue};
    use std::collections::HashMap;

    #[test]
    fn test_build_context_with_targeting_key() {
        let operator = Operator::new();
        let ctx = EvaluationContext::default().with_targeting_key("user-123");

        let result = operator.build_context("test-flag", &ctx);

        assert!(result.is_object());
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("targetingKey").unwrap(), "user-123");
        assert!(obj.contains_key("$flagd"));

        let flagd = obj.get("$flagd").unwrap().as_object().unwrap();
        assert_eq!(flagd.get("flagKey").unwrap(), "test-flag");
        assert!(flagd.contains_key("timestamp"));
    }

    #[test]
    fn test_build_context_with_custom_fields() {
        let operator = Operator::new();
        let ctx = EvaluationContext::default()
            .with_custom_field("string_field", "value")
            .with_custom_field("int_field", 42i64)
            .with_custom_field("bool_field", true)
            .with_custom_field("float_field", 3.14f64);

        let result = operator.build_context("test-flag", &ctx);
        let obj = result.as_object().unwrap();

        assert_eq!(obj.get("string_field").unwrap(), "value");
        assert_eq!(obj.get("int_field").unwrap(), 42);
        assert_eq!(obj.get("bool_field").unwrap(), true);
        assert_eq!(obj.get("float_field").unwrap(), 3.14);
    }

    #[test]
    fn test_open_feature_value_to_json_primitives() {
        let operator = Operator::new();

        assert_eq!(
            operator.open_feature_value_to_json(&OFValue::String("test".to_string())),
            Value::String("test".to_string())
        );
        assert_eq!(
            operator.open_feature_value_to_json(&OFValue::Bool(true)),
            Value::Bool(true)
        );
        assert_eq!(
            operator.open_feature_value_to_json(&OFValue::Int(42)),
            Value::Number(42.into())
        );
        assert_eq!(
            operator.open_feature_value_to_json(&OFValue::Float(3.14)),
            Value::Number(serde_json::Number::from_f64(3.14).unwrap())
        );
    }

    #[test]
    fn test_struct_value_to_json() {
        let operator = Operator::new();

        let mut fields = HashMap::new();
        fields.insert("name".to_string(), OFValue::String("test".to_string()));
        fields.insert("count".to_string(), OFValue::Int(5));
        fields.insert("enabled".to_string(), OFValue::Bool(true));

        let struct_value = StructValue { fields };
        let result = operator.struct_value_to_json(&struct_value);

        assert!(result.is_object());
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("name").unwrap(), "test");
        assert_eq!(obj.get("count").unwrap(), 5);
        assert_eq!(obj.get("enabled").unwrap(), true);
    }

    #[test]
    fn test_nested_struct_value_to_json() {
        let operator = Operator::new();

        // Create nested struct
        let mut inner_fields = HashMap::new();
        inner_fields.insert(
            "inner_key".to_string(),
            OFValue::String("inner_value".to_string()),
        );
        let inner_struct = StructValue {
            fields: inner_fields,
        };

        let mut outer_fields = HashMap::new();
        outer_fields.insert(
            "outer_key".to_string(),
            OFValue::String("outer_value".to_string()),
        );
        outer_fields.insert("nested".to_string(), OFValue::Struct(inner_struct));

        let outer_struct = StructValue {
            fields: outer_fields,
        };
        let result = operator.struct_value_to_json(&outer_struct);

        assert!(result.is_object());
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("outer_key").unwrap(), "outer_value");

        let nested = obj.get("nested").unwrap().as_object().unwrap();
        assert_eq!(nested.get("inner_key").unwrap(), "inner_value");
    }

    #[test]
    fn test_array_value_to_json() {
        let operator = Operator::new();

        let array = vec![
            OFValue::String("a".to_string()),
            OFValue::Int(1),
            OFValue::Bool(true),
        ];

        let result = operator.open_feature_value_to_json(&OFValue::Array(array));

        assert!(result.is_array());
        let arr = result.as_array().unwrap();
        assert_eq!(arr.len(), 3);
        assert_eq!(arr[0], "a");
        assert_eq!(arr[1], 1);
        assert_eq!(arr[2], true);
    }

    #[test]
    fn test_apply_simple_targeting_rule() {
        let operator = Operator::new();
        let ctx = EvaluationContext::default().with_custom_field("tier", "premium");

        // Simple if rule: if tier == "premium" then "gold" else "silver"
        let rule = r#"{
            "if": [
                {"==": [{"var": "tier"}, "premium"]},
                "gold",
                "silver"
            ]
        }"#;

        let result = operator.apply("test-flag", rule, &ctx).unwrap();
        assert_eq!(result, Some("gold".to_string()));
    }

    #[test]
    fn test_apply_targeting_rule_with_default() {
        let operator = Operator::new();
        let ctx = EvaluationContext::default().with_custom_field("tier", "basic");

        let rule = r#"{
            "if": [
                {"==": [{"var": "tier"}, "premium"]},
                "gold",
                "silver"
            ]
        }"#;

        let result = operator.apply("test-flag", rule, &ctx).unwrap();
        assert_eq!(result, Some("silver".to_string()));
    }

    #[test]
    fn test_apply_targeting_rule_with_string_operators() {
        let operator = Operator::new();
        let ctx = EvaluationContext::default().with_custom_field("email", "employee@company.com");

        let ends_with_rule = r#"{
            "if": [
                {"ends_with": [{"var": "email"}, "@company.com"]},
                "internal",
                "external"
            ]
        }"#;

        let result = operator.apply("test-flag", ends_with_rule, &ctx).unwrap();
        assert_eq!(result, Some("internal".to_string()));

        let starts_with_rule = r#"{
            "if": [
                {"starts_with": [{"var": "email"}, "employee@"]},
                "internal",
                "external"
            ]
        }"#;

        let result = operator.apply("test-flag", starts_with_rule, &ctx).unwrap();
        assert_eq!(result, Some("internal".to_string()));
    }

    #[test]
    fn test_apply_empty_targeting_returns_none() {
        let operator = Operator::new();
        let ctx = EvaluationContext::default();

        let rule = "null";
        let result = operator.apply("test-flag", rule, &ctx).unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn test_apply_substring_operators_with_numeric_pattern() {
        let operator = Operator::new();
        let ctx = EvaluationContext::default().with_custom_field("id", "3");

        let rule = r#"{
            "if": [
                {"starts_with": [{"var": "id"}, "abc"]},
                "prefix",
                {"if": [
                    {"ends_with": [{"var": "id"}, "xyz"]},
                    "postfix",
                    {"if": [
                        {"ends_with": [{"var": "id"}, 3]},
                        "fail",
                        "none"
                    ]}
                ]}
            ]
        }"#;

        let result = operator.apply("test-flag", rule, &ctx).unwrap();
        assert_eq!(result, Some("none".to_string()));
    }
}