From 45113e62e34190a9264e8d826469178e655fe3b6 Mon Sep 17 00:00:00 2001 From: Bryan Hanner Date: Tue, 28 Jul 2020 15:04:23 -0700 Subject: [PATCH] stop overriding max backoff when none is set (#189) --- retry/retry.go | 9 ++++++--- retry/retry_test.go | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/retry/retry.go b/retry/retry.go index d468ccae..88ef54e6 100644 --- a/retry/retry.go +++ b/retry/retry.go @@ -124,7 +124,8 @@ 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. +// If initial backoff is larger than max backoff and the max backoff is nonzero, the initial backoff will be +// used as the max. func WithInitialBackoff(initialBackoff time.Duration) Option { return func(o *options) { o.initialBackoff = initialBackoff @@ -181,8 +182,10 @@ 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) + // If initial backoff is larger than max backoff and the max backoff is set, initial takes precedence. + if r.options.maxBackoff != 0 { + r.options.maxBackoff = max(r.options.maxBackoff, r.options.initialBackoff) + } r.Reset() return r } diff --git a/retry/retry_test.go b/retry/retry_test.go index eb584455..870ff131 100644 --- a/retry/retry_test.go +++ b/retry/retry_test.go @@ -97,6 +97,27 @@ func TestRetrier_Next_WithInitialBackoffLargerThanMax(t *testing.T) { } } +func TestRetrier_Next_WithInitialBackoffLargerThanMaxAndMaxNotSet(t *testing.T) { + const initialBackoff = time.Second * 5 + const maxBackoff = 0 + const multiplier = 2 + + options := []Option{ + WithInitialBackoff(initialBackoff), + WithMaxBackoff(maxBackoff), + WithMultiplier(multiplier), + WithMaxAttempts(11), + WithRandomizationFactor(0), + } + + r := Start(context.Background(), options...).(*retrier) + r.currentAttempt = 1 + d := r.retryIn() + if d != initialBackoff*multiplier { + t.Fatalf("expected second attempt to increase backoff: %s vs %s", d, initialBackoff*multiplier) + } +} + func TestRetrier_Next_WithMaxAttempts(t *testing.T) { const maxAttempts = 2