This repository has been archived by the owner on Apr 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 99
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #33 from mailgun/thrawn/develop
PIP-675: Add support for persistent store
- v2.4.0
- v2.3.2
- v2.3.1
- v2.3.0
- v2.2.1
- v2.2.0
- v2.1.4
- v2.1.3
- v2.1.2
- v2.1.1
- v2.1.0
- v2.0.2
- v2.0.1
- v2.0.0
- v2.0.0-rc.51
- v2.0.0-rc.50
- v2.0.0-rc.49
- v2.0.0-rc.48
- v2.0.0-rc.47
- v2.0.0-rc.46
- v2.0.0-rc.45
- v2.0.0-rc.44
- v2.0.0-rc.43
- v2.0.0-rc.42
- v2.0.0-rc.41
- v2.0.0-rc.40
- v2.0.0-rc.39
- v2.0.0-rc.38
- v2.0.0-rc.37
- v2.0.0-rc.36
- v2.0.0-rc.35
- v2.0.0-rc.34
- v2.0.0-rc.33
- v2.0.0-rc.32
- v2.0.0-rc.31
- v2.0.0-rc.30
- v2.0.0-rc.29
- v2.0.0-rc.28
- v2.0.0-rc.27
- v2.0.0-rc.26
- v2.0.0-rc.25
- v2.0.0-rc.24
- v2.0.0-rc.23
- v2.0.0-rc.22
- v2.0.0-rc.21
- v2.0.0-rc.20
- v2.0.0-rc.19
- v2.0.0-rc.18
- v2.0.0-rc.17
- v2.0.0-rc.16
- v2.0.0-rc.15
- v2.0.0-rc.14
- v2.0.0-rc.13
- v2.0.0-rc.12
- v2.0.0-rc.11
- v2.0.0-rc.10
- v2.0.0-rc.9
- v2.0.0-rc.8
- v2.0.0-rc.7
- v2.0.0-rc.6
- v2.0.0-rc.5
- v2.0.0-rc.4
- v2.0.0-rc.3
- v2.0.0-rc.2
- v2.0.0-rc.1
- v1.0.1-rc.3
- v1.0.1-rc.2
- v1.0.1-rc.1
- v1.0.0-rc.9
- v1.0.0-rc.8
- v1.0.0-rc.7
- v1.0.0-rc.5
- v1.0.0-rc.4
- v1.0.0-rc.3
- v1.0.0-rc.2
- v1.0.0-rc.1
- v0.9.2
- v0.9.1
- v0.9.0
- v0.8.3
- v0.8.2
- v0.8.1
- v0.8.0
- v0.7.1
Showing
18 changed files
with
838 additions
and
345 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,29 +1,205 @@ | ||
/* | ||
Copyright 2018-2019 Mailgun Technologies Inc | ||
Modifications Copyright 2018 Mailgun Technologies Inc | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
This work is derived from github.com/golang/groupcache/lru | ||
*/ | ||
|
||
package gubernator | ||
|
||
import ( | ||
"github.com/mailgun/gubernator/cache" | ||
"fmt" | ||
"sync" | ||
"time" | ||
|
||
"container/list" | ||
"github.com/mailgun/holster" | ||
"github.com/prometheus/client_golang/prometheus" | ||
) | ||
|
||
// So algorithms can interface with different cache implementations | ||
type Cache interface { | ||
// Access methods | ||
Add(*CacheItem) bool | ||
UpdateExpiration(key interface{}, expireAt int64) bool | ||
GetItem(key interface{}) (value *CacheItem, ok bool) | ||
Each() chan *CacheItem | ||
Remove(key interface{}) | ||
|
||
// If the cache is exclusive, this will control access to the cache | ||
Unlock() | ||
Lock() | ||
} | ||
|
||
// Holds stats collected about the cache | ||
type cachStats struct { | ||
Size int64 | ||
Miss int64 | ||
Hit int64 | ||
} | ||
|
||
// Cache is an thread unsafe LRU cache that supports expiration | ||
type LRUCache struct { | ||
cache map[interface{}]*list.Element | ||
mutex sync.Mutex | ||
ll *list.List | ||
stats cachStats | ||
cacheSize int | ||
|
||
// Stats | ||
sizeMetric *prometheus.Desc | ||
accessMetric *prometheus.Desc | ||
} | ||
|
||
type CacheItem struct { | ||
Algorithm Algorithm | ||
Key string | ||
ExpireAt int64 | ||
Value interface{} | ||
} | ||
|
||
var _ Cache = &LRUCache{} | ||
|
||
// New creates a new Cache with a maximum size | ||
func NewCache(maxSize int) *cache.LRUCache { | ||
func NewLRUCache(maxSize int) *LRUCache { | ||
holster.SetDefault(&maxSize, 50000) | ||
|
||
return cache.NewLRUCache(maxSize) | ||
return &LRUCache{ | ||
cache: make(map[interface{}]*list.Element), | ||
ll: list.New(), | ||
cacheSize: maxSize, | ||
sizeMetric: prometheus.NewDesc("cache_size", | ||
"Size of the LRU Cache which holds the rate limits.", nil, nil), | ||
accessMetric: prometheus.NewDesc("cache_access_count", | ||
"Cache access counts.", []string{"type"}, nil), | ||
} | ||
} | ||
|
||
func (c *LRUCache) Lock() { | ||
c.mutex.Lock() | ||
} | ||
|
||
func (c *LRUCache) Unlock() { | ||
c.mutex.Unlock() | ||
} | ||
|
||
func (c *LRUCache) Each() chan *CacheItem { | ||
out := make(chan *CacheItem) | ||
fmt.Printf("Each size: %d\n", len(c.cache)) | ||
go func() { | ||
for _, ele := range c.cache { | ||
out <- ele.Value.(*CacheItem) | ||
} | ||
close(out) | ||
}() | ||
return out | ||
} | ||
|
||
// Adds a value to the cache. | ||
func (c *LRUCache) Add(record *CacheItem) bool { | ||
// If the key already exist, set the new value | ||
if ee, ok := c.cache[record.Key]; ok { | ||
c.ll.MoveToFront(ee) | ||
temp := ee.Value.(*CacheItem) | ||
*temp = *record | ||
return true | ||
} | ||
|
||
ele := c.ll.PushFront(record) | ||
c.cache[record.Key] = ele | ||
if c.cacheSize != 0 && c.ll.Len() > c.cacheSize { | ||
c.removeOldest() | ||
} | ||
return false | ||
} | ||
|
||
// Return unix epoch in milliseconds | ||
func MillisecondNow() int64 { | ||
return time.Now().UnixNano() / 1000000 | ||
} | ||
|
||
// GetItem returns the item stored in the cache | ||
func (c *LRUCache) GetItem(key interface{}) (item *CacheItem, ok bool) { | ||
|
||
if ele, hit := c.cache[key]; hit { | ||
entry := ele.Value.(*CacheItem) | ||
|
||
// If the entry has expired, remove it from the cache | ||
if entry.ExpireAt < MillisecondNow() { | ||
c.removeElement(ele) | ||
c.stats.Miss++ | ||
return | ||
} | ||
c.stats.Hit++ | ||
c.ll.MoveToFront(ele) | ||
return entry, true | ||
} | ||
c.stats.Miss++ | ||
return | ||
} | ||
|
||
// Remove removes the provided key from the cache. | ||
func (c *LRUCache) Remove(key interface{}) { | ||
if ele, hit := c.cache[key]; hit { | ||
c.removeElement(ele) | ||
} | ||
} | ||
|
||
// RemoveOldest removes the oldest item from the cache. | ||
func (c *LRUCache) removeOldest() { | ||
ele := c.ll.Back() | ||
if ele != nil { | ||
c.removeElement(ele) | ||
} | ||
} | ||
|
||
func (c *LRUCache) removeElement(e *list.Element) { | ||
c.ll.Remove(e) | ||
kv := e.Value.(*CacheItem) | ||
delete(c.cache, kv.Key) | ||
} | ||
|
||
// Len returns the number of items in the cache. | ||
func (c *LRUCache) Size() int { | ||
return c.ll.Len() | ||
} | ||
|
||
func (c *LRUCache) Stats(_ bool) cachStats { | ||
return c.stats | ||
} | ||
|
||
// Update the expiration time for the key | ||
func (c *LRUCache) UpdateExpiration(key interface{}, expireAt int64) bool { | ||
if ele, hit := c.cache[key]; hit { | ||
entry := ele.Value.(*CacheItem) | ||
entry.ExpireAt = expireAt | ||
return true | ||
} | ||
return false | ||
} | ||
|
||
// Describe fetches prometheus metrics to be registered | ||
func (c *LRUCache) Describe(ch chan<- *prometheus.Desc) { | ||
ch <- c.sizeMetric | ||
ch <- c.accessMetric | ||
} | ||
|
||
// Collect fetches metric counts and gauges from the cache | ||
func (c *LRUCache) Collect(ch chan<- prometheus.Metric) { | ||
c.mutex.Lock() | ||
defer c.mutex.Unlock() | ||
ch <- prometheus.MustNewConstMetric(c.accessMetric, prometheus.CounterValue, float64(c.stats.Hit), "hit") | ||
ch <- prometheus.MustNewConstMetric(c.accessMetric, prometheus.CounterValue, float64(c.stats.Miss), "miss") | ||
ch <- prometheus.MustNewConstMetric(c.sizeMetric, prometheus.GaugeValue, float64(len(c.cache))) | ||
} |
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
package gubernator | ||
|
||
// PERSISTENT STORE DETAILS | ||
|
||
// The storage interfaces defined here allows the implementor flexibility in storage options. Depending on the | ||
// use case an implementor can only implement the `Loader` interface and only support persistence of | ||
// ratelimits at startup and shutdown or implement `Store` and gubernator will continuously call `OnChange()` | ||
// and `Get()` to keep the in memory cache and persistent store up to date with the latest ratelimit data. | ||
// Both interfaces can be implemented simultaneously to ensure data is always saved to persistent storage. | ||
|
||
type LeakyBucketItem struct { | ||
Limit int64 | ||
Duration int64 | ||
Remaining int64 | ||
TimeStamp int64 | ||
} | ||
|
||
// Store interface allows implementors to off load storage of all or a subset of ratelimits to | ||
// some persistent store. Methods OnChange() and Get() should avoid blocking as much as possible as these | ||
// methods are called on every rate limit request and will effect the performance of gubernator. | ||
type Store interface { | ||
// Called by gubernator when a rate limit item is updated. It's up to the store to | ||
// decide if this rate limit item should be persisted in the store. It's up to the | ||
// store to expire old rate limit items. | ||
OnChange(r *RateLimitReq, item *CacheItem) | ||
|
||
// Called by gubernator when a rate limit is missing from the cache. It's up to the store | ||
// to decide if this request is fulfilled. Should return true if the request is fulfilled | ||
// and false if the request is not fulfilled or doesn't exist in the store. | ||
Get(r *RateLimitReq) (*CacheItem, bool) | ||
|
||
// Called by gubernator when an existing rate limit should be removed from the store. | ||
// NOTE: This is NOT called when an rate limit expires from the cache, store implementors | ||
// must expire rate limits in the store. | ||
Remove(key string) | ||
} | ||
|
||
// Loader interface allows implementors to store all or a subset of ratelimits into a persistent | ||
// store during startup and shutdown of the gubernator instance. | ||
type Loader interface { | ||
// Load is called by gubernator just before the instance is ready to accept requests. The implementation | ||
// should return a channel gubernator can read to load all rate limits that should be loaded into the | ||
// instance cache. The implementation should close the channel to indicate no more rate limits left to load. | ||
Load() (chan *CacheItem, error) | ||
|
||
// Save is called by gubernator just before the instance is shutdown. The passed channel should be | ||
// read until the channel is closed. | ||
Save(chan *CacheItem) error | ||
} | ||
|
||
func NewMockStore() *MockStore { | ||
ml := &MockStore{ | ||
Called: make(map[string]int), | ||
CacheItems: make(map[string]*CacheItem), | ||
} | ||
ml.Called["OnChange()"] = 0 | ||
ml.Called["Remove()"] = 0 | ||
ml.Called["Get()"] = 0 | ||
return ml | ||
} | ||
|
||
type MockStore struct { | ||
Called map[string]int | ||
CacheItems map[string]*CacheItem | ||
} | ||
|
||
var _ Store = &MockStore{} | ||
|
||
func (ms *MockStore) OnChange(r *RateLimitReq, item *CacheItem) { | ||
ms.Called["OnChange()"] += 1 | ||
ms.CacheItems[item.Key] = item | ||
} | ||
|
||
func (ms *MockStore) Get(r *RateLimitReq) (*CacheItem, bool) { | ||
ms.Called["Get()"] += 1 | ||
item, ok := ms.CacheItems[r.HashKey()] | ||
return item, ok | ||
} | ||
|
||
func (ms *MockStore) Remove(key string) { | ||
ms.Called["Remove()"] += 1 | ||
delete(ms.CacheItems, key) | ||
} | ||
|
||
func NewMockLoader() *MockLoader { | ||
ml := &MockLoader{ | ||
Called: make(map[string]int), | ||
} | ||
ml.Called["Load()"] = 0 | ||
ml.Called["Save()"] = 0 | ||
return ml | ||
} | ||
|
||
type MockLoader struct { | ||
Called map[string]int | ||
CacheItems []*CacheItem | ||
} | ||
|
||
var _ Loader = &MockLoader{} | ||
|
||
func (ml *MockLoader) Load() (chan *CacheItem, error) { | ||
ml.Called["Load()"] += 1 | ||
|
||
ch := make(chan *CacheItem, 10) | ||
go func() { | ||
for _, i := range ml.CacheItems { | ||
ch <- i | ||
} | ||
close(ch) | ||
}() | ||
return ch, nil | ||
} | ||
|
||
func (ml *MockLoader) Save(in chan *CacheItem) error { | ||
ml.Called["Save()"] += 1 | ||
|
||
for i := range in { | ||
ml.CacheItems = append(ml.CacheItems, i) | ||
} | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,253 @@ | ||
/* | ||
Copyright 2018-2019 Mailgun Technologies Inc | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package gubernator_test | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
"time" | ||
|
||
"github.com/mailgun/gubernator" | ||
"github.com/mailgun/gubernator/cluster" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestLoader(t *testing.T) { | ||
loader := gubernator.NewMockLoader() | ||
|
||
ins, err := cluster.StartInstance("", gubernator.Config{ | ||
Behaviors: gubernator.BehaviorConfig{ | ||
GlobalSyncWait: time.Millisecond * 50, // Suitable for testing but not production | ||
GlobalTimeout: time.Second, | ||
}, | ||
Loader: loader, | ||
}) | ||
assert.Nil(t, err) | ||
|
||
// loader.Load() should have been called for gubernator startup | ||
assert.Equal(t, 1, loader.Called["Load()"]) | ||
assert.Equal(t, 0, loader.Called["Save()"]) | ||
|
||
client, err := gubernator.DialV1Server(ins.Address) | ||
assert.Nil(t, err) | ||
|
||
resp, err := client.GetRateLimits(context.Background(), &gubernator.GetRateLimitsReq{ | ||
Requests: []*gubernator.RateLimitReq{ | ||
{ | ||
Name: "test_over_limit", | ||
UniqueKey: "account:1234", | ||
Algorithm: gubernator.Algorithm_TOKEN_BUCKET, | ||
Duration: gubernator.Second, | ||
Limit: 2, | ||
Hits: 1, | ||
}, | ||
}, | ||
}) | ||
require.Nil(t, err) | ||
require.NotNil(t, resp) | ||
require.Equal(t, 1, len(resp.Responses)) | ||
require.Equal(t, "", resp.Responses[0].Error) | ||
|
||
err = ins.Stop() | ||
require.Nil(t, err) | ||
|
||
// Loader.Save() should been called during gubernator shutdown | ||
assert.Equal(t, 1, loader.Called["Load()"]) | ||
assert.Equal(t, 1, loader.Called["Save()"]) | ||
|
||
// Loader instance should have 1 rate limit | ||
require.Equal(t, 1, len(loader.CacheItems)) | ||
item, ok := loader.CacheItems[0].Value.(*gubernator.RateLimitResp) | ||
require.Equal(t, true, ok) | ||
assert.Equal(t, int64(2), item.Limit) | ||
assert.Equal(t, int64(1), item.Remaining) | ||
assert.Equal(t, gubernator.Status_UNDER_LIMIT, item.Status) | ||
} | ||
|
||
func TestStore(t *testing.T) { | ||
tests := []struct { | ||
name string | ||
firstRemaining int64 | ||
firstStatus gubernator.Status | ||
secondRemaining int64 | ||
secondStatus gubernator.Status | ||
algorithm gubernator.Algorithm | ||
switchAlgorithm gubernator.Algorithm | ||
testCase func(gubernator.RateLimitReq, *gubernator.MockStore) | ||
}{ | ||
{ | ||
name: "Given there are no token bucket limits in the store", | ||
firstRemaining: int64(9), | ||
firstStatus: gubernator.Status_UNDER_LIMIT, | ||
secondRemaining: int64(8), | ||
secondStatus: gubernator.Status_UNDER_LIMIT, | ||
algorithm: gubernator.Algorithm_TOKEN_BUCKET, | ||
switchAlgorithm: gubernator.Algorithm_LEAKY_BUCKET, | ||
testCase: func(req gubernator.RateLimitReq, store *gubernator.MockStore) {}, | ||
}, | ||
{ | ||
name: "Given the store contains a token bucket rate limit not in the guber cache", | ||
firstRemaining: int64(0), | ||
firstStatus: gubernator.Status_UNDER_LIMIT, | ||
secondRemaining: int64(0), | ||
secondStatus: gubernator.Status_OVER_LIMIT, | ||
algorithm: gubernator.Algorithm_TOKEN_BUCKET, | ||
switchAlgorithm: gubernator.Algorithm_LEAKY_BUCKET, | ||
testCase: func(req gubernator.RateLimitReq, store *gubernator.MockStore) { | ||
// Expire 1 second from now | ||
expire := gubernator.MillisecondNow() + gubernator.Second | ||
store.CacheItems[req.HashKey()] = &gubernator.CacheItem{ | ||
Algorithm: gubernator.Algorithm_TOKEN_BUCKET, | ||
ExpireAt: expire, | ||
Key: req.HashKey(), | ||
Value: &gubernator.RateLimitResp{ | ||
ResetTime: expire, | ||
Limit: req.Limit, | ||
Remaining: 1, | ||
}, | ||
} | ||
}, | ||
}, | ||
{ | ||
name: "Given there are no leaky bucket limits in the store", | ||
firstRemaining: int64(9), | ||
firstStatus: gubernator.Status_UNDER_LIMIT, | ||
secondRemaining: int64(8), | ||
secondStatus: gubernator.Status_UNDER_LIMIT, | ||
algorithm: gubernator.Algorithm_LEAKY_BUCKET, | ||
switchAlgorithm: gubernator.Algorithm_TOKEN_BUCKET, | ||
testCase: func(req gubernator.RateLimitReq, store *gubernator.MockStore) {}, | ||
}, | ||
{ | ||
name: "Given the store contains a leaky bucket rate limit not in the guber cache", | ||
firstRemaining: int64(0), | ||
firstStatus: gubernator.Status_UNDER_LIMIT, | ||
secondRemaining: int64(0), | ||
secondStatus: gubernator.Status_OVER_LIMIT, | ||
algorithm: gubernator.Algorithm_LEAKY_BUCKET, | ||
switchAlgorithm: gubernator.Algorithm_TOKEN_BUCKET, | ||
testCase: func(req gubernator.RateLimitReq, store *gubernator.MockStore) { | ||
// Expire 1 second from now | ||
expire := gubernator.MillisecondNow() + gubernator.Second | ||
store.CacheItems[req.HashKey()] = &gubernator.CacheItem{ | ||
Algorithm: gubernator.Algorithm_LEAKY_BUCKET, | ||
ExpireAt: expire, | ||
Key: req.HashKey(), | ||
Value: &gubernator.LeakyBucketItem{ | ||
TimeStamp: gubernator.MillisecondNow(), | ||
Duration: req.Duration, | ||
Limit: req.Limit, | ||
Remaining: 1, | ||
}, | ||
} | ||
}, | ||
}, | ||
} | ||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
store := gubernator.NewMockStore() | ||
|
||
ins, err := cluster.StartInstance("", gubernator.Config{ | ||
Behaviors: gubernator.BehaviorConfig{ | ||
GlobalSyncWait: time.Millisecond * 50, // Suitable for testing but not production | ||
GlobalTimeout: time.Second, | ||
}, | ||
Store: store, | ||
}) | ||
assert.Nil(t, err) | ||
|
||
// No calls to store | ||
assert.Equal(t, 0, store.Called["OnChange()"]) | ||
assert.Equal(t, 0, store.Called["Get()"]) | ||
|
||
client, err := gubernator.DialV1Server(ins.Address) | ||
assert.Nil(t, err) | ||
|
||
req := gubernator.RateLimitReq{ | ||
Name: "test_over_limit", | ||
UniqueKey: "account:1234", | ||
Algorithm: tt.algorithm, | ||
Duration: gubernator.Second, | ||
Limit: 10, | ||
Hits: 1, | ||
} | ||
|
||
tt.testCase(req, store) | ||
|
||
// This request for the rate limit should ask the store via Get() and then | ||
// tell the store about the change to the rate limit by calling OnChange() | ||
resp, err := client.GetRateLimits(context.Background(), &gubernator.GetRateLimitsReq{ | ||
Requests: []*gubernator.RateLimitReq{&req}, | ||
}) | ||
require.Nil(t, err) | ||
require.NotNil(t, resp) | ||
require.Equal(t, 1, len(resp.Responses)) | ||
require.Equal(t, "", resp.Responses[0].Error) | ||
assert.Equal(t, tt.firstRemaining, resp.Responses[0].Remaining) | ||
assert.Equal(t, int64(10), resp.Responses[0].Limit) | ||
assert.Equal(t, tt.firstStatus, resp.Responses[0].Status) | ||
|
||
// Should have called OnChange() and Get() | ||
assert.Equal(t, 1, store.Called["OnChange()"]) | ||
assert.Equal(t, 1, store.Called["Get()"]) | ||
|
||
// Should have updated the store | ||
assert.Equal(t, tt.firstRemaining, getRemaining(store.CacheItems[req.HashKey()])) | ||
|
||
// Next call should not call `Get()` but only `OnChange()` | ||
resp, err = client.GetRateLimits(context.Background(), &gubernator.GetRateLimitsReq{ | ||
Requests: []*gubernator.RateLimitReq{&req}, | ||
}) | ||
require.Nil(t, err) | ||
require.NotNil(t, resp) | ||
assert.Equal(t, tt.secondRemaining, resp.Responses[0].Remaining) | ||
assert.Equal(t, int64(10), resp.Responses[0].Limit) | ||
assert.Equal(t, tt.secondStatus, resp.Responses[0].Status) | ||
|
||
// Should have called OnChange() not Get() since rate limit is in the cache | ||
assert.Equal(t, 2, store.Called["OnChange()"]) | ||
assert.Equal(t, 1, store.Called["Get()"]) | ||
|
||
// Should have updated the store | ||
assert.Equal(t, tt.secondRemaining, getRemaining(store.CacheItems[req.HashKey()])) | ||
|
||
// Should have called `Remove()` when algorithm changed | ||
req.Algorithm = tt.switchAlgorithm | ||
resp, err = client.GetRateLimits(context.Background(), &gubernator.GetRateLimitsReq{ | ||
Requests: []*gubernator.RateLimitReq{&req}, | ||
}) | ||
require.Nil(t, err) | ||
require.NotNil(t, resp) | ||
assert.Equal(t, 1, store.Called["Remove()"]) | ||
assert.Equal(t, 3, store.Called["OnChange()"]) | ||
assert.Equal(t, 2, store.Called["Get()"]) | ||
|
||
assert.Equal(t, tt.switchAlgorithm, store.CacheItems[req.HashKey()].Algorithm) | ||
}) | ||
} | ||
} | ||
|
||
func getRemaining(item *gubernator.CacheItem) int64 { | ||
switch item.Algorithm { | ||
case gubernator.Algorithm_TOKEN_BUCKET: | ||
return item.Value.(*gubernator.RateLimitResp).Remaining | ||
case gubernator.Algorithm_LEAKY_BUCKET: | ||
return item.Value.(*gubernator.LeakyBucketItem).Remaining | ||
} | ||
return 0 | ||
} |