Skip to content

Commit

Permalink
Merge 3d88a77 into 1a179ab
Browse files Browse the repository at this point in the history
  • Loading branch information
vetinari committed Mar 20, 2018
2 parents 1a179ab + 3d88a77 commit 44d3962
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
12 changes: 12 additions & 0 deletions circularbuffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,15 @@ func (cb *CircularBuffer) Add(t time.Time) bool {
}
return false
}

func (cb *CircularBuffer) delta() time.Duration {
cb.RLock()
next := cb.slots[cb.offset]
curOff := cb.offset - 1
if curOff < 0 {
curOff += len(cb.slots)
}
cur := cb.slots[curOff]
cb.RUnlock()
return cur.Sub(next)
}
15 changes: 15 additions & 0 deletions circularbuffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,21 @@ func TestFree(t *testing.T) {
}
}

func TestDelta(t *testing.T) {
l := 4
window := 1 * time.Second
cb := NewCircularBuffer(l, window)
start := time.Now()
for i := 0; i < l; i++ {
cb.Add(start.Add(time.Duration(i) * window))
}
want := time.Duration(3) * window
delta := cb.delta()
if delta != want {
t.Errorf("want != delta => %s / %s", want, delta)
}
}

func TestAdd(t *testing.T) {
l := 4
window := 1 * time.Second
Expand Down
16 changes: 16 additions & 0 deletions ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type RateLimiter interface {
Allow(string) bool
// Close cleans up the RateLimiter implementation.
Close()
Delta(string) time.Duration
}

// NewRateLimiter returns a new initialized RateLimitter with maxHits
Expand All @@ -34,6 +35,10 @@ func (cb *CircularBuffer) Allow(s string) bool {
func (cb *CircularBuffer) Close() {
}

func (cb *CircularBuffer) Delta(s string) time.Duration {
return cb.delta()
}

// ClientRateLimiter implements the RateLimiter interface and does
// rate limiting based on the the String passed to Allow(). This can
// be used to limit per client calls to the backend. For example you
Expand Down Expand Up @@ -81,6 +86,17 @@ func (rl *ClientRateLimiter) Allow(s string) bool {
return present
}

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

// DeleteOld removes old entries from state bag
func (rl *ClientRateLimiter) DeleteOld() {
rl.Lock()
Expand Down

0 comments on commit 44d3962

Please sign in to comment.