Skip to content

Commit

Permalink
Update example to include a withoutSlack option (#96)
Browse files Browse the repository at this point in the history
In #90 @twelsh-aw found a bug in a new implementation. This turned out
to be caused by us mocking time.

Since time mocking will always have some risks this diff proposes
to expand the `examples` we're using - since they use "real" time
they should be good enough to cover most basic cases like #90.

In particular:
- we add a "withoutSlack" test so that the exact case reported in #90
  doesn't happen. No slack option seems common enough to add it.
- updates "withSlack" example to actually show how slack operates.
  Due to non-even execution times I'm forced to round the time a bit.

Possible issues:
- test stability: I re-run the test a 1000 times without issues - the
  timing seems to be stable.
- test duration: in total we're extending the examples by 5ms, which
  shouldn't be human noticeable.
  • Loading branch information
rabbbit committed Jul 7, 2022
1 parent 783ade2 commit 29ac3a2
Showing 1 changed file with 29 additions and 6 deletions.
35 changes: 29 additions & 6 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,38 @@ import (
"go.uber.org/ratelimit"
)

func Example() {
rl := ratelimit.New(100) // per second
func Example_default() {
rl := ratelimit.New(100) // per second, some slack.

rl.Take() // Initialize.
time.Sleep(time.Millisecond * 45) // Let some time pass.

prev := time.Now()
for i := 0; i < 10; i++ {
now := rl.Take()
if i > 0 {
fmt.Println(i, now.Sub(prev).Round(time.Millisecond*2))
}
prev = now
}

// Output:
// 1 0s
// 2 0s
// 3 0s
// 4 4ms
// 5 10ms
// 6 10ms
// 7 10ms
// 8 10ms
// 9 10ms
}

func Example_withoutSlack() {
rl := ratelimit.New(100, ratelimit.WithoutSlack) // per second, no slack.

prev := time.Now()
for i := 0; i < 6; i++ {
now := rl.Take()
if i > 0 {
fmt.Println(i, now.Sub(prev))
Expand All @@ -25,8 +52,4 @@ func Example() {
// 3 10ms
// 4 10ms
// 5 10ms
// 6 10ms
// 7 10ms
// 8 10ms
// 9 10ms
}

0 comments on commit 29ac3a2

Please sign in to comment.