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

add Wait and WaitCtx convenience functions #1

Merged
merged 1 commit into from
Aug 7, 2023
Merged
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
31 changes: 30 additions & 1 deletion token_bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package tokenbucket

import (
"context"
"time"
)

Expand Down Expand Up @@ -50,7 +51,8 @@ func (tb *TokenBucket) Init(rate TokensPerSecond, burst Tokens) {
})
}

// Init the token bucket with a custom "Now" fuction.
// Init the token bucket with a custom "Now" function.
// Note that Wait/WaitCtx cannot be used with a custom time function.
func (tb *TokenBucket) InitWithNowFn(rate TokensPerSecond, burst Tokens, nowFn func() time.Time) {
*tb = TokenBucket{
rate: rate,
Expand Down Expand Up @@ -137,6 +139,33 @@ func (tb *TokenBucket) TryToFulfill(amount Tokens) (fulfilled bool, tryAgainAfte
return true, 0
}

// Wait removes the given amount, waiting as long as necessary.
func (tb *TokenBucket) Wait(amount Tokens) {
Copy link
Member

Choose a reason for hiding this comment

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

Is Wait equivalent to WaitCtx(context.Background(), amount)? Is it worth expressing it like that, or are you concerned about the added cost of the context accesses?

Copy link
Member Author

Choose a reason for hiding this comment

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

Good point, I removed the no-context version.

Copy link
Member

Choose a reason for hiding this comment

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

Oh, I wasn't saying to remove it, I was just suggesting that you could implement Wait as WaitCtx(context.Background(), amount). But this works too.

Copy link
Member Author

Choose a reason for hiding this comment

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

I was thinking callers can just pass context.Background(). I realized that it is annoying that it returns an error in that case though, added it back.

_ = tb.WaitCtx(context.Background(), amount)
}

// WaitCtx removes the given amount, waiting as long as necessary or until the
// context is canceled.
func (tb *TokenBucket) WaitCtx(ctx context.Context, amount Tokens) error {
// We want to check for context cancelation even if we don't need to wait.
select {
case <-ctx.Done():
return ctx.Err()
default:
}
for {
fulfilled, tryAgainAfter := tb.TryToFulfill(amount)
if fulfilled {
return nil
}
select {
case <-time.After(tryAgainAfter):
case <-ctx.Done():
return ctx.Err()
}
}
}

// Exhausted returns the cumulative duration over which this token bucket was
// exhausted. Exported only for metrics.
func (tb *TokenBucket) Exhausted() time.Duration {
Expand Down
34 changes: 34 additions & 0 deletions token_bucket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
package tokenbucket

import (
"context"
"errors"
"testing"
"time"
)
Expand Down Expand Up @@ -135,3 +137,35 @@ func TestTokenBucket(t *testing.T) {
// the positive.
checkExhausted(initialExhausted + (20+90)*time.Millisecond)
}

func TestWaitCtx(t *testing.T) {
var tb TokenBucket
tb.Init(1, 100)
// Drain the initial tokens.
if fulfilled, _ := tb.TryToFulfill(100); !fulfilled {
t.Fatalf("could not drain initial tokens")
}
waitResult := make(chan error, 1)
ctx, ctxCancel := context.WithCancel(context.Background())
go func() {
// This would take 100 seconds to return unless we cancel the context.
waitResult <- tb.WaitCtx(ctx, 100)
}()

time.Sleep(10 * time.Millisecond)
select {
case <-waitResult:
t.Fatal("WaitCtx terminated unexpectedly")
default:
}

ctxCancel()
select {
case err := <-waitResult:
if err == nil || !errors.Is(err, context.Canceled) {
t.Errorf("unexpected error from WaitCtx: %v", err)
}
case <-time.After(10 * time.Second):
t.Fatalf("WaitCtx did not return after context cancelation")
}
}