rust-rule-engine 0.5.1

A high-performance rule engine for Rust with GRL support and AI integration
Documentation

๐Ÿฆ€ Rust Rule Engine - AI-Powered Edition

A powerful, high-performance rule engine for Rust supporting GRL (Grule Rule Language) syntax with advanced features like AI integration, method calls, custom functions, object interactions, and both file-based and inline rule management.

Crates.io Documentation License: MIT

๐Ÿ“‹ Table of Contents

๐ŸŒŸ Key Features

  • ๐Ÿ”ฅ GRL-Only Support: Pure Grule Rule Language syntax (no JSON)
  • ๐Ÿค– AI Integration: Built-in support for ML models, LLMs, and AI-powered decision making
  • ๐Ÿ“„ Rule Files: External .grl files for organized rule management
  • ๐Ÿ“ Inline Rules: Define rules as strings directly in your code
  • ๐Ÿ“ž Custom Functions: Register and call user-defined functions from rules
  • ๐ŸŽฏ Method Calls: Support for Object.method(args) and property access
  • ๐Ÿง  Knowledge Base: Centralized rule management with salience-based execution
  • ๐Ÿ’พ Working Memory: Facts system for complex object interactions
  • โšก High Performance: Optimized execution engine with cycle detection and no-loop support
  • ๐Ÿ”„ No-Loop Protection: Prevent rules from firing themselves infinitely (Drools-compatible)
  • ๐Ÿ›ก๏ธ Type Safety: Rust's type system ensures runtime safety
  • ๐Ÿ—๏ธ Builder Pattern: Clean API with RuleEngineBuilder
  • ๐Ÿ“ˆ Execution Statistics: Detailed performance metrics and debugging
  • ๐Ÿ” Smart Dependency Analysis: AST-based field dependency detection and conflict resolution
  • ๐Ÿš€ Parallel Processing: Multi-threaded rule execution with automatic dependency management
  • ๐ŸŒ Distributed Architecture: Scale across multiple nodes for high-performance processing
  • ๐Ÿ“Š Rule Templates: Parameterized rule templates for scalable rule generation
  • ๐ŸŒŠ Stream Processing: Real-time event processing with time windows (optional)
  • ๐Ÿ“Š Analytics: Built-in aggregations and trend analysis
  • ๐Ÿšจ Action Handlers: Custom action execution for rule consequences
  • ๐Ÿ“ˆ Advanced Analytics: Production-ready performance monitoring and optimization insights

๐Ÿค– AI Integration (NEW!)

Integrate AI/ML models seamlessly into your rules, similar to Drools Pragmatic AI:

Features

  • ๐Ÿค– Sentiment Analysis: Real-time text sentiment evaluation
  • ๐Ÿ›ก๏ธ Fraud Detection: ML-powered fraud scoring and detection
  • ๐Ÿ† Predictive Analytics: Customer tier prediction and scoring
  • ๐Ÿง  LLM Reasoning: Large Language Model decision support
  • ๐Ÿ“Š Real-time ML Scoring: Dynamic model inference in rules

Example AI Rules

rule "AI Customer Service" salience 100 {
    when
        CustomerMessage.type == "complaint"
    then
        analyzeSentiment(CustomerMessage.text);
        set(Ticket.priority, "high");
        logMessage("๐Ÿค– AI analyzing customer sentiment");
}

rule "AI Fraud Detection" salience 90 {
    when
        Transaction.amount > 1000
    then
        detectFraud(Transaction.amount, Transaction.userId);
        set(Transaction.status, "under_review");
        sendNotification("๐Ÿ›ก๏ธ Checking for potential fraud", "security@company.com");
}

rule "AI Tier Prediction" salience 80 {
    when
        Customer.tier == "pending"
    then
        predictTier(Customer.id);
        set(Customer.tierAssignedBy, "AI");
        logMessage("๐Ÿ† AI predicting customer tier");
}

Register AI Functions

// Register AI-powered functions
engine.register_function("analyzeSentiment", |args, _facts| {
    let text = args[0].as_string().unwrap_or("".to_string());
    
    // Call actual AI API (OpenAI, Anthropic, Hugging Face, etc.)
    let rt = tokio::runtime::Runtime::new().unwrap();
    let sentiment = rt.block_on(async {
        call_openai_sentiment_api(&text).await
    }).unwrap_or_else(|_| "neutral".to_string());
    
    Ok(Value::String(sentiment))
});

engine.register_function("detectFraud", |args, facts| {
    let amount = args[0].as_number().unwrap_or(0.0);
    let user_id = args[1].as_string().unwrap_or("unknown".to_string());
    
    // Call actual ML fraud detection API
    let rt = tokio::runtime::Runtime::new().unwrap();
    let is_fraud = rt.block_on(async {
        call_fraud_detection_api(amount, &user_id, facts).await
    }).unwrap_or_else(|_| false);
    
    Ok(Value::Boolean(is_fraud))
});

engine.register_function("predictTier", |args, facts| {
    let customer_id = args[0].as_string().unwrap_or("unknown".to_string());
    
    // Call actual ML tier prediction API
    let rt = tokio::runtime::Runtime::new().unwrap();
    let predicted_tier = rt.block_on(async {
        call_tier_prediction_api(&customer_id, facts).await
    }).unwrap_or_else(|_| "bronze".to_string());
    
    Ok(Value::String(predicted_tier))
});

๐Ÿ“‹ Changelog

v0.5.0 (October 2025) - AI Integration ๐Ÿค–

  • ๐Ÿค– AI-Powered Rules: Built-in support for AI/ML model integration
    • Sentiment analysis functions for customer service automation
    • ML-powered fraud detection with real-time risk scoring
    • Predictive analytics for customer tier assignment
    • LLM reasoning for complex business decision support
    • Real-time ML scoring for dynamic pricing and recommendations
  • ๐Ÿง  AI Function Registry: Easy registration and management of AI model functions
  • ๐Ÿš€ Production AI Examples: Complete examples with simulated AI APIs
  • ๐Ÿ“Š AI Insights: Track AI model performance and decision outcomes
  • ๐ŸŒ AI-Enhanced REST API: HTTP endpoints for AI-powered rule execution

