Overview
TheRuleEngine is the core component responsible for evaluating rule expressions against data contexts. It provides high-performance rule evaluation with intelligent caching, operator management, and built-in security features.
The Rule Engine is designed to be stateless and reusable. Create a single instance and reuse it throughout your application for optimal performance.
Creating an Engine
Use the factory function to create a new engine instance:Configuration Options
Enable strict type checking for operators. When enabled, type coercion is disabled.
Maximum nesting depth for rule expressions. Prevents infinite recursion.
Enable LRU caching for expression results and path resolution.
Maximum number of cached expression results. Uses LRU eviction strategy.
Maximum number of operators allowed in a single rule expression.
Enable debug logging for rule evaluation failures.
Allow access to prototype properties. Always keep
false in production for security.Core Methods
evaluateExpr()
Evaluate a rule expression against a data context:registerOperator()
Register custom operators for business-specific logic:name(string): Operator identifierhandler(function): Implementation function with signature(args, context, evaluateExpr, depth) => booleanoptions(object): Optional configurationallowOverwrite(boolean): Allow replacing existing operators
Performance Methods
getMetrics()
Get real-time performance metrics:Monitor these metrics in production to identify performance bottlenecks and optimize rule complexity.
getCacheStats()
Get cache statistics for monitoring:clearCache()
Clear all caches (expression and path resolver):Utility Methods
getOperators()
Get list of all registered operators:getConfig()
Get current engine configuration:Architecture
1
Rule Validation
The engine validates rule structure, checks depth limits, and counts operators before evaluation.
2
Cache Check
Looks up the expression in the LRU cache using a composite key of expression + context.
3
Expression Evaluation
Recursively evaluates operators, resolving paths and applying operator logic.
4
Cache Storage
Successful evaluations are cached with LRU eviction when cache is full.
5
Metrics Update
Performance metrics are updated including timing, cache hits, and errors.
Caching Strategy
The Rule Engine uses a two-tier caching system:Expression Cache
Caches complete rule evaluation results based on expression + context hash.
- LRU Eviction: Oldest entries removed when cache is full
- Default Size: 500 entries
- Key Strategy: Composite of rule structure and context values
Path Resolution Cache
Caches dot-notation path lookups for nested data access.
- LRU Eviction: Automatic cleanup of least-used paths
- Default Size: 500 entries
- Scope: Shared across all rule evaluations
Cache Key Generation
The engine creates intelligent cache keys based on:- Expression Structure: JSON-stringified rule object
- Context Identity: Context ID, shape hash, or value hash
- Composite Key:
expr:{rule}:ctx:{contextId}
Security Features
Prototype Pollution Protection
Prototype Pollution Protection
The engine blocks access to dangerous paths like
__proto__, constructor, and prototype:Depth Limiting
Depth Limiting
Prevents stack overflow attacks through deeply nested rules:
Operator Count Limiting
Operator Count Limiting
Prevents resource exhaustion from overly complex rules:
Function Access Prevention
Function Access Prevention
Functions in context data are automatically blocked:
Best Practices
Reuse Engine Instances
Create a single engine instance and reuse it across your application for optimal caching.
Configure Cache Size
Adjust cache size based on your rule complexity and data variability.
Monitor Performance
Regularly check metrics to identify slow rules and optimization opportunities.
Handle Errors Gracefully
Always check the success flag and provide fallback behavior.
