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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
#![allow(deprecated)]

use crate::engine::rule::Rule;
use crate::errors::{Result, RuleEngineError};
use crate::parser::grl::GRLParser;
use crate::types::Value;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

/// Knowledge Base - manages collections of rules and facts
/// Similar to Grule's KnowledgeBase concept
#[derive(Debug)]
pub struct KnowledgeBase {
    name: String,
    rules: Arc<RwLock<Vec<Rule>>>,
    rule_index: Arc<RwLock<HashMap<String, usize>>>,
    version: Arc<RwLock<u64>>,
}

impl KnowledgeBase {
    /// Create a new knowledge base
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            rules: Arc::new(RwLock::new(Vec::new())),
            rule_index: Arc::new(RwLock::new(HashMap::new())),
            version: Arc::new(RwLock::new(0)),
        }
    }

    /// Get the knowledge base name
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the current version of the knowledge base
    pub fn version(&self) -> u64 {
        *self.version.read().unwrap()
    }

    /// Add a rule to the knowledge base
    pub fn add_rule(&self, rule: Rule) -> Result<()> {
        let mut rules = self.rules.write().unwrap();
        let mut index = self.rule_index.write().unwrap();
        let mut version = self.version.write().unwrap();

        // Check for duplicate rule names
        if index.contains_key(&rule.name) {
            return Err(RuleEngineError::ParseError {
                message: format!("Rule '{}' already exists", rule.name),
            });
        }

        let rule_position = rules.len();
        index.insert(rule.name.clone(), rule_position);
        rules.push(rule);

        // Sort rules by priority (salience)
        rules.sort_by(|a, b| b.salience.cmp(&a.salience));

        // Rebuild index after sorting
        index.clear();
        for (pos, rule) in rules.iter().enumerate() {
            index.insert(rule.name.clone(), pos);
        }

        *version += 1;
        Ok(())
    }

    /// Add multiple rules from GRL text
    pub fn add_rules_from_grl(&self, grl_text: &str) -> Result<usize> {
        let rules = GRLParser::parse_rules(grl_text)?;
        let count = rules.len();

        for rule in rules {
            self.add_rule(rule)?;
        }

        Ok(count)
    }

    /// Remove a rule by name
    pub fn remove_rule(&self, rule_name: &str) -> Result<bool> {
        let mut rules = self.rules.write().unwrap();
        let mut index = self.rule_index.write().unwrap();
        let mut version = self.version.write().unwrap();

        if let Some(&position) = index.get(rule_name) {
            rules.remove(position);

            // Rebuild index
            index.clear();
            for (pos, rule) in rules.iter().enumerate() {
                index.insert(rule.name.clone(), pos);
            }

            *version += 1;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Get a rule by name
    pub fn get_rule(&self, rule_name: &str) -> Option<Rule> {
        let rules = self.rules.read().unwrap();
        let index = self.rule_index.read().unwrap();

        if let Some(&position) = index.get(rule_name) {
            rules.get(position).cloned()
        } else {
            None
        }
    }

    /// Get all rules
    pub fn get_rules(&self) -> Vec<Rule> {
        let rules = self.rules.read().unwrap();
        rules.clone()
    }

    /// Get rules sorted by salience without cloning individual rules
    /// Returns references to rules in descending salience order
    pub fn get_rules_by_salience(&self) -> Vec<usize> {
        let rules = self.rules.read().unwrap();
        let mut indices: Vec<usize> = (0..rules.len()).collect();
        indices.sort_by(|&a, &b| rules[b].salience.cmp(&rules[a].salience));
        indices
    }

    /// Get rule by index - avoids cloning
    pub fn get_rule_by_index(&self, index: usize) -> Option<Rule> {
        let rules = self.rules.read().unwrap();
        rules.get(index).cloned()
    }

    /// Get all rule names
    pub fn get_rule_names(&self) -> Vec<String> {
        let index = self.rule_index.read().unwrap();
        index.keys().cloned().collect()
    }

    /// Get rule count
    pub fn rule_count(&self) -> usize {
        let rules = self.rules.read().unwrap();
        rules.len()
    }

    /// Enable or disable a rule
    pub fn set_rule_enabled(&self, rule_name: &str, enabled: bool) -> Result<bool> {
        let mut rules = self.rules.write().unwrap();
        let index = self.rule_index.read().unwrap();
        let mut version = self.version.write().unwrap();

        if let Some(&position) = index.get(rule_name) {
            if let Some(rule) = rules.get_mut(position) {
                rule.enabled = enabled;
                *version += 1;
                Ok(true)
            } else {
                Ok(false)
            }
        } else {
            Ok(false)
        }
    }

    /// Clear all rules
    pub fn clear(&self) {
        let mut rules = self.rules.write().unwrap();
        let mut index = self.rule_index.write().unwrap();
        let mut version = self.version.write().unwrap();

        rules.clear();
        index.clear();
        *version += 1;
    }

    /// Get a snapshot of all rules (for execution)
    pub fn get_rules_snapshot(&self) -> Vec<Rule> {
        let rules = self.rules.read().unwrap();
        rules.clone()
    }

    /// Get knowledge base statistics
    pub fn get_statistics(&self) -> KnowledgeBaseStats {
        let rules = self.rules.read().unwrap();

        let enabled_count = rules.iter().filter(|r| r.enabled).count();
        let disabled_count = rules.len() - enabled_count;

        let mut priority_distribution = HashMap::new();
        for rule in rules.iter() {
            *priority_distribution.entry(rule.salience).or_insert(0) += 1;
        }

        KnowledgeBaseStats {
            name: self.name.clone(),
            version: self.version(),
            total_rules: rules.len(),
            enabled_rules: enabled_count,
            disabled_rules: disabled_count,
            priority_distribution,
        }
    }

    /// Export rules to GRL format
    pub fn export_to_grl(&self) -> String {
        let rules = self.rules.read().unwrap();
        let mut grl_output = String::new();

        grl_output.push_str(&format!("// Knowledge Base: {}\n", self.name));
        grl_output.push_str(&format!("// Version: {}\n", self.version()));
        grl_output.push_str(&format!("// Rules: {}\n\n", rules.len()));

        for rule in rules.iter() {
            grl_output.push_str(&rule.to_grl());
            grl_output.push_str("\n\n");
        }

        grl_output
    }
}

impl Clone for KnowledgeBase {
    fn clone(&self) -> Self {
        let rules = self.rules.read().unwrap();
        let new_kb = KnowledgeBase::new(&self.name);

        for rule in rules.iter() {
            let _ = new_kb.add_rule(rule.clone());
        }

        new_kb
    }
}

/// Statistics about a Knowledge Base
#[derive(Debug, Clone)]
pub struct KnowledgeBaseStats {
    /// The name of the knowledge base
    pub name: String,
    /// The version number of the knowledge base
    pub version: u64,
    /// Total number of rules in the knowledge base
    pub total_rules: usize,
    /// Number of enabled rules
    pub enabled_rules: usize,
    /// Number of disabled rules
    pub disabled_rules: usize,
    /// Distribution of rules by priority/salience
    pub priority_distribution: HashMap<i32, usize>,
}

impl std::fmt::Display for KnowledgeBaseStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Knowledge Base: {}", self.name)?;
        writeln!(f, "Version: {}", self.version)?;
        writeln!(f, "Total Rules: {}", self.total_rules)?;
        writeln!(f, "Enabled Rules: {}", self.enabled_rules)?;
        writeln!(f, "Disabled Rules: {}", self.disabled_rules)?;
        writeln!(f, "Priority Distribution:")?;

        let mut priorities: Vec<_> = self.priority_distribution.iter().collect();
        priorities.sort_by(|a, b| b.0.cmp(a.0));

        for (priority, count) in priorities {
            writeln!(f, "  Priority {}: {} rules", priority, count)?;
        }

        Ok(())
    }
}

