Skip to content

Commit 97a7785

Browse files
authored
Merge pull request #43 from projectdiscovery/feat-can-take
Adding optimistic CanTake method
2 parents fe39c81 + 8a98186 commit 97a7785

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

keyratelimit.go

+9
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,15 @@ func (m *MultiLimiter) Take(key string) error {
8181
return nil
8282
}
8383

84+
// CanTake checks if the rate limiter with the given key has any token
85+
func (m *MultiLimiter) CanTake(key string) bool {
86+
limiter, err := m.get(key)
87+
if err != nil {
88+
return false
89+
}
90+
return limiter.CanTake()
91+
}
92+
8493
// AddAndTake adds key if not present and then takes token from bucket
8594
func (m *MultiLimiter) AddAndTake(opts *Options) {
8695
if limiter, err := m.get(opts.Key); err == nil {

ratelimit.go

+5
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ func (limiter *Limiter) Take() {
4949
<-limiter.tokens
5050
}
5151

52+
// CanTake checks if the rate limiter has any token
53+
func (limiter *Limiter) CanTake() bool {
54+
return limiter.count.Load() > 0
55+
}
56+
5257
// GetLimit returns current rate limit per given duration
5358
func (limiter *Limiter) GetLimit() uint {
5459
return uint(limiter.maxCount)

ratelimit_test.go

+10
Original file line numberDiff line numberDiff line change
@@ -85,4 +85,14 @@ func TestRateLimit(t *testing.T) {
8585
expected := time.Duration(6) * time.Second
8686
require.GreaterOrEqualf(t, timetaken.Nanoseconds(), expected.Nanoseconds(), "more tokens sent than expected with ratelimit")
8787
})
88+
89+
t.Run("Test Take and CanTake", func(t *testing.T) {
90+
limiter := New(context.TODO(), 3, time.Hour)
91+
92+
require.True(t, limiter.CanTake())
93+
limiter.Take()
94+
limiter.Take()
95+
limiter.Take()
96+
require.False(t, limiter.CanTake())
97+
})
8898
}

0 commit comments

Comments
 (0)