Skip to content

Commit

Permalink
Add cache mechanism for LoadRules in flow module (#268)
Browse files Browse the repository at this point in the history
* Add cache mechanism for LoadRules in flow module 

Co-authored-by: louyuting <[email protected]>
  • Loading branch information
binbin0325 and louyuting authored Nov 16, 2020
1 parent b98d989 commit 854b3f7
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
12 changes: 12 additions & 0 deletions core/flow/rule_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package flow

import (
"fmt"
"reflect"
"sync"

"github.com/alibaba/sentinel-golang/core/base"
Expand Down Expand Up @@ -34,6 +35,7 @@ var (
readOnlyMetric: base.NopReadStat(),
writeOnlyMetric: base.NopWriteStat(),
}
currentRules = make([]*Rule, 0)
)

func init() {
Expand Down Expand Up @@ -165,12 +167,22 @@ func onRuleUpdate(rules []*Rule) (err error) {
}
}
tcMap = m
currentRules = rules
return nil
}

// LoadRules loads the given flow rules to the rule manager, while all previous rules will be replaced.
// the first returned value indicates whether do real load operation, if the rules is the same with previous rules, return false
func LoadRules(rules []*Rule) (bool, error) {
// TODO: rethink the design
tcMux.RLock()
isEqual := reflect.DeepEqual(currentRules, rules)
tcMux.RUnlock()
if isEqual {
logging.Info("[Flow] Load rules is the same with current rules, so ignore load operation.")
return false, nil
}

err := onRuleUpdate(rules)
return true, err
}
Expand Down
24 changes: 24 additions & 0 deletions core/flow/rule_manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -418,3 +418,27 @@ func Test_buildRulesOfRes(t *testing.T) {
assert.True(t, tcs[3].boundStat == stat4)
})
}

func TestLoadRules(t *testing.T) {
t.Run("loadSameRules", func(t *testing.T) {
_, err := LoadRules([]*Rule{
{
Resource: "some-test",
Threshold: 10,
TokenCalculateStrategy: Direct,
ControlBehavior: Reject,
},
})
assert.Nil(t, err)
ok, err := LoadRules([]*Rule{
{
Resource: "some-test",
Threshold: 10,
TokenCalculateStrategy: Direct,
ControlBehavior: Reject,
},
})
assert.Nil(t, err)
assert.False(t, ok)
})
}
4 changes: 2 additions & 2 deletions ext/datasource/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ func FlowRulesUpdater(data interface{}) error {
fmt.Sprintf("Fail to type assert data to []flow.Rule or []*flow.Rule, in fact, data: %+v", data),
)
}
succ, err := flow.LoadRules(rules)
if succ && err == nil {
_, err := flow.LoadRules(rules)
if err == nil {
return nil
}
return NewError(
Expand Down

0 comments on commit 854b3f7

Please sign in to comment.