Skip to content
This repository has been archived by the owner on Apr 19, 2024. It is now read-only.

Commit

Permalink
Merge pull request #87 from Neal/fix/leaky-bucket-remaining
Browse files Browse the repository at this point in the history
Fix leaky bucket algorithm returning remaining more than limit
  • Loading branch information
thrawn01 authored Mar 10, 2021
2 parents e1f998a + 18b969f commit e7dbde1
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
8 changes: 4 additions & 4 deletions algorithms.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,15 +235,15 @@ func leakyBucket(s Store, c Cache, r *RateLimitReq) (resp *RateLimitResp, err er
elapsed := now - b.UpdatedAt
leak := float64(elapsed) / rate

if int64(b.Remaining) > b.Limit {
b.Remaining = float64(b.Limit)
}

if int64(leak) > 0 {
b.Remaining += leak
b.UpdatedAt = now
}

if int64(b.Remaining) > b.Limit {
b.Remaining = float64(b.Limit)
}

rl := &RateLimitResp{
Limit: b.Limit,
Remaining: int64(b.Remaining),
Expand Down
12 changes: 9 additions & 3 deletions functional_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,11 +308,17 @@ func TestLeakyBucket(t *testing.T) {
Hits: 0,
Remaining: 1,
Status: guber.Status_UNDER_LIMIT,
Sleep: clock.Second * 60,
},
{
Name: "should max out the limit",
Hits: 0,
Remaining: 10,
Status: guber.Status_UNDER_LIMIT,
Sleep: clock.Second,
},
}

now := clock.Now()
for _, test := range tests {
t.Run(test.Name, func(t *testing.T) {
resp, err := client.GetRateLimits(context.Background(), &guber.GetRateLimitsReq{
Expand All @@ -327,15 +333,15 @@ func TestLeakyBucket(t *testing.T) {
},
},
})
clock.Freeze(clock.Now())
require.NoError(t, err)
require.Len(t, resp.Responses, 1)

rl := resp.Responses[0]

assert.Equal(t, test.Status, rl.Status)
assert.Equal(t, test.Remaining, rl.Remaining)
assert.Equal(t, int64(10), rl.Limit)
assert.True(t, rl.ResetTime > now.Unix())
assert.Equal(t, clock.Now().Unix()+3, rl.ResetTime/1000)
clock.Advance(test.Sleep)
})
}
Expand Down

0 comments on commit e7dbde1

Please sign in to comment.