Skip to content

Commit

Permalink
Merge pull request #84 from lizhiquan/master
Browse files Browse the repository at this point in the history
fix: zero attempt should return error when the error is either unrecoverable or context error
  • Loading branch information
JaSei authored Feb 8, 2023
2 parents c65eeae + f540612 commit 9ae5a72
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 19 deletions.
6 changes: 5 additions & 1 deletion retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,15 @@ func Do(retryableFunc RetryableFunc, opts ...Option) error {
for err := retryableFunc(); err != nil; err = retryableFunc() {
n++

if !IsRecoverable(err) {
return err
}

config.onRetry(n, err)
select {
case <-config.timer.After(delay(config, n, err)):
case <-config.context.Done():
return nil
return config.context.Err()
}
}

Expand Down
33 changes: 15 additions & 18 deletions retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,18 @@ func TestZeroAttemptsWithoutError(t *testing.T) {
assert.Equal(t, count, 1)
}

func TestZeroAttemptsWithUnrecoverableError(t *testing.T) {
err := Do(
func() error {
return Unrecoverable(assert.AnError)
},
Attempts(0),
MaxDelay(time.Nanosecond),
)
assert.Error(t, err)
assert.Equal(t, Unrecoverable(assert.AnError), err)
}

func TestAttemptsForError(t *testing.T) {
count := uint(0)
testErr := os.ErrInvalid
Expand Down Expand Up @@ -395,9 +407,6 @@ func TestContext(t *testing.T) {
})

t.Run("cancel in retry progress - infinite attempts", func(t *testing.T) {
testFailedInRetry := make(chan bool)
testEnded := make(chan bool)

go func() {
ctx, cancel := context.WithCancel(context.Background())

Expand All @@ -410,27 +419,15 @@ func TestContext(t *testing.T) {
if retrySum > 1 {
cancel()
}

if retrySum > 2 {
testFailedInRetry <- true
}

}),
Context(ctx),
Attempts(0),
)

assert.NoError(t, err, "infinite attempts should not report error")
assert.Error(t, ctx.Err(), "immediately canceled after context cancel called")
testEnded <- true
}()

select {
case <-testFailedInRetry:
t.Error("Test ran longer than expected, cancel did not work")
case <-testEnded:
}
assert.Equal(t, context.Canceled, err)

assert.Equal(t, 2, retrySum, "called at most once")
}()
})
}

Expand Down

0 comments on commit 9ae5a72

Please sign in to comment.