v0.4.1 (October 2025) - Enhanced Parser & Publishing

  • ๐Ÿ”ง Enhanced GRL Parser: Improved parsing with complex nested conditions
    • Support for parentheses grouping: (age >= 18) && (status == "active")
    • Better handling of compound boolean expressions
    • Improved error messages and validation
  • ๐Ÿ“ฆ Published to Crates.io: Available as rust-rule-engine = "0.4.1"
  • ๐Ÿ“š Comprehensive Examples: Added 40+ examples covering all features
  • ๐Ÿ“– Complete Documentation: Full API documentation and usage guides

v0.3.1 (October 2025) - REST API with Monitoring

  • ๐ŸŒ Production REST API: Complete web API with advanced analytics integration
    • Comprehensive endpoints for rule execution and monitoring
    • Real-time analytics dashboard with performance insights
    • Health monitoring and system status endpoints
    • CORS support and proper error handling
    • Sample requests and complete API documentation
    • Production-ready demo script for testing

v0.3.0 (October 2025) - AST-Based Dependency Analysis & Advanced Analytics

๐Ÿš€ Quick Start

Add to your Cargo.toml:

[dependencies]
rust-rule-engine = "0.3.1"

# For streaming features
rust-rule-engine = { version = "0.3.1", features = ["streaming"] }

๐Ÿ“„ File-Based Rules

Create a rule file rules/example.grl:

rule "AgeCheck" salience 10 {
    when
        User.Age >= 18 && User.Country == "US"
    then
        User.setIsAdult(true);
        User.setCategory("Adult");
        log("User qualified as adult");
}

rule "VIPUpgrade" salience 20 {
    when
        User.IsAdult == true && User.SpendingTotal > 1000.0
    then
        User.setIsVIP(true);
        log("User upgraded to VIP status");
}
use rust_rule_engine::{RuleEngineBuilder, Value, Facts};
use std::collections::HashMap;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create engine with rule file
    let mut engine = RuleEngineBuilder::new()
        .with_rule_file("rules/example.grl")?
        .build();

    // Register custom functions
    engine.register_function("User.setIsAdult", |args, _| {
        println!("Setting adult status: {}", args[0]);
        Ok(Value::Boolean(true))
    });

    engine.register_function("User.setCategory", |args, _| {
        println!("Setting category: {}", args[0]);
        Ok(Value::String(args[0].to_string()))
    });

    // Create facts
    let facts = Facts::new();
    let mut user = HashMap::new();
    user.insert("Age".to_string(), Value::Integer(25));
    user.insert("Country".to_string(), Value::String("US".to_string()));
    user.insert("SpendingTotal".to_string(), Value::Number(1500.0));

    facts.add_value("User", Value::Object(user))?;

    // Execute rules
    let result = engine.execute(&facts)?;
    println!("Rules fired: {}", result.rules_fired);

    Ok(())
}

๐Ÿ“ Inline String Rules

Define rules directly in your code:

use rust_rule_engine::{RuleEngineBuilder, Value, Facts};
use std::collections::HashMap;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let grl_rules = r#"
        rule "HighValueCustomer" salience 20 {
            when
                Customer.TotalSpent > 1000.0
            then
                sendWelcomeEmail(Customer.Email, "GOLD");
                log("Customer upgraded to GOLD tier");
        }

        rule "LoyaltyBonus" salience 15 {
            when
                Customer.OrderCount >= 10
            then
                applyLoyaltyBonus(Customer.Id, 50.0);
                log("Loyalty bonus applied");
        }
    "#;

    // Create engine with inline rules
    let mut engine = RuleEngineBuilder::new()
        .with_inline_grl(grl_rules)?
        .build();

    // Register custom functions
    engine.register_function("sendWelcomeEmail", |args, _| {
        println!("๐Ÿ“ง Welcome email sent to {} for {} tier", args[0], args[1]);
        Ok(Value::Boolean(true))
    });

    engine.register_function("applyLoyaltyBonus", |args, _| {
        println!("๐Ÿ’ฐ Loyalty bonus of {} applied to customer {}", args[1], args[0]);
        Ok(Value::Number(args[1].as_number().unwrap_or(0.0)))
    });

    // Create facts
    let facts = Facts::new();
    let mut customer = HashMap::new();
    customer.insert("TotalSpent".to_string(), Value::Number(1250.0));
    customer.insert("OrderCount".to_string(), Value::Integer(12));
    customer.insert("Email".to_string(), Value::String("john@example.com".to_string()));
    customer.insert("Id".to_string(), Value::String("CUST001".to_string()));

    facts.add_value("Customer", Value::Object(customer))?;

    // Execute rules
    let result = engine.execute(&facts)?;
    println!("Rules fired: {}", result.rules_fired);

    Ok(())
}

๐Ÿค– Complete AI Integration Example

Here's a complete example showing how to build an AI-powered business rule system:

