Runtime Engine

From FlexRule Wiki
(Redirected from RuntimeEngine)
Jump to: navigation, search

Introduction

In order to execute logic, your application should:

  1. Create an execution plan
  2. Create multiple processing engines to execute the requests against the execution plan

This process can be simplified by using RuntimeEngine

For example, the following code creates an instance of an engine to process leave eligibility:

// Load or build a ruleset
var rs = GetRuleSet();
 
// create an instance of engine
var engine = RuntimeEngine.FromRuleSet(rs, "ruleset:///purchase");
 
// get a data to pass to engine to run
var person = new Person("arash", 10, Gender.Male);
 
// call Run method of engine
var result = engine.Run(person);
 
// use result to retrieve execution context, variable container, notification, outputs...

Creating Runtime Engine

To create an instance of RuntimeEngine, you should use any of the static methods available on the RuntimeEngine type:

In short, you can create your model from different types:

  1. From Spreadsheet document contents
  2. From XML contents
  3. From RuleSet reference
Bulbgraph.pngMake sure you do not create engine every time. Create it once and use it across multiple request. You can store the engine instance in a static variable.
  1. public class RuntimeEngine : IRuntimeEngine
  2. {
  3.     /// <summary>
  4.     /// Creates an <see cref="IRuntimeEngine"/> instance from a stream of a spreadsheet document.
  5.     /// </summary>
  6.     /// <param name="stream">A stream to an XML content of a base model</param>
  7.     /// <param name="baseFolder">Path to resolve all dependencies on execution plan creation</param>
  8.     /// <returns></returns>
  9.     public static IRuntimeEngine FromSpreadSheet(Stream spreadSheet, string activeSheet, bool newFormat = true);
  10.  
  11.     /// <summary>
  12.     /// Creates an <see cref="IRuntimeEngine"/> instance from a stream of XML content.
  13.     /// </summary>
  14.     /// <param name="stream">A stream to XML content of a base model</param>
  15.     /// <param name="baseFolder">Path to resolve all dependencies on execution plan creation</param>
  16.     /// <returns></returns>
  17.     public static IRuntimeEngine FromXml(Stream stream, string baseFolder);
  18.  
  19.     /// <summary>
  20.     /// Creates an <see cref="IRuntimeEngine"/> instance.
  21.     /// </summary>
  22.     /// <param name="stream">A stream to an XML content of a base model</param>
  23.     /// <param name="ruleSet">Dependency resolver <see cref="IRuleSet"/> to resolve all dependencies on the execution plan creation</param>
  24.     /// <returns></returns>
  25.     public static IRuntimeEngine FromXml(Stream stream, IRuleSet ruleSet);
  26.  
  27.     /// <summary>
  28.     /// Creates an <see cref="IRuntimeEngine"/> instance.
  29.     /// </summary>
  30.     /// <param name="content">An XML content of a base model</param>
  31.     /// <param name="ruleSet">Dependency resolver <see cref="IRuleSet"/> to resolve all dependencies on execution plan creation</param>
  32.     /// <returns></returns>
  33.     public static IRuntimeEngine FromXml(byte[] content, IRuleSet ruleSet);
  34.  
  35.     /// <summary>
  36.     /// Creates an <see cref="IRuntimeEngine"/> instance.
  37.     /// </summary>
  38.     /// <param name="content">An XML content of a base model</param>
  39.     /// <param name="baseFolder">Path to resolve all dependencies on execution plan creation</param>
  40.     /// <returns></returns>
  41.     public static IRuntimeEngine FromXml(byte[] content, string baseFolder);
  42.  
  43.     /// <summary>
  44.     /// Creates an <see cref="IRuntimeEngine"/> instance.
  45.     /// </summary>
  46.     /// <param name="ruleSet">A <see cref="IRuleSet"/> that holds all the related models for loading execution plan and executing logic</param>
  47.     /// <param name="ruleSetQuery">Address to the main model within the provided <paramref name="ruleSet"/></param>
  48.     public static IRuntimeEngine FromRuleSet(IRuleSet ruleSet, string ruleSetQuery);
  49. }

From XML File

  1. /* 
  2.    Here is the content binary or stream to the rule file. 
  3.    You could have the rule  
  4.    * stored in file system (folders and files such as XML files in your application folder) 
  5.    * stored in database
  6.    * embedded in assembly
  7.    * stored in cloud storage
  8.    Or any location, no limitation
  9. */ 
  10. var content = ... // <-- Here you reference the content of the rule
  11. var engine = RuntimeEngine.FromXml(content);

From Spreadsheet

  1. /* 
  2.    Here is the content binary or stream to the rule file. 
  3.    You could have the rule:  
  4.    * stored in file system (folders and files such as XML files in your application folder) 
  5.    * stored in database
  6.    * embedded in assembly
  7.    * stored in cloud storage
  8.    Or any location, no limitation
  9. */ 
  10. var content = ... // <-- Here you reference the binary content of the Excel document
  11. var engine = RuntimeEngine.FromSpreadSheet(content, "GroupDiscount");  // GroupDiscount is the sheet in the Excel document

