@@ -21,7 +21,7 @@ func New(dataStore LimitStore, requestsLimit int64, windowSize time.Duration) *R
21
21
}
22
22
}
23
23
24
- // Inc increments limiter counter for a given key or returns error when it's not possible. Inc should be called when a request for a given limited resource has been fulfilled
24
+ // Inc increments limiter counter for a given key or returns error when it's not possible
25
25
func (r * RateLimiter ) Inc (key string ) error {
26
26
currentWindow := time .Now ().UTC ().Truncate (r .windowSize )
27
27
return r .dataStore .Inc (key , currentWindow )
@@ -49,7 +49,7 @@ func (r *RateLimiter) Check(key string) (limitStatus *LimitStatus, err error) {
49
49
50
50
rate := float64 ((float64 (r .windowSize )- float64 (timeFromCurrWindow ))/ float64 (r .windowSize ))* float64 (prevValue ) + float64 (currentValue )
51
51
limitStatus = & LimitStatus {}
52
- if rate > float64 (r .requestsLimit ) {
52
+ if rate >= float64 (r .requestsLimit ) {
53
53
limitStatus .IsLimited = true
54
54
limitDuration := r .calcLimitDuration (prevValue , currentValue , timeFromCurrWindow )
55
55
limitStatus .LimitDuration = & limitDuration
@@ -73,9 +73,14 @@ func (r *RateLimiter) calcLimitDuration(prevValue, currValue int64, timeFromCurr
73
73
var limitDuration time.Duration
74
74
if prevValue == 0 {
75
75
// unblock in the next window where prevValue is currValue and currValue is zero (assuming that since limit start all requests are blocked)
76
- nextWindowUnblockPoint := float64 (r .windowSize ) * (1.0 - (float64 (r .requestsLimit ) / float64 (currValue )))
77
- timeToNextWindow := r .windowSize - timeFromCurrWindow
78
- limitDuration = timeToNextWindow + time .Duration (int64 (nextWindowUnblockPoint )+ 1 )
76
+ if currValue != 0 {
77
+ nextWindowUnblockPoint := float64 (r .windowSize ) * (1.0 - (float64 (r .requestsLimit ) / float64 (currValue )))
78
+ timeToNextWindow := r .windowSize - timeFromCurrWindow
79
+ limitDuration = timeToNextWindow + time .Duration (int64 (nextWindowUnblockPoint )+ 1 )
80
+ } else {
81
+ // when requestsLimit is 0 we want to block all requests - set limitDuration to -1
82
+ limitDuration = - 1
83
+ }
79
84
} else {
80
85
currWindowUnblockPoint := float64 (r .windowSize ) * (1.0 - (float64 (r .requestsLimit - currValue ) / float64 (prevValue )))
81
86
limitDuration = time .Duration (int64 (currWindowUnblockPoint + 1 )) - timeFromCurrWindow
0 commit comments