Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix bonus tokens by function adjustavailableTokens (#31) #31

Merged
merged 2 commits into from
Oct 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -310,14 +310,15 @@ func (tb *Bucket) currentTick(now time.Time) int64 {
// available in the bucket at the given time, which must
// be in the future (positive) with respect to tb.latestTick.
func (tb *Bucket) adjustavailableTokens(tick int64) {
lastTick := tb.latestTick
tb.latestTick = tick
kingsamchen marked this conversation as resolved.
Show resolved Hide resolved
if tb.availableTokens >= tb.capacity {
return
}
tb.availableTokens += (tick - tb.latestTick) * tb.quantum
tb.availableTokens += (tick - lastTick) * tb.quantum
if tb.availableTokens > tb.capacity {
tb.availableTokens = tb.capacity
}
tb.latestTick = tick
return
}

Expand Down
25 changes: 25 additions & 0 deletions ratelimit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,31 @@ func TestAvailable(t *testing.T) {

}

func TestNoBonusTokenAfterBucketIsFull(t *testing.T) {
tb := NewBucketWithQuantum(time.Second*1, 100, 20)
curAvail := tb.Available()
if curAvail != 100 {
t.Fatalf("initially: actual available = %d, expected = %d", curAvail, 100)
}

time.Sleep(time.Second * 5)

curAvail = tb.Available()
if curAvail != 100 {
t.Fatalf("after pause: actual available = %d, expected = %d", curAvail, 100)
}

cnt := tb.TakeAvailable(100)
if cnt != 100 {
t.Fatalf("taking: actual taken count = %d, expected = %d", cnt, 100)
}

curAvail = tb.Available()
if curAvail != 0 {
t.Fatalf("after taken: actual available = %d, expected = %d", curAvail, 0)
}
}

func BenchmarkWait(b *testing.B) {
tb := NewBucket(1, 16*1024)
for i := b.N - 1; i >= 0; i-- {
Expand Down