Skip to content
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
37 changes: 5 additions & 32 deletions retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,38 +136,6 @@ func DoWithData[T any](retryableFunc RetryableFuncWithData[T], opts ...Option) (
return emptyT, err
}

// Setting attempts to 0 means we'll retry until we succeed
var lastErr error
if config.attempts == 0 {
for {
t, err := retryableFunc()
if err == nil {
return t, nil
}

if !IsRecoverable(err) {
return emptyT, err
}

if !config.retryIf(err) {
return emptyT, err
}

lastErr = err

config.onRetry(n, err)
n++
select {
case <-config.timer.After(delay(config, n, err)):
case <-config.context.Done():
if config.wrapContextErrorWithLastError {
return emptyT, Error{context.Cause(config.context), lastErr}
}
return emptyT, context.Cause(config.context)
}
}
}

errorLog := Error{}

attemptsForError := make(map[error]uint, len(config.attemptsForError))
Expand All @@ -184,6 +152,10 @@ shouldRetry:

errorLog = append(errorLog, unpackUnrecoverable(err))

if !IsRecoverable(err) {
return emptyT, err
}

if !config.retryIf(err) {
break
}
Expand All @@ -198,6 +170,7 @@ shouldRetry:
}
}

// Setting attempts to 0 means we'll retry until we succeed
// if this is last attempt - don't wait
if n == config.attempts-1 {
break shouldRetry
Expand Down
7 changes: 4 additions & 3 deletions retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ func TestRetryIf_ZeroAttempts(t *testing.T) {
return err.Error() != "special"
}),
Delay(time.Nanosecond),
LastErrorOnly(true),
Attempts(0),
)
assert.Error(t, err)
Expand Down Expand Up @@ -216,16 +217,15 @@ func TestLastErrorOnly(t *testing.T) {
func TestUnrecoverableError(t *testing.T) {
attempts := 0
testErr := errors.New("error")
expectedErr := Error{testErr}
err := Do(
func() error {
attempts++
return Unrecoverable(testErr)
},
Attempts(2),
)
assert.Equal(t, expectedErr, err)
assert.Equal(t, testErr, errors.Unwrap(err))
assert.Error(t, err)
assert.Equal(t, Unrecoverable(testErr), err)
assert.Equal(t, 1, attempts, "unrecoverable error broke the loop")
}

Expand Down Expand Up @@ -465,6 +465,7 @@ func TestContext(t *testing.T) {
cancel()
}
}),
LastErrorOnly(true),
Context(ctx),
Attempts(0),
)
Expand Down