Skip to content

Commit

Permalink
Merge pull request kubernetes#6314 from bparees/tokenbucket
Browse files Browse the repository at this point in the history
add a blocking accept method to RateLimiter
  • Loading branch information
bprashanth committed Apr 2, 2015
2 parents 4a2000c + 70be667 commit 3fe4224
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions pkg/apiserver/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ type fakeRL bool

func (fakeRL) Stop() {}
func (f fakeRL) CanAccept() bool { return bool(f) }
func (f fakeRL) Accept() {}

func expectHTTP(url string, code int, t *testing.T) {
r, err := http.Get(url)
Expand Down
7 changes: 7 additions & 0 deletions pkg/util/throttle.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import (
type RateLimiter interface {
// CanAccept returns true if the rate is below the limit, false otherwise
CanAccept() bool
// Accept returns once a token becomes available.
Accept()
// Stop stops the rate limiter, subsequent calls to CanAccept will return false
Stop()
}
Expand Down Expand Up @@ -73,6 +75,11 @@ func (t *tickRateLimiter) CanAccept() bool {
}
}

// Accept will block until a token becomes available
func (t *tickRateLimiter) Accept() {
<-t.tokens
}

func (t *tickRateLimiter) Stop() {
close(t.stop)
}
Expand Down
14 changes: 14 additions & 0 deletions pkg/util/throttle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,17 @@ func TestOverBurst(t *testing.T) {
r.step()
}
}

func TestThrottle(t *testing.T) {
r := NewTokenBucketRateLimiter(10, 5)

// Should consume 5 tokens immediately, then
// the remaining 11 should take at least 1 second (0.1s each)
expectedFinish := time.Now().Add(time.Second * 1)
for i := 0; i < 16; i++ {
r.Accept()
}
if time.Now().Before(expectedFinish) {
t.Error("rate limit was not respected, finished too early")
}
}

0 comments on commit 3fe4224

Please sign in to comment.