Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for contexts during infinite attempts #61

Merged
merged 1 commit into from
Jun 10, 2022
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
7 changes: 5 additions & 2 deletions retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,11 @@ func Do(retryableFunc RetryableFunc, opts ...Option) error {
n++

config.onRetry(n, err)

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

return nil
Expand Down
39 changes: 39 additions & 0 deletions retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -359,4 +359,43 @@ func TestContext(t *testing.T) {

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

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())

retrySum := 0
err := Do(
func() error { return errors.New("test") },
OnRetry(func(n uint, err error) {
fmt.Println(n)
retrySum += 1
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:
}

})
}