Skip to main content

Overview

The StatefulRuleEngine extends the base RuleEngine with state tracking capabilities, enabling you to detect changes in data over time and trigger actions based on state transitions.
Perfect for monitoring systems, event-driven workflows, and reactive business logic.

Key Features

State Tracking

Maintains previous states for comparison across evaluations

Event System

Subscribe to rule state changes with event listeners

Change Detection

Specialized operators for detecting value changes

History Management

Optional storage of evaluation history

Creating a Stateful Engine

Configuration Options

Core Options

boolean
default:"false"
When false, triggers only on false → true transitions. When true, triggers on any state change.
boolean
default:"false"
Enable storage of evaluation history for analysis and debugging.
number
default:"100"
Global limit for total history entries across all rules. Uses FIFO queue (legacy mode).
number
Per-rule history limit. Recommended for multi-rule scenarios to prevent history domination.

Phase 3.1: State Management Options

number
default:"null"
Time-to-live for rule states in milliseconds. Set to null for no expiration.
number
default:"60000"
Interval for automatic expired state cleanup (in milliseconds).
boolean
default:"true"
Deep copy contexts to prevent mutation. Handles circular references automatically.
number
default:"100"
Threshold for listener count warnings to detect potential memory leaks.

Phase 3.2: Concurrency Control Options

object
Configure concurrent evaluation behavior.Properties:
  • maxConcurrent (number, default: 10): Maximum concurrent evaluations per rule
  • timeout (number, default: 30000): Evaluation timeout in milliseconds
  • onTimeout (function): Callback when evaluation times out
  • onQueueFull (function): Callback when queue reaches capacity

Phase 3.3: Error Recovery Options

object
Configure error recovery strategies.Properties:
  • enabled (boolean, default: true): Enable error recovery
  • retry (object): Retry configuration
    • enabled (boolean): Enable retry mechanism
    • maxAttempts (number, default: 3): Maximum retry attempts
    • strategy (string): ‘exponential’, ‘fixed’, or ‘linear’
    • initialDelay (number, default: 100): Initial delay in ms
    • maxDelay (number, default: 5000): Maximum delay cap
    • onRetry (function): Callback on each retry
  • circuitBreaker (object): Circuit breaker configuration
    • enabled (boolean): Enable circuit breaker
    • failureThreshold (number, default: 5): Failures before opening
    • resetTimeout (number, default: 60000): Time before half-open state
    • onCircuitOpen (function): Callback when circuit opens
  • fallback (object): Fallback configuration
    • enabled (boolean): Enable fallback strategies
    • defaultValue (any): Default fallback value
    • onFallback (function): Callback when fallback used

Event System

Subscribe to rule state changes:

State Change Operators

Real-World Example

Methods

Core Methods

evaluate()

Evaluate a single rule with state tracking:
All evaluation methods are now async as of Phase 3.2

evaluateBatch()

Evaluate multiple rules at once with error handling:

getRuleState()

Get current state of a specific rule:

clearRuleState()

Clear state for a specific rule:

getHistory()

Get evaluation history (if enabled):

Phase 3.1: State Management Methods

getStateStats()

Get comprehensive state statistics:

cleanupExpiredStates()

Manually trigger cleanup of expired states:

getListenerCount()

Get listener count for a specific event:

getAllListenerCounts()

Get listener counts for all events:

startCleanupTimer() / stopCleanupTimer()

Control automatic state cleanup:

destroy()

Complete resource cleanup (timers, listeners, state):
Always call destroy() when shutting down to prevent memory leaks

Phase 3.2: Concurrency Methods

getConcurrencyStats()

Get concurrency statistics for all rules:

getConcurrencyState()

Get current concurrency state for a specific rule:

Phase 3.3: Error Recovery Methods

registerFallbackRule()

Register a fallback rule for a specific rule:

registerFallbackValue()

Register a fallback value for a specific rule:

getErrorRecoveryStats()

Get comprehensive error recovery statistics:

getCircuitState()

Get circuit breaker state for a specific rule:

resetCircuit()

Manually reset circuit breaker:

getErrorHistory()

Get error history for a specific rule:

getErrorRate()

Get error rate for a specific rule:

Best Practices

Use Meaningful IDs

Use descriptive rule IDs that indicate the rule’s purpose

Batch Evaluations

Use evaluateBatch() for multiple related rules

Clean Up State

Periodically clear state for inactive rules

Limit History

Set appropriate maxHistoryPerRule to manage memory per rule

Phase 3 Best Practices

Next Steps

State Operators

Complete state change operators reference

Examples

Real-world stateful engine examples