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

Handle context cancellations in retry middleware #32

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
8 changes: 7 additions & 1 deletion retry/retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package retry

import (
"context"
"github.com/slok/goresilience/errors"
"math"
"math/rand"
"time"
Expand Down Expand Up @@ -52,7 +53,7 @@ func NewMiddleware(cfg Config) goresilience.Middleware {
var err error
metricsRecorder, _ := metrics.RecorderFromContext(ctx)

// Start the attemps. (it's 1 + the number of retries.)
// Start the attempts. (it's 1 + the number of retries.)
for i := 0; i <= cfg.Times; i++ {
// Only measure the retries.
if i != 0 {
Expand All @@ -64,6 +65,11 @@ func NewMiddleware(cfg Config) goresilience.Middleware {
return nil
}

// If the context is cancelled no retry will succeed
if err == errors.ErrContextCanceled {
return err
}

// We need to sleep before making a retry.
waitDuration := cfg.WaitBase

Expand Down
26 changes: 26 additions & 0 deletions retry/retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"context"
"errors"
"fmt"
goresilienceerrors "github.com/slok/goresilience/errors"
"math"
"testing"
"time"

Expand Down Expand Up @@ -193,3 +195,27 @@ func TestBackoffJitterRetry(t *testing.T) {
})
}
}

func TestRetryWithContextCancel(t *testing.T) {
t.Run("Context is cancelled pre-execution", func(t *testing.T) {
assert := assert.New(t)
ctx, cancel := context.WithCancel(context.TODO())
cancel()
exec := retry.New(retry.Config{Times: math.MaxInt32})
err := exec.Run(ctx, func(ctx context.Context) error {
return fmt.Errorf("test error")
})
assert.EqualError(err, goresilienceerrors.ErrContextCanceled.Error())
})

t.Run("Context is cancel after deadline", func(t *testing.T) {
assert := assert.New(t)
ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Nanosecond)
defer cancel()
exec := retry.New(retry.Config{Times: math.MaxInt32})
err := exec.Run(ctx, func(ctx context.Context) error {
return fmt.Errorf("test error")
})
assert.EqualError(err, goresilienceerrors.ErrContextCanceled.Error())
})
}