use rust_rule_engine::{RuleEngineBuilder, Value, Facts};
use std::collections::HashMap;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let ai_rules = r#"
        rule "AI Customer Service" salience 100 {
            when
                CustomerMessage.type == "complaint"
            then
                analyzeSentiment(CustomerMessage.text);
                set(Ticket.priority, "high");
                logMessage("๐Ÿค– AI analyzing customer sentiment");
        }

        rule "AI Fraud Detection" salience 90 {
            when
                Transaction.amount > 1000
            then
                detectFraud(Transaction.amount, Transaction.userId);
                set(Transaction.status, "under_review");
                sendNotification("๐Ÿ›ก๏ธ Checking for potential fraud", "security@company.com");
        }

        rule "AI Tier Prediction" salience 80 {
            when
                Customer.tier == "pending"
            then
                predictTier(Customer.id);
                set(Customer.tierAssignedBy, "AI");
                logMessage("๐Ÿ† AI predicting customer tier");
        }

        rule "LLM Decision Support" salience 70 {
            when
                Customer.needsReview == true
            then
                askLLM("Should we approve this customer for premium tier?", Customer.id);
                set(Customer.reviewedBy, "AI-LLM");
                logMessage("๐Ÿง  LLM analyzing customer for approval");
        }

        rule "ML Dynamic Pricing" salience 60 {
            when
                Product.category == "dynamic" && Customer.tier != "unknown"
            then
                calculateMLPrice(Product.basePrice, Customer.tier, Product.demand);
                set(Product.priceSource, "ML");
                logMessage("๐Ÿ“Š ML calculating dynamic price");
        }
    "#;

    let mut engine = RuleEngineBuilder::new()
        .with_inline_grl(ai_rules)?
        .with_max_cycles(5)
        .build();

    // Register AI functions (in production, these would call real AI APIs)
    engine.register_function("analyzeSentiment", |args, facts| {
        let text = args[0].as_string().unwrap_or("".to_string());
        
        // Simulate sentiment analysis (OpenAI, Anthropic, HuggingFace, etc.)
        let sentiment = if text.contains("terrible") || text.contains("awful") {
            "negative"
        } else if text.contains("love") || text.contains("great") {
            "positive"
        } else {
            "neutral"
        };
        
        // Store result in facts for other rules
        facts.set_value("Analysis.sentiment", Value::String(sentiment.to_string()))?;
        
        println!("๐Ÿค– Sentiment Analysis: '{}' โ†’ {}", text, sentiment);
        Ok(Value::String(sentiment.to_string()))
    });

    engine.register_function("detectFraud", |args, facts| {
        let amount = args[0].as_number().unwrap_or(0.0);
        let user_id = args[1].as_string().unwrap_or("unknown".to_string());
        
        // Simulate ML fraud detection model
        let risk_score = if amount > 5000.0 { 0.95 } else if amount > 2000.0 { 0.75 } else { 0.2 };
        let is_fraud = risk_score > 0.8;
        
        facts.set_value("FraudCheck.riskScore", Value::Number(risk_score))?;
        facts.set_value("FraudCheck.isFraud", Value::Boolean(is_fraud))?;
        
        println!("๐Ÿ›ก๏ธ Fraud Detection: Amount {} for user {} โ†’ Risk: {:.2}, Fraud: {}", 
                amount, user_id, risk_score, is_fraud);
        
        Ok(Value::Boolean(is_fraud))
    });

    engine.register_function("predictTier", |args, facts| {
        let customer_id = args[0].as_string().unwrap_or("unknown".to_string());
        
        // Simulate customer tier prediction model
        let predicted_tiers = ["bronze", "silver", "gold", "platinum"];
        let tier = predicted_tiers[customer_id.len() % predicted_tiers.len()];
        
        facts.set_value("TierPrediction.tier", Value::String(tier.to_string()))?;
        facts.set_value("TierPrediction.confidence", Value::Number(0.87))?;
        
        println!("๐Ÿ† Tier Prediction: Customer {} โ†’ {} tier (87% confidence)", customer_id, tier);
        Ok(Value::String(tier.to_string()))
    });

    engine.register_function("askLLM", |args, facts| {
        let question = args[0].as_string().unwrap_or("".to_string());
        let customer_id = args[1].as_string().unwrap_or("unknown".to_string());
        
        // Simulate LLM reasoning (GPT-4, Claude, etc.)
        let decision = if customer_id.contains("VIP") { "approve" } else { "review_further" };
        let reasoning = format!("Based on customer profile analysis, recommendation: {}", decision);
        
        facts.set_value("LLMDecision.result", Value::String(decision.to_string()))?;
        facts.set_value("LLMDecision.reasoning", Value::String(reasoning.clone()))?;
        
        println!("๐Ÿง  LLM Analysis: {} โ†’ {}", question, reasoning);
        Ok(Value::String(decision.to_string()))
    });

    engine.register_function("calculateMLPrice", |args, facts| {
        let base_price = args[0].as_number().unwrap_or(100.0);
        let tier = args[1].as_string().unwrap_or("bronze".to_string());
        let demand = args[2].as_number().unwrap_or(1.0);
        
        // Simulate ML pricing model
        let tier_multiplier = match tier.as_str() {
            "platinum" => 0.8,
            "gold" => 0.9,
            "silver" => 0.95,
            _ => 1.0,
        };
        
        let dynamic_price = base_price * tier_multiplier * demand;
        
        facts.set_value("Pricing.dynamicPrice", Value::Number(dynamic_price))?;
        facts.set_value("Pricing.discount", Value::Number((1.0 - tier_multiplier) * 100.0))?;
        
        println!("๐Ÿ“Š ML Pricing: Base ${:.2} ร— {} tier ร— {:.1}x demand โ†’ ${:.2}", 
                base_price, tier, demand, dynamic_price);
        
        Ok(Value::Number(dynamic_price))
    });

    // Helper functions
    engine.register_function("set", |args, facts| {
        if args.len() >= 2 {
            let key = args[0].as_string().unwrap_or("unknown".to_string());
            facts.set_value(&key, args[1].clone())?;
        }
        Ok(Value::Boolean(true))
    });

    engine.register_function("logMessage", |args, _| {
        println!("๐Ÿ“ {}", args[0]);
        Ok(Value::Boolean(true))
    });

    engine.register_function("sendNotification", |args, _| {
        println!("๐Ÿ“ง Notification: {} โ†’ {}", args[0], args[1]);
        Ok(Value::Boolean(true))
    });

    // Set up test facts
    let facts = Facts::new();
    
    // Customer service scenario
    let mut customer_message = HashMap::new();
    customer_message.insert("type".to_string(), Value::String("complaint".to_string()));
    customer_message.insert("text".to_string(), Value::String("This service is terrible!".to_string()));
    facts.add_value("CustomerMessage", Value::Object(customer_message))?;

    // Transaction for fraud detection
    let mut transaction = HashMap::new();
    transaction.insert("amount".to_string(), Value::Number(2500.0));
    transaction.insert("userId".to_string(), Value::String("user123".to_string()));
    facts.add_value("Transaction", Value::Object(transaction))?;

    // Customer for tier prediction
    let mut customer = HashMap::new();
    customer.insert("id".to_string(), Value::String("VIP_customer_456".to_string()));
    customer.insert("tier".to_string(), Value::String("pending".to_string()));
    customer.insert("needsReview".to_string(), Value::Boolean(true));
    facts.add_value("Customer", Value::Object(customer))?;

    // Product for dynamic pricing
    let mut product = HashMap::new();
    product.insert("category".to_string(), Value::String("dynamic".to_string()));
    product.insert("basePrice".to_string(), Value::Number(150.0));
    product.insert("demand".to_string(), Value::Number(1.3));
    facts.add_value("Product", Value::Object(product))?;

    let mut ticket = HashMap::new();
    facts.add_value("Ticket", Value::Object(ticket))?;

    // Execute AI-powered rules
    println!("\n๐Ÿš€ Executing AI-Powered Rule Engine...\n");
    let result = engine.execute(&facts)?;
    
    println!("\n๐Ÿ“Š Execution Results:");
    println!("   Rules fired: {}", result.rules_fired);
    println!("   Cycles: {}", result.cycles);
    println!("   Duration: {:?}", result.duration);
    
    Ok(())
}

