Package: zen-engine
Python Rules EngineZEN Engine is a cross-platform, Open-Source Business Rules Engine (BRE). It is written inRustand provides native bindings forNodeJS,PythonandGo. ZEN Engine allows to load and executeJSON Decision Model (JDM)from JSON files.An open-source React editor is available on ourJDM Editorrepo.UsageZEN Engine is built as embeddable BRE for yourRust,NodeJS,PythonorGoapplications.
It parses JDM from JSON content. It is up to you to obtain the JSON content, e.g. from file system, database or service call.Installationpipinstallzen-engineUsageTo execute a simple decision you can use the code below.importzen# Example filesystem content, it is up to you how you obtain contentwithopen("./jdm_graph.json","r")asf:content=f.read()engine=zen.ZenEngine()decision=engine.create_decision(content)result=decision.evaluate({"input":15})LoadersFor more advanced use cases where you want to load multiple decisions and utilise graphs you can build loaders.importzendefloader(key):withopen("./jdm_directory/"+key,"r")asf:returnf.read()engine=zen.ZenEngine({"loader":loader})result=engine.evaluate("jdm_graph1.json",{"input":5})When engine.evaluate is invoked it will call loader and pass a key expecting a content of the JDM decision graph.
In the case above we will assume filejdm_directory/jdm_graph1.jsonexists.Similar to this example you can also utilise loader to load from different places, for example from REST API, from S3, Database, etc.Supported PlatformsList of platforms where Zen Engine is natively available:NodeJS-GitHub|Documentation|npmjsPython-GitHub|Documentation|pypiGo-GitHub|DocumentationRust (Core)-GitHub|Documentation|crates.ioFor a completeBusiness Rules Management Systems (BRMS)solution:Self-hosted BRMSGoRules Cloud BRMSJSON Decision Model (JDM)GoRules JDM (JSON Decision Model) is a modeling framework designed to streamline the representation and implementation of decision models.Understanding GoRules JDMAt its core, GoRules JDM revolves around the concept of decision models as interconnected graphs stored in JSON format.
These graphs capture the intricate relationships between various decision points, conditions, and outcomes in a GoRules Zen-Engine.Graphs are made by linking nodes with edges, which act like pathways for moving information from one node to another, usually from the left to the right.The Input node serves as an entry for all data relevant to the context, while the Output nodes produce the result of decision-making process. The progression of data follows a path from the Input Node to the Output Node, traversing all interconnected nodes in between. As the data flows through this network, it undergoes evaluation at each node, and connections determine where the data is passed along the graph.To see JDM Graph in action you can useFree Online Editorwith built in Simulator.There are 5 main node types in addition to a graph Input Node (Request) and Output Node (Response):Decision Table NodeSwitch NodeFunction NodeExpression NodeDecision NodeDecision Table NodeOverviewTables provide a structured representation of decision-making processes, allowing developers and business users to express complex rules in a clear and concise manner.StructureAt the core of the Decision Table is its schema, defining the structure with inputs and outputs. Inputs encompass business-friendly expressions using the ZEN Expression Language, accommodating a range of conditions such as equality, numeric comparisons, boolean values, date time functions, array functions and more. The schema's outputs dictate the form of results generated by the Decision Table.
Inputs and outputs are expressed through a user-friendly interface, often resembling a spreadsheet. This facilitates easy modification and addition of rules, enabling business users to contribute to decision logic without delving into intricate code.Evaluation ProcessDecision Tables are evaluated row by row, from top to bottom, adhering to a specified hit policy.
Single row is evaluated via Inputs columns, from left to right. Each input column representsANDoperator. If cell is empty that column is evaluatedtruthfully, independently of the value.If a single cell within a row fails (due to error, or otherwise), the row is skipped.HitPolicyThe hit policy determines the outcome calculation based on matching rules.The result of the evaluation is:an objectif the hit policy of the decision table isfirstand a rule matched. The structure is defined by the output fields. Qualified field names with a dot (.) inside lead to nested objects.null/undefinedif no rule matched infirsthit policyan array of objectsif the hit policy of the decision table iscollect(one array item for each matching rule) or empty array if no rules matchInputsIn the assessment of rules or rows, input columns embody theANDoperator. The values typically consist of (qualified) names, such ascustomer.countryorcustomer.age.There are two types of evaluation of inputs,UnaryandExpression.Unary EvaluationUnary evaluation is usually used when we would like to compare single fields from incoming context separately, for examplecustomer.countryandcart.total. It is activated when a column hasfielddefined in its schema.ExampleFor the input:{"customer":{"country":"US"},"cart":{"total":1500}}This evaluation translates toIF customer.country == 'US' AND cart.total > 1000 THEN {"fees": {"percent": 2}}
ELSE IF customer.country == 'US' THEN {"fees": {"flat": 30}}
ELSE IF customer.country == 'CA' OR customer.country == 'MX' THEN {"fees": {"flat": 50}}
ELSE {"fees": {"flat": 150}}List shows basic example of the unary tests in the Input Fields:Input entryInput Expression"A"the field equals "A""A", "B"the field is either "A" or "B"36the numeric value equals 36< 36a value less than 36> 36a value greater than 36[20..39]a value between 20 and 39 (inclusive)20,39a value either 20 or 39<20, >39a value either less than 20 or greater than 39truethe boolean value truefalsethe boolean value falseany value, even null/undefinednullthe value null or undefinedNote: For the full list please visitZEN Expression Language.Expression EvaluationExpression evaluation is used when we would like to create more complex evaluation logic inside single cell. It allows us to compare multiple fields from the incoming context inside same cell.It can be used by providing an emptySelector (field)inside column configuration.ExampleFor the input:{"transaction":{"country":"US","createdAt":"2023-11-20T19:00:25Z","amount":10000}}IF time(transaction.createdAt) > time("17:00:00") AND transaction.amount > 1000 THEN {"status": "reject"}
ELSE {"status": "approve"}Note: For the full list please visitZEN Expression Language.OutputsOutput columns serve as the blueprint for the data that the decision table will generate when the conditions are met during evaluation.When a row in the decision table satisfies its specified conditions, the output columns determine the nature and structure of the information that will be returned. Each output column represents a distinct field, and the collective set of these fields forms the output or result associated with the validated row. This mechanism allows decision tables to precisely define and control the data output.ExampleAnd the result would be:{"flatProperty":"A","output":{"nested":{"property":"B"},"property":36}}Switch Node (NEW)The Switch node in GoRules JDM introduces a dynamic branching mechanism to decision models, enabling the graph to diverge based on conditions.Conditions are written in a Zen Expression Language.By incorporating the Switch node, decision models become more flexible and context-aware. This capability is particularly valuable in scenarios where diverse decision logic is required based on varying inputs. The Switch node efficiently manages branching within the graph, enhancing the overall complexity and realism of decision models in GoRules JDM, making it a pivotal component for crafting intelligent and adaptive systems.The Switch node preserves the incoming data without modification; it forwards the entire context to the output branch(es).HitPolicyThere are two HitPolicy options for the switch node,firstandcollect.In the context of a first hit policy, the graph branches to the initial matching condition, analogous to the behavior observed in a table. Conversely, under a collect hit policy, the graph extends to all branches where conditions hold true, allowing branching to multiple paths.Note: If there are multiple edges from the same condition, there is no guaranteed order of execution.Available from:Python 0.16.0NodeJS 0.13.0Rust 0.16.0Go 0.1.0Functions NodeFunction nodes are JavaScript snippets that allow for quick and easy parsing, re-mapping or otherwise modifying the data using JavaScript. Inputs of the node are provided as function's arguments. Functions are executed on top of QuickJS Engine that is bundled into the ZEN Engine.Function timeout is set to a 50ms.consthandler=(input,{dayjs,Big})=>{return{...input,someField:'hello'};};There are two built in libraries:dayjs- for Date Manipulationbig.js- for arbitrary-precision decimal arithmetic.Expression NodeThe Expression node serves as a tool for transforming input objects into alternative objects using the Zen Expression Language. When specifying the output properties, each property requires a separate row. These rows are defined by two fields:Key - qualified name of the output propertyValue - value expressed through the Zen Expression LanguageNote: Any errors within the Expression node will bring the graph to a halt.Decision NodeThe "Decision" node is designed to extend the capabilities of decision models. Its function is to invoke and reuse other decision models during execution.By incorporating the "Decision" node, developers can modularize decision logic, promoting reusability and maintainability in complex systems.Support matrixArchRustNodeJSPythonGolinux-x64-gnu:heavy_check_mark::heavy_check_mark::heavy_check_mark::heavy_check_mark:linux-arm64-gnu:heavy_check_mark::heavy_check_mark::heavy_check_mark::heavy_check_mark:darwin-x64:heavy_check_mark::heavy_check_mark::heavy_check_mark::heavy_check_mark:darwin-arm64:heavy_check_mark::heavy_check_mark::heavy_check_mark::heavy_check_mark:win32-x64-msvc:heavy_check_mark::heavy_check_mark::heavy_check_mark::heavy_check_mark:We do not support linux-musl currently.ContributionJDM standard is growing and we need to keep tight control over its development and roadmap as there are number of
companies that are using GoRules Zen-Engine and GoRules BRMS.
For this reason we can't accept any code contributions at this moment, apart from help with documentation and additional
tests.