63 releases (35 breaking)

new 0.35.0 Nov 28, 2024
0.33.0 Oct 23, 2024
0.24.2 Jul 17, 2024
0.19.0 Mar 25, 2024
0.0.0 Mar 13, 2023

#399 in Filesystem

Download history 346/week @ 2024-08-05 100/week @ 2024-08-12 185/week @ 2024-08-19 159/week @ 2024-08-26 133/week @ 2024-09-02 516/week @ 2024-09-09 287/week @ 2024-09-16 719/week @ 2024-09-23 937/week @ 2024-09-30 605/week @ 2024-10-07 185/week @ 2024-10-14 177/week @ 2024-10-21 167/week @ 2024-10-28 36/week @ 2024-11-04 46/week @ 2024-11-11 380/week @ 2024-11-18

638 downloads per month

MIT license

540KB
13K SLoC

Rust 10K SLoC // 0.0% comments JavaScript 3K SLoC // 0.1% comments

ZEN Engine

ZEN Engine is business friendly Open-Source Business Rules Engine (BRE) to execute decision models according to the GoRules JSON Decision Model (JDM) standard. It is written in Rust and provides native bindings for NodeJS and Python. ZEN Engine allows to load and execute JSON Decision Model (JDM) from JSON files.

Resources

Documentation

Online Rules Engine Editor

Installation

Add the following to your Cargo.toml file:

[dependencies]
zen-engine = "0"

Usage

To execute a simple decision using a Noop (default) loader you can use the code below.

use serde_json::json;
use zen_engine::DecisionEngine;
use zen_engine::model::DecisionContent;

async fn evaluate() {
    let decision_content: DecisionContent = serde_json::from_str(include_str!("jdm_graph.json")).unwrap();
    let engine = DecisionEngine::default();
    let decision = engine.create_decision(decision_content.into());

    let result = decision.evaluate(&json!({ "input": 12 })).await;
}

Alternatively, you may create decision indirectly without constructing the engine utilising Decision::from function.

Loaders

For more advanced use cases where you want to load multiple decisions and utilise graphs you may use one of the following pre-made loaders:

  • FilesystemLoader - with a given path as a root it tries to load a decision based on relative path
  • MemoryLoader - works as a HashMap (key-value store)
  • ClosureLoader - allows for definition of simple async callback function which takes key as a parameter and returns an Arc<DecisionContent> instance
  • NoopLoader - (default) fails to load decision, allows for usage of create_decision (mostly existing for streamlining API across languages)

Filesystem loader

Assuming that you have a folder with decision models (.json files) which is located under /app/decisions, you may use FilesystemLoader in the following way:

use serde_json::json;
use zen_engine::DecisionEngine;
use zen_engine::loader::{FilesystemLoader, FilesystemLoaderOptions};

async fn evaluate() {
    let engine = DecisionEngine::new(FilesystemLoader::new(FilesystemLoaderOptions {
        keep_in_memory: true, // optionally, keep in memory for increase performance
        root: "/app/decisions"
    }));

    let context = json!({ "customer": { "joinedAt": "2022-01-01" } });
    // If you plan on using it multiple times, you may cache JDM for minor performance gains
    // In case of bindings (in other languages, this increase is much greater)
    {
        let promotion_decision = engine.get_decision("commercial/promotion.json").await.unwrap();
        let result = promotion_decision.evaluate(&context).await.unwrap();
    }

    // Or on demand
    {
        let result = engine.evaluate("commercial/promotion.json", &context).await.unwrap();
    }
}

Custom loader

You may create a custom loader for zen engine by implementing DecisionLoader trait. Here's an example of how MemoryLoader has been implemented.

use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use zen_engine::loader::{DecisionLoader, LoaderError, LoaderResponse};
use zen_engine::model::DecisionContent;

#[derive(Debug, Default)]
pub struct MemoryLoader {
    memory_refs: RwLock<HashMap<String, Arc<DecisionContent>>>,
}

impl MemoryLoader {
    pub fn add<K, D>(&self, key: K, content: D)
    where
        K: Into<String>,
        D: Into<DecisionContent>,
    {
        let mut mref = self.memory_refs.write().unwrap();
        mref.insert(key.into(), Arc::new(content.into()));
    }
    pub fn get<K>(&self, key: K) -> Option<Arc<DecisionContent>>
    where
        K: AsRef<str>,
    {
        let mref = self.memory_refs.read().unwrap();
        mref.get(key.as_ref()).map(|r| r.clone())
    }
    pub fn remove<K>(&self, key: K) -> bool
    where
        K: AsRef<str>,
    {
        let mut mref = self.memory_refs.write().unwrap();
        mref.remove(key.as_ref()).is_some()
    }
}

impl DecisionLoader for MemoryLoader {
    fn load<'a>(&'a self, key: &'a str) -> impl Future<Output=LoaderResponse> + 'a {
        async move {
            self.get(&key)
                .ok_or_else(|| LoaderError::NotFound(key.to_string()).into())
        }
    }
}

Dependencies

~18–30MB
~497K SLoC