Skip to content

Commit

Permalink
refine backoff
Browse files Browse the repository at this point in the history
Signed-off-by: husharp <[email protected]>
  • Loading branch information
HuSharp committed Aug 28, 2023
1 parent d9a6ff4 commit 6e9d931
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
15 changes: 10 additions & 5 deletions client/retry/backoff.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,17 @@ import (
"context"
"time"

"github.com/pingcap/log"

"github.com/pingcap/failpoint"
"go.uber.org/multierr"
)

// BackOffer is a backoff policy for retrying operations.
type BackOffer struct {
maxBackoff time.Duration
nextBackoff time.Duration
maxBackoff time.Duration
nextBackoff time.Duration
initialBackoff time.Duration
}

// WithBackoff is a helper function to add backoff.
Expand All @@ -40,6 +43,7 @@ func WithBackoff(
allErrors = multierr.Append(allErrors, err)
select {
case <-ctx.Done():
log.Info("context done")
return allErrors
case <-time.After(bo.NextBackoff()):
failpoint.Inject("backOffExecute", func() {
Expand All @@ -56,8 +60,9 @@ func WithBackoff(
// InitialBackOffer make the initial state for retrying.
func InitialBackOffer(initialBackoff, maxBackoff time.Duration) BackOffer {
return BackOffer{
maxBackoff: maxBackoff,
nextBackoff: initialBackoff,
maxBackoff: maxBackoff,
initialBackoff: initialBackoff,
nextBackoff: initialBackoff,
}
}

Expand All @@ -78,7 +83,7 @@ func (rs *BackOffer) ExponentialBackoff() time.Duration {

// ResetBackoff reset the backoff to initial state.
func (rs *BackOffer) ResetBackoff() {
rs.nextBackoff = 0
rs.nextBackoff = rs.initialBackoff
}

// Only used for test.
Expand Down
7 changes: 4 additions & 3 deletions client/retry/backoff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import (
"testing"
"time"

"github.com/pingcap/errors"

"github.com/stretchr/testify/require"
)

Expand All @@ -40,8 +42,7 @@ func TestExponentialBackoff(t *testing.T) {
// Reset backoff
backoff.ResetBackoff()
err := WithBackoff(context.Background(), func() error {
return nil
return errors.New("test")
}, &backoff)
re.Nil(err)

re.NotNil(err)
}

0 comments on commit 6e9d931

Please sign in to comment.