Executing Logic

To execute logic, you simply call the 'Run' method of the RuntimeEngine instance, which returns the result.

You can pass all your input parameters to the 'Run' method. The RuntimeEngine does all the magic.

  1. var person = new Person(); // This is an input to an input parameter of the logic
  2. var address = new Address(); // This is another input to an input parameter of the logic
  3. var result = engine.Run(person, address);

Runtime Result

After calling into Run engine would return an instance of RuntimeResult. If the logic has an Output parameter, return value (i.e., Validation logic), Exception or notification, then you can use RuntimeResult to retrieve those values when execution is finished.

Example

From XML file

In the following example, we load a validation rule from a file called DeprecationValidation.xml and execute it against an input object from the application.

  1. // Creating an engine for validation from a file named DeprecationValidation.xml 
  2. // This engine reference can be shared. There is no need to create it every time.
  3. var eng = RuntimeEngine.FromXml(File.ReadAllBytes("Rules\\Validations\\DeprecationValidation.xml"));
  4.  
  5. // Get the input parameter of the validation rule (i.e., load it from database, input from user interface, call from web api or service, etc.)
  6. var expense = new Expense(){ItemAmount=10, Deprecation = true};
  7.  
  8. // Calling the validation by passing the input values
  9. var res = eng.Run(expense);
  10.  
  11. // Was the object valid? Have the eligibility criteria been met (i.e., were rules satisfied)?
  12. if (!res.Outcome.Value)
  13. {
  14.     // Write (feedback) from rule to the users (i.e., error, warning, info, etc.)
  15.     foreach (var notice in res.Context.Notifications.Default.Notices)
  16.     {
  17.         Console.WriteLine("{0}: {1}", notice.Type, notice.Message);
  18.     }
  19. }

From Excel file

In the following example, we load a decision table named CalculatePremiums from an Excel file called Insurance-Rules.xls and execute the decision table against an input object from the application.

  1. // Creating engine from file named Insurance-Rules.xlsx 
  2. // This engine reference can be shared, there is no need to create it every time.
  3. var engine = RuntimeEngine.FromSpreadSheet(File.OpenRead(@"Insurance-Rules.xlsx"), "CalculatePremiums");
  4.  
  5. // The rule CalculatePremiums requires an input parameter
  6. // Get the input parameter of the validation rule (i.e., load it from the database, input from user interface, call from web api or service, etc.)
  7. var car = new Car()
  8. {
  9.     ModelYear = 2015,
  10.     Style = CarStyle.Compact,
  11. };
  12.  
  13. // Calling the Run on the engine to execute the rules
  14. engine.Run(car);


Please note, you should 'NOT' create an engine for processing each request. Simply hold on to the engine reference and reuse it in future in order to process all your requests. Creating the RuntimeEngine instance is a once-off process for your whole application life cycle. You can do it with either of the following approaches:

  1. in the load of your application
  2. lazily when the first time rules are being executed

Only re-create the RuntimeEngine instance when your rules model has changed.

Run with Parameters

Sometimes, in NL or Validation logic, you want to specifically run a particular logic, then this overload can be used:

var order = new Order();
order.Lines.Add(new OrderLine { Product = { Name = "Case" } });
order.Lines.Add(new OrderLine { Product = { Name = "Sound Card" } });
 
var engine = RuntimeEngine.FromXml(File.OpenRead("ComputerProduct_CaseCannotHaveExtra.xml"));
// order in this case is the input of the whole document, not this specific logic group
var result = engine.Run(new RunParameter("Order"), order);
Bulbgraph.pngUse RunParameter to specify the name of Logic

Behind the Scene

Behind the scenes, RuntimeEngine does all the magic:

  1. Creates an execution plan
  2. Manages execution plan life-cycle
  3. Creates an execution engine for a loaded plan
  4. Registers all the transformer and command handlers
  5. Execute the logic using passing parameters
  6. Handles exceptions
  7. Manages notifications and notices
  8. Updates the results when necessary (e.g., in DMN Decision Tables)
  9. Creates Conclusion Log
  10. Registers custom functions
  11. Handles glossaries for different type of logic

and finally returns a result to your code!

Execution Plan

An execution plan is an optimized orchestration in order to execute a logic. This plan will be created based on your logic model. For each type of logic, there is an execution plan:

Logic Execution Plan Type Execution Engine Type
Validation Logic Validator ValidatorEngine
Procedural Logic Procedure ProcedureEngine
Flow Logic Flow FlowEngine
Workflow Logic Workflow WorkflowEngine
Decision Table Logic DecisionTable DecisionTableEngine
Natural Language Logic NaturalLanguageValidator ValidatorEngine
Decision Graph Logic DRD FlowEngine

Some of the logic types may not have a specific execution plan or execution engine. These just use other types of execution plans or engines. RuntimeEngine uses these execution plans and execution engines in order to provide a single point of integration to your application.