Documentation
¶
Overview ¶
Package ratelimit implements a reserving token bucket.
A caller takes its tokens at once, letting the balance go negative, and then sleeps until the debt is repaid. Callers are therefore served in arrival order, and an expensive request cannot be starved by a stream of cheap ones.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ErrStopped = errors.New("ratelimit: stopped")
ErrStopped is returned by Wait when its stop channel is closed.
Functions ¶
This section is empty.
Types ¶
type Bucket ¶
type Bucket struct {
// contains filtered or unexported fields
}
Bucket is a reserving token bucket. It is safe for concurrent use.
func (*Bucket) SetTokens ¶
SetTokens sets the balance. It exists for tests that need a bucket in a given state.
func (*Bucket) Tokens ¶
Tokens returns the current balance, negative while tokens are reserved ahead of the refill.
func (*Bucket) Wait ¶
Wait reserves n tokens and blocks until they are available. A cost above the bucket size is capped at it.
If the wait would end after ctx's deadline, Wait fails at once without reserving anything. If ctx ends or stop is closed while waiting, the reservation is returned and ctx's error (or ErrStopped) is reported. A nil stop channel never fires.