Skip to content

Commit f540612

Browse files
committed
fix: zero attempt should return error when the error is either unrecoverable or context error
1 parent c65eeae commit f540612

File tree

2 files changed

+20
-19
lines changed

2 files changed

+20
-19
lines changed

retry.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,11 +99,15 @@ func Do(retryableFunc RetryableFunc, opts ...Option) error {
9999
for err := retryableFunc(); err != nil; err = retryableFunc() {
100100
n++
101101

102+
if !IsRecoverable(err) {
103+
return err
104+
}
105+
102106
config.onRetry(n, err)
103107
select {
104108
case <-config.timer.After(delay(config, n, err)):
105109
case <-config.context.Done():
106-
return nil
110+
return config.context.Err()
107111
}
108112
}
109113

retry_test.go

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,18 @@ func TestZeroAttemptsWithoutError(t *testing.T) {
112112
assert.Equal(t, count, 1)
113113
}
114114

115+
func TestZeroAttemptsWithUnrecoverableError(t *testing.T) {
116+
err := Do(
117+
func() error {
118+
return Unrecoverable(assert.AnError)
119+
},
120+
Attempts(0),
121+
MaxDelay(time.Nanosecond),
122+
)
123+
assert.Error(t, err)
124+
assert.Equal(t, Unrecoverable(assert.AnError), err)
125+
}
126+
115127
func TestAttemptsForError(t *testing.T) {
116128
count := uint(0)
117129
testErr := os.ErrInvalid
@@ -395,9 +407,6 @@ func TestContext(t *testing.T) {
395407
})
396408

397409
t.Run("cancel in retry progress - infinite attempts", func(t *testing.T) {
398-
testFailedInRetry := make(chan bool)
399-
testEnded := make(chan bool)
400-
401410
go func() {
402411
ctx, cancel := context.WithCancel(context.Background())
403412

@@ -410,27 +419,15 @@ func TestContext(t *testing.T) {
410419
if retrySum > 1 {
411420
cancel()
412421
}
413-
414-
if retrySum > 2 {
415-
testFailedInRetry <- true
416-
}
417-
418422
}),
419423
Context(ctx),
420424
Attempts(0),
421425
)
422426

423-
assert.NoError(t, err, "infinite attempts should not report error")
424-
assert.Error(t, ctx.Err(), "immediately canceled after context cancel called")
425-
testEnded <- true
426-
}()
427-
428-
select {
429-
case <-testFailedInRetry:
430-
t.Error("Test ran longer than expected, cancel did not work")
431-
case <-testEnded:
432-
}
427+
assert.Equal(t, context.Canceled, err)
433428

429+
assert.Equal(t, 2, retrySum, "called at most once")
430+
}()
434431
})
435432
}
436433

0 commit comments

Comments
 (0)