Skip to content

Commit

Permalink
Add fractional refund test.
Browse files Browse the repository at this point in the history
  • Loading branch information
beautifulentropy committed Jul 20, 2023
1 parent 9ec09f0 commit bb77c0b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
3 changes: 1 addition & 2 deletions ratelimits/gcra.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package ratelimits

import (
"math"
"time"

"github.com/jmhodges/clock"
Expand All @@ -10,7 +9,7 @@ import (
// divThenFloor divides two int64s and returns the floor of the result. This
// This is used to calculate request intervals and costs in nanoseconds.
func divThenFloor(x, y int64) int64 {
return int64(math.Floor(float64(x) / float64(y)))
return int64(float64(x) / float64(y))
}

// maybeSpend uses the GCRA algorithm to decide whether to allow a request. It
Expand Down
17 changes: 17 additions & 0 deletions ratelimits/gcra_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,4 +201,21 @@ func Test_maybeRefund(t *testing.T) {
test.Assert(t, d.Allowed, "should be allowed")
test.AssertEquals(t, d.Remaining, int64(6))
test.AssertEquals(t, d.RetryIn, time.Duration(0))

// Wait, a 2.5 seconds to refill to 8.5 requests.
clk.Add(time.Millisecond * 2500)

// Ensure we have 8.5 requests.
d = maybeSpend(clk, limit, d.newTAT, 0)
test.Assert(t, d.Allowed, "should be allowed")
test.AssertEquals(t, d.Remaining, int64(8))
test.AssertEquals(t, d.RetryIn, time.Duration(0))
// Check that ResetIn represents the fractional earned request.
test.AssertEquals(t, d.ResetIn, time.Millisecond*1500)

// Refund 2 requests, we should only have 10, not 10.5.
d = maybeRefund(clk, limit, d.newTAT, 2)
test.AssertEquals(t, d.Remaining, int64(10))
test.AssertEquals(t, d.RetryIn, time.Duration(0))
test.AssertEquals(t, d.ResetIn, time.Duration(0))
}

0 comments on commit bb77c0b

Please sign in to comment.