Skip to content

Commit

Permalink
Merge pull request #43 from projectdiscovery/feat-can-take
Browse files Browse the repository at this point in the history
Adding optimistic CanTake method
  • Loading branch information
Mzack9999 committed Jun 28, 2023
2 parents fe39c81 + 8a98186 commit 97a7785
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
9 changes: 9 additions & 0 deletions keyratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,15 @@ func (m *MultiLimiter) Take(key string) error {
return nil
}

// CanTake checks if the rate limiter with the given key has any token
func (m *MultiLimiter) CanTake(key string) bool {
limiter, err := m.get(key)
if err != nil {
return false
}
return limiter.CanTake()
}

// AddAndTake adds key if not present and then takes token from bucket
func (m *MultiLimiter) AddAndTake(opts *Options) {
if limiter, err := m.get(opts.Key); err == nil {
Expand Down
5 changes: 5 additions & 0 deletions ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ func (limiter *Limiter) Take() {
<-limiter.tokens
}

// CanTake checks if the rate limiter has any token
func (limiter *Limiter) CanTake() bool {
return limiter.count.Load() > 0
}

// GetLimit returns current rate limit per given duration
func (limiter *Limiter) GetLimit() uint {
return uint(limiter.maxCount)
Expand Down
10 changes: 10 additions & 0 deletions ratelimit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,14 @@ func TestRateLimit(t *testing.T) {
expected := time.Duration(6) * time.Second
require.GreaterOrEqualf(t, timetaken.Nanoseconds(), expected.Nanoseconds(), "more tokens sent than expected with ratelimit")
})

t.Run("Test Take and CanTake", func(t *testing.T) {
limiter := New(context.TODO(), 3, time.Hour)

require.True(t, limiter.CanTake())
limiter.Take()
limiter.Take()
limiter.Take()
require.False(t, limiter.CanTake())
})
}

0 comments on commit 97a7785

Please sign in to comment.