rust-rule-engine 1.20.1

A blazing-fast Rust rule engine with RETE algorithm, backward chaining inference, and GRL (Grule Rule Language) syntax. Features: forward/backward chaining, pattern matching, unification, O(1) rule indexing, TMS, expression evaluation, method calls, streaming with Redis state backend, watermarking, and custom functions. Production-ready for business rules, expert systems, real-time stream processing, and decision automation.
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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Represents a value that can be used in rule conditions and actions
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Value {
    /// String value
    String(String),
    /// Floating point number
    Number(f64),
    /// Integer value
    Integer(i64),
    /// Boolean value
    Boolean(bool),
    /// Array of values
    Array(Vec<Value>),
    /// Object with key-value pairs
    Object(HashMap<String, Value>),
    /// Null value
    Null,
    /// Expression to be evaluated at runtime (e.g., "Order.quantity * Order.price")
    Expression(String),
}

impl Value {
    /// Convert Value to string representation  
    #[allow(clippy::inherent_to_string_shadow_display)]
    pub fn to_string(&self) -> String {
        match self {
            Value::String(s) => s.clone(), // TODO: Can be optimized with Cow<str>
            Value::Number(n) => n.to_string(),
            Value::Integer(i) => i.to_string(),
            Value::Boolean(b) => b.to_string(),
            Value::Array(_) => "[Array]".to_string(),
            Value::Object(_) => "[Object]".to_string(),
            Value::Null => "null".to_string(),
            Value::Expression(expr) => format!("[Expr: {}]", expr),
        }
    }

    /// Get string reference without cloning (when possible)
    pub fn as_str(&self) -> std::borrow::Cow<'_, str> {
        match self {
            Value::String(s) => std::borrow::Cow::Borrowed(s),
            Value::Number(n) => std::borrow::Cow::Owned(n.to_string()),
            Value::Integer(i) => std::borrow::Cow::Owned(i.to_string()),
            Value::Boolean(b) => std::borrow::Cow::Borrowed(if *b { "true" } else { "false" }),
            Value::Array(_) => std::borrow::Cow::Borrowed("[Array]"),
            Value::Object(_) => std::borrow::Cow::Borrowed("[Object]"),
            Value::Null => std::borrow::Cow::Borrowed("null"),
            Value::Expression(expr) => std::borrow::Cow::Owned(format!("[Expr: {}]", expr)),
        }
    }

    /// Convert Value to number if possible
    pub fn to_number(&self) -> Option<f64> {
        match self {
            Value::Number(n) => Some(*n),
            Value::Integer(i) => Some(*i as f64),
            Value::String(s) => s.parse::<f64>().ok(),
            _ => None,
        }
    }

    /// Get string value if this is a string
    pub fn as_string(&self) -> Option<String> {
        match self {
            Value::String(s) => Some(s.clone()),
            _ => None,
        }
    }

    /// Get string reference without cloning (returns None for non-String variants)
    pub fn as_string_ref(&self) -> Option<&str> {
        match self {
            Value::String(s) => Some(s),
            _ => None,
        }
    }

    /// Get integer value if this is an integer
    pub fn as_integer(&self) -> Option<i64> {
        match self {
            Value::Integer(i) => Some(*i),
            _ => None,
        }
    }

    /// Get boolean value if this is a boolean
    pub fn as_boolean(&self) -> Option<bool> {
        match self {
            Value::Boolean(b) => Some(*b),
            _ => None,
        }
    }

    /// Get number value if this is a number
    pub fn as_number(&self) -> Option<f64> {
        match self {
            Value::Number(n) => Some(*n),
            _ => None,
        }
    }

    /// Convert Value to boolean
    pub fn to_bool(&self) -> bool {
        match self {
            Value::Boolean(b) => *b,
            Value::String(s) => !s.is_empty(),
            Value::Number(n) => *n != 0.0,
            Value::Integer(i) => *i != 0,
            Value::Array(arr) => !arr.is_empty(),
            Value::Object(obj) => !obj.is_empty(),
            Value::Null => false,
            Value::Expression(_) => false, // Expression needs to be evaluated first
        }
    }

    /// Call a method on this value with given arguments
    pub fn call_method(&mut self, method: &str, args: Vec<Value>) -> Result<Value, String> {
        match self {
            Value::Object(ref mut obj) => match method {
                "setSpeed" => {
                    if let Some(Value::Number(speed)) = args.first() {
                        obj.insert("Speed".to_string(), Value::Number(*speed));
                        Ok(Value::Null)
                    } else if let Some(Value::Integer(speed)) = args.first() {
                        obj.insert("Speed".to_string(), Value::Integer(*speed));
                        Ok(Value::Null)
                    } else {
                        Err("setSpeed requires a number argument".to_string())
                    }
                }
                "setTotalDistance" => {
                    if let Some(Value::Number(distance)) = args.first() {
                        obj.insert("TotalDistance".to_string(), Value::Number(*distance));
                        Ok(Value::Null)
                    } else if let Some(Value::Integer(distance)) = args.first() {
                        obj.insert("TotalDistance".to_string(), Value::Integer(*distance));
                        Ok(Value::Null)
                    } else {
                        Err("setTotalDistance requires a number argument".to_string())
                    }
                }
                "getTotalDistance" => Ok(obj
                    .get("TotalDistance")
                    .cloned()
                    .unwrap_or(Value::Number(0.0))),
                "getSpeed" => Ok(obj.get("Speed").cloned().unwrap_or(Value::Number(0.0))),
                _ => Err(format!("Method {} not found", method)),
            },
            _ => Err("Cannot call method on non-object value".to_string()),
        }
    }

    /// Get a property from this object
    pub fn get_property(&self, property: &str) -> Option<Value> {
        match self {
            Value::Object(obj) => obj.get(property).cloned(),
            _ => None,
        }
    }

    /// Set a property on this object
    pub fn set_property(&mut self, property: &str, value: Value) -> Result<(), String> {
        match self {
            Value::Object(ref mut obj) => {
                obj.insert(property.to_string(), value);
                Ok(())
            }
            _ => Err("Cannot set property on non-object value".to_string()),
        }
    }
}

