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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow last error to be returned with context error #96

Merged
merged 5 commits into from
Aug 7, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 5 additions & 1 deletion .github/workflows/workflow.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
name: Go

on: [push]
on:
push:
pull_request:
branches:
- master
JaSei marked this conversation as resolved.
Show resolved Hide resolved

jobs:
golangci-lint:
Expand Down
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,30 @@ retry.Do(

)

#### func WrapContextErrorWithLastError

```go
func WrapContextErrorWithLastError(wrapContextErrorWithLastError bool) Option
```
WrapContextErrorWithLastError allows the context error to be returned wrapped
with the last error that the retried function returned. This is only applicable
when Attempts is set to 0 to retry indefinitly and when using a context to
cancel / timeout

default is false

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

retry.Do(
func() error {
...
},
retry.Context(ctx),
retry.Attempts(0),
retry.WrapContextErrorWithLastError(true),
)

#### type RetryIfFunc

```go
Expand Down
46 changes: 35 additions & 11 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,18 @@ type Timer interface {
}

type Config struct {
attempts uint
attemptsForError map[error]uint
delay time.Duration
maxDelay time.Duration
maxJitter time.Duration
onRetry OnRetryFunc
retryIf RetryIfFunc
delayType DelayTypeFunc
lastErrorOnly bool
context context.Context
timer Timer
attempts uint
attemptsForError map[error]uint
delay time.Duration
maxDelay time.Duration
maxJitter time.Duration
onRetry OnRetryFunc
retryIf RetryIfFunc
delayType DelayTypeFunc
lastErrorOnly bool
context context.Context
timer Timer
wrapContextErrorWithLastError bool

maxBackOffN uint
}
Expand Down Expand Up @@ -250,3 +251,26 @@ func WithTimer(t Timer) Option {
c.timer = t
}
}

// WrapContextErrorWithLastError allows the context error to be returned wrapped with the last error that the
// retried function returned. This is only applicable when Attempts is set to 0 to retry indefinitly and when
// using a context to cancel / timeout
//
// default is false
//
// ctx, cancel := context.WithCancel(context.Background())
// defer cancel()
//
// retry.Do(
// func() error {
// ...
// },
// retry.Context(ctx),
// retry.Attempts(0),
// retry.WrapContextErrorWithLastError(true),
// )
func WrapContextErrorWithLastError(wrapContextErrorWithLastError bool) Option {
return func(c *Config) {
c.wrapContextErrorWithLastError = wrapContextErrorWithLastError
}
}
6 changes: 6 additions & 0 deletions retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ func Do(retryableFunc RetryableFunc, opts ...Option) error {
}

// Setting attempts to 0 means we'll retry until we succeed
var lastErr error
if config.attempts == 0 {
for err := retryableFunc(); err != nil; err = retryableFunc() {
if !IsRecoverable(err) {
Expand All @@ -105,11 +106,16 @@ func Do(retryableFunc RetryableFunc, opts ...Option) error {
return err
}

lastErr = err

n++
config.onRetry(n, err)
select {
case <-config.timer.After(delay(config, n, err)):
case <-config.context.Done():
if config.wrapContextErrorWithLastError {
return Error{config.context.Err(), lastErr}
}
return config.context.Err()
}
}
Expand Down
39 changes: 39 additions & 0 deletions retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,45 @@ func TestContext(t *testing.T) {
assert.Equal(t, 2, retrySum, "called at most once")
}()
})

t.Run("cancelled on retry infinte attempts - wraps context error with last retried function error", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

retrySum := 0
err := Do(
func() error { return fooErr{str: fmt.Sprintf("error %d", retrySum+1)} },
OnRetry(func(n uint, err error) {
retrySum += 1
if retrySum == 2 {
cancel()
}
}),
Context(ctx),
Attempts(0),
WrapContextErrorWithLastError(true),
)
assert.ErrorIs(t, err, context.Canceled)
assert.ErrorIs(t, err, fooErr{str: "error 2"})
})

t.Run("timed out on retry infinte attempts - wraps context error with last retried function error", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*500)
defer cancel()

retrySum := 0
err := Do(
func() error { return fooErr{str: fmt.Sprintf("error %d", retrySum+1)} },
OnRetry(func(n uint, err error) {
retrySum += 1
}),
Context(ctx),
Attempts(0),
WrapContextErrorWithLastError(true),
)
assert.ErrorIs(t, err, context.DeadlineExceeded)
assert.ErrorIs(t, err, fooErr{str: "error 2"})
})
}

type testTimer struct {
Expand Down