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

rate: add limiter sentinel errors #15

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
15 changes: 13 additions & 2 deletions rate/rate.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package rate

import (
"context"
"errors"
"fmt"
"math"
"sync"
Expand All @@ -29,6 +30,16 @@ func Every(interval time.Duration) Limit {
return 1 / Limit(interval.Seconds())
}

var (
// ErrExceedsBurst is returned when the limiter's burst is exceeded. The
// error is wrapped with additional context.
ErrExceedsBurst = errors.New("exceeds limiter's burst")

// ErrWouldExceedDeadline is returned when the limiter's deadline would be
// exceeded. The error is wrapped with additional context.
ErrWouldExceedDeadline = errors.New("would exceed context deadline")
)

// A Limiter controls how frequently events are allowed to happen.
// It implements a "token bucket" of size b, initially full and refilled
// at rate r tokens per second.
Expand Down Expand Up @@ -230,7 +241,7 @@ func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) {
lim.mu.Unlock()

if n > burst && limit != Inf {
return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, burst)
return fmt.Errorf("rate: Wait(n=%d) %w %d", n, ErrExceedsBurst, burst)
}
// Check if ctx is already cancelled
select {
Expand All @@ -247,7 +258,7 @@ func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) {
// Reserve
r := lim.reserveN(now, n, waitLimit)
if !r.ok {
return fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n)
return fmt.Errorf("rate: Wait(n=%d) %w", n, ErrWouldExceedDeadline)
}
// Wait if necessary
delay := r.DelayFrom(now)
Expand Down