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

Change backoff semantics in case of initialBackoff #186

Merged
merged 3 commits into from
Jun 9, 2020
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
10 changes: 10 additions & 0 deletions retry/retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ func WithMaxAttempts(maxAttempts int) Option {
// WithInitialBackoff sets initial backoff.
//
// If initial backoff option is not used, then default value of 50 milliseconds is used.
// If initial backoff is larger than max backoff, it takes precedence.
func WithInitialBackoff(initialBackoff time.Duration) Option {
return func(o *options) {
o.initialBackoff = initialBackoff
Expand Down Expand Up @@ -180,6 +181,8 @@ func Start(ctx context.Context, opts ...Option) Retrier {
for _, option := range opts {
option(&r.options)
}
// If initial backoff is larger than max backoff, it takes precedence.
r.options.maxBackoff = max(r.options.maxBackoff, r.options.initialBackoff)
r.Reset()
return r
}
Expand Down Expand Up @@ -259,3 +262,10 @@ func (r retrier) retryIn() time.Duration {
func (r retrier) CurrentAttempt() int {
return r.currentAttempt
}

func max(a, b time.Duration) time.Duration {
if a > b {
return a
}
return b
}
19 changes: 19 additions & 0 deletions retry/retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,25 @@ func TestRetrier_Next_WithMaxBackoff(t *testing.T) {
}
}

func TestRetrier_Next_WithInitialBackoffLargerThanMax(t *testing.T) {
const initialBackoff = time.Second * 5
const maxBackoff = time.Second * 2

options := []Option{
WithInitialBackoff(initialBackoff),
WithMaxBackoff(maxBackoff),
WithMultiplier(2),
WithMaxAttempts(11),
WithRandomizationFactor(0),
}

r := Start(context.Background(), options...).(*retrier)
d := r.retryIn()
if d != initialBackoff {
t.Fatalf("expected initial backoff to be used: %s vs %s", d, initialBackoff)
}
}

func TestRetrier_Next_WithMaxAttempts(t *testing.T) {
const maxAttempts = 2

Expand Down