๐Ÿ” Dependency Analysis Example

use rust_rule_engine::dependency::DependencyAnalyzer;

fn analyze_rule_dependencies() -> Result<(), Box<dyn std::error::Error>> {
    let grl_content = r#"
        rule "VIPUpgrade" {
            when Customer.TotalSpent > 1000.0 && Customer.IsVIP == false
            then 
                Customer.setIsVIP(true);
                Customer.setTier("GOLD");
        }
        
        rule "VIPBenefits" {
            when Customer.IsVIP == true
            then
                Order.setDiscountRate(0.15);
                log("VIP discount applied");
        }
    "#;

    let analyzer = DependencyAnalyzer::new();
    let analysis = analyzer.analyze_grl_rules(grl_content)?;
    
    // Show detected dependencies
    for rule in &analysis.rules {
        println!("๐Ÿ“‹ Rule '{}' reads: {:?}", rule.name, rule.reads);
        println!("โœ๏ธ  Rule '{}' writes: {:?}", rule.name, rule.writes);
    }
    
    // Check for conflicts
    let conflicts = analysis.find_conflicts();
    if conflicts.is_empty() {
        println!("โœ… No conflicts detected - rules can execute safely in parallel");
    } else {
        println!("โš ๏ธ  {} conflicts detected", conflicts.len());
    }
    
    Ok(())
}

๐ŸŽฏ GRL Rule Language Features

Supported Syntax

// Basic rule
rule "RuleName" salience 10 {
    when
        Object.Property > 100 &&
        Object.Status == "ACTIVE"
    then
        Object.setCategory("HIGH_VALUE");
        processTransaction(Object.Id, Object.Amount);
        log("Rule executed successfully");
}

// Rule with no-loop protection (prevents infinite self-activation)
rule "ScoreUpdater" no-loop salience 15 {
    when
        Player.score < 100
    then
        set(Player.score, Player.score + 10);
        log("Score updated with no-loop protection");
}

Operators

  • Comparison: >, >=, <, <=, ==, !=
  • Logical: &&, ||
  • Value Types: Numbers, Strings (quoted), Booleans (true/false)

Actions

  • Method Calls: Object.method(args)
  • Function Calls: functionName(args)
  • Logging: log("message")

๐Ÿ“š Examples

๐Ÿ›’ E-commerce Rules

rule "VIPCustomer" salience 20 {
    when
        Customer.TotalSpent > 5000.0 && Customer.YearsActive >= 2
    then
        Customer.setTier("VIP");
        sendWelcomePackage(Customer.Email, "VIP");
        applyDiscount(Customer.Id, 15.0);
        log("Customer upgraded to VIP");
}

rule "LoyaltyReward" salience 15 {
    when
        Customer.OrderCount >= 50
    then
        addLoyaltyPoints(Customer.Id, 500);
        log("Loyalty reward applied");
}

๐Ÿš— Vehicle Monitoring

rule "SpeedLimit" salience 25 {
    when
        Vehicle.Speed > Vehicle.SpeedLimit
    then
        triggerAlert(Vehicle.Id, "SPEED_VIOLATION");
        logViolation(Vehicle.Driver, Vehicle.Speed);
        Vehicle.setStatus("FLAGGED");
}

rule "MaintenanceDue" salience 10 {
    when
        Vehicle.Mileage > Vehicle.NextMaintenance
    then
        scheduleService(Vehicle.Id, Vehicle.Mileage);
        notifyDriver(Vehicle.Driver, "Maintenance due");
}

๐ŸŒ REST API with Monitoring

The engine provides a production-ready REST API with comprehensive analytics monitoring.

Quick Start

# Run the REST API server with full analytics monitoring
cargo run --example rest_api_monitoring

# Or use the demo script for testing
./demo_rest_api.sh

Available Endpoints

Rule Execution:

  • POST /api/v1/rules/execute - Execute rules with provided facts
  • POST /api/v1/rules/batch - Execute rules in batch mode

Analytics & Monitoring:

  • GET /api/v1/analytics/dashboard - Comprehensive analytics dashboard
  • GET /api/v1/analytics/stats - Overall performance statistics
  • GET /api/v1/analytics/recent - Recent execution activity
  • GET /api/v1/analytics/recommendations - Performance optimization recommendations
  • GET /api/v1/analytics/rules/{rule_name} - Rule-specific analytics

System:

  • GET / - API documentation
  • GET /api/v1/health - Health check
  • GET /api/v1/status - System status

Example Requests

Execute Rules:

curl -X POST "http://localhost:3000/api/v1/rules/execute" \
  -H "Content-Type: application/json" \
  -d '{
    "facts": {
      "Customer": {
        "Age": 35,
        "IsNew": false,
        "OrderCount": 75,
        "TotalSpent": 15000.0,
        "YearsActive": 3,
        "Email": "customer@example.com"
      },
      "Order": {
        "Amount": 750.0,
        "CustomerEmail": "customer@example.com"
      }
    }
  }'

Analytics Dashboard:

curl "http://localhost:3000/api/v1/analytics/dashboard"

Sample Response:

{
  "overall_stats": {
    "total_executions": 1250,
    "avg_execution_time_ms": 2.3,
    "success_rate": 99.8,
    "rules_per_second": 435.2,
    "uptime_hours": 24.5
  },
  "top_performing_rules": [
    {
      "name": "VIPCustomerRule",
      "execution_count": 340,
      "avg_duration_ms": 1.8,
      "success_rate": 100.0
    }
  ],
  "recommendations": [
    "Consider caching customer data to improve performance",
    "Rule 'ComplexValidation' shows high execution time"
  ]
}

Production Configuration

