ZEN Engine Documentation

repository·master·Indexed 23 days ago

https://github.com/gorules/zen

A high-performance, cross-platform Business Rules Engine (BRE) written in Rust that decouples business logic from application code using JSON-based decision models (JDM). It supports multiple languages including Python, .NET (via GoRules.ZenEngine), Rust, Go, and NodeJS. Key features include Decision Table nodes with various hit policies, Switch nodes for dynamic branching, Function nodes powered by QuickJS, Expression nodes using ZEN Expression Language, and Decision nodes for modularization.

Tokens
30K
Snippets
45
Records
208
Agent score
83%

What's inside ZEN Engine

  1. What is ZEN Engine?

    master

    ZEN Engine is a cross-platform, Open-Source Business Rules Engine (BRE) written in Rust. It is designed to be embedded into applications to execute business logic defined via the JSON Decision Model (JDM).

    Users provide the JDM logic as JSON content (from a file, database, or service), and the engine parses and executes it against provided inputs.

  2. What is the JSON Decision Model (JDM)?

    master

    GoRules JDM is a modeling framework where decision models are represented as interconnected graphs in JSON format. These graphs capture relationships between decision points, conditions, and outcomes.

    Graph Structure

    • Input Node (Request): The entry point for all data relevant to the context.
    • Output Node (Response): The final result of the decision-making process.
    • Nodes & Edges: Nodes represent decision logic, while edges act as pathways moving information through the graph (typically from left to right).

    Core Node Types

    • Decision Table Node: Structured rules (spreadsheet-like).
    • Switch Node: Dynamic branching based on conditions.
    • Function Node: JavaScript-based data manipulation.
    • Expression Node: Transformation using ZEN Expression Language.
    • Decision Node: Reuses other decision models (modularization).
  3. Use Decision Table Nodes for structured rules

    master

    Decision Tables provide a spreadsheet-like interface for expressing complex rules. They evaluate rows from top to bottom based on a HitPolicy.

    Evaluation Logic:

    • Each row is evaluated using an AND operator across its input columns.
    • If a cell is empty, that column is considered truthful and is skipped.
    • If a single cell in a row fails (due to error or mismatch), the entire row is skipped.

    Hit Policies:

    • first: Returns the object defined by the output fields of the first matching rule. Returns null/undefined if no rule matches.
    • collect: Returns an array of objects, containing one item for each matching rule. Returns an empty array if no rules match.

    Input Types:

    1. Unary Evaluation: Compares single fields (e.g., customer.country) using a defined field in the schema.
    2. Expression Evaluation: Uses the ZEN Expression Language within a cell to compare multiple fields (e.g., comparing transaction.amount and transaction.createdAt in one cell).
  4. How loaders work in ZEN Engine

    master

    Loaders are responsible for retrieving DecisionContent (JSON Decision Models) based on a key. ZEN Engine provides several pre-made loaders:

    • FilesystemLoader: Loads decisions from a filesystem path relative to a specified root.
    • MemoryLoader: Uses a HashMap as a key-value store for decisions.
    • ClosureLoader: Uses an async callback function that takes a key and returns an Arc<DecisionContent>.
    • NoopLoader: The default loader; it fails to load decisions and is primarily used to allow the create_decision API to remain consistent across different language bindings.
  5. How Expression Nodes work

    master

    The Expression node transforms input objects into alternative objects using the ZEN Expression Language.

    To define the output, you must specify individual rows for each property. Each row requires:

    1. Key: The qualified name of the output property.
    2. Value: The value expressed through the ZEN Expression Language.

    Warning: Any errors occurring within an Expression node will cause the entire graph execution to halt.

  6. Use Decision Nodes to modularize logic

    master
    The Decision node is used to invoke and reuse other decision models during execution. This allows you to modularize complex decision logic, promoting reusability and maintainability across your models.
  7. How Switch Nodes work

    master

    The Switch node provides a dynamic branching mechanism. It allows the decision graph to diverge into different paths based on conditions written in the ZEN Expression Language.

    Key Characteristics

    • Data Preservation: The Switch node does not modify incoming data; it forwards the entire context to the output branch(es).
    • Hit Policies:
      • first: The graph branches to the initial matching condition (similar to a table).
      • collect: The graph extends to all branches where conditions hold true.

    Note: If multiple edges originate from the same condition, there is no guaranteed order of execution.

    Available from: Python 0.16.0, NodeJS 0.13.0, Rust 0.16.0, Go 0.1.0

  8. How Decision Table Nodes work

    master

    Decision Tables allow expressing complex rules in a structured, spreadsheet-like format. They are evaluated row by row from top to bottom based on a HitPolicy.

    Evaluation Logic

    • Row Evaluation: Each row is evaluated via input columns using an AND operator. If a cell is empty, that column is considered truthfully (it passes regardless of value).
    • Error Handling: If a single cell in a row fails (due to an error), the entire row is skipped.

    Hit Policies

    • first: Returns an object containing the output fields of the first matching rule. Returns null/undefined if no rules match.
    • collect: Returns an array of objects (one for each matching rule). Returns an empty array if no rules match.

    Input Evaluation Types

    1. Unary Evaluation: Used to compare single fields (e.g., customer.country). It is activated when a column has a field defined in its schema.
    2. Expression Evaluation: Used for complex logic within a single cell (e.g., comparing multiple fields). This is used by providing an empty Selector (field) in the column configuration.

    Input Syntax Examples (Unary)

    Input entryMeaning
    "A"field equals "A"
    "A", "B"field is either "A" or "B"
    36numeric value equals 36
    < 36value less than 36
    > 36value greater than 36
    [20..39]value between 20 and 39 (inclusive)
    20,39value is either 20 or 39
    <20, >39value is either less than 20 or greater than 39
    trueboolean value true
    falseboolean value false
    nullvalue is null or undefined
  9. How Function Nodes work

    master

    Function nodes allow for quick data parsing, re-mapping, or modification using JavaScript snippets. These snippets are executed on top of the QuickJS Engine bundled with the ZEN Engine.

    Implementation Details

    • Arguments: The node's inputs are provided as arguments to the function.
    • Timeout: Function execution is capped at 50ms.
    • Built-in Libraries:
      • dayjs: For date manipulation.
      • big.js: For arbitrary-precision decimal arithmetic.

    Example Usage

    const handler = (input, {dayjs, Big}) => {
        return {
            ...input,
            someField: 'hello'
        };
    };
  10. Use Switch Nodes for dynamic branching

    master

    The Switch node allows a decision model to diverge into different paths based on conditions written in the ZEN Expression Language. It preserves the incoming data without modification, forwarding the entire context to the output branches.

    Hit Policies:

    • first: The graph branches to the first matching condition.
    • collect: The graph extends to all branches where conditions hold true (multiple paths).

    Note: If multiple edges exist from the same condition, execution order is not guaranteed.

    Supported Versions:

    • Python 0.16.0+
    • NodeJS 0.13.0+
    • Rust 0.16.0+
    • Go 0.1.0+
  11. Understand the GoRules JSON Decision Model (JDM)

    master

    GoRules JDM is a modeling framework where decision models are represented as interconnected graphs in JSON format.

    Graph Structure:

    • Nodes: The building blocks of the graph (Decision Table, Switch, Function, Expression, and Decision nodes).
    • Edges: Pathways that move information from one node to another, typically flowing from left to right.
    • Input Node (Request): The entry point for all data relevant to the context.
    • Output Node (Response): The final result of the decision-making process.

    Data flows from the Input Node through the interconnected nodes, undergoing evaluation at each step, until it reaches the Output Node.