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
//! Template System (inspired by CLIPS deftemplate)
//!
//! Provides type-safe structured facts with schema validation.
//! Similar to CLIPS deftemplate and Drools declared types.

use crate::errors::{Result, RuleEngineError};
use crate::rete::facts::{FactValue, TypedFacts};
use std::collections::HashMap;

/// Field definition in a template
#[derive(Debug, Clone, PartialEq)]
pub struct FieldDef {
    pub name: String,
    pub field_type: FieldType,
    pub default_value: Option<FactValue>,
    pub required: bool,
}

/// Supported field types
#[derive(Debug, Clone, PartialEq)]
pub enum FieldType {
    String,
    Integer,
    Float,
    Boolean,
    Array(Box<FieldType>),
    Any,
}

impl FieldType {
    /// Check if a value matches this field type
    pub fn matches(&self, value: &FactValue) -> bool {
        match (self, value) {
            (FieldType::String, FactValue::String(_)) => true,
            (FieldType::Integer, FactValue::Integer(_)) => true,
            (FieldType::Float, FactValue::Float(_)) => true,
            (FieldType::Boolean, FactValue::Boolean(_)) => true,
            (FieldType::Array(inner), FactValue::Array(arr)) => {
                // Check if all elements match the inner type
                arr.iter().all(|v| inner.matches(v))
            }
            (FieldType::Any, _) => true,
            _ => false,
        }
    }

    /// Get default value for this type
    pub fn default_value(&self) -> FactValue {
        match self {
            FieldType::String => FactValue::String(String::new()),
            FieldType::Integer => FactValue::Integer(0),
            FieldType::Float => FactValue::Float(0.0),
            FieldType::Boolean => FactValue::Boolean(false),
            FieldType::Array(_) => FactValue::Array(Vec::new()),
            FieldType::Any => FactValue::Null,
        }
    }
}

/// Template definition (like CLIPS deftemplate)
#[derive(Debug, Clone)]
pub struct Template {
    pub name: String,
    pub fields: Vec<FieldDef>,
    field_map: HashMap<String, usize>,
}

impl Template {
    /// Create a new template
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            fields: Vec::new(),
            field_map: HashMap::new(),
        }
    }

    /// Add a field to the template
    pub fn add_field(&mut self, field: FieldDef) -> &mut Self {
        let idx = self.fields.len();
        self.field_map.insert(field.name.clone(), idx);
        self.fields.push(field);
        self
    }

    /// Validate that facts conform to this template
    pub fn validate(&self, facts: &TypedFacts) -> Result<()> {
        // Check required fields
        for field in &self.fields {
            let value = facts.get(&field.name);

            if field.required && value.is_none() {
                return Err(RuleEngineError::EvaluationError {
                    message: format!(
                        "Required field '{}' missing in template '{}'",
                        field.name, self.name
                    ),
                });
            }

            // Check type if value exists
            if let Some(val) = value {
                if !field.field_type.matches(val) {
                    return Err(RuleEngineError::EvaluationError {
                        message: format!(
                            "Field '{}' has wrong type. Expected {:?}, got {:?}",
                            field.name, field.field_type, val
                        ),
                    });
                }
            }
        }

        Ok(())
    }

    /// Create facts from template with default values
    pub fn create_instance(&self) -> TypedFacts {
        let mut facts = TypedFacts::new();

        for field in &self.fields {
            let value = field
                .default_value
                .clone()
                .unwrap_or_else(|| field.field_type.default_value());
            facts.set(&field.name, value);
        }

        facts
    }

    /// Get field definition by name
    pub fn get_field(&self, name: &str) -> Option<&FieldDef> {
        self.field_map
            .get(name)
            .and_then(|idx| self.fields.get(*idx))
    }
}

/// Template builder for fluent API
pub struct TemplateBuilder {
    template: Template,
}

impl TemplateBuilder {
    /// Start building a template
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            template: Template::new(name),
        }
    }

    /// Add a string field
    pub fn string_field(mut self, name: impl Into<String>) -> Self {
        self.template.add_field(FieldDef {
            name: name.into(),
            field_type: FieldType::String,
            default_value: None,
            required: false,
        });
        self
    }

    /// Add a required string field
    pub fn required_string(mut self, name: impl Into<String>) -> Self {
        self.template.add_field(FieldDef {
            name: name.into(),
            field_type: FieldType::String,
            default_value: None,
            required: true,
        });
        self
    }

    /// Add an integer field
    pub fn integer_field(mut self, name: impl Into<String>) -> Self {
        self.template.add_field(FieldDef {
            name: name.into(),
            field_type: FieldType::Integer,
            default_value: None,
            required: false,
        });
        self
    }

    /// Add a float field
    pub fn float_field(mut self, name: impl Into<String>) -> Self {
        self.template.add_field(FieldDef {
            name: name.into(),
            field_type: FieldType::Float,
            default_value: None,
            required: false,
        });
        self
    }

    /// Add a boolean field
    pub fn boolean_field(mut self, name: impl Into<String>) -> Self {
        self.template.add_field(FieldDef {
            name: name.into(),
            field_type: FieldType::Boolean,
            default_value: None,
            required: false,
        });
        self
    }

    /// Add a field with custom default
    pub fn field_with_default(
        mut self,
        name: impl Into<String>,
        field_type: FieldType,
        default: FactValue,
    ) -> Self {
        self.template.add_field(FieldDef {
            name: name.into(),
            field_type,
            default_value: Some(default),
            required: false,
        });
        self
    }

    /// Add an array field
    pub fn array_field(mut self, name: impl Into<String>, element_type: FieldType) -> Self {
        self.template.add_field(FieldDef {
            name: name.into(),
            field_type: FieldType::Array(Box::new(element_type)),
            default_value: None,
            required: false,
        });
        self
    }

    /// Add a multislot field (CLIPS-style naming for arrays)
    ///
    /// This is an alias for `array_field` that uses CLIPS terminology.
    /// In CLIPS, multislot fields can hold multiple values of the same type.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let template = TemplateBuilder::new("Order")
    ///     .required_string("order_id")
    ///     .multislot_field("items", FieldType::String)  // CLIPS style
    ///     .build();
    /// ```
    ///
    /// Equivalent to:
    /// ```clips
    /// (deftemplate order
    ///   (slot order-id (type STRING))
    ///   (multislot items (type STRING)))
    /// ```
    pub fn multislot_field(self, name: impl Into<String>, element_type: FieldType) -> Self {
        self.array_field(name, element_type)
    }

    /// Add a required array field
    pub fn required_array_field(
        mut self,
        name: impl Into<String>,
        element_type: FieldType,
    ) -> Self {
        self.template.add_field(FieldDef {
            name: name.into(),
            field_type: FieldType::Array(Box::new(element_type)),
            default_value: None,
            required: true,
        });
        self
    }

    /// Add a required multislot field (CLIPS-style)
    pub fn required_multislot_field(
        self,
        name: impl Into<String>,
        element_type: FieldType,
    ) -> Self {
        self.required_array_field(name, element_type)
    }

    /// Build the template
    pub fn build(self) -> Template {
        self.template
    }
}

