Skip to content

Commit

Permalink
Fix no slack option for int64 based option (#95)
Browse files Browse the repository at this point in the history
This PR fixes the issue found by @twelsh-aw with int64 based implementation #90

Our tests did not detect this issue, so we have a separate PR #93 that enhances our tests approach to detect potential errors better.
  • Loading branch information
storozhukBM committed Jul 13, 2022
1 parent 2cba897 commit b62b799
Showing 1 changed file with 4 additions and 7 deletions.
11 changes: 4 additions & 7 deletions limiter_atomic_int64.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ func (t *atomicInt64Limiter) Take() time.Time {
timeOfNextPermissionIssue := atomic.LoadInt64(&t.state)

switch {
case timeOfNextPermissionIssue == 0:
// If this is our first request, then we allow it.
case timeOfNextPermissionIssue == 0 || (t.maxSlack == 0 && now-timeOfNextPermissionIssue > int64(t.perRequest)):
// if this is our first call or t.maxSlack == 0 we need to shrink issue time to now
newTimeOfNextPermissionIssue = now
case now-timeOfNextPermissionIssue > int64(t.maxSlack):
case t.maxSlack > 0 && now-timeOfNextPermissionIssue > int64(t.maxSlack):
// a lot of nanoseconds passed since the last Take call
// we will limit max accumulated time to maxSlack
newTimeOfNextPermissionIssue = now - int64(t.maxSlack)
Expand All @@ -82,9 +82,6 @@ func (t *atomicInt64Limiter) Take() time.Time {
break
}
}
nanosToSleepUntilOurPermissionIsIssued := newTimeOfNextPermissionIssue - now
if nanosToSleepUntilOurPermissionIsIssued > 0 {
t.clock.Sleep(time.Duration(nanosToSleepUntilOurPermissionIsIssued))
}
t.clock.Sleep(time.Duration(newTimeOfNextPermissionIssue - now))
return time.Unix(0, newTimeOfNextPermissionIssue)
}

0 comments on commit b62b799

Please sign in to comment.