FlexiRule Docs
Trigger System
The FlexiRule Trigger System determines when a rule should begin its execution. It is managed by the `RuleCoordinator`, which acts as a high-perfor...
Trigger System#
The FlexiRule Trigger System determines when a rule should begin its execution. It is managed by the RuleCoordinator, which acts as a high-performance dispatcher integrated into the Frappe lifecycle.
Trigger Types#
FlexiRule supports three primary trigger types, each serving a different architectural purpose:
1. DocType Event#
This is the most common trigger type. It hooks directly into Frappe’s doc_events.
- Standard Hooks: Supports all standard Frappe hooks (e.g.,
Before Insert,Before Save,Validate,On Submit,On Change,On Trash). - Optimization: Uses
watched_fieldsto avoid executing rules if unrelated fields are modified. - Context: Provides the current
docandold_doc(state before save) to the execution engine.
2. Scheduler Event#
Used for background, time-based automation.
- Mechanism: Integrated with Frappe’s scheduled tasks.
- Context: Since it’s not tied to a specific document event, these rules typically start with a
Query Recordsaction to find the documents they need to process.
3. Callable Event (Sub-Rules)#
These rules do not trigger automatically. Instead, they are designed to be called by other rules.
- Exposability: Must have the
exposed_as_subruleflag enabled to be visible in theSub-Ruleaction picker. - Priority: Always has a priority of
0because execution is determined by the caller.
The Rule Coordinator#
The RuleCoordinator is responsible for identifying and qualifying rules for execution.
Dispatching Logic#
When a document event occurs, the Coordinator:
- Fast Lookup: Queries a request-local cache (then Redis) for rules matching the
DocTypeandEvent. - Pruning: Checks if the rule’s
watched_fieldsintersect with the fields changed in the current transaction. - Eligibility: Evaluates the
compiled_expressionof the rule. - Execution: Dispatches the rule to the
RuleEngine(Synchronous) or enqueues it (Asynchronous).
Runtime Registry & Caching#
To maintain high performance, FlexiRule uses a layered caching strategy for rule metadata:
- Level 1 (Request):
frappe.localstorage for the duration of a single request. - Level 2 (Redis): A global
flexirule_runtime_registryin Redis. - Level 3 (Database): Rebuilds the registry from the
RuleDocType on cache miss or manual clear.
Trigger Conditions#
Trigger conditions are written visually in the builder and compiled into pure Python.
Features#
- Field Access: Access fields via
doc.statusor deep paths likedoc.items.0.qty. - Change Detection: Compare
docvsold_doc(e.g.,doc.status != old_doc.status). - Safety: Evaluation is strictly read-only via
SafeFrappeAPI.
Performance Note#
Trigger conditions are designed to be “ultra-fast.” They are evaluated before the full RuleEngine is initialized to ensure that rules that don’t meet the criteria consume minimal resources.
Was this page helpful?