Skip to content

Commit

Permalink
Handle ctx errors in retry
Browse files Browse the repository at this point in the history
  • Loading branch information
swift1337 committed Jul 12, 2024
1 parent 5ff1728 commit 7e96f9d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
13 changes: 9 additions & 4 deletions pkg/retry/retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package retry

import (
"context"
"time"

"github.com/cenkalti/backoff/v4"
Expand Down Expand Up @@ -116,13 +117,17 @@ func DoTypedWithBackoffAndRetry[T any](cb TypedCallback[T], bo Backoff) (T, erro
return DoTypedWithBackoff(wrapper, bo)

Check warning on line 117 in pkg/retry/retry.go

View check run for this annotation

Codecov / codecov/patch

pkg/retry/retry.go#L117

Added line #L117 was not covered by tests
}

// Retry wraps error to mark it as retryable
// Retry wraps error to mark it as retryable. Skips retry for context errors.
func Retry(err error) error {
if err == nil {
switch {
case err == nil:
return nil
case errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded):

Check warning on line 125 in pkg/retry/retry.go

View check run for this annotation

Codecov / codecov/patch

pkg/retry/retry.go#L123-L125

Added lines #L123 - L125 were not covered by tests
// do not retry context errors
return err

Check warning on line 127 in pkg/retry/retry.go

View check run for this annotation

Codecov / codecov/patch

pkg/retry/retry.go#L127

Added line #L127 was not covered by tests
default:
return errRetryable{error: err}
}

return errRetryable{error: err}
}

// RetryTyped wraps error to mark it as retryable
Expand Down
21 changes: 21 additions & 0 deletions pkg/retry/retry_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package retry

import (
"context"
"errors"
"testing"
"time"
Expand Down Expand Up @@ -77,6 +78,26 @@ func TestDo(t *testing.T) {
assert.ErrorContains(t, err, "retry limit exceeded")
})

t.Run("context errors are non-retryable", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()

var counter int
err := Do(func() error {
time.Sleep(100 * time.Millisecond)

if err := ctx.Err(); err != nil {
return err
}

counter++

return nil
})

assert.Equal(t, 0, counter)
assert.ErrorIs(t, err, context.DeadlineExceeded)
})
}

func TestDoTyped(t *testing.T) {
Expand Down

0 comments on commit 7e96f9d

Please sign in to comment.