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
2 changes: 2 additions & 0 deletions retry/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## To be Released

* fix(retry): do not call the method if the context is already done

## v1.4.1

* chore(deps): bump multiple dependencies
Expand Down
8 changes: 8 additions & 0 deletions retry/retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,14 @@ func (r Retryer) Do(ctx context.Context, method Retryable) error {

var err error
for attempt := 0; attempt < r.maxAttempts; attempt++ {
if ctx.Err() != nil {
return RetryError{
Scope: ContextScope,
Err: ctx.Err(),
LastErr: err,
}
}

err = method(ctx)
if err == nil {
return nil
Expand Down
22 changes: 22 additions & 0 deletions retry/retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,28 @@ func TestRetrier(t *testing.T) {
})
})

t.Run("When the context is already canceled, it should not call the method", func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
retrier := New(WithWaitDuration(1 * time.Millisecond))
tries := 0
ctx, cancel := context.WithCancel(t.Context())
cancel()

err := retrier.Do(ctx, func(ctx context.Context) error {
tries++
return nil
})
synctest.Wait()

var retryError RetryError
require.ErrorAs(t, err, &retryError)
assert.Equal(t, ContextScope, retryError.Scope)
require.ErrorIs(t, retryError.Err, context.Canceled)
require.NoError(t, retryError.LastErr)
assert.Equal(t, 0, tries)
})
})

t.Run("With timeout should ignore sleep", func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
retrier := New(WithWaitDuration(1 * time.Second))
Expand Down
Loading