-
Notifications
You must be signed in to change notification settings - Fork 2
/
engine.go
58 lines (50 loc) · 1.11 KB
/
engine.go
1
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//Package rule_engine is the Rule Engine Implementation.
package rule_engine
import "sort"
// Engine is to analyze the fact with rules
type Engine struct {
fact Fact
rules []*Rule
}
// NewEngine is to create a new Engine instance
func NewEngine() *Engine {
return &Engine{}
}
// AppendRule is to append a rule. It can be used as "method chain" pattern
// engine.AppendRule(rule1).AppendRule(rule2)
func (eng *Engine) AppendRule(rule *Rule) *Engine {
eng.rules = append(eng.rules, rule)
return eng
}
func (eng *Engine) Rules(newRules ...*Rule) {
eng.rules = newRules
}
func (eng *Engine) reset() {
for _, rule := range eng.rules {
rule.reset()
}
}
// Analyze the fact with the rules.
func (eng *Engine) Analyze(fact Fact) {
sort.Sort(RuleSlice(eng.rules))
eng.reset()
needAnalyzing := true
for {
if !needAnalyzing {
return
}
needAnalyzing = false
for _, rule := range eng.rules {
if rule.processed && !rule.Repeatable {
continue
}
if rule.ConditionFun(fact) {
rule.processed = true
updated := rule.PositiveAction(fact)
if updated {
needAnalyzing = true
}
}
}
}
}