/// Extension trait to add GRL export functionality to Rule
trait RuleGRLExport {
    fn to_grl(&self) -> String;
}

impl RuleGRLExport for Rule {
    fn to_grl(&self) -> String {
        let mut grl = String::new();

        // Rule declaration
        grl.push_str(&format!("rule {}", self.name));

        if let Some(ref description) = self.description {
            grl.push_str(&format!(" \"{}\"", description));
        }

        if self.salience != 0 {
            grl.push_str(&format!(" salience {}", self.salience));
        }

        grl.push_str(" {\n");

        // When clause
        grl.push_str("    when\n");
        grl.push_str(&format!("        {}\n", self.conditions.to_grl()));

        // Then clause
        grl.push_str("    then\n");
        for action in &self.actions {
            grl.push_str(&format!("        {};\n", action.to_grl()));
        }

        grl.push('}');

        if !self.enabled {
            grl = format!("// DISABLED\n{}", grl);
        }

        grl
    }
}

/// Extension trait for ConditionGroup GRL export
trait ConditionGroupGRLExport {
    fn to_grl(&self) -> String;
}

impl ConditionGroupGRLExport for crate::engine::rule::ConditionGroup {
    fn to_grl(&self) -> String {
        match self {
            crate::engine::rule::ConditionGroup::Single(condition) => {
                format!(
                    "{} {} {}",
                    condition.field,
                    condition.operator.to_grl(),
                    condition.value.to_grl()
                )
            }
            crate::engine::rule::ConditionGroup::Compound {
                left,
                operator,
                right,
            } => {
                let op_str = match operator {
                    crate::types::LogicalOperator::And => "&&",
                    crate::types::LogicalOperator::Or => "||",
                    crate::types::LogicalOperator::Not => "!",
                };
                format!("{} {} {}", left.to_grl(), op_str, right.to_grl())
            }
            crate::engine::rule::ConditionGroup::Not(condition) => {
                format!("!{}", condition.to_grl())
            }
            crate::engine::rule::ConditionGroup::Exists(condition) => {
                format!("exists({})", condition.to_grl())
            }
            crate::engine::rule::ConditionGroup::Forall(condition) => {
                format!("forall({})", condition.to_grl())
            }
            crate::engine::rule::ConditionGroup::Accumulate {
                source_pattern,
                extract_field,
                source_conditions,
                function,
                function_arg,
                ..
            } => {
                let conditions_str = if source_conditions.is_empty() {
                    String::new()
                } else {
                    format!(", {}", source_conditions.join(", "))
                };
                format!(
                    "accumulate({}(${}: {}{}), {}({}))",
                    source_pattern,
                    function_arg.trim_start_matches('$'),
                    extract_field,
                    conditions_str,
                    function,
                    function_arg
                )
            }

            #[cfg(feature = "streaming")]
            crate::engine::rule::ConditionGroup::StreamPattern {
                var_name,
                event_type,
                stream_name,
                window,
            } => {
                // Format: login: LoginEvent from stream("logins") over window(10 min, sliding)
                let event_type_str = event_type
                    .as_ref()
                    .map(|t| format!("{} ", t))
                    .unwrap_or_default();
                let window_str = window
                    .as_ref()
                    .map(|w| {
                        let dur_secs = w.duration.as_secs();
                        let (dur_val, dur_unit) = if dur_secs >= 3600 {
                            (dur_secs / 3600, "hour")
                        } else if dur_secs >= 60 {
                            (dur_secs / 60, "min")
                        } else {
                            (dur_secs, "sec")
                        };
                        let window_type_str = match &w.window_type {
                            crate::engine::rule::StreamWindowType::Sliding => "sliding",
                            crate::engine::rule::StreamWindowType::Tumbling => "tumbling",
                            crate::engine::rule::StreamWindowType::Session { .. } => "session",
                        };
                        format!(
                            " over window({} {}, {})",
                            dur_val, dur_unit, window_type_str
                        )
                    })
                    .unwrap_or_default();
                format!(
                    "{}: {}from stream(\"{}\"){}",
                    var_name, event_type_str, stream_name, window_str
                )
            }
        }
    }
}

