Rust Rule Engine v0.9.0 ๐ฆโก
A high-performance rule engine for Rust with Plugin System, Built-in Utilities, GRL (Grule Rule Language) support, and advanced pattern matching capabilities. Designed for production use with comprehensive error handling, type safety, and extensibility.
๐ GitHub Repository | Documentation | Crates.io
๏ฟฝ Table of Contents
- ๐ Key Features
- ๐ฆ Installation
- ๐ฏ Quick Start
- ๐ Plugin System
- ๐ฏ Advanced Features
- ๐ Examples
- ๐ง Configuration
- ๐ Performance
- ๐บ Roadmap
- ๐งฉ Advanced Pattern Matching
- ๐ฏ Rule Attributes
- ๐จ Advanced Action Handlers
- ๐ Advanced Workflow Engine
- ๐ค AI Integration
- ๐จ Visual Rule Builder
- ๐ REST API with Monitoring
- โก Performance & Architecture
- ๐ Changelog
- ๐ฏ GRL Rule Language Features
- ๐ Distributed & Cloud Features
- ๐ API Reference
- ๐ค Contributing
- ๐ License
- ๐ Acknowledgments
- ๐ Support
๏ฟฝ๐ Key Features
๐ฅ NEW in v0.9.0: Plugin System
- Modular Plugin Architecture: Extensible plugin system with lifecycle management
- Built-in Plugin Suite: 44+ actions & 33+ functions for common operations
- Plugin Health Monitoring: Real-time health checks and status tracking
- Hot-reload Support: Dynamic plugin loading and unloading
- Custom Plugin Creation: Easy-to-use RulePlugin trait for custom extensions
๐ฏ Core Engine Features
- GRL Support: Full Grule-compatible syntax with method calls and object interactions
- Knowledge Base: Centralized rule management with salience and priority control
- Working Memory: Advanced facts system for complex data relationships
- Type Safety: Rust's type system ensures runtime safety and performance
- High Performance: Optimized execution with cycle detection and parallel processing
- Flexible Facts API: Support for nested objects, arrays, and complex data structures
๐งฉ Advanced Pattern Matching
- EXISTS Pattern: Check if at least one fact matches condition (
exists(...)) - NOT Pattern: Check if no facts match condition (
!exists(...)) - FORALL Pattern: Check if all facts of a type match condition (
forall(...)) - Complex Patterns: Combine patterns with logical operators (AND, OR, NOT)
- Drools Compatibility: ~85% compatible with Drools pattern matching
๐ฏ Rule Attributes & Workflow
- Agenda Groups: Organize rules into execution phases for workflow control
- Activation Groups: Mutually exclusive rule execution with salience priority
- Lock-on-Active: Prevent rules from firing multiple times per agenda activation
- Date Effective/Expires: Time-based rule activation with DateTime support
- No-Loop Protection: Prevent infinite rule self-activation
- Salience Control: Priority-based rule execution ordering
๐จ Action Handler System
- Custom Action Execution: Register handlers for real business logic
- Parameter Resolution: Automatic fact value substitution in parameters
- External System Integration: Connect to emails, databases, APIs, services
- Error Handling: Graceful failure handling with meaningful messages
- Facts Integration: Full access to rule engine fact data within handlers
๐ Workflow Engine Features
- Scheduled Task System: Time-based task execution with flexible scheduling
- Workflow State Tracking: Real-time workflow monitoring and progress tracking
- Dynamic Rule Activation: Context-aware rule execution based on workflow state
- Comprehensive Analytics: Detailed workflow performance metrics and insights
๐ Built-in Plugin Suite
- String Utilities: 13 actions, 7 functions for text manipulation
- Math Operations: 12 actions, 8 functions for calculations
- Date/Time: 8 actions, 6 functions for temporal operations
- Data Validation: 6 actions, 6 functions for input validation
- Collections: 7 actions, 6 functions for array/object manipulation
๐ค AI Integration
- 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
๐ Production Features
- REST API: Complete web API with analytics monitoring
- Real-time Analytics: Live performance monitoring and insights
- Health Checks: Comprehensive system health monitoring
- CORS Support: Cross-origin resource sharing
- Memory Management: Automatic cleanup and retention policies
- Error Handling: Proper HTTP status codes and error messages
โก Performance & Architecture
- Ultra-fast Execution: Rules execute in microseconds (2-5ยตs)
- Efficient Parsing: GRL rules parse in under 2ยตs
- Low Memory Footprint: Minimal overhead per rule (~1-2KB)
- Zero GC Pauses: No garbage collection overhead
- Parallel Processing: Multi-threaded rule execution when safe
- Dependency Analysis: AST-based conflict detection and optimization
๐ฆ Installation
Add this to your Cargo.toml:
[]
= "0.9.0"
๐ฏ Quick Start
Basic Rule Engine with Built-in Plugins
use *;
use RulePlugin;
use *;
Simple Rule without Plugins
use *;
๐ Plugin System
Built-in Plugins Overview
The v0.9.0 release includes a comprehensive plugin suite:
๐ String Utilities Plugin
// Actions: ToUpperCase, ToLowerCase, StringTrim, StringLength,
// StringContains, StringReplace, StringSplit, StringJoin
// Functions: concat, repeat, substring, padLeft, padRight
ToUpperCase;
let result = concat; // "Hello World"
๐ข Math Operations Plugin
// Actions: Add, Subtract, Multiply, Divide, Modulo, Power, Abs, Round, Ceil, Floor
// Functions: max, min, sqrt, sum, avg, random
Add;
let maximum = max; // 10.5
๐ Date/Time Plugin
// Actions: CurrentDate, CurrentTime, FormatDate, ParseDate, AddDays, AddHours, DateDiff, IsWeekend
// Functions: now, today, dayOfWeek, dayOfYear, year, month, day
CurrentDate;
let day = dayOfWeek; // Returns day number
โ Validation Plugin
// Actions: ValidateEmail, ValidatePhone, ValidateUrl, ValidateRegex, ValidateRange, ValidateLength, ValidateNotEmpty, ValidateNumeric
// Functions: isEmail, isPhone, isUrl, isNumeric, isEmpty, inRange
ValidateEmail;
let valid = isEmail; // true
๐ Collection Operations Plugin
// Actions: ArrayLength, ArrayPush, ArrayPop, ArraySort, ArrayFilter, ArrayMap, ArrayFind, ObjectKeys, ObjectValues, ObjectMerge
// Functions: length, contains, first, last, reverse, join, slice, keys, values
ArrayLength;
let size = length; // 4
Creating Custom Plugins
use ;
๐ฏ Advanced Features
Knowledge Base Management
let mut kb = new;
// Add rules with different salience (priority)
kb.add_rule_from_grl?;
kb.add_rule_from_grl?;
// Rules execute in salience order (highest first)
let mut engine = new;
Complex Data Objects
use HashMap;
let mut facts = new;
// Nested object structures
let mut customer = new;
customer.insert;
customer.insert;
let mut address = new;
address.insert;
address.insert;
customer.insert;
facts.set;
// Access nested properties in rules
let rule = r#"
rule "LocationRule" {
when
Customer.address.country == "US" &&
Customer.address.state == "CA" &&
Customer.age >= 21
then
Customer.eligible = true;
Customer.discount = 0.1;
}
"#;
Method Calls and Functions
// Built-in functions in conditions
let rule = r#"
rule "ValidationRule" {
when
isEmail(Customer.email) == true &&
length(Customer.name) > 2 &&
inRange(Customer.age, 18, 120) == true
then
Customer.validated = true;
}
"#;
// Custom function registration
engine.register_function;
Error Handling and Debugging
use ;
// Comprehensive error handling
match engine.execute
๐ Examples
The repository includes comprehensive examples:
- Basic Usage:
examples/basic_demo.rs - Plugin System:
examples/builtin_plugins_demo.rs - E-commerce Rules:
examples/ecommerce.rs - Fraud Detection:
examples/fraud_detection.rs - GRL Compatibility:
examples/grule_demo.rs - Streaming Data:
examples/realtime_trading_stream.rs
Run examples:
๐ง Configuration
Engine Configuration
use EngineConfig;
let config = EngineConfig ;
let engine = with_config;
Plugin Configuration
use ;
let plugin_config = PluginConfig ;
let plugin_manager = new;
๐ Performance
Rust Rule Engine v0.9.0 is designed for high-performance scenarios:
- Zero-copy: Efficient memory usage with minimal allocations
- Parallel Execution: Multi-threaded rule processing when safe
- Optimized Parsing: Fast GRL parsing with minimal overhead
- Plugin Caching: Efficient plugin management and reuse
- Cycle Detection: Prevents infinite loops in rule chains
๐บ Roadmap
v0.10.0 (Planned)
- Advanced Plugin Features
- Plugin dependency management
- Plugin versioning and compatibility
- Plugin marketplace integration
- Performance Enhancements
- Rule compilation to bytecode
- Advanced caching strategies
- Memory pool optimization
- Developer Experience
- Visual rule debugger
- Rule testing framework
- IDE plugins and syntax highlighting
v1.0.0 (Future)
- Production Features
- Distributed rule execution
- Rule versioning and migration
- Advanced monitoring and metrics
- Enterprise Features
- Role-based access control
- Audit logging
- Integration with external systems
๐ค Contributing
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
Development Setup
Running Tests
# Run all tests
# Run with coverage
# Run benchmarks
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
- Inspired by Grule rule engine
- Built with Rust's powerful type system and performance capabilities
- Community feedback and contributions
๐ Support
- ๐ Documentation
- ๐ Issue Tracker
- ๐ฌ Discussions
- ๐ง Email: tonthatvu.hust@gmail.com
Rust Rule Engine v0.9.0 - Powerful, extensible, and production-ready rule engine for Rust ๐ฆโก
- ๐ Stream Processing: Real-time event processing with time windows (optional)
- ๐ Analytics: Built-in aggregations and trend analysis
- ๐จ Action Handlers: Custom action execution for external system integration
- ๐ Advanced Analytics: Production-ready performance monitoring and optimization insights
๐ Advanced Workflow Engine v0.8.0 (Latest!)
The rule engine now features a comprehensive workflow engine with agenda group management, scheduled task execution, and real-time workflow state tracking for complex business process automation.
Workflow Features
- ๐ Agenda Group Management: Organize rules into execution phases with automatic transitions
- โฐ Scheduled Task System: Time-based task execution with flexible scheduling
- ๐ Workflow State Tracking: Real-time workflow monitoring and progress tracking
- ๐ฏ Dynamic Rule Activation: Context-aware rule execution based on workflow state
- ๏ฟฝ Comprehensive Analytics: Detailed workflow performance metrics and insights
Workflow Example
use ;
use KnowledgeBase;
use GRLParser;
use Value;
use Facts;
// Create workflow engine
let config = EngineConfig ;
let mut engine = with_config;
// Define workflow rules with agenda groups
let workflow_rules = vec!;
// Execute workflow with automatic agenda management
let result = engine.execute_workflow?;
println!;
๐จ Advanced Action Handlers v0.7.1
The rule engine now supports advanced custom action execution with simplified parameter syntax and automatic fact resolution, enabling seamless integration with external systems.
Action Handler System
Register custom handlers for ActionType::Custom actions that can execute real business logic instead of just debug printing.
โจ Simplified Parameter Syntax v0.7.1
use ;
use Value;
use HashMap;
// Create engine
let mut engine = with_config;
// Register email handler with indexed parameters
engine.register_action_handler;
// Register database logger with simplified syntax
engine.register_action_handler;
Parameter Resolution
Action handlers automatically resolve fact references in parameters:
// In GRL rule:
rule "WelcomeCustomer"
// Parameter resolution in action:
// Parameter 0: "Customer.email" โ "john.doe@example.com"
// Parameter 1: "Welcome!" โ "Welcome!"
// Parameter 2: "Customer.name" โ "John Doe"
GRL Usage with Action Handlers
rule "VIPCustomerWelcome" salience 20 no-loop {
when
Customer.tier == "VIP" && Customer.welcome_sent != true
then
SendEmail(Customer.email, "VIP Welcome Package", "Welcome to our VIP program!");
LogToDatabase("customer_events", "vip_welcome_sent");
Customer.welcome_sent = true;
}
rule "HighValueOrderAlert" salience 15 no-loop {
when
Order.total > 5000 && Order.alert_sent != true
then
SendAlert("HIGH", "High-value order requires review");
ProcessPayment(Order.total, "secure_processing");
Order.alert_sent = true;
}
Action Handler Examples
See complete examples:
- Action Handlers Demo - Comprehensive action handler showcase
Benefits
โ
External System Integration: Connect rules to emails, databases, APIs, services
โ
Real Business Logic: Execute actual business operations, not just debug prints
โ
Parameter Resolution: Automatic fact value substitution in action parameters
โ
Facts Integration: Full access to rule engine fact data within handlers
โ
Error Handling: Graceful failure handling with meaningful error messages
โ
Performance: Efficient execution with minimal overhead
โ
Flexibility: Register any custom business logic as action handlers
โ
Testability: Mock handlers for unit testing rule behavior
๐งฉ Advanced Pattern Matching v0.7.0
The rule engine now supports advanced pattern matching capabilities similar to Drools, enabling complex conditional logic with EXISTS, NOT, and FORALL patterns.
Pattern Types
EXISTS Pattern
Check if at least one fact matches the condition:
// Programmatic API
let condition = exists;
// GRL Syntax
rule "ActivateVIPService" salience 20 {
when
exists(Customer.tier == "VIP")
then
System.vipServiceActive = true;
log("VIP service activated");
}
NOT Pattern
Check if no facts match the condition:
// Programmatic API
let condition = not;
// GRL Syntax
rule "SendMarketingEmail" salience 15 {
when
!exists(Order.status == "pending")
then
Marketing.emailSent = true;
log("Marketing email sent - no pending orders");
}
FORALL Pattern
Check if all facts of a type match the condition:
// Programmatic API
let condition = forall;
// GRL Syntax
rule "EnableShipping" salience 10 {
when
forall(Order.status == "processed")
then
Shipping.enabled = true;
log("All orders processed - shipping enabled");
}
Combined Patterns
Combine multiple patterns with logical operators:
rule "ComplexBusinessRule" salience 25 {
when
exists(Customer.tier == "VIP") &&
!exists(Alert.priority == "high") &&
forall(Order.status == "processed")
then
System.premiumModeEnabled = true;
log("Premium mode activated - all conditions met");
}
Pattern Matching Examples
See complete examples:
- Pattern Matching Demo - Programmatic API
- GRL Pattern Matching Demo - GRL file syntax
- Complex Patterns from File - Advanced GRL patterns
Drools Compatibility
Pattern matching brings ~85% compatibility with Drools rule engine, supporting the core pattern matching features that enable complex business logic modeling.
๐ฏ Rule Attributes v0.6.0
Advanced rule attributes providing Drools-compatible workflow control and execution management:
๐ Agenda Groups - Workflow Control
Organize rules into execution phases with agenda group control:
rule "ValidateCustomer" agenda-group "validation" salience 10 {
when
Customer.age >= 18
then
Customer.status = "valid";
log("Customer validated");
}
rule "ProcessPayment" agenda-group "processing" salience 5 {
when
Customer.status == "valid"
then
Order.status = "processed";
log("Payment processed");
}
// Control workflow execution
engine.set_agenda_focus;
engine.execute?; // Only validation rules fire
engine.set_agenda_focus;
engine.execute?; // Only processing rules fire
๐ฏ Activation Groups - Mutually Exclusive Rules
Ensure only one rule from a group fires:
rule "PremiumDiscount" activation-group "discount" salience 10 {
when Customer.tier == "premium"
then Order.discount = 0.20;
}
rule "GoldDiscount" activation-group "discount" salience 8 {
when Customer.tier == "gold"
then Order.discount = 0.15;
}
๐ Lock-on-Active - One-time Execution
Prevent rules from firing again until agenda group changes:
rule "WelcomeEmail" lock-on-active salience 10 {
when Customer.isNew == true
then sendWelcomeEmail(Customer);
}
โฐ Date Effective/Expires - Time-based Rules
Create seasonal or time-limited rules:
rule "ChristmasDiscount"
date-effective "2025-12-01T00:00:00Z"
date-expires "2025-12-31T23:59:59Z"
salience 20 {
when Order.total > 100
then Order.seasonalDiscount = 0.25;
}
๐ Combined Attributes - Complex Rules
Mix multiple attributes for sophisticated control:
rule "ComplexPaymentRule"
agenda-group "processing"
activation-group "payment"
lock-on-active
no-loop
salience 30 {
when
Order.status == "pending" && Payment.method == "credit"
then
Order.status = "processed";
Payment.confirmed = true;
}
๐ Programmatic API
Use attributes with the Rust API:
let rule = new
.with_agenda_group
.with_activation_group
.with_lock_on_active
.with_date_effective_str?
.with_date_expires_str?;
// Get available groups
let agenda_groups = engine.get_agenda_groups;
let activation_groups = engine.get_activation_groups;
// Workflow control
engine.set_agenda_focus;
engine.execute?;
๐ค 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;
engine.register_function;
engine.register_function;
๐ Changelog
v0.8.0 (October 2025) - Advanced Workflow Engine Implementation ๐
- ๐ Advanced Workflow Engine: Complete workflow management system with comprehensive features
- ๐ Agenda Group Management: Organize rules into execution phases with automatic focus transitions
- โฐ Scheduled Task System: Time-based task execution with flexible scheduling and conditional triggers
- ๐ Workflow State Tracking: Real-time workflow monitoring with start/complete lifecycle management
- ๐ฏ Dynamic Agenda Activation: Context-aware agenda group activation based on workflow state
- ๐ Workflow Analytics: Detailed performance metrics including execution statistics and task monitoring
- ๐ Seamless Integration: Unified API combining rule execution with workflow orchestration
- ๐ง Enhanced Rule Engine: Improved fact handling and condition evaluation
- Facts API Enhancement: Extended Facts system with workflow data integration
- Condition Evaluation: Optimized condition processing with better error handling
- Action Processing: Enhanced action execution with workflow context awareness
- ๐งช Comprehensive Demos: Real-world workflow examples
- Basic order processing workflow with VIP customer routing
- Advanced workflow with scheduled tasks and multi-phase execution
- Complete workflow lifecycle demonstrations with detailed logging
- ๐ก๏ธ Production Ready: Enhanced error handling and performance optimization for workflow scenarios
v0.7.1 (October 2025) - Advanced Action Handlers Implementation ๐จ
- ๐จ Advanced Action Handlers: Custom action execution system for external integrations
- Action Handler Registry: Register custom handlers for
ActionType::Customexecution - Parameter Resolution: Automatic fact value substitution in action parameters
- Facts Integration: Full access to fact data within action handlers
- Error Handling: Graceful failure handling with meaningful error messages
- Built-in Handler Examples: Email, database logging, alerts, payment processing
- Action Handler Registry: Register custom handlers for
- ๐ง Enhanced Custom Actions: Fix
ActionType::Customfrom debug-only to fully functional- Previously:
ActionType::Customonly printed debug messages - Now: Executes registered business logic handlers with real functionality
- Previously:
- โก Parameter Resolution Engine: Smart fact reference resolution in action parameters
"Customer.email"โ resolves to actual email value from facts"Order.total"โ resolves to actual order total amount- Supports nested fact path resolution with dot notation
- ๐งช Comprehensive Demo: Real-world action handler examples
- Email sending with template parameters
- Database event logging with fact context
- Multi-level alert system (INFO, HIGH, CRITICAL)
- Payment processing with business rule validation
- ๐ก๏ธ No-Loop Protection: Enhanced rule execution control for action-triggered rules
v0.7.0 (October 2025) - Advanced Pattern Matching & Drools Compatibility ๐งฉ
- ๐งฉ Advanced Pattern Matching: Complete implementation of EXISTS, NOT, and FORALL patterns
- EXISTS pattern: Check if at least one fact matches condition
- NOT pattern: Check if no facts match condition (using
!exists(...)) - FORALL pattern: Check if all facts of a type match condition
- Complex patterns: Combine patterns with logical operators (AND, OR, NOT)
- ๐ฏ GRL Syntax Support: Full pattern matching support in GRL files
exists(Customer.tier == "VIP")syntax for existence checking!exists(Order.status == "pending")syntax for non-existenceforall(Order.status == "processed")syntax for universal quantification- Combined patterns:
exists(...) && !exists(...) && forall(...)
- ๐ง Parser Extensions: Enhanced GRL parser with pattern matching keywords
- Recursive pattern parsing with proper parentheses handling
- Seamless integration with existing logical operators
- Comprehensive parser tests for all pattern types
- โก Pattern Evaluation Engine: High-performance pattern matching evaluation
- Smart fact type detection and mapping (e.g., Customer1 โ Customer)
- Efficient fact iteration and filtering algorithms
- Full backward compatibility with existing rule engine
- ๐งช Comprehensive Testing: Full test coverage for pattern matching features
- 4 dedicated pattern matcher unit tests (all passing)
- Real-world business scenario demonstrations
- GRL file parsing and execution integration tests
- Multiple example files showcasing pattern matching capabilities
v0.6.0 (October 2025) - Rule Attributes Enhancement ๐ฏ
- ๐ฏ Comprehensive Rule Attributes: Drools-compatible rule attributes system
- ๐ Agenda Groups: Structured workflow control with focus management
- ๐ Activation Groups: Mutually exclusive rule execution with salience priority
- ๐ Lock-on-Active: Prevent rules from firing multiple times per agenda activation
- โฐ Date Effective/Expires: Time-based rule activation with DateTime support
- ๐ Programmatic API: Full Rust API for attribute management
- ๐ง Enhanced GRL Parser: Support for flexible rule attribute syntax in any position
- ๐งช Comprehensive Testing: 27/27 unit tests including new agenda management tests
- ๐ Complete Demo: Full demonstration of all 4 attribute features
- โก Performance Optimized: Efficient agenda focus stack and activation group management
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
- Support for parentheses grouping:
- ๐ฆ 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:
[]
= "0.8.0"
= "0.4" # For date-based rule attributes
# For streaming features (optional)
= { = "0.8.0", = ["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 ;
use HashMap;
๐ Inline String Rules
Define rules directly in your code:
use ;
use HashMap;
๐ฏ Rule Attributes Quick Example
Experience the power of Rule Attributes v0.6.0 with workflow control:
use ;
use HashMap;
๐จ Visual Rule Builder (NEW!)
Create rules visually with our drag-and-drop interface!
๐ Visual Rule Builder - Build GRL rules without coding!
โจ Features
- ๐ฏ Drag & Drop Interface: Intuitive visual rule creation
- ๐ Real-time GRL Generation: See your rules as GRL code instantly
- ๐ Syntax Validation: Automatic validation and error checking
- ๐ Template Library: Pre-built rule templates for common scenarios
- ๐พ Export & Import: Save and load your rule configurations
- ๐ One-Click Integration: Copy-paste generated GRL directly into your Rust projects
๐ฎ Quick Demo
- Visit: https://visual-rule-builder.amalthea.cloud/
- Build: Drag conditions and actions to create your business logic
- Generate: Get clean, optimized GRL code automatically
- Integrate: Copy the GRL into your Rust Rule Engine project
๐ Perfect For
- ๐ Learning: Understand rule structure and syntax visually
- โก Rapid Prototyping: Quickly build and test rule logic
- ๐ฅ Business Users: Create rules without programming knowledge
- ๐ง Complex Rules: Visualize intricate business logic flows
๐ก Example Workflow
// Generated from Visual Builder
rule "CustomerUpgrade" salience 20 {
when
Customer.totalSpent > 1000.0 &&
Customer.loyaltyYears >= 2 &&
!exists(Customer.tier == "VIP")
then
Customer.tier = "VIP";
sendWelcomePackage(Customer.email);
log("Customer upgraded to VIP status");
}
Try it now: Build this rule visually in under 2 minutes! ๐
๐ค Complete AI Integration Example
Here's a complete example showing how to build an AI-powered business rule system:
use ;
use HashMap;
๐ Dependency Analysis Example
use DependencyAnalyzer;
๐ฏ 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");
}
๐งฉ Pattern Matching Examples
rule "VIPServiceActivation" "Activate VIP service when VIP customer exists" salience 20 {
when
exists(Customer.tier == "VIP")
then
System.vipServiceActive = true;
log("VIP service activated - VIP customer detected");
}
rule "MarketingCampaign" "Send marketing when no pending orders" salience 15 {
when
!exists(Order.status == "pending")
then
Marketing.emailSent = true;
sendMarketingEmail();
log("Marketing campaign sent - no pending orders");
}
rule "ShippingEnable" "Enable shipping when all orders processed" salience 10 {
when
forall(Order.status == "processed")
then
Shipping.enabled = true;
enableShippingService();
log("Shipping enabled - all orders processed");
}
rule "ComplexBusinessLogic" "Complex pattern combination" salience 25 {
when
exists(Customer.tier == "VIP") &&
!exists(Alert.priority == "high") &&
forall(Order.status == "processed")
then
System.premiumModeEnabled = true;
activatePremiumFeatures();
log("Premium mode activated - all conditions met");
}
Run Pattern Matching Examples:
# Programmatic pattern matching demo
# GRL file-based pattern matching
# Complex patterns from GRL files
๐ 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
# Or use the demo script for testing
Available Endpoints
Rule Execution:
POST /api/v1/rules/execute- Execute rules with provided factsPOST /api/v1/rules/batch- Execute rules in batch mode
Analytics & Monitoring:
GET /api/v1/analytics/dashboard- Comprehensive analytics dashboardGET /api/v1/analytics/stats- Overall performance statisticsGET /api/v1/analytics/recent- Recent execution activityGET /api/v1/analytics/recommendations- Performance optimization recommendationsGET /api/v1/analytics/rules/{rule_name}- Rule-specific analytics
System:
GET /- API documentationGET /api/v1/health- Health checkGET /api/v1/status- System status
Example Requests
Execute Rules:
Analytics Dashboard:
Sample Response:
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 ;
// 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 = new;
let analysis = analyzer.analyze_grl_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
// 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
new
.with_rule_file?
.with_inline_grl?
.with_config
.build
// Value types
Integer
Number
String
Boolean
Object
// Facts management
let facts = new;
facts.add_value?;
facts.get?;
// 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;
โก Parallel Rule Execution
The engine supports parallel execution for improved performance with large rule sets:
use ;
// Create parallel engine with custom configuration
let config = ParallelConfig ;
let mut engine = new;
// Add rules and facts
engine.add_rule;
engine.insert_fact;
// Execute rules in parallel
let result = engine.execute_parallel.await;
println!;
println!;
println!;
Parallel Execution Examples
# Simple parallel demo
# Performance comparison
๐ 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
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
# E-commerce rules
# Custom functions
# Method calls
Workflow Engine (v0.8.0)
# Basic workflow demo with order processing
# Advanced workflow with scheduled tasks
Action Handlers (v0.7.1)
# Action handlers with programmatic API
# Action handlers from GRL files
Performance & Scaling
# Parallel processing comparison
# Financial stress testing
# Distributed architecture demo
Advanced Features
# Pattern matching (v0.7.0)
# REST API with analytics
# Analytics and monitoring
# Rule file processing
# Advanced dependency analysis
Production Examples
# Fraud detection system
# Complete speedup demo
# 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 ;
async
๐ WebSocket Stream
use ;
async
๐ HTTP API Polling
async
๐๏ธ Database Change Streams
async
๐ File Watching
use ;
async
Use Case Examples
๐ Financial Trading
rule "CircuitBreaker"
๐ก๏ธ IoT Monitoring
rule "OverheatingAlert"
๐ก๏ธ Fraud Detection
rule "SuspiciousActivity"
๐ E-commerce Analytics
rule "FlashSaleOpportunity"
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 ;
// Configure analytics for production use
let analytics_config = AnalyticsConfig ;
// Enable analytics
let analytics = new;
engine.enable_analytics;
// Execute rules - analytics automatically collected
let result = engine.execute?;
// Access comprehensive insights
if let Some = engine.analytics
๐ 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 *;
// 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 = parse_rules?;
// Method 2: Via API
let rule = new
.with_no_loop
.with_salience;
// Method 3: Multiple positions supported
// rule "Name" no-loop salience 10 { ... } โ
// rule "Name" salience 10 no-loop { ... } โ
๐ฌ How It Works
- Per-Cycle Tracking: Engine tracks which rules fired in current cycle
- Skip Logic: Rules with
no_loop=trueskip if already fired this cycle - Fresh Start: Tracking resets at beginning of each new cycle
- Drools Compatible: Matches Drools behavior exactly
๐ฎ Real Example
๐ 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 = production; // Built-in production preset
// Or custom configuration
let custom_config = AnalyticsConfig ;
๐ Rich Analytics Dashboard
// Get comprehensive performance report
let analytics = engine.analytics.unwrap;
// Overall statistics
let stats = analytics.overall_stats;
println!;
println!;
println!;
println!;
println!;
// Top performing rules
for rule_metrics in analytics.slowest_rules
// Recent activity timeline
for event in analytics.get_recent_events
๐ 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
# 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
.grlfile support - โก Performance Optimizations: Microsecond-level rule execution
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Support
- ๐ Documentation: docs.rs/rust-rule-engine
- ๐ Issues: GitHub Issues
- ๐ฌ Discussions: GitHub Discussions
Built with โค๏ธ in Rust ๐ฆ