impl From<String> for Value {
    fn from(s: String) -> Self {
        Value::String(s)
    }
}

impl From<&str> for Value {
    fn from(s: &str) -> Self {
        Value::String(s.to_string())
    }
}

impl From<f64> for Value {
    fn from(n: f64) -> Self {
        Value::Number(n)
    }
}

impl From<i64> for Value {
    fn from(i: i64) -> Self {
        Value::Integer(i)
    }
}

impl From<bool> for Value {
    fn from(b: bool) -> Self {
        Value::Boolean(b)
    }
}

impl From<serde_json::Value> for Value {
    fn from(json_value: serde_json::Value) -> Self {
        match json_value {
            serde_json::Value::String(s) => Value::String(s),
            serde_json::Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    Value::Integer(i)
                } else if let Some(f) = n.as_f64() {
                    Value::Number(f)
                } else {
                    Value::Null
                }
            }
            serde_json::Value::Bool(b) => Value::Boolean(b),
            serde_json::Value::Array(arr) => {
                Value::Array(arr.into_iter().map(Value::from).collect())
            }
            serde_json::Value::Object(obj) => {
                let mut map = HashMap::new();
                for (k, v) in obj {
                    map.insert(k, Value::from(v));
                }
                Value::Object(map)
            }
            serde_json::Value::Null => Value::Null,
        }
    }
}

/// Comparison operators for rule conditions
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Operator {
    /// Equality comparison
    Equal,
    /// Inequality comparison
    NotEqual,
    /// Greater than comparison
    GreaterThan,
    /// Greater than or equal comparison
    GreaterThanOrEqual,
    /// Less than comparison
    LessThan,
    /// Less than or equal comparison
    LessThanOrEqual,
    /// String contains check
    Contains,
    /// String does not contain check
    NotContains,
    /// String starts with check
    StartsWith,
    /// String ends with check
    EndsWith,
    /// Regex pattern match
    Matches,
    /// Array membership check (value in array)
    In,
}