The REST API includes:

  • Real-time Analytics: Live performance monitoring
  • Health Checks: Comprehensive system health monitoring
  • CORS Support: Cross-origin resource sharing
  • Error Handling: Proper HTTP status codes and error messages
  • Sampling: Configurable analytics sampling for high-volume scenarios
  • Memory Management: Automatic cleanup and retention policies

โšก Performance & Architecture

Benchmarks

Performance benchmarks on a typical development machine:

Simple Rule Execution:
โ€ข Single condition rule:     ~4.5 ยตs per execution
โ€ข With custom function call: ~4.8 ยตs per execution

Complex Rule Execution:
โ€ข Multi-condition rules:     ~2.7 ยตs per execution  
โ€ข 3 rules with conditions:   ~2.8 ยตs per execution

Rule Parsing:
โ€ข Simple GRL rule:          ~1.1 ยตs per parse
โ€ข Medium complexity rule:   ~1.4 ยตs per parse  
โ€ข Complex multi-line rule:  ~2.0 ยตs per parse

Facts Operations:
โ€ข Create complex facts:     ~1.8 ยตs
โ€ข Get nested fact:          ~79 ns
โ€ข Set nested fact:          ~81 ns

Memory Usage:
โ€ข Base engine overhead:     ~10KB
โ€ข Per rule storage:         ~1-2KB  
โ€ข Per fact storage:         ~100-500 bytes

Run benchmarks: cargo bench

Key Performance Insights:

  • Ultra-fast execution: Rules execute in microseconds
  • Efficient parsing: GRL rules parse in under 2ยตs
  • Optimized facts: Nanosecond-level fact operations
  • Low memory footprint: Minimal overhead per rule
  • Scales linearly: Performance consistent across rule counts

๐Ÿ† Performance Comparison

Benchmark comparison with other rule engines:

Language/Engine        Rule Execution    Memory Usage    Startup Time
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Rust (this engine)     2-5ยตs            1-2KB/rule     ~1ms
.NET Rules Engine       15-50ยตs          3-8KB/rule     ~50-100ms
Go Rules Framework      10-30ยตs          2-5KB/rule     ~10-20ms
Java Drools            50-200ยตs          5-15KB/rule    ~200-500ms
Python rule-engine     500-2000ยตs        8-20KB/rule    ~100-300ms

Rust Advantages:

  • 10x faster than .NET rule engines
  • 5x faster than Go-based rule frameworks
  • 50x faster than Java Drools
  • 400x faster than Python implementations
  • Zero GC pauses (unlike .NET/Java/Go)
  • Minimal memory footprint
  • Instant startup time

Why Rust Wins:

  • No garbage collection overhead
  • Zero-cost abstractions
  • Direct memory management
  • LLVM optimizations
  • No runtime reflection costs

Key Design Decisions

  • GRL-Only: Removed JSON support for cleaner, focused API
  • Dual Sources: Support both file-based and inline rule definitions
  • Custom Functions: Extensible function registry for business logic
  • Builder Pattern: Fluent API for easy engine configuration
  • Type Safety: Leverages Rust's type system for runtime safety
  • Zero-Copy: Efficient string and memory management

๏ฟฝ Advanced Dependency Analysis (v0.3.0+)

The rule engine features sophisticated AST-based dependency analysis that automatically detects field dependencies and potential conflicts between rules.

Smart Field Detection

use rust_rule_engine::{RuleEngineBuilder, dependency::DependencyAnalyzer};

// Automatic field dependency detection
let rules = r#"
    rule "DiscountRule" {
        when Customer.VIP == true && Order.Amount > 100.0
        then 
            Order.setDiscount(0.2);
            Customer.setPoints(Customer.Points + 50);
    }
    
    rule "ShippingRule" {
        when Order.Amount > 50.0
        then
            Order.setFreeShipping(true);
            log("Free shipping applied");
    }
"#;

let analyzer = DependencyAnalyzer::new();
let analysis = analyzer.analyze_grl_rules(rules)?;

// Automatically detected dependencies:
// DiscountRule reads: [Customer.VIP, Order.Amount, Customer.Points]
// DiscountRule writes: [Order.Discount, Customer.Points]
// ShippingRule reads: [Order.Amount]  
// ShippingRule writes: [Order.FreeShipping]

Conflict Detection

// Detect read-write conflicts between rules
let conflicts = analysis.find_conflicts();
for conflict in conflicts {
    println!("โš ๏ธ  Conflict: {} reads {} while {} writes {}",
        conflict.reader_rule, conflict.field,
        conflict.writer_rule, conflict.field
    );
}

// Smart execution ordering based on dependencies
let execution_order = analysis.suggest_execution_order();

Advanced Features

  • ๐ŸŽฏ AST-Based Analysis: Proper parsing instead of regex pattern matching
  • ๐Ÿ”„ Recursive Conditions: Handles nested condition groups (AND/OR/NOT)
  • ๐Ÿง  Function Side-Effects: Infers field modifications from function calls
  • โšก Zero False Positives: Accurate dependency detection
  • ๐Ÿ“Š Conflict Resolution: Automatic rule ordering suggestions
  • ๐Ÿš€ Parallel Safety: Enables safe concurrent rule execution

๏ฟฝ๐Ÿ“‹ API Reference

Core Types

// Main engine builder
RuleEngineBuilder::new()
    .with_rule_file("path/to/rules.grl")?
    .with_inline_grl("rule content")?
    .with_config(config)
    .build()

// Value types
Value::Integer(42)
Value::Number(3.14)
Value::String("text".to_string())
Value::Boolean(true)
Value::Object(HashMap<String, Value>)

// Facts management
let facts = Facts::new();
facts.add_value("Object", value)?;
facts.get("Object")?;

// Execution results
result.rules_fired       // Number of rules that executed
result.cycle_count       // Number of execution cycles
result.execution_time    // Duration of execution

Function Registration

engine.register_function("functionName", |args, facts| {
    // args: Vec<Value> - function arguments
    // facts: &Facts - current facts state
    // Return: Result<Value, RuleEngineError>
    
    let param1 = &args[0];
    let param2 = args[1].as_number().unwrap_or(0.0);
    
    // Your custom business logic here
    println!("Function called with: {:?}", args);
    
    Ok(Value::String("Success".to_string()))
});

โšก Parallel Rule Execution

The engine supports parallel execution for improved performance with large rule sets:

use rust_rule_engine::engine::parallel::{ParallelEngine, ParallelConfig};

