Skip to content

Commit

Permalink
Allow configuring custom slack (#64)
Browse files Browse the repository at this point in the history
Resolves #20

This is to allow people to configure custom slack - we previously
defaulted to 10, and only allowed to disable it.

The tests are a bit painful to read, I had a stab at generating
the same set of tests for both with, and without per, but that was
even more hard to read.
  • Loading branch information
rabbbit authored Mar 3, 2021
1 parent a30c09a commit 4e70b7f
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
7 changes: 7 additions & 0 deletions ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,13 @@ func (o slackOption) apply(c *config) {
// previously "unspent" requests for future bursts of traffic.
var WithoutSlack Option = slackOption(0)

// WithSlack configures custom slack.
// Slack allows the limiter to accumulate "unspent" requests
// for future bursts of traffic.
func WithSlack(slack int) Option {
return slackOption(slack)
}

type perOption time.Duration

func (p perOption) apply(c *config) {
Expand Down
40 changes: 38 additions & 2 deletions ratelimit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,6 @@ func TestSlack(t *testing.T) {
// - faster limiter running for 1 second
// - slack accumulated by the faster limiter during the two seconds.
// it was blocked by slower limiter.

tests := []struct {
msg string
opt []Option
Expand All @@ -213,12 +212,50 @@ func TestSlack(t *testing.T) {
// 2*10 + 1*100 + 1*10 (slack)
want: 130,
},
{
msg: "slack of 10, like default",
opt: []Option{WithSlack(10)},
// 2*10 + 1*100 + 1*10 (slack)
want: 130,
},
{
msg: "slack of 20",
opt: []Option{WithSlack(20)},
// 2*10 + 1*100 + 1*20 (slack)
want: 140,
},
{
// Note this is bigger then the rate of the limiter.
msg: "slack of 150",
opt: []Option{WithSlack(150)},
// 2*10 + 1*100 + 1*150 (slack)
want: 270,
},
{
msg: "no option, defaults to 10, with per",
// 2*(10*2) + 1*(100*2) + 1*10 (slack)
opt: []Option{Per(500 * time.Millisecond)},
want: 230,
},
{
msg: "slack of 10, like default, with per",
opt: []Option{WithSlack(10), Per(500 * time.Millisecond)},
// 2*(10*2) + 1*(100*2) + 1*10 (slack)
want: 230,
},
{
msg: "slack of 20, with per",
opt: []Option{WithSlack(20), Per(500 * time.Millisecond)},
// 2*(10*2) + 1*(100*2) + 1*20 (slack)
want: 240,
},
{
// Note this is bigger then the rate of the limiter.
msg: "slack of 150, with per",
opt: []Option{WithSlack(150), Per(500 * time.Millisecond)},
// 2*(10*2) + 1*(100*2) + 1*150 (slack)
want: 370,
},
}

for _, tt := range tests {
Expand All @@ -240,5 +277,4 @@ func TestSlack(t *testing.T) {
})
})
}

}

0 comments on commit 4e70b7f

Please sign in to comment.