impl Operator {
    /// Parse operator from string representation
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "==" | "eq" => Some(Operator::Equal),
            "!=" | "ne" => Some(Operator::NotEqual),
            ">" | "gt" => Some(Operator::GreaterThan),
            ">=" | "gte" => Some(Operator::GreaterThanOrEqual),
            "<" | "lt" => Some(Operator::LessThan),
            "<=" | "lte" => Some(Operator::LessThanOrEqual),
            "contains" => Some(Operator::Contains),
            "not_contains" => Some(Operator::NotContains),
            "starts_with" | "startsWith" => Some(Operator::StartsWith),
            "ends_with" | "endsWith" => Some(Operator::EndsWith),
            "matches" => Some(Operator::Matches),
            "in" => Some(Operator::In),
            _ => None,
        }
    }

    /// Evaluate the operator against two values
    pub fn evaluate(&self, left: &Value, right: &Value) -> bool {
        match self {
            Operator::Equal => {
                // Special handling for null comparison
                // "null" string should be treated as Value::Null
                if matches!(left, Value::Null) || matches!(right, Value::Null) {
                    // Convert "null" string to Value::Null for comparison
                    let left_is_null = matches!(left, Value::Null)
                        || (matches!(left, Value::String(s) if s == "null"));
                    let right_is_null = matches!(right, Value::Null)
                        || (matches!(right, Value::String(s) if s == "null"));

                    left_is_null == right_is_null
                } else {
                    left == right
                }
            }
            Operator::NotEqual => {
                // Special handling for null comparison
                if matches!(left, Value::Null) || matches!(right, Value::Null) {
                    let left_is_null = matches!(left, Value::Null)
                        || (matches!(left, Value::String(s) if s == "null"));
                    let right_is_null = matches!(right, Value::Null)
                        || (matches!(right, Value::String(s) if s == "null"));

                    left_is_null != right_is_null
                } else {
                    left != right
                }
            }
            Operator::GreaterThan => {
                if let (Some(l), Some(r)) = (left.to_number(), right.to_number()) {
                    l > r
                } else {
                    false
                }
            }
            Operator::GreaterThanOrEqual => {
                if let (Some(l), Some(r)) = (left.to_number(), right.to_number()) {
                    l >= r
                } else {
                    false
                }
            }
            Operator::LessThan => {
                if let (Some(l), Some(r)) = (left.to_number(), right.to_number()) {
                    l < r
                } else {
                    false
                }
            }
            Operator::LessThanOrEqual => {
                if let (Some(l), Some(r)) = (left.to_number(), right.to_number()) {
                    l <= r
                } else {
                    false
                }
            }
            Operator::Contains => {
                if let (Some(l), Some(r)) = (left.as_string_ref(), right.as_string_ref()) {
                    l.contains(r)
                } else {
                    false
                }
            }
            Operator::NotContains => {
                if let (Some(l), Some(r)) = (left.as_string_ref(), right.as_string_ref()) {
                    !l.contains(r)
                } else {
                    false
                }
            }
            Operator::StartsWith => {
                if let (Some(l), Some(r)) = (left.as_string_ref(), right.as_string_ref()) {
                    l.starts_with(r)
                } else {
                    false
                }
            }
            Operator::EndsWith => {
                if let (Some(l), Some(r)) = (left.as_string_ref(), right.as_string_ref()) {
                    l.ends_with(r)
                } else {
                    false
                }
            }
            Operator::Matches => {
                // Simple regex match implementation
                if let (Some(l), Some(r)) = (left.as_string_ref(), right.as_string_ref()) {
                    // For now, just use contains as a simple match
                    l.contains(r)
                } else {
                    false
                }
            }
            Operator::In => {
                // Check if left value is in right array
                match right {
                    Value::Array(arr) => arr.contains(left),
                    _ => false,
                }
            }
        }
    }
}

/// Logical operators for combining conditions
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum LogicalOperator {
    /// Logical AND
    And,
    /// Logical OR
    Or,
    /// Logical NOT
    Not,
}

impl LogicalOperator {
    /// Parse logical operator from string representation
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "and" | "&&" => Some(LogicalOperator::And),
            "or" | "||" => Some(LogicalOperator::Or),
            "not" | "!" => Some(LogicalOperator::Not),
            _ => None,
        }
    }
}

/// Represents the data context for rule evaluation
pub type Context = HashMap<String, Value>;

/// Action types that can be performed when a rule matches
#[derive(Debug, Clone, PartialEq)]
pub enum ActionType {
    /// Set a field to a specific value
    Set {
        /// Field name to set
        field: String,
        /// Value to set
        value: Value,
    },
    /// Log a message
    Log {
        /// Message to log
        message: String,
    },
    /// Call a method on an object
    MethodCall {
        /// Object name
        object: String,
        /// Method name
        method: String,
        /// Method arguments
        args: Vec<Value>,
    },
    /// Retract (delete) a fact from working memory
    Retract {
        /// Object/fact to retract
        object: String,
    },
    /// Custom action
    Custom {
        /// Action type identifier
        action_type: String,
        /// Action parameters
        params: HashMap<String, Value>,
    },
    /// Activate a specific agenda group for workflow progression
    ActivateAgendaGroup {
        /// Agenda group name to activate
        group: String,
    },
    /// Schedule a rule to execute after a delay
    ScheduleRule {
        /// Rule name to schedule
        rule_name: String,
        /// Delay in milliseconds
        delay_ms: u64,
    },
    /// Complete a workflow and trigger cleanup
    CompleteWorkflow {
        /// Workflow name to complete
        workflow_name: String,
    },
    /// Set workflow-specific data
    SetWorkflowData {
        /// Data key
        key: String,
        /// Data value
        value: Value,
    },
    /// Append a value to an array field
    Append {
        /// Field name (must be an array)
        field: String,
        /// Value to append
        value: Value,
    },
}

// Efficient Display implementation for Value to avoid unnecessary cloning
impl std::fmt::Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Value::String(s) => write!(f, "{}", s),
            Value::Number(n) => write!(f, "{}", n),
            Value::Integer(i) => write!(f, "{}", i),
            Value::Boolean(b) => write!(f, "{}", b),
            Value::Array(_) => write!(f, "[Array]"),
            Value::Object(_) => write!(f, "[Object]"),
            Value::Null => write!(f, "null"),
            Value::Expression(expr) => write!(f, "[Expr: {}]", expr),
        }
    }
}