1#![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
23pub struct GrlReteLoader;
26
27impl GrlReteLoader {
28 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 pub fn load_from_string(grl_text: &str, engine: &mut IncrementalEngine) -> Result<usize> {
43 let rules = GRLParser::parse_rules(grl_text)?;
45
46 let mut loaded_count = 0;
47
48 for rule in rules {
49 let rete_rule = Self::convert_rule_to_rete(rule)?;
51
52 let dependencies = Self::extract_dependencies(&rete_rule);
54
55 engine.add_rule(rete_rule, dependencies);
57 loaded_count += 1;
58 }
59
60 Ok(loaded_count)
61 }
62
63 fn convert_rule_to_rete(rule: Rule) -> Result<TypedReteUlRule> {
65 let node = Self::convert_condition_group(&rule.conditions)?;
67
68 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 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 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 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 fn convert_condition(condition: &Condition) -> Result<ReteUlNode> {
165 use crate::engine::rule::ConditionExpression;
166
167 match &condition.expression {
169 ConditionExpression::MultiField {
170 field,
171 operation,
172 variable: _,
173 } => {
174 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 let (op, cmp_val) = if operation == "count" && operator_str != "==" {
184 (Some(operator_str), value_str)
186 } else {
187 (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 _ => {
204 let operator_str = Self::operator_to_string(&condition.operator);
206 let value_str = Self::value_to_string(&condition.value);
207
208 let alpha = AlphaNode {
209 field: condition.field.clone(),
210 operator: operator_str,
211 value: value_str,
212 };
213
214 Ok(ReteUlNode::UlAlpha(alpha))
215 }
216 }
217 }
218
219 fn operator_to_string(op: &Operator) -> String {
221 match op {
222 Operator::Equal => "==".to_string(),
223 Operator::NotEqual => "!=".to_string(),
224 Operator::GreaterThan => ">".to_string(),
225 Operator::GreaterThanOrEqual => ">=".to_string(),
226 Operator::LessThan => "<".to_string(),
227 Operator::LessThanOrEqual => "<=".to_string(),
228 Operator::Contains => "contains".to_string(),
229 Operator::NotContains => "!contains".to_string(),
230 Operator::StartsWith => "startsWith".to_string(),
231 Operator::EndsWith => "endsWith".to_string(),
232 Operator::Matches => "matches".to_string(),
233 Operator::In => "in".to_string(),
234 }
235 }
236
237 fn value_to_string(value: &Value) -> String {
239 match value {
240 Value::Number(n) => n.to_string(),
241 Value::Integer(i) => i.to_string(),
242 Value::String(s) => s.clone(),
243 Value::Boolean(b) => b.to_string(),
244 Value::Null => "null".to_string(),
245 Value::Array(arr) => {
246 let items: Vec<String> = arr.iter().map(Self::value_to_string).collect();
248 format!("[{}]", items.join(","))
249 }
250 Value::Object(_) => {
251 "object".to_string()
253 }
254 Value::Expression(expr) => {
255 expr.clone()
257 }
258 }
259 }
260
261 fn create_action_closure(
263 actions: Vec<crate::types::ActionType>,
264 ) -> std::sync::Arc<dyn Fn(&mut TypedFacts, &mut super::ActionResults) + Send + Sync> {
265 std::sync::Arc::new(
266 move |facts: &mut TypedFacts, results: &mut super::ActionResults| {
267 for action in &actions {
269 Self::execute_action(action, facts, results);
270 }
271 },
272 )
273 }
274
275 fn execute_action(
277 action: &crate::types::ActionType,
278 facts: &mut TypedFacts,
279 results: &mut super::ActionResults,
280 ) {
281 use crate::types::ActionType;
282
283 match action {
284 ActionType::Set { field, value } => {
285 let evaluated_value = match value {
291 Value::Expression(expr) => {
292 Self::evaluate_expression_for_rete(expr, facts)
294 }
295 _ => value.clone(),
296 };
297
298 let fact_value = Self::value_to_fact_value(&evaluated_value);
300 facts.set(field, fact_value);
301 }
302 ActionType::Log { message } => {
303 info!("📝 {}", message);
304 }
305 ActionType::MethodCall {
306 object,
307 method,
308 args,
309 } => {
310 let mut all_args = vec![object.clone()];
312 all_args.extend(args.iter().map(Self::value_to_string));
313
314 results.add(super::ActionResult::CallFunction {
315 function_name: format!("{}.{}", object, method),
316 args: all_args,
317 });
318 println!("� METHOD: {}.{}", object, method);
319 }
320 ActionType::Retract { object } => {
321 let object_name = object.trim_matches('"');
323
324 if let Some(handle) = facts.get_fact_handle(object_name) {
326 results.add(super::ActionResult::Retract(handle));
328 println!("🗑️ RETRACT: {} (handle: {:?})", object_name, handle);
329 } else {
330 results.add(super::ActionResult::RetractByType(object_name.to_string()));
332 println!("🗑️ RETRACT: {} (by type, no handle found)", object_name);
333 }
334 }
335 ActionType::Custom {
336 action_type,
337 params,
338 } => {
339 let args: Vec<String> = params.values().map(Self::value_to_string).collect();
341
342 results.add(super::ActionResult::CallFunction {
343 function_name: action_type.clone(),
344 args,
345 });
346 println!("🔧 CUSTOM CALL: {}", action_type);
347 }
348 ActionType::ActivateAgendaGroup { group } => {
349 results.add(super::ActionResult::ActivateAgendaGroup(group.clone()));
351 println!("📋 ACTIVATE GROUP: {}", group);
352 }
353 ActionType::ScheduleRule {
354 rule_name,
355 delay_ms,
356 } => {
357 results.add(super::ActionResult::ScheduleRule {
359 rule_name: rule_name.clone(),
360 delay_ms: *delay_ms,
361 });
362 println!("⏰ SCHEDULE: {} (delay: {}ms)", rule_name, delay_ms);
363 }
364 ActionType::CompleteWorkflow { workflow_name } => {
365 let completion_key = format!("workflow.{}.completed", workflow_name);
367 facts.set(&completion_key, FactValue::Boolean(true));
368
369 let timestamp_key = format!("workflow.{}.completed_at", workflow_name);
370 facts.set(
371 ×tamp_key,
372 FactValue::Integer(chrono::Utc::now().timestamp()),
373 );
374
375 println!("✔️ WORKFLOW COMPLETED: {}", workflow_name);
376 }
377 ActionType::SetWorkflowData { key, value } => {
378 let data_key = format!("workflow.data.{}", key);
380 let fact_value = Self::value_to_fact_value(value);
381 facts.set(&data_key, fact_value);
382
383 println!("📊 WORKFLOW DATA SET: {} = {:?}", key, value);
384 }
385 ActionType::Append { field, value } => {
386 let current_value = facts.get(field);
389
390 let mut array = match current_value {
391 Some(FactValue::Array(arr)) => arr.clone(),
392 Some(_) => {
393 log::warn!("Field {} is not an array, creating new array", field);
395 Vec::new()
396 }
397 None => {
398 Vec::new()
400 }
401 };
402
403 let evaluated_value = match value {
405 Value::Expression(expr) => Self::evaluate_expression_for_rete(expr, facts),
406 _ => value.clone(),
407 };
408
409 let fact_value = Self::value_to_fact_value(&evaluated_value);
411 array.push(fact_value);
412
413 facts.set(field, FactValue::Array(array));
415
416 info!("➕ APPEND: {} += {:?}", field, evaluated_value);
417 }
418 }
419 }
420
421 fn value_to_fact_value(value: &Value) -> FactValue {
423 match value {
424 Value::Number(n) => {
425 if n.fract() == 0.0 {
427 FactValue::Integer(*n as i64)
428 } else {
429 FactValue::Float(*n)
430 }
431 }
432 Value::Integer(i) => FactValue::Integer(*i),
433 Value::String(s) => FactValue::String(s.clone()),
434 Value::Boolean(b) => FactValue::Boolean(*b),
435 Value::Null => FactValue::Null,
436 Value::Array(arr) => {
437 let fact_arr: Vec<FactValue> = arr.iter().map(Self::value_to_fact_value).collect();
438 FactValue::Array(fact_arr)
439 }
440 Value::Object(_) => {
441 FactValue::String("object".to_string())
443 }
444 Value::Expression(expr) => {
445 FactValue::String(format!("[EXPR: {}]", expr))
447 }
448 }
449 }
450
451 fn extract_dependencies(rule: &TypedReteUlRule) -> Vec<String> {
453 let mut deps = Vec::new();
454 Self::extract_deps_from_node(&rule.node, &mut deps);
455
456 deps.sort();
458 deps.dedup();
459
460 deps
461 }
462
463 fn extract_deps_from_node(node: &ReteUlNode, deps: &mut Vec<String>) {
465 match node {
466 ReteUlNode::UlAlpha(alpha) => {
467 if let Some(dot_pos) = alpha.field.find('.') {
469 let fact_type = alpha.field[..dot_pos].to_string();
470 deps.push(fact_type);
471 }
472 }
473 ReteUlNode::UlMultiField { field, .. } => {
474 if let Some(dot_pos) = field.find('.') {
476 let fact_type = field[..dot_pos].to_string();
477 deps.push(fact_type);
478 }
479 }
480 ReteUlNode::UlAnd(left, right) | ReteUlNode::UlOr(left, right) => {
481 Self::extract_deps_from_node(left, deps);
482 Self::extract_deps_from_node(right, deps);
483 }
484 ReteUlNode::UlNot(inner)
485 | ReteUlNode::UlExists(inner)
486 | ReteUlNode::UlForall(inner) => {
487 Self::extract_deps_from_node(inner, deps);
488 }
489 ReteUlNode::UlAccumulate { source_pattern, .. } => {
490 deps.push(source_pattern.clone());
492 }
493 #[cfg(feature = "streaming")]
494 ReteUlNode::UlStream { stream_name, .. } => {
495 deps.push(stream_name.clone());
497 }
498 ReteUlNode::UlTerminal(_) => {
499 }
501 }
502 }
503
504 fn evaluate_expression_for_rete(expr: &str, typed_facts: &TypedFacts) -> Value {
506 use crate::engine::facts::Facts;
508
509 let facts = Facts::new();
510
511 for (key, value) in typed_facts.get_all() {
515 let converted_value = Self::fact_value_to_value(value);
516
517 facts.set(key, converted_value.clone());
520
521 if !key.contains('.') {
523 facts.set(&format!("Order.{}", key), converted_value);
524 }
525 }
526
527 match crate::expression::evaluate_expression(expr, &facts) {
529 Ok(result) => result,
530 Err(_e) => {
531 Value::String(expr.to_string())
534 }
535 }
536 }
537
538 fn fact_value_to_value(fact_value: &FactValue) -> Value {
540 match fact_value {
541 FactValue::String(s) => {
542 if let Ok(i) = s.parse::<i64>() {
544 Value::Integer(i)
545 } else if let Ok(f) = s.parse::<f64>() {
546 Value::Number(f)
547 } else if s == "true" {
548 Value::Boolean(true)
549 } else if s == "false" {
550 Value::Boolean(false)
551 } else {
552 Value::String(s.clone())
553 }
554 }
555 FactValue::Integer(i) => Value::Integer(*i),
556 FactValue::Float(f) => Value::Number(*f),
557 FactValue::Boolean(b) => Value::Boolean(*b),
558 FactValue::Array(arr) => {
559 Value::Array(arr.iter().map(Self::fact_value_to_value).collect())
560 }
561 FactValue::Null => Value::Null,
562 }
563 }
564}
565
566#[cfg(test)]
567mod tests {
568 use super::*;
569
570 #[test]
571 fn test_convert_simple_rule() {
572 let grl = r#"
573 rule "TestRule" salience 10 no-loop {
574 when
575 Person.age > 18
576 then
577 Person.is_adult = true;
578 }
579 "#;
580
581 let rules = GRLParser::parse_rules(grl).unwrap();
582 assert_eq!(rules.len(), 1);
583
584 let rete_rule = GrlReteLoader::convert_rule_to_rete(rules[0].clone()).unwrap();
585 assert_eq!(rete_rule.name, "TestRule");
586 assert_eq!(rete_rule.priority, 10);
587 assert!(rete_rule.no_loop);
588 }
589
590 #[test]
591 fn test_extract_dependencies() {
592 let grl = r#"
593 rule "MultiTypeRule" {
594 when
595 Person.age > 18 && Order.amount > 1000
596 then
597 Person.premium = true;
598 }
599 "#;
600
601 let rules = GRLParser::parse_rules(grl).unwrap();
602 let rete_rule = GrlReteLoader::convert_rule_to_rete(rules[0].clone()).unwrap();
603 let deps = GrlReteLoader::extract_dependencies(&rete_rule);
604
605 assert_eq!(deps.len(), 2);
606 assert!(deps.contains(&"Person".to_string()));
607 assert!(deps.contains(&"Order".to_string()));
608 }
609
610 #[test]
611 fn test_load_from_string() {
612 let grl = r#"
613 rule "Rule1" {
614 when
615 Person.age > 18
616 then
617 Person.is_adult = true;
618 }
619
620 rule "Rule2" {
621 when
622 Order.amount > 1000
623 then
624 Order.high_value = true;
625 }
626 "#;
627
628 let mut engine = IncrementalEngine::new();
629 let count = GrlReteLoader::load_from_string(grl, &mut engine).unwrap();
630
631 assert_eq!(count, 2);
632 }
633}