/// Extension trait for Operator GRL export
trait OperatorGRLExport {
    fn to_grl(&self) -> &'static str;
}

impl OperatorGRLExport for crate::types::Operator {
    fn to_grl(&self) -> &'static str {
        match self {
            crate::types::Operator::Equal => "==",
            crate::types::Operator::NotEqual => "!=",
            crate::types::Operator::GreaterThan => ">",
            crate::types::Operator::GreaterThanOrEqual => ">=",
            crate::types::Operator::LessThan => "<",
            crate::types::Operator::LessThanOrEqual => "<=",
            crate::types::Operator::Contains => "contains",
            crate::types::Operator::NotContains => "not_contains",
            crate::types::Operator::StartsWith => "startsWith",
            crate::types::Operator::EndsWith => "endsWith",
            crate::types::Operator::Matches => "matches",
            crate::types::Operator::In => "in",
        }
    }
}

/// Extension trait for Value GRL export
trait ValueGRLExport {
    fn to_grl(&self) -> String;
}

impl ValueGRLExport for Value {
    fn to_grl(&self) -> String {
        match self {
            Value::String(s) => format!("\"{}\"", s),
            Value::Number(n) => n.to_string(),
            Value::Integer(i) => i.to_string(),
            Value::Boolean(b) => b.to_string(),
            Value::Null => "null".to_string(),
            Value::Array(_) => "[array]".to_string(),
            Value::Object(_) => "{object}".to_string(),
            Value::Expression(expr) => expr.clone(), // Export as-is
        }
    }
}

/// Extension trait for ActionType GRL export
trait ActionTypeGRLExport {
    fn to_grl(&self) -> String;
}

impl ActionTypeGRLExport for crate::types::ActionType {
    fn to_grl(&self) -> String {
        match self {
            crate::types::ActionType::Set { field, value } => {
                format!("{} = {}", field, value.to_grl())
            }
            crate::types::ActionType::Log { message } => {
                format!("Log(\"{}\")", message)
            }
            crate::types::ActionType::MethodCall {
                object,
                method,
                args,
            } => {
                let args_str = args
                    .iter()
                    .map(|arg| arg.to_grl())
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("{}.{}({})", object, method, args_str)
            }
            crate::types::ActionType::Retract { object } => {
                format!("retract(${})", object)
            }
            crate::types::ActionType::Custom { action_type, .. } => {
                format!("Custom(\"{}\")", action_type)
            }
            crate::types::ActionType::ActivateAgendaGroup { group } => {
                format!("ActivateAgendaGroup(\"{}\")", group)
            }
            crate::types::ActionType::ScheduleRule {
                rule_name,
                delay_ms,
            } => {
                format!("ScheduleRule({}, \"{}\")", delay_ms, rule_name)
            }
            crate::types::ActionType::CompleteWorkflow { workflow_name } => {
                format!("CompleteWorkflow(\"{}\")", workflow_name)
            }
            crate::types::ActionType::SetWorkflowData { key, value } => {
                format!("SetWorkflowData(\"{}={}\")", key, value.to_grl())
            }
            crate::types::ActionType::Append { field, value } => {
                format!("{} += {}", field, value.to_grl())
            }
        }
    }
}