-
Notifications
You must be signed in to change notification settings - Fork 2
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
Conversation
CC @RahulAggarwal1016 |
@@ -137,6 +139,39 @@ 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) { |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
token_bucket_test.go
Outdated
ctxCancel() | ||
select { | ||
case err := <-waitResult: | ||
if err == nil || !strings.Contains(err.Error(), "context canceled") { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: can we replace the string comparison with errors.Is(err, context.Canceled)
?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM, with or without Wait
.
The common usage for `TryToFulfill` is to sleep in a loop. This code adds a convenience `Wait` method and a corresponding `WaitCtx` which respects context cancelation.
TFTR! |
The common usage for
TryToFulfill
is to sleep in a loop. This code adds a convenienceWait
method and a correspondingWaitCtx
which respects context cancelation.