Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix immediate slack re-apply issue #120

Closed
Closed
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion limiter_atomic_int64.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func (t *atomicInt64Limiter) Take() time.Time {
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 t.maxSlack > 0 && now-timeOfNextPermissionIssue > int64(t.maxSlack):
case t.maxSlack > 0 && now-timeOfNextPermissionIssue > int64(t.maxSlack)+int64(t.perRequest):
Copy link

@VovkoO VovkoO Jan 25, 2024

Choose a reason for hiding this comment

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

Wouldn't this solution make the withSlack and withoutSlack options work exactly the same.
Looks like without slack you condition looks like:
now - prev > period
and withSlack
now - (prev - slack) > slack + period
Which is the same thing

Copy link
Contributor Author

Choose a reason for hiding this comment

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

We apply now - int64(t.maxSlack) only under condition and that makes the difference.

// a lot of nanoseconds passed since the last Take call
// we will limit max accumulated time to maxSlack
newTimeOfNextPermissionIssue = now - int64(t.maxSlack)
Expand Down
15 changes: 15 additions & 0 deletions ratelimit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,21 @@ func TestInitial(t *testing.T) {
}
}

func TestImmediateSlackReapply(t *testing.T) {
t.Parallel()
rl := New(1, Per(time.Second), WithSlack(1))
rl.Take() // we take one immediately
time.Sleep(2 * time.Second) // waiting for slack to accumulate
start := time.Now()
for i := 0; i < 5; i++ {
rl.Take() // consume 2 immediately and then 1 every second after it
// sleep 1ns for now-timeOfNextPermissionIssue != int64(t.maxSlack)
time.Sleep(1 * time.Nanosecond)
}

assert.Condition(t, func() bool { return time.Since(start) > 3*time.Second }, "too fast consumption: %v", time.Since(start))
}

func TestSlack(t *testing.T) {
t.Parallel()
// To simulate slack, we combine two limiters.
Expand Down