Skip to content

Commit

Permalink
Merge pull request #7 from szuecs/expose/Oldest
Browse files Browse the repository at this point in the history
expose Oldest() to get the oldest value of a ratelimiter bucket
  • Loading branch information
szuecs committed Oct 10, 2018
2 parents 4b1461d + 0c80567 commit 31803ef
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
26 changes: 22 additions & 4 deletions ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ type RateLimiter interface {
Allow(string) bool
// Close cleans up the RateLimiter implementation.
Close()
Current(string) time.Time
Oldest(string) time.Time
Delta(string) time.Duration
Resize(string, int)
// RetryAfter returns how many seconds until the next allowed request
Expand All @@ -39,8 +39,15 @@ func (cb *CircularBuffer) Allow(s string) bool {
// do.
func (*CircularBuffer) Close() {}

// Current implements the RateLimiter interface to shutdown, nothing to
// do.
// Oldest implements the RateLimiter interface
func (cb *CircularBuffer) Oldest(string) time.Time {
cb.RLock()
cur := cb.slots[cb.offset]
cb.RUnlock()
return cur
}

// Current implements the RateLimiter interface
func (cb *CircularBuffer) Current(string) time.Time {
return cb.current()
}
Expand Down Expand Up @@ -115,13 +122,24 @@ func (rl *ClientRateLimiter) Allow(s string) bool {
return present
}

func (rl *ClientRateLimiter) Oldest(s string) time.Time {
rl.RLock()
if _, present := rl.bag[s]; !present {
rl.RUnlock()
return time.Time{}
}
delta := rl.bag[s].Oldest(s)
rl.RUnlock()
return delta
}

func (rl *ClientRateLimiter) Current(s string) time.Time {
rl.RLock()
if _, present := rl.bag[s]; !present {
rl.RUnlock()
return time.Time{}
}
delta := rl.bag[s].current()
delta := rl.bag[s].Current(s)
rl.RUnlock()
return delta
}
Expand Down
22 changes: 22 additions & 0 deletions ratelimit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,35 @@ func TestClientRateLimiterDeleteOld(t *testing.T) {
rl.Close()
}

func TestClientRateLimiterOldest(t *testing.T) {
window := 1 * time.Second
rl := newClientRateLimiter(2, window) // [ , ]
zero := time.Time{}

if !rl.Oldest("foo").Equal(zero) { // [0, 0]
t.Errorf("0foo should return zero")
}

rl.Allow("foo") // [t0, 0]
if !rl.Oldest("foo").Equal(zero) {
t.Errorf("1foo should return zero")
}

t0 := rl.Current("foo")
rl.Allow("foo") // [t0, t1]
if !rl.Oldest("foo").Equal(t0) {
t.Errorf("2foo should return t0")
}
}

func TestClientRateLimiterCurrent(t *testing.T) {
window := 1 * time.Second
rl := newClientRateLimiter(2, window)

t0 := time.Now()
rl.Allow("foo")
rl.Allow("foo")

t1 := time.Now()
rl.Allow("bar")
rl.Allow("bar")
Expand Down

0 comments on commit 31803ef

Please sign in to comment.