Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
case t.maxSlack > 0 && now-timeOfNextPermissionIssue > int64(t.maxSlack):
now-timeOfNextPermissionIssue > int64(t.maxSlack):

I think the maxSlack check here is unnecessary - the previous iff should have covered that.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wait, no, this is wrong - > int64(t.maxSlack): vs > int64(t.perRequest)).

I clearly need to understand this code more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there can be a case where t.maxSlack == 0 is true, but now-timeOfNextPermissionIssue > int64(t.perRequest) is false, in that case we will try to evaluate now-timeOfNextPermissionIssue > int64(t.maxSlack) and it can be true, so we will end up in a wrong branch. So we need t.maxSlack > 0 check here to step into default branch.

// 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)
}