/// Template registry for managing templates
pub struct TemplateRegistry {
    templates: HashMap<String, Template>,
}

impl TemplateRegistry {
    /// Create a new template registry
    pub fn new() -> Self {
        Self {
            templates: HashMap::new(),
        }
    }

    /// Register a template
    pub fn register(&mut self, template: Template) {
        self.templates.insert(template.name.clone(), template);
    }

    /// Get a template by name
    pub fn get(&self, name: &str) -> Option<&Template> {
        self.templates.get(name)
    }

    /// Create an instance from a template
    pub fn create_instance(&self, template_name: &str) -> Result<TypedFacts> {
        let template = self
            .get(template_name)
            .ok_or_else(|| RuleEngineError::EvaluationError {
                message: format!("Template '{}' not found", template_name),
            })?;

        Ok(template.create_instance())
    }

    /// Validate facts against a template
    pub fn validate(&self, template_name: &str, facts: &TypedFacts) -> Result<()> {
        let template = self
            .get(template_name)
            .ok_or_else(|| RuleEngineError::EvaluationError {
                message: format!("Template '{}' not found", template_name),
            })?;

        template.validate(facts)
    }

    /// List all registered templates
    pub fn list_templates(&self) -> Vec<&str> {
        self.templates.keys().map(|s| s.as_str()).collect()
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_template_builder() {
        let template = TemplateBuilder::new("Person")
            .required_string("name")
            .integer_field("age")
            .boolean_field("is_adult")
            .build();

        assert_eq!(template.name, "Person");
        assert_eq!(template.fields.len(), 3);
        assert!(template.get_field("name").unwrap().required);
    }

    #[test]
    fn test_create_instance() {
        let template = TemplateBuilder::new("Person")
            .string_field("name")
            .integer_field("age")
            .build();

        let instance = template.create_instance();
        assert_eq!(
            instance.get("name"),
            Some(&FactValue::String(String::new()))
        );
        assert_eq!(instance.get("age"), Some(&FactValue::Integer(0)));
    }

    #[test]
    fn test_validation_success() {
        let template = TemplateBuilder::new("Person")
            .required_string("name")
            .integer_field("age")
            .build();

        let mut facts = TypedFacts::new();
        facts.set("name", FactValue::String("Alice".to_string()));
        facts.set("age", FactValue::Integer(30));

        assert!(template.validate(&facts).is_ok());
    }

    #[test]
    fn test_validation_missing_required() {
        let template = TemplateBuilder::new("Person")
            .required_string("name")
            .integer_field("age")
            .build();

        let mut facts = TypedFacts::new();
        facts.set("age", FactValue::Integer(30));

        assert!(template.validate(&facts).is_err());
    }

    #[test]
    fn test_validation_wrong_type() {
        let template = TemplateBuilder::new("Person")
            .string_field("name")
            .integer_field("age")
            .build();

        let mut facts = TypedFacts::new();
        facts.set("name", FactValue::String("Alice".to_string()));
        facts.set("age", FactValue::String("thirty".to_string())); // Wrong type!

        assert!(template.validate(&facts).is_err());
    }

    #[test]
    fn test_template_registry() {
        let mut registry = TemplateRegistry::new();

        let template = TemplateBuilder::new("Order")
            .required_string("order_id")
            .float_field("amount")
            .build();

        registry.register(template);

        assert!(registry.get("Order").is_some());
        assert!(registry.create_instance("Order").is_ok());
        assert_eq!(registry.list_templates(), vec!["Order"]);
    }

    #[test]
    fn test_array_field() {
        let template = TemplateBuilder::new("ShoppingCart")
            .array_field("items", FieldType::String)
            .build();

        let mut facts = TypedFacts::new();
        facts.set(
            "items",
            FactValue::Array(vec![
                FactValue::String("item1".to_string()),
                FactValue::String("item2".to_string()),
            ]),
        );

        assert!(template.validate(&facts).is_ok());
    }

    #[test]
    fn test_field_with_default() {
        let template = TemplateBuilder::new("Config")
            .field_with_default("timeout", FieldType::Integer, FactValue::Integer(30))
            .build();

        let instance = template.create_instance();
        assert_eq!(instance.get("timeout"), Some(&FactValue::Integer(30)));
    }
}