Skip to content
Open
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
21 changes: 18 additions & 3 deletions pkg/backoff/backoff.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package backoff

import (
"context"
"errors"
"time"
)

Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand Down
104 changes: 103 additions & 1 deletion pkg/backoff/backoff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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 {
Expand All @@ -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())
}
10 changes: 8 additions & 2 deletions pkg/backoff/exponential.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand All @@ -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())),
}
}
41 changes: 41 additions & 0 deletions pkg/backoff/exponential_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package backoff

import (
"fmt"
"sync"
"testing"
"time"

Expand All @@ -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)
}
Loading