diff --git a/pkg/backoff/backoff.go b/pkg/backoff/backoff.go index 855b31a40c..bcdf4e5ca3 100644 --- a/pkg/backoff/backoff.go +++ b/pkg/backoff/backoff.go @@ -16,6 +16,7 @@ package backoff import ( "context" + "errors" "time" ) @@ -32,9 +33,16 @@ func NewError(err error, retriable bool) *Error { } func (e *Error) Error() string { + if e.Err == nil { + return "" + } return e.Err.Error() } +func (e *Error) Unwrap() error { + return e.Err +} + type Backoff interface { Next() time.Duration Calls() int @@ -83,6 +91,7 @@ func (r *retry) WaitNext(ctx context.Context) bool { } t := time.NewTimer(d) + defer t.Stop() select { case <-ctx.Done(): return false @@ -104,11 +113,17 @@ func (r *retry) Do(ctx context.Context, operation func() (any, error)) (any, err if err == nil { return data, nil } - if e, ok := err.(*Error); ok { - err = e.Err - if !e.Retriable { + var bErr *Error + if errors.As(err, &bErr) { + if !bErr.Retriable { + if err == bErr { + return nil, bErr.Err + } return nil, err } + if err == bErr { + err = bErr.Err + } } } if err != nil { diff --git a/pkg/backoff/backoff_test.go b/pkg/backoff/backoff_test.go index 538456dfb8..e0c08da40b 100644 --- a/pkg/backoff/backoff_test.go +++ b/pkg/backoff/backoff_test.go @@ -17,10 +17,12 @@ package backoff import ( "context" "errors" + "fmt" "testing" "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestWaitNext(t *testing.T) { @@ -48,6 +50,29 @@ func TestWaitNextCancel(t *testing.T) { assert.Equal(t, false, ok) } +func TestWaitNext_ContextCancelDuringWait(t *testing.T) { + t.Parallel() + + bo := NewConstant(time.Minute) + r := NewRetry(3, bo) + ctx, cancel := context.WithCancel(context.Background()) + + // First call has 0 delay. + ok := r.WaitNext(ctx) + assert.True(t, ok) + + // Second call waits for 1 minute; cancel context during wait. + go func() { + time.Sleep(10 * time.Millisecond) + cancel() + }() + + start := time.Now() + ok = r.WaitNext(ctx) + assert.False(t, ok) + assert.True(t, time.Since(start) < time.Second) +} + func TestDo(t *testing.T) { var calls int @@ -123,6 +148,26 @@ func TestDo(t *testing.T) { expectedErr: nil, expectedCalls: 2, }, + { + name: "wrapped non-retriable error stops retry", + operation: func() (any, error) { + calls++ + return nil, fmt.Errorf("wrapped: %w", NewError(errors.New("non-retriable"), false)) + }, + expected: nil, + expectedErr: fmt.Errorf("wrapped: %w", NewError(errors.New("non-retriable"), false)), + expectedCalls: 1, + }, + { + name: "wrapped retriable error continues retry", + operation: func() (any, error) { + calls++ + return nil, fmt.Errorf("wrapped: %w", NewError(errors.New("retriable"), true)) + }, + expected: nil, + expectedErr: fmt.Errorf("wrapped: %w", NewError(errors.New("retriable"), true)), + expectedCalls: 3, + }, } for _, tc := range testcases { @@ -142,8 +187,65 @@ func TestDo(t *testing.T) { data, err := r.Do(ctx, tc.operation) assert.Equal(t, tc.expected, data) - assert.Equal(t, tc.expectedErr, err) + if tc.expectedErr != nil { + require.Error(t, err) + assert.Equal(t, tc.expectedErr.Error(), err.Error()) + } else { + assert.NoError(t, err) + } assert.Equal(t, tc.expectedCalls, calls) }) } } + +func TestError_Unwrap(t *testing.T) { + t.Parallel() + + baseErr := errors.New("base error") + bErr := NewError(baseErr, true) + + assert.Equal(t, baseErr, bErr.Unwrap()) + assert.True(t, errors.Is(bErr, baseErr)) + + var target *Error + assert.True(t, errors.As(bErr, &target)) + assert.Equal(t, true, target.Retriable) + + wrapped := fmt.Errorf("outer: %w", bErr) + assert.True(t, errors.Is(wrapped, baseErr)) + var targetFromWrapped *Error + assert.True(t, errors.As(wrapped, &targetFromWrapped)) + assert.Equal(t, true, targetFromWrapped.Retriable) +} + +func TestError_NilErr(t *testing.T) { + t.Parallel() + + bErr := NewError(nil, false) + assert.Equal(t, "", bErr.Error()) + assert.Nil(t, bErr.Unwrap()) +} + +func TestRetry_Calls(t *testing.T) { + t.Parallel() + + r := NewRetry(5, NewConstant(time.Millisecond)) + assert.Equal(t, 0, r.Calls()) + + ctx := context.Background() + r.WaitNext(ctx) + assert.Equal(t, 1, r.Calls()) +} + +func TestConstant_Clone(t *testing.T) { + t.Parallel() + + c := NewConstant(10 * time.Millisecond) + _ = c.Next() + assert.Equal(t, 1, c.Calls()) + + clone := c.Clone() + assert.Equal(t, 0, clone.Calls()) + assert.Equal(t, time.Duration(0), clone.Next()) + assert.Equal(t, 10*time.Millisecond, clone.Next()) +} diff --git a/pkg/backoff/exponential.go b/pkg/backoff/exponential.go index ab45bfebad..7bf80ce212 100644 --- a/pkg/backoff/exponential.go +++ b/pkg/backoff/exponential.go @@ -45,7 +45,13 @@ func (b *exponential) Next() time.Duration { return 0 } d := math.Min(float64(b.max), float64(b.base)*math.Pow(2, float64(b.calls-1))) - d *= b.rand.Float64() + var r float64 + if b.rand != nil { + r = b.rand.Float64() + } else { + r = rand.Float64() + } + d *= r return time.Duration(d) } @@ -61,6 +67,6 @@ func (b *exponential) Clone() Backoff { return &exponential{ base: b.base, max: b.max, - rand: b.rand, + rand: rand.New(rand.NewSource(time.Now().UTC().UnixNano())), } } diff --git a/pkg/backoff/exponential_test.go b/pkg/backoff/exponential_test.go index 16a8f5aaec..181c6e798b 100644 --- a/pkg/backoff/exponential_test.go +++ b/pkg/backoff/exponential_test.go @@ -16,6 +16,7 @@ package backoff import ( "fmt" + "sync" "testing" "time" @@ -40,3 +41,43 @@ func TestExponential(t *testing.T) { eb.Reset() assert.Equal(t, 0, eb.Calls()) } + +func TestExponential_Clone(t *testing.T) { + t.Parallel() + + eb := NewExponential(time.Millisecond, time.Second) + _ = eb.Next() + assert.Equal(t, 1, eb.Calls()) + + clone := eb.Clone() + assert.Equal(t, 0, clone.Calls()) + assert.Equal(t, time.Duration(0), clone.Next()) + assert.Equal(t, 1, clone.Calls()) + + // Verify that clones can be called concurrently without data race. + var wg sync.WaitGroup + for i := 0; i < 10; i++ { + wg.Add(1) + c := eb.Clone() + go func() { + defer wg.Done() + for j := 0; j < 50; j++ { + _ = c.Next() + } + }() + } + wg.Wait() +} + +func TestExponential_NilRand(t *testing.T) { + t.Parallel() + + eb := &exponential{ + base: time.Millisecond, + max: time.Second, + } + assert.Equal(t, time.Duration(0), eb.Next()) + d := eb.Next() + assert.True(t, d >= 0) + assert.True(t, d <= time.Second) +}