This repository was archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 63
Add RateLimit middleware using TokenBucket algorithm #557
Open
LaPetiteSouris
wants to merge
8
commits into
flyteorg:master
Choose a base branch
from
LaPetiteSouris:feat-rate-limit
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
271bc9f
Add rate_limiter in plugins
LaPetiteSouris 9f8daf7
Add configs for rate limit
LaPetiteSouris 2b7fb81
Add Interceptor for RateLimit
LaPetiteSouris 808ec45
Add details docs for configs
LaPetiteSouris 260e71d
Add lastAccess timestamp test for RateLimiter
LaPetiteSouris e9585fb
Add timestamp unit test for RateLimiter
LaPetiteSouris 6061035
Use sync.Map to avoid contention on RateLimiter
LaPetiteSouris dfaf183
Remove global lock in RateLimitStore
LaPetiteSouris File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or 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 hidden or 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,116 @@ | ||
package plugins | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"fmt" | ||
"sync" | ||
"time" | ||
|
||
auth "github.com/flyteorg/flyteadmin/auth" | ||
"golang.org/x/time/rate" | ||
"google.golang.org/grpc" | ||
"google.golang.org/grpc/codes" | ||
"google.golang.org/grpc/status" | ||
) | ||
|
||
type RateLimitExceeded error | ||
|
||
// accessRecords stores the rate limiter and the last access time | ||
type accessRecords struct { | ||
limiter *rate.Limiter | ||
lastAccess time.Time | ||
mutex *sync.Mutex | ||
} | ||
|
||
// LimiterStore stores the access records for each user | ||
type LimiterStore struct { | ||
// accessPerUser is a synchronized map of userID to accessRecords | ||
accessPerUser *sync.Map | ||
requestPerSec int | ||
burstSize int | ||
cleanupInterval time.Duration | ||
} | ||
|
||
// Allow takes a userID and returns an error if the user has exceeded the rate limit | ||
func (l *LimiterStore) Allow(userID string) error { | ||
accessRecord, _ := l.accessPerUser.LoadOrStore(userID, &accessRecords{ | ||
limiter: rate.NewLimiter(rate.Limit(l.requestPerSec), l.burstSize), | ||
lastAccess: time.Now(), | ||
mutex: &sync.Mutex{}, | ||
}) | ||
accessRecord.(*accessRecords).mutex.Lock() | ||
defer accessRecord.(*accessRecords).mutex.Unlock() | ||
|
||
accessRecord.(*accessRecords).lastAccess = time.Now() | ||
l.accessPerUser.Store(userID, accessRecord) | ||
|
||
if !accessRecord.(*accessRecords).limiter.Allow() { | ||
return RateLimitExceeded(fmt.Errorf("rate limit exceeded")) | ||
} | ||
Comment on lines
+48
to
+50
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. shouldn't this happen before we modify the map? |
||
|
||
return nil | ||
} | ||
|
||
// clean removes the access records for users who have not accessed the system for a while | ||
func (l *LimiterStore) clean() { | ||
l.accessPerUser.Range(func(key, value interface{}) bool { | ||
value.(*accessRecords).mutex.Lock() | ||
defer value.(*accessRecords).mutex.Unlock() | ||
if time.Since(value.(*accessRecords).lastAccess) > l.cleanupInterval { | ||
l.accessPerUser.Delete(key) | ||
} | ||
return true | ||
}) | ||
} | ||
|
||
func newRateLimitStore(requestPerSec int, burstSize int, cleanupInterval time.Duration) *LimiterStore { | ||
l := &LimiterStore{ | ||
accessPerUser: &sync.Map{}, | ||
requestPerSec: requestPerSec, | ||
burstSize: burstSize, | ||
cleanupInterval: cleanupInterval, | ||
} | ||
|
||
go func() { | ||
for { | ||
time.Sleep(l.cleanupInterval) | ||
l.clean() | ||
} | ||
}() | ||
|
||
return l | ||
} | ||
|
||
// RateLimiter is a struct that implements the RateLimiter interface from grpc middleware | ||
type RateLimiter struct { | ||
limiter *LimiterStore | ||
} | ||
|
||
func (r *RateLimiter) Limit(ctx context.Context) error { | ||
IdenCtx := auth.IdentityContextFromContext(ctx) | ||
if IdenCtx.IsEmpty() { | ||
return errors.New("no identity context found") | ||
} | ||
userID := IdenCtx.UserID() | ||
if err := r.limiter.Allow(userID); err != nil { | ||
return err | ||
} | ||
return nil | ||
} | ||
|
||
func NewRateLimiter(requestPerSec int, burstSize int, cleanupInterval time.Duration) *RateLimiter { | ||
limiter := newRateLimitStore(requestPerSec, burstSize, cleanupInterval) | ||
return &RateLimiter{limiter: limiter} | ||
} | ||
|
||
func RateLimiteInterceptor(limiter RateLimiter) grpc.UnaryServerInterceptor { | ||
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) ( | ||
resp interface{}, err error) { | ||
if err := limiter.Limit(ctx); err != nil { | ||
return nil, status.Errorf(codes.ResourceExhausted, "rate limit exceeded") | ||
} | ||
|
||
return handler(ctx, req) | ||
} | ||
} |
This file contains hidden or 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,126 @@ | ||
package plugins | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
"time" | ||
|
||
auth "github.com/flyteorg/flyteadmin/auth" | ||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestNewRateLimiter(t *testing.T) { | ||
rlStore := newRateLimitStore(1, 1, time.Second) | ||
assert.NotNil(t, rlStore) | ||
} | ||
|
||
func TestLimiterAllow(t *testing.T) { | ||
rlStore := newRateLimitStore(1, 1, 10*time.Second) | ||
assert.NoError(t, rlStore.Allow("hello")) | ||
assert.Error(t, rlStore.Allow("hello")) | ||
time.Sleep(time.Second) | ||
assert.NoError(t, rlStore.Allow("hello")) | ||
} | ||
|
||
func TestLimiterAllowBurst(t *testing.T) { | ||
rlStore := newRateLimitStore(1, 2, time.Second) | ||
assert.NoError(t, rlStore.Allow("hello")) | ||
assert.NoError(t, rlStore.Allow("hello")) | ||
assert.Error(t, rlStore.Allow("hello")) | ||
assert.NoError(t, rlStore.Allow("world")) | ||
} | ||
|
||
func TestLimiterClean(t *testing.T) { | ||
rlStore := newRateLimitStore(1, 1, time.Second) | ||
assert.NoError(t, rlStore.Allow("hello")) | ||
assert.Error(t, rlStore.Allow("hello")) | ||
time.Sleep(time.Second) | ||
rlStore.clean() | ||
assert.NoError(t, rlStore.Allow("hello")) | ||
} | ||
|
||
func TestLimiterAllowOnMultipleRequests(t *testing.T) { | ||
rlStore := newRateLimitStore(1, 1, time.Second) | ||
assert.NoError(t, rlStore.Allow("a")) | ||
assert.NoError(t, rlStore.Allow("b")) | ||
assert.NoError(t, rlStore.Allow("c")) | ||
assert.Error(t, rlStore.Allow("a")) | ||
assert.Error(t, rlStore.Allow("b")) | ||
|
||
time.Sleep(time.Second) | ||
|
||
assert.NoError(t, rlStore.Allow("a")) | ||
assert.Error(t, rlStore.Allow("a")) | ||
assert.NoError(t, rlStore.Allow("b")) | ||
assert.Error(t, rlStore.Allow("b")) | ||
assert.NoError(t, rlStore.Allow("c")) | ||
} | ||
|
||
func TestRateLimiterLimitPass(t *testing.T) { | ||
rateLimit := NewRateLimiter(1, 1, time.Second) | ||
assert.NotNil(t, rateLimit) | ||
|
||
identityCtx, err := auth.NewIdentityContext("audience", "user1", "app1", time.Now(), nil, nil, nil) | ||
assert.NoError(t, err) | ||
|
||
ctx := context.WithValue(context.TODO(), auth.ContextKeyIdentityContext, identityCtx) | ||
err = rateLimit.Limit(ctx) | ||
assert.NoError(t, err) | ||
|
||
} | ||
|
||
func TestRateLimiterLimitStop(t *testing.T) { | ||
rateLimit := NewRateLimiter(1, 1, time.Second) | ||
assert.NotNil(t, rateLimit) | ||
|
||
identityCtx, err := auth.NewIdentityContext("audience", "user1", "app1", time.Now(), nil, nil, nil) | ||
assert.NoError(t, err) | ||
ctx := context.WithValue(context.TODO(), auth.ContextKeyIdentityContext, identityCtx) | ||
err = rateLimit.Limit(ctx) | ||
assert.NoError(t, err) | ||
|
||
err = rateLimit.Limit(ctx) | ||
assert.Error(t, err) | ||
|
||
} | ||
|
||
func TestRateLimiterLimitWithoutUserIdentity(t *testing.T) { | ||
rateLimit := NewRateLimiter(1, 1, time.Second) | ||
assert.NotNil(t, rateLimit) | ||
|
||
ctx := context.TODO() | ||
|
||
err := rateLimit.Limit(ctx) | ||
assert.Error(t, err) | ||
} | ||
|
||
func TestRateLimiterUpdateLastAccessTime(t *testing.T) { | ||
rlStore := newRateLimitStore(2, 2, time.Second) | ||
assert.NoError(t, rlStore.Allow("hello")) | ||
// get last access time | ||
|
||
accessRecord, _ := rlStore.accessPerUser.Load("hello") | ||
accessRecord.(*accessRecords).mutex.Lock() | ||
firstAccessTime := accessRecord.(*accessRecords).lastAccess | ||
accessRecord.(*accessRecords).mutex.Unlock() | ||
|
||
assert.NoError(t, rlStore.Allow("hello")) | ||
|
||
accessRecord, _ = rlStore.accessPerUser.Load("hello") | ||
accessRecord.(*accessRecords).mutex.Lock() | ||
secondAccessTime := accessRecord.(*accessRecords).lastAccess | ||
accessRecord.(*accessRecords).mutex.Unlock() | ||
|
||
assert.True(t, secondAccessTime.After(firstAccessTime)) | ||
|
||
// Verify that the last access time is updated even when user is rate limited | ||
assert.Error(t, rlStore.Allow("hello")) | ||
|
||
accessRecord, _ = rlStore.accessPerUser.Load("hello") | ||
accessRecord.(*accessRecords).mutex.Lock() | ||
thirdAccessTime := accessRecord.(*accessRecords).lastAccess | ||
accessRecord.(*accessRecords).mutex.Unlock() | ||
|
||
assert.True(t, thirdAccessTime.After(secondAccessTime)) | ||
|
||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.