Skip to main content

rust_rule_engine/rete/
grl_loader.rs

1//! GRL to RETE Converter
2//!
3//! This module converts GRL (Grule Rule Language) rules into RETE-UL structures
4//! for efficient pattern matching and rule execution.
5
6#![allow(clippy::type_complexity)]
7#![allow(deprecated)]
8
9use crate::engine::rule::{Condition, ConditionGroup, Rule};
10use crate::errors::{Result, RuleEngineError};
11use crate::parser::GRLParser;
12use crate::rete::facts::{FactValue, TypedFacts};
13use crate::rete::propagation::IncrementalEngine;
14use crate::rete::{AlphaNode, ReteUlNode, TypedReteUlRule};
15use crate::types::{Operator, Value};
16use log::info;
17use std::fs;
18use std::path::Path;
19
20#[cfg(feature = "streaming")]
21use crate::rete::network::{StreamWindowSpec, StreamWindowTypeRete};
22
23/// GRL to RETE Loader
24/// Converts GRL rules into RETE-UL structures
25pub struct GrlReteLoader;
26
27impl GrlReteLoader {
28    /// Load rules from a GRL file into RETE engine
29    pub fn load_from_file<P: AsRef<Path>>(
30        path: P,
31        engine: &mut IncrementalEngine,
32    ) -> Result<usize> {
33        let grl_text =
34            fs::read_to_string(path.as_ref()).map_err(|e| RuleEngineError::ParseError {
35                message: format!("Failed to read GRL file: {}", e),
36            })?;
37
38        Self::load_from_string(&grl_text, engine)
39    }
40
41    /// Load rules from GRL string into RETE engine
42    pub fn load_from_string(grl_text: &str, engine: &mut IncrementalEngine) -> Result<usize> {
43        // Parse GRL rules
44        let rules = GRLParser::parse_rules(grl_text)?;
45
46        let mut loaded_count = 0;
47
48        for rule in rules {
49            // Convert GRL rule to RETE rule
50            let rete_rule = Self::convert_rule_to_rete(rule)?;
51
52            // Extract dependencies (fact types used in conditions)
53            let dependencies = Self::extract_dependencies(&rete_rule);
54
55            // Add to engine
56            engine.add_rule(rete_rule, dependencies);
57            loaded_count += 1;
58        }
59
60        Ok(loaded_count)
61    }
62
63    /// Convert GRL Rule to TypedReteUlRule
64    fn convert_rule_to_rete(rule: Rule) -> Result<TypedReteUlRule> {
65        // Convert ConditionGroup to ReteUlNode
66        let node = Self::convert_condition_group(&rule.conditions)?;
67
68        // Create RETE rule
69        let rete_rule = TypedReteUlRule {
70            name: rule.name.clone(),
71            node,
72            priority: rule.salience,
73            no_loop: rule.no_loop,
74            action: Self::create_action_closure(rule.actions),
75        };
76
77        Ok(rete_rule)
78    }
79
80    /// Convert ConditionGroup to ReteUlNode
81    fn convert_condition_group(group: &ConditionGroup) -> Result<ReteUlNode> {
82        match group {
83            ConditionGroup::Single(condition) => Self::convert_condition(condition),
84            ConditionGroup::Compound {
85                left,
86                operator,
87                right,
88            } => {
89                let left_node = Self::convert_condition_group(left)?;
90                let right_node = Self::convert_condition_group(right)?;
91
92                match operator {
93                    crate::types::LogicalOperator::And => {
94                        Ok(ReteUlNode::UlAnd(Box::new(left_node), Box::new(right_node)))
95                    }
96                    crate::types::LogicalOperator::Or => {
97                        Ok(ReteUlNode::UlOr(Box::new(left_node), Box::new(right_node)))
98                    }
99                    crate::types::LogicalOperator::Not => {
100                        // For NOT, we only use left node
101                        Ok(ReteUlNode::UlNot(Box::new(left_node)))
102                    }
103                }
104            }
105            ConditionGroup::Not(inner) => {
106                let inner_node = Self::convert_condition_group(inner)?;
107                Ok(ReteUlNode::UlNot(Box::new(inner_node)))
108            }
109            ConditionGroup::Exists(inner) => {
110                let inner_node = Self::convert_condition_group(inner)?;
111                Ok(ReteUlNode::UlExists(Box::new(inner_node)))
112            }
113            ConditionGroup::Forall(inner) => {
114                let inner_node = Self::convert_condition_group(inner)?;
115                Ok(ReteUlNode::UlForall(Box::new(inner_node)))
116            }
117            ConditionGroup::Accumulate {
118                result_var,
119                source_pattern,
120                extract_field,
121                source_conditions,
122                function,
123                function_arg,
124            } => Ok(ReteUlNode::UlAccumulate {
125                result_var: result_var.clone(),
126                source_pattern: source_pattern.clone(),
127                extract_field: extract_field.clone(),
128                source_conditions: source_conditions.clone(),
129                function: function.clone(),
130                function_arg: function_arg.clone(),
131            }),
132            #[cfg(feature = "streaming")]
133            ConditionGroup::StreamPattern {
134                var_name,
135                event_type,
136                stream_name,
137                window,
138            } => {
139                // Convert stream pattern to RETE UlStream node
140                Ok(ReteUlNode::UlStream {
141                    var_name: var_name.clone(),
142                    event_type: event_type.clone(),
143                    stream_name: stream_name.clone(),
144                    window: window.as_ref().map(|w| StreamWindowSpec {
145                        duration: w.duration,
146                        window_type: match &w.window_type {
147                            crate::engine::rule::StreamWindowType::Sliding => {
148                                StreamWindowTypeRete::Sliding
149                            }
150                            crate::engine::rule::StreamWindowType::Tumbling => {
151                                StreamWindowTypeRete::Tumbling
152                            }
153                            crate::engine::rule::StreamWindowType::Session { timeout } => {
154                                StreamWindowTypeRete::Session { timeout: *timeout }
155                            }
156                        },
157                    }),
158                })
159            }
160        }
161    }
162
163    /// Convert single Condition to ReteUlNode (AlphaNode or UlMultiField)
164    fn convert_condition(condition: &Condition) -> Result<ReteUlNode> {
165        use crate::engine::rule::ConditionExpression;
166
167        // Check if this is a multifield condition
168        match &condition.expression {
169            ConditionExpression::MultiField {
170                field,
171                operation,
172                variable: _,
173            } => {
174                // Convert to UlMultiField node
175                let operator_str = Self::operator_to_string(&condition.operator);
176                let value_str = if !matches!(condition.value, Value::Boolean(_)) {
177                    Some(Self::value_to_string(&condition.value))
178                } else {
179                    None
180                };
181
182                // Determine if this is a count operation with comparison
183                let (op, cmp_val) = if operation == "count" && operator_str != "==" {
184                    // Count with comparison: "count > 5"
185                    (Some(operator_str), value_str)
186                } else {
187                    // Other operations
188                    (None, value_str)
189                };
190
191                Ok(ReteUlNode::UlMultiField {
192                    field: field.clone(),
193                    operation: operation.clone(),
194                    value: if operation == "contains" {
195                        cmp_val.clone()
196                    } else {
197                        None
198                    },
199                    operator: op,
200                    compare_value: if operation == "count" { cmp_val } else { None },
201                })
202            }
203            ConditionExpression::FunctionCall { name, args } => Ok(ReteUlNode::UlFunctionCall {
204                name: name.clone(),
205                args: args.clone(),
206                operator: Self::operator_to_string(&condition.operator),
207                value: Self::value_to_string(&condition.value),
208            }),
209            _ => {
210                // Standard alpha node for regular conditions
211                let operator_str = Self::operator_to_string(&condition.operator);
212                let value_str = Self::value_to_string(&condition.value);
213
214                let alpha = AlphaNode {
215                    field: condition.field.clone(),
216                    operator: operator_str,
217                    value: value_str,
218                };
219
220                Ok(ReteUlNode::UlAlpha(alpha))
221            }
222        }
223    }
224
225    /// Convert Operator to string
226    fn operator_to_string(op: &Operator) -> String {
227        match op {
228            Operator::Equal => "==".to_string(),
229            Operator::NotEqual => "!=".to_string(),
230            Operator::GreaterThan => ">".to_string(),
231            Operator::GreaterThanOrEqual => ">=".to_string(),
232            Operator::LessThan => "<".to_string(),
233            Operator::LessThanOrEqual => "<=".to_string(),
234            Operator::Contains => "contains".to_string(),
235            Operator::NotContains => "!contains".to_string(),
236            Operator::StartsWith => "startsWith".to_string(),
237            Operator::EndsWith => "endsWith".to_string(),
238            Operator::Matches => "matches".to_string(),
239            Operator::In => "in".to_string(),
240        }
241    }
242
243    /// Convert Value to string for AlphaNode
244    fn value_to_string(value: &Value) -> String {
245        match value {
246            Value::Number(n) => n.to_string(),
247            Value::Integer(i) => i.to_string(),
248            Value::String(s) => s.clone(),
249            Value::Boolean(b) => b.to_string(),
250            Value::Null => "null".to_string(),
251            Value::Array(arr) => {
252                // Convert array to JSON-like string
253                let items: Vec<String> = arr.iter().map(Self::value_to_string).collect();
254                format!("[{}]", items.join(","))
255            }
256            Value::Object(_) => {
257                // For objects, we'll use a simplified representation
258                "object".to_string()
259            }
260            Value::Expression(expr) => {
261                // For expressions, return the expression string
262                expr.clone()
263            }
264        }
265    }
266
267    /// Create action closure from ActionType list
268    fn create_action_closure(
269        actions: Vec<crate::types::ActionType>,
270    ) -> std::sync::Arc<dyn Fn(&mut TypedFacts, &mut super::ActionResults) + Send + Sync> {
271        std::sync::Arc::new(
272            move |facts: &mut TypedFacts, results: &mut super::ActionResults| {
273                // Execute actions
274                for action in &actions {
275                    Self::execute_action(action, facts, results);
276                }
277            },
278        )
279    }
280
281    /// Execute a single action
282    fn execute_action(
283        action: &crate::types::ActionType,
284        facts: &mut TypedFacts,
285        results: &mut super::ActionResults,
286    ) {
287        use crate::types::ActionType;
288
289        match action {
290            ActionType::Set { field, value } => {
291                // Assignment action (from "field = value" syntax in GRL)
292                // Note: Set() function syntax is NOT supported.
293                // Use: Player.score = Player.score + 10;
294
295                // Check if value is an expression that needs evaluation
296                let evaluated_value = match value {
297                    Value::Expression(expr) => {
298                        // Evaluate expression with current facts
299                        Self::evaluate_expression_for_rete(expr, facts)
300                    }
301                    _ => value.clone(),
302                };
303
304                // Convert evaluated value to FactValue
305                let fact_value = Self::value_to_fact_value(&evaluated_value);
306                facts.set(field, fact_value);
307            }
308            ActionType::Log { message } => {
309                info!("📝 {}", message);
310            }
311            ActionType::MethodCall {
312                object,
313                method,
314                args,
315            } => {
316                // Method calls can be treated as function calls with object as first arg
317                let mut all_args = vec![object.clone()];
318                all_args.extend(args.iter().map(Self::value_to_string));
319
320                results.add(super::ActionResult::CallFunction {
321                    function_name: format!("{}.{}", object, method),
322                    args: all_args,
323                });
324                println!("� METHOD: {}.{}", object, method);
325            }
326            ActionType::Retract { object } => {
327                // Strip quotes from object name if present
328                let object_name = object.trim_matches('"');
329
330                // Try to get the handle for this fact type from metadata
331                if let Some(handle) = facts.get_fact_handle(object_name) {
332                    // Retract specific fact by handle
333                    results.add(super::ActionResult::Retract(handle));
334                    println!("🗑️ RETRACT: {} (handle: {:?})", object_name, handle);
335                } else {
336                    // Fallback: retract by type (first matching fact)
337                    results.add(super::ActionResult::RetractByType(object_name.to_string()));
338                    println!("🗑️ RETRACT: {} (by type, no handle found)", object_name);
339                }
340            }
341            ActionType::Custom {
342                action_type,
343                params,
344            } => {
345                // Treat custom actions as function calls
346                let args: Vec<String> = params.values().map(Self::value_to_string).collect();
347
348                results.add(super::ActionResult::CallFunction {
349                    function_name: action_type.clone(),
350                    args,
351                });
352                println!("🔧 CUSTOM CALL: {}", action_type);
353            }
354            ActionType::ActivateAgendaGroup { group } => {
355                // Queue agenda group activation
356                results.add(super::ActionResult::ActivateAgendaGroup(group.clone()));
357                println!("📋 ACTIVATE GROUP: {}", group);
358            }
359            ActionType::ScheduleRule {
360                rule_name,
361                delay_ms,
362            } => {
363                // Queue rule scheduling
364                results.add(super::ActionResult::ScheduleRule {
365                    rule_name: rule_name.clone(),
366                    delay_ms: *delay_ms,
367                });
368                println!("⏰ SCHEDULE: {} (delay: {}ms)", rule_name, delay_ms);
369            }
370            ActionType::CompleteWorkflow { workflow_name } => {
371                // Mark workflow as completed by setting a fact
372                let completion_key = format!("workflow.{}.completed", workflow_name);
373                facts.set(&completion_key, FactValue::Boolean(true));
374
375                let timestamp_key = format!("workflow.{}.completed_at", workflow_name);
376                facts.set(
377                    &timestamp_key,
378                    FactValue::Integer(chrono::Utc::now().timestamp()),
379                );
380
381                println!("✔️ WORKFLOW COMPLETED: {}", workflow_name);
382            }
383            ActionType::SetWorkflowData { key, value } => {
384                // Store workflow data as facts with "workflow.data." prefix
385                let data_key = format!("workflow.data.{}", key);
386                let fact_value = Self::value_to_fact_value(value);
387                facts.set(&data_key, fact_value);
388
389                println!("📊 WORKFLOW DATA SET: {} = {:?}", key, value);
390            }
391            ActionType::Append { field, value } => {
392                // Append to array field
393                // Get current array or create new one
394                let current_value = facts.get(field);
395
396                let mut array = match current_value {
397                    Some(FactValue::Array(arr)) => arr.clone(),
398                    Some(_) => {
399                        // Field exists but is not an array, create new array
400                        log::warn!("Field {} is not an array, creating new array", field);
401                        Vec::new()
402                    }
403                    None => {
404                        // Field doesn't exist, create new array
405                        Vec::new()
406                    }
407                };
408
409                // Evaluate value if it's an expression
410                let evaluated_value = match value {
411                    Value::Expression(expr) => Self::evaluate_expression_for_rete(expr, facts),
412                    _ => value.clone(),
413                };
414
415                // Convert to FactValue and append
416                let fact_value = Self::value_to_fact_value(&evaluated_value);
417                array.push(fact_value);
418
419                // Set the updated array
420                facts.set(field, FactValue::Array(array));
421
422                info!("➕ APPEND: {} += {:?}", field, evaluated_value);
423            }
424        }
425    }
426
427    /// Convert Value to FactValue
428    fn value_to_fact_value(value: &Value) -> FactValue {
429        match value {
430            Value::Number(n) => {
431                // Try integer first, fall back to float
432                if n.fract() == 0.0 {
433                    FactValue::Integer(*n as i64)
434                } else {
435                    FactValue::Float(*n)
436                }
437            }
438            Value::Integer(i) => FactValue::Integer(*i),
439            Value::String(s) => FactValue::String(s.clone()),
440            Value::Boolean(b) => FactValue::Boolean(*b),
441            Value::Null => FactValue::Null,
442            Value::Array(arr) => {
443                let fact_arr: Vec<FactValue> = arr.iter().map(Self::value_to_fact_value).collect();
444                FactValue::Array(fact_arr)
445            }
446            Value::Object(_) => {
447                // For now, treat objects as strings
448                FactValue::String("object".to_string())
449            }
450            Value::Expression(expr) => {
451                // For expressions, store as string - will be evaluated at runtime
452                FactValue::String(format!("[EXPR: {}]", expr))
453            }
454        }
455    }
456
457    /// Extract fact type dependencies from rule
458    fn extract_dependencies(rule: &TypedReteUlRule) -> Vec<String> {
459        let mut deps = Vec::new();
460        Self::extract_deps_from_node(&rule.node, &mut deps);
461
462        // Deduplicate
463        deps.sort();
464        deps.dedup();
465
466        deps
467    }
468
469    /// Recursively extract dependencies from ReteUlNode
470    fn extract_deps_from_node(node: &ReteUlNode, deps: &mut Vec<String>) {
471        match node {
472            ReteUlNode::UlAlpha(alpha) => {
473                // Extract fact type from field (e.g., "Person.age" -> "Person")
474                if let Some(dot_pos) = alpha.field.find('.') {
475                    let fact_type = alpha.field[..dot_pos].to_string();
476                    deps.push(fact_type);
477                }
478            }
479            ReteUlNode::UlMultiField { field, .. } => {
480                // Extract fact type from field (e.g., "Order.items" -> "Order")
481                if let Some(dot_pos) = field.find('.') {
482                    let fact_type = field[..dot_pos].to_string();
483                    deps.push(fact_type);
484                }
485            }
486            ReteUlNode::UlAnd(left, right) | ReteUlNode::UlOr(left, right) => {
487                Self::extract_deps_from_node(left, deps);
488                Self::extract_deps_from_node(right, deps);
489            }
490            ReteUlNode::UlNot(inner)
491            | ReteUlNode::UlExists(inner)
492            | ReteUlNode::UlForall(inner) => {
493                Self::extract_deps_from_node(inner, deps);
494            }
495            ReteUlNode::UlAccumulate { source_pattern, .. } => {
496                // Add source pattern as a dependency
497                deps.push(source_pattern.clone());
498            }
499            #[cfg(feature = "streaming")]
500            ReteUlNode::UlStream { stream_name, .. } => {
501                // Add stream name as a dependency
502                deps.push(stream_name.clone());
503            }
504            ReteUlNode::UlFunctionCall { args, .. } => {
505                for arg in args {
506                    if let Some(dot_pos) = arg.find('.') {
507                        deps.push(arg[..dot_pos].to_string());
508                    }
509                }
510            }
511            ReteUlNode::UlTerminal(_) => {}
512        }
513    }
514
515    /// Evaluate expression for RETE engine (converts TypedFacts to Facts temporarily)
516    fn evaluate_expression_for_rete(expr: &str, typed_facts: &TypedFacts) -> Value {
517        // Convert TypedFacts to Facts for expression evaluation
518        use crate::engine::facts::Facts;
519
520        let facts = Facts::new();
521
522        // Copy all facts from TypedFacts to Facts
523        // RETE stores facts as "quantity" while GRL uses "Order.quantity"
524        // We need to support both formats
525        for (key, value) in typed_facts.get_all() {
526            let converted_value = Self::fact_value_to_value(value);
527
528            // Store both with and without prefix
529            // E.g., "quantity" -> both "quantity" and "Order.quantity"
530            facts.set(key, converted_value.clone());
531
532            // Also try to add with "Order." prefix if not already present
533            if !key.contains('.') {
534                facts.set(&format!("Order.{}", key), converted_value);
535            }
536        }
537
538        // Evaluate expression
539        match crate::expression::evaluate_expression(expr, &facts) {
540            Ok(result) => result,
541            Err(_e) => {
542                // Silently fallback - this can happen with chained expressions in RETE
543                // due to working memory complexity
544                Value::String(expr.to_string())
545            }
546        }
547    }
548
549    /// Convert FactValue back to Value (reverse of value_to_fact_value)
550    fn fact_value_to_value(fact_value: &FactValue) -> Value {
551        match fact_value {
552            FactValue::String(s) => {
553                // Try to parse as number first
554                if let Ok(i) = s.parse::<i64>() {
555                    Value::Integer(i)
556                } else if let Ok(f) = s.parse::<f64>() {
557                    Value::Number(f)
558                } else if s == "true" {
559                    Value::Boolean(true)
560                } else if s == "false" {
561                    Value::Boolean(false)
562                } else {
563                    Value::String(s.clone())
564                }
565            }
566            FactValue::Integer(i) => Value::Integer(*i),
567            FactValue::Float(f) => Value::Number(*f),
568            FactValue::Boolean(b) => Value::Boolean(*b),
569            FactValue::Array(arr) => {
570                Value::Array(arr.iter().map(Self::fact_value_to_value).collect())
571            }
572            FactValue::Null => Value::Null,
573        }
574    }
575}
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580
581    #[test]
582    fn test_convert_simple_rule() {
583        let grl = r#"
584        rule "TestRule" salience 10 no-loop {
585            when
586                Person.age > 18
587            then
588                Person.is_adult = true;
589        }
590        "#;
591
592        let rules = GRLParser::parse_rules(grl).unwrap();
593        assert_eq!(rules.len(), 1);
594
595        let rete_rule = GrlReteLoader::convert_rule_to_rete(rules[0].clone()).unwrap();
596        assert_eq!(rete_rule.name, "TestRule");
597        assert_eq!(rete_rule.priority, 10);
598        assert!(rete_rule.no_loop);
599    }
600
601    #[test]
602    fn test_extract_dependencies() {
603        let grl = r#"
604        rule "MultiTypeRule" {
605            when
606                Person.age > 18 && Order.amount > 1000
607            then
608                Person.premium = true;
609        }
610        "#;
611
612        let rules = GRLParser::parse_rules(grl).unwrap();
613        let rete_rule = GrlReteLoader::convert_rule_to_rete(rules[0].clone()).unwrap();
614        let deps = GrlReteLoader::extract_dependencies(&rete_rule);
615
616        assert_eq!(deps.len(), 2);
617        assert!(deps.contains(&"Person".to_string()));
618        assert!(deps.contains(&"Order".to_string()));
619    }
620
621    #[test]
622    fn test_load_from_string() {
623        let grl = r#"
624        rule "Rule1" {
625            when
626                Person.age > 18
627            then
628                Person.is_adult = true;
629        }
630
631        rule "Rule2" {
632            when
633                Order.amount > 1000
634            then
635                Order.high_value = true;
636        }
637        "#;
638
639        let mut engine = IncrementalEngine::new();
640        let count = GrlReteLoader::load_from_string(grl, &mut engine).unwrap();
641
642        assert_eq!(count, 2);
643    }
644}