Config
The config of the rule engine instance Config (opens new window) is a global configuration. You can modify the config by the following way:
config := rulego.NewConfig()
ruleEngine, err := rulego.New("rule01", []byte(ruleChainFile), rulego.WithConfig(config))
2
# OnDebug
Type: func(flowType string, nodeId string, msg RuleMsg, relationType string, err error)
- flowType: IN/OUT, the event type of flowing into (IN) or out of (OUT) the component
- nodeId: node ID
- msg: message structure, where the msg id is unique
- relationType: if flowType=IN, it represents the connection relationship between the previous node and this node, such as (True/False); if flowType=OUT, it represents the connection relationship between this node and the next node, such as (True/False)
- err: error information
Node debugging information callback global function. The In and Out processes of the rule chain node will be triggered after setting debugMode=true
in the node configuration. You can record the log and execution situation of each node in this callback function, such as: time consumption, input message and output message.
Support dynamic setting of the node's debugMode
field to turn it on or off.
TIP
OnDebug
callback function contains custom logic that is triggered asynchronously, and the execution order cannot be guaranteed.
Visualization interface reference:
# OnEnd (deprecated)
(deprecated, use types.WithOnEnd instead)
Type: func(msg RuleMsg, err error)
- msg: the msg after the end point component processing
- err: error information
Rule chain execution completion callback global function, if the rule chain has multiple end points, it will be executed multiple times. For example: after executing s1, s2, s3, and s4 are triggered at the same time, then the onEnd event will be triggered 3 times, and msg are the execution results of s2, s3, and s4 respectively. The rule chain is as follows:
TIP
The OnEnd function configured by config is global for the rule chain engine instance. You can also configure the end callback function for each message, using the following method:
ruleEngine.OnMsg(msg, types.WithOnEnd(func(ctx types.RuleContext,msg types.RuleMsg, err error) {
//End callback function
}))
2
3
If you wish to execute a function once after the completion of rule chain processing, you can use the following method:
ruleEngine.OnMsg(msg, types.WithOnAllNodeCompleted(func() {
// Processing after completion
}))
2
3
# ScriptMaxExecutionTime
Type: time.Duration
JS script execution timeout, default 2000 milliseconds.
# Pool
Type: types.Pool
Coroutine pool interface, if not configured, use go func method.
Use the built-in pool.WorkerPool
by default. Compatible with ants coroutine pool, you can use ants coroutine pool implementation, you need to import the corresponding library yourself. For example:
pool, _ := ants.NewPool(math.MaxInt32)
config := rulego.NewConfig(types.WithPool(pool))
2
TIP
The built-in pool.WorkerPool
is based on the implementation of FastHttp, which has higher performance and saves memory than ants
.
# ComponentsRegistry
Type: types.ComponentRegistry
Component library registrar, use rulego.Registry
by default
# Parser
Type: types.Parser
Rule chain parsing interface, use rulego.JsonParser
by default, you can implement custom rule chain DSL.
# Logger
Type: types.Logger
Log recording interface, use DefaultLogger()
by default. log component uses this recorder.
# Properties
Type: types.Metadata
Global properties, key-value form.
The rule chain node configuration can replace the content of the variable by using ${global.propertyKey}
or ${metadataKey}
.
- Among them,
global.
is a built-in variable, which means to get the content from config.Properties for replacement (the replacement logic is executed only once when the node is initialized). ${metadataKey}
is obtained from the message metadata for replacement (the replacement logic is executed every time the node processes the message).
Note: There can be no spaces in
${}
.
TIP
In addition, you can also get the global Properties variable value when the js script is running, the calling method is:
var value=global.propertyKey;
Use example reference: node_config (opens new window)
# Udf
Type: map[string]interface{}
Register custom Golang functions and native scripts, which can be directly called by the script engine at runtime. This feature enables js and other script engines to have the ability to call Golang functions and extend native script functions.
Example:
config := rulego.NewConfig()
//Get global variables at js script runtime: global.xx
config.Properties.PutValue("globalValue", "addValueFromConfig")
//Register custom function
config.RegisterUdf("add", func(a, b int) int {
return a + b
})
config.RegisterUdf("handleMsg", func(msg map[string]interface{}, metadata map[string]string, msgType string) string {
msg["returnFromGo"] = "returnFromGo"
_, ok := rulego.Get("aa")
msg["hasAaRuleChain"] = ok
return "returnFromGoMsgType"
})
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Register native scripts using types.Script
to encapsulate the script content, the default is Js
type, example:
// Use: utilsFunc.dateFormat(new Date(), "yyyyMMddhh")
config.RegisterUdf(
"utilsFunScript", types.Script{
Type: types.Js,
Content: `var utilsFunc={
dateFormat:function(date,fmt){
var o = {
"M+": date.getMonth() + 1,
/*month*/ "d+": date.getDate(),
/*day*/ "h+": date.getHours(),
/*hour*/ "m+": date.getMinutes(),
/*minute*/ "s+": date.getSeconds(),
/*second*/ "q+": Math.floor((date.getMonth() + 3) / 3),
/*quarter*/ S: date.getMilliseconds() /*millisecond*/,
};
fmt = fmt.replace(/(y+)/, function(match, group) {
return (date.getFullYear() + "").substr(4 - group.length);
});
for (var k in o) {
fmt = fmt.replace(new RegExp("(" + k + ")"), function(match, group) {
return group.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length);
});
}
return fmt;
},
isArray:function(arg){
if (typeof Array.isArray === "undefined") {
return Object.prototype.toString.call(arg) === "[object Array]";
}
return Array.isArray(arg);
}
};`,
})
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
To invoke in the js script:
//Call the global configuration parameters
var value=global.globalValue;
msg['addField2']=value;
//Call the custom golang function add
msg['addValue']=add(1,5);
//Format the time
msg['today']=utilsFunc.dateFormat(new Date(), "yyyyMMddhh");
//Call the custom golang function handleMsg
msgType=handleMsg(msg,metadata,msgType);
return {'msg':msg,'metadata':metadata,'msgType':msgType};
2
3
4
5
6
7
8
9
10
For usage examples: node_config (opens new window)
# Aspects
Type:[]Aspect
AOP aspects list.For examples:
//add SkipFallbackAspect
config := rulego.NewConfig(
types.WithAspects(&aspect.SkipFallbackAspect{ErrorCountLimit: 3, LimitDuration: time.Second * 10})
)
2
3
4