// Create parallel engine with custom configuration
let config = ParallelConfig {
    enabled: true,
    max_threads: 4,
};

let mut engine = ParallelEngine::new(config);

// Add rules and facts
engine.add_rule(rule);
engine.insert_fact("User", user_data);

// Execute rules in parallel
let result = engine.execute_parallel(10).await;
println!("Rules fired: {}", result.total_rules_fired);
println!("Execution time: {:?}", result.execution_time);
println!("Parallel speedup: {:.2}x", result.parallel_speedup);

Parallel Execution Examples

# Simple parallel demo
cargo run --example simple_parallel_demo

# Performance comparison
cargo run --example financial_stress_test

๐ŸŒ Distributed & Cloud Features

Scale your rule engine across multiple nodes for high-performance distributed processing:

Architecture Overview

                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚   Load Balancer     โ”‚
                    โ”‚   (Route Requests)  โ”‚
                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                               โ”‚
        โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
        โ”‚                      โ”‚                      โ”‚
   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”            โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”            โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
   โ”‚ Node 1  โ”‚            โ”‚ Node 2  โ”‚            โ”‚ Node 3  โ”‚
   โ”‚Validationโ”‚           โ”‚ Pricing โ”‚            โ”‚ Loyalty โ”‚
   โ”‚  Rules  โ”‚            โ”‚  Rules  โ”‚            โ”‚  Rules  โ”‚
   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜            โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜            โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
        โ”‚                      โ”‚                      โ”‚
        โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                               โ”‚
                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚   Shared Data       โ”‚
                    โ”‚ (Redis/PostgreSQL)  โ”‚
                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Performance Benefits

  • โšก 3x Performance: Parallel processing across specialized nodes
  • ๐Ÿ›ก๏ธ Fault Tolerance: If one node fails, others continue operation
  • ๐Ÿ“ˆ Horizontal Scaling: Add nodes to increase capacity
  • ๐ŸŒ Geographic Distribution: Deploy closer to users for reduced latency

Quick Demo

# Compare single vs distributed processing
cargo run --example distributed_concept_demo

Results:

Single Node:    1.4 seconds (sequential)
Distributed:    0.47 seconds (parallel)
โ†’ 3x Performance Improvement!

Implementation Guide

See our comprehensive guides:

Cloud Deployment

Deploy on major cloud platforms:

Kubernetes:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: rule-engine-workers
spec:
  replicas: 3
  selector:
    matchLabels:
      app: rule-engine

Docker:

FROM rust:alpine
COPY target/release/rust-rule-engine /app/
EXPOSE 8080
CMD ["/app/rust-rule-engine"]

When to Use Distributed Architecture

โœ… Recommended for:

  • High traffic (>10,000 requests/day)
  • Complex rule sets (>500 rules)
  • High availability requirements
  • Geographic distribution needs

โŒ Not needed for:

  • Simple applications (<100 rules)
  • Low traffic scenarios
  • Development/prototyping
  • Limited infrastructure budget

๐Ÿงช All Examples

Core Features

# Basic rule execution
cargo run --example grule_demo

# E-commerce rules
cargo run --example ecommerce

# Custom functions
cargo run --example custom_functions_demo

# Method calls
cargo run --example method_calls_demo

Performance & Scaling

# Parallel processing comparison
cargo run --example simple_parallel_demo

# Financial stress testing
cargo run --example financial_stress_test

# Distributed architecture demo
cargo run --example distributed_concept_demo

Advanced Features

# REST API with analytics
cargo run --example rest_api_monitoring

# Analytics and monitoring
cargo run --example analytics_demo

# Rule file processing
cargo run --example rule_file_functions_demo

# Advanced dependency analysis
cargo run --example advanced_dependency_demo

Production Examples

# Fraud detection system
cargo run --example fraud_detection

# Complete speedup demo
cargo run --example complete_speedup_demo

# Debug conditions
cargo run --example debug_conditions

๐ŸŒŠ Streaming Rule Engine (v0.2.0+)

For real-time event processing, enable the streaming feature:


## ๐ŸŒŠ Streaming Rule Engine (v0.2.0+)

For real-time rule processing with streaming data:

```rust
use rust_rule_engine::streaming::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut engine = StreamRuleEngine::new();
    
    // Add streaming rules
    engine.add_rule(r#"
    rule "HighVolumeAlert" {
        when
            WindowEventCount > 100 && volumeSum > 1000000
        then
            AlertService.trigger("High volume detected");
    }
    "#).await?;
    
    // Register action handlers
    engine.register_action_handler("AlertService", |action| {
        println!("๐Ÿšจ Alert: {:?}", action.parameters);
    }).await;
    
    // Start processing
    engine.start().await?;
    
    // Send events
    let event = StreamEvent::new("TradeEvent", data, "exchange");
    engine.send_event(event).await?;
    
    Ok(())
}

Streaming Features:

  • โฐ Time Windows: Sliding/tumbling window aggregations
  • ๐Ÿ“Š Real-time Analytics: Count, sum, average, min/max over windows
  • ๐ŸŽฏ Pattern Matching: Event correlation and filtering
  • โšก High Throughput: Async processing with backpressure handling
  • ๐Ÿšจ Action Handlers: Custom callbacks for rule consequences

Real-World Integration Examples

๐Ÿ”Œ Kafka Consumer

use rdkafka::consumer::{Consumer, StreamConsumer};

async fn consume_from_kafka(engine: Arc<StreamRuleEngine>) {
    let consumer: StreamConsumer = ClientConfig::new()
        .set("group.id", "trading-group")
        .set("bootstrap.servers", "localhost:9092")
        .create().unwrap();
    
    consumer.subscribe(&["trading-events"]).unwrap();
    
    loop {
        match consumer.recv().await {
            Ok(message) => {
                let event = parse_kafka_message(message);
                engine.send_event(event).await?;
            }
            Err(e) => eprintln!("Kafka error: {}", e),
        }
    }
}

๐ŸŒ WebSocket Stream

use tokio_tungstenite::{connect_async, tungstenite::Message};

async fn consume_from_websocket(engine: Arc<StreamRuleEngine>) {
    let (ws_stream, _) = connect_async("wss://api.exchange.com/stream").await?;
    let (_, mut read) = ws_stream.split();
    
    while let Some(msg) = read.next().await {
        match msg? {
            Message::Text(text) => {
                let trade_data: TradeData = serde_json::from_str(&text)?;
                let event = convert_to_stream_event(trade_data);
                engine.send_event(event).await?;
            }
            _ => {}
        }
    }
}

๐Ÿ”„ HTTP API Polling

async fn poll_trading_api(engine: Arc<StreamRuleEngine>) {
    let client = reqwest::Client::new();
    let mut interval = interval(Duration::from_secs(1));
    
    loop {
        interval.tick().await;
        
        match client.get("https://api.exchange.com/trades").send().await {
            Ok(response) => {
                let trades: Vec<Trade> = response.json().await?;
                
                for trade in trades {
                    let event = StreamEvent::new(
                        "TradeEvent",
                        trade.to_hashmap(),
                        "exchange_api"
                    );
                    engine.send_event(event).await?;
                }
            }
            Err(e) => eprintln!("API error: {}", e),
        }
    }
}

๐Ÿ—„๏ธ Database Change Streams

async fn watch_database_changes(engine: Arc<StreamRuleEngine>) {
    let mut change_stream = db.collection("trades")
        .watch(None, None).await?;
    
    while let Some(change) = change_stream.next().await {
        let change_doc = change?;
        
        if let Some(full_document) = change_doc.full_document {
            let event = StreamEvent::new(
                "DatabaseChange",
                document_to_hashmap(full_document),
                "mongodb"
            );
            engine.send_event(event).await?;
        }
    }
}

๐Ÿ“‚ File Watching

use notify::{Watcher, RecursiveMode, watcher};

async fn watch_log_files(engine: Arc<StreamRuleEngine>) {
    let (tx, mut rx) = tokio::sync::mpsc::channel(100);
    
    let mut watcher = watcher(move |res| {
        // Parse log lines into StreamEvents
    }, Duration::from_secs(1))?;
    
    watcher.watch("/var/log/trading", RecursiveMode::Recursive)?;
    
    while let Some(file_event) = rx.recv().await {
        let stream_event = parse_log_event(file_event);
        engine.send_event(stream_event).await?;
    }
}

Use Case Examples

๐Ÿ“ˆ Financial Trading

rule "CircuitBreaker" {
    when
        priceMax > 200.0 || priceMin < 50.0
    then
        MarketService.halt("extreme_movement");
}

๐ŸŒก๏ธ IoT Monitoring

rule "OverheatingAlert" {
    when
        temperatureAverage > 80.0 && WindowEventCount > 20
    then
        CoolingSystem.activate();
        AlertService.notify("overheating_detected");
}

๐Ÿ›ก๏ธ Fraud Detection

rule "SuspiciousActivity" {
    when
        transactionCountSum > 10 && amountAverage > 1000.0
    then
        SecurityService.flag("potential_fraud");
        AccountService.freeze();
}

๐Ÿ“Š E-commerce Analytics

rule "FlashSaleOpportunity" {
    when
        viewCountSum > 1000 && conversionRateAverage < 0.02
    then
        PromotionService.trigger("flash_sale");
        InventoryService.prepare();
}

See docs/STREAMING.md for complete documentation and examples.

๐Ÿ“Š Advanced Analytics & Performance Monitoring (v0.3.0+)

Get deep insights into your rule engine performance with built-in analytics and monitoring:

๐Ÿ”ง Quick Analytics Setup

use rust_rule_engine::{RustRuleEngine, AnalyticsConfig, RuleAnalytics};

// Configure analytics for production use
let analytics_config = AnalyticsConfig {
    track_execution_time: true,
    track_memory_usage: true,
    track_success_rate: true,
    sampling_rate: 0.8,  // 80% sampling for high-volume production
    retention_period: Duration::from_secs(30 * 24 * 60 * 60), // 30 days
    max_recent_samples: 100,
};

// Enable analytics
let analytics = RuleAnalytics::new(analytics_config);
engine.enable_analytics(analytics);

// Execute rules - analytics automatically collected
let result = engine.execute(&facts)?;

// Access comprehensive insights
if let Some(analytics) = engine.analytics() {
    let stats = analytics.overall_stats();
    println!("Total executions: {}", stats.total_evaluations);
    println!("Average execution time: {:.2}ms", 
        stats.avg_execution_time.as_secs_f64() * 1000.0);
    println!("Success rate: {:.1}%", stats.success_rate);
    
    // Get optimization recommendations
    let recommendations = analytics.generate_recommendations();
    for rec in recommendations {
        println!("๐Ÿ’ก {}", rec);
    }
}

๐Ÿ”„ No-Loop Protection

Prevent rules from infinitely triggering themselves - essential for rules that modify their own conditions:

๐ŸŽฏ The Problem

// โŒ Without no-loop: INFINITE LOOP!
rule "ScoreBooster" {
    when
        Player.score < 100
    then
        set(Player.score, Player.score + 10);  // This changes the condition!
}
// Rule keeps firing: 50 โ†’ 60 โ†’ 70 โ†’ 80 โ†’ 90 โ†’ 100 โ†’ STOP (only due to max_cycles)

โœ… The Solution

// โœ… With no-loop: SAFE!
rule "ScoreBooster" no-loop {
    when
        Player.score < 100
    then
        set(Player.score, Player.score + 10);  // Rule fires once per cycle
}
// Rule fires once: 50 โ†’ 60, then waits for next cycle

๐Ÿงช Usage Examples

use rust_rule_engine::*;

// Method 1: Via GRL parsing
let grl = r#"
    rule "SafeUpdater" no-loop salience 10 {
        when Player.level < 5
        then set(Player.level, Player.level + 1);
    }
"#;
let rules = GRLParser::parse_rules(grl)?;

// Method 2: Via API
let rule = Rule::new("SafeUpdater".to_string(), conditions, actions)
    .with_no_loop(true)
    .with_salience(10);

// Method 3: Multiple positions supported
// rule "Name" no-loop salience 10 { ... }  โœ…
// rule "Name" salience 10 no-loop { ... }  โœ…

๐Ÿ”ฌ How It Works

  1. Per-Cycle Tracking: Engine tracks which rules fired in current cycle
  2. Skip Logic: Rules with no_loop=true skip if already fired this cycle
  3. Fresh Start: Tracking resets at beginning of each new cycle
  4. Drools Compatible: Matches Drools behavior exactly

๐ŸŽฎ Real Example

fn demo_no_loop() -> Result<()> {
    let grl = r#"
        rule "LevelUp" no-loop {
            when Player.xp >= 100
            then 
                set(Player.level, Player.level + 1);
                set(Player.xp, 0);
                log("Player leveled up!");
        }
    "#;
    
    let rules = GRLParser::parse_rules(grl)?;
    // Rule fires once: level 1โ†’2, xp 150โ†’0
    // Without no-loop: would fire again since xp >= 100 still true initially
}

๐Ÿ“ˆ Analytics Features

  • โฑ๏ธ Execution Timing: Microsecond-precision rule performance tracking
  • ๐Ÿ“Š Success Rate Monitoring: Track fired vs evaluated rule ratios
  • ๐Ÿ’พ Memory Usage Estimation: Optional memory footprint analysis
  • ๐ŸŽฏ Performance Rankings: Identify fastest and slowest rules
  • ๐Ÿ”ฎ Smart Recommendations: AI-powered optimization suggestions
  • ๐Ÿ“… Timeline Analysis: Recent execution history and trends
  • โš™๏ธ Production Sampling: Configurable sampling rates for high-volume environments
  • ๐Ÿ—‚๏ธ Automatic Cleanup: Configurable data retention policies

๐ŸŽ›๏ธ Production Configuration

// Production configuration with optimized settings
let production_config = AnalyticsConfig::production(); // Built-in production preset

// Or custom configuration
let custom_config = AnalyticsConfig {
    track_execution_time: true,
    track_memory_usage: false,    // Disable for performance
    track_success_rate: true,
    sampling_rate: 0.1,          // 10% sampling for high traffic
    retention_period: Duration::from_secs(7 * 24 * 60 * 60), // 1 week
    max_recent_samples: 50,      // Limit memory usage
};

๐Ÿ“Š Rich Analytics Dashboard

// Get comprehensive performance report
let analytics = engine.analytics().unwrap();

// Overall statistics
let stats = analytics.overall_stats();
println!("๐Ÿ“Š Performance Summary:");
println!("  Rules: {}", stats.total_rules);
println!("  Executions: {}", stats.total_evaluations);
println!("  Success Rate: {:.1}%", stats.success_rate);
println!("  Avg Time: {:.2}ms", stats.avg_execution_time.as_secs_f64() * 1000.0);

// Top performing rules
for rule_metrics in analytics.slowest_rules(3) {
    println!("โš ๏ธ Slow Rule: {} ({:.2}ms avg)", 
        rule_metrics.rule_name, 
        rule_metrics.avg_execution_time().as_secs_f64() * 1000.0
    );
}

// Recent activity timeline
for event in analytics.get_recent_events(5) {
    let status = if event.success { "โœ…" } else { "โŒ" };
    println!("{} {} - {:.2}ms", status, event.rule_name, 
        event.duration.as_secs_f64() * 1000.0);
}

๐Ÿ” Performance Insights

The analytics system provides actionable insights:

  • Slow Rule Detection: "Consider optimizing 'ComplexValidation' - average execution time is 15.3ms"
  • Low Success Rate Alerts: "Rule 'RareCondition' has low success rate (12.5%) - review conditions"
  • Dead Rule Detection: "Rule 'ObsoleteCheck' never fires despite 156 evaluations - review logic"
  • Memory Usage Warnings: "Rule 'DataProcessor' uses significant memory - consider optimization"

๐Ÿ“š Analytics Examples

Check out the comprehensive analytics demo:

# Run the analytics demonstration
cargo run --example analytics_demo

# Output includes:
# - Configuration summary
# - Performance rankings  
# - Success rate analysis
# - Optimization recommendations
# - Recent execution timeline

Key Benefits:

  • ๐Ÿš€ Performance Optimization: Identify bottlenecks automatically
  • ๐Ÿ“ˆ Production Monitoring: Real-time insights in live environments
  • ๐Ÿ”ง Development Debugging: Detailed execution analysis during development
  • ๐Ÿ“Š Trend Analysis: Historical performance tracking and regression detection
  • โšก Zero-Overhead Option: Configurable sampling with minimal performance impact

๏ฟฝ Changelog

v0.3.0 (October 2025) - AST-Based Dependency Analysis & Advanced Analytics

  • ๐Ÿ” Revolutionary Dependency Analysis: Complete rewrite from hard-coded pattern matching to proper AST parsing
  • ๐ŸŽฏ Smart Field Detection: Recursive condition tree traversal for accurate field dependency extraction
  • ๐Ÿง  Function Side-Effect Analysis: Intelligent inference of field modifications from function calls
  • โšก Zero False Positives: Elimination of brittle string-based detection methods
  • ๐Ÿš€ Parallel Processing Foundation: AST-based analysis enables safe concurrent rule execution
  • ๐Ÿ“Š Advanced Conflict Detection: Real data flow analysis for read-write conflict identification
  • ๐Ÿ—๏ธ Production-Ready Safety: Robust dependency analysis for enterprise-grade rule management
  • ๐Ÿ“ˆ Advanced Analytics System: Comprehensive performance monitoring and optimization insights
    • Real-time execution metrics with microsecond precision
    • Success rate tracking and trend analysis
    • Memory usage estimation and optimization recommendations
    • Production-ready sampling and data retention policies
    • Automated performance optimization suggestions
    • Rich analytics dashboard with timeline analysis
  • ๐ŸŒ REST API with Monitoring: Production-ready web API with full analytics integration
    • Comprehensive REST endpoints for rule execution
    • Real-time analytics dashboard with performance insights
    • Health monitoring and system status endpoints
    • CORS support and proper error handling
    • Sample requests and complete API documentation

v0.2.x - Core Features & Streaming

  • ๐ŸŒŠ Stream Processing: Real-time event processing with time windows
  • ๐Ÿ“Š Rule Templates: Parameterized rule generation system
  • ๐Ÿ”ง Method Calls: Enhanced object method call support
  • ๐Ÿ“„ File-Based Rules: External .grl file support
  • โšก Performance Optimizations: Microsecond-level rule execution

๏ฟฝ๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ“ž Support


Built with โค๏ธ in Rust ๐Ÿฆ€