Skip to content

Commit

Permalink
commit flow rule cache
Browse files Browse the repository at this point in the history
  • Loading branch information
binbin0325 committed Oct 7, 2020
1 parent 0b7f723 commit ff71204
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
2 changes: 1 addition & 1 deletion adapter/micro/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func TestServerLimiter(t *testing.T) {
_, err = flow.LoadRules([]*flow.Rule{
{
Resource: req.Method(),
Threshold: 1,
Threshold: 0,
TokenCalculateStrategy: flow.Direct,
ControlBehavior: flow.Reject,
},
Expand Down
6 changes: 6 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 All @@ -28,6 +29,7 @@ var (
tcGenFuncMap = make(map[trafficControllerGenKey]TrafficControllerGenFunc)
tcMap = make(TrafficControllerMap)
tcMux = new(sync.RWMutex)
currentRules = make([]*Rule, 0)
)

func init() {
Expand Down Expand Up @@ -157,12 +159,16 @@ func onRuleUpdate(rules []*Rule) (err error) {
m[res] = buildRulesOfRes(res, rulesOfRes)
}
tcMap = m
currentRules = rules
return nil
}

// LoadRules loads the given flow rules to the rule manager, while all previous rules will be replaced.
func LoadRules(rules []*Rule) (bool, error) {
// TODO: rethink the design
if isEqual := reflect.DeepEqual(currentRules, rules); isEqual {
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 @@ -373,3 +373,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)
})
}

0 comments on commit ff71204

Please sign in to comment.