|
|
|
@ -2,7 +2,6 @@ package fx
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"errors"
|
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
"github.com/zeromicro/go-zero/core/errorx"
|
|
|
|
@ -10,8 +9,6 @@ import (
|
|
|
|
|
|
|
|
|
|
const defaultRetryTimes = 3
|
|
|
|
|
|
|
|
|
|
var errTimeout = errors.New("retry timeout")
|
|
|
|
|
|
|
|
|
|
type (
|
|
|
|
|
// RetryOption defines the method to customize DoWithRetry.
|
|
|
|
|
RetryOption func(*retryOptions)
|
|
|
|
@ -28,7 +25,7 @@ type (
|
|
|
|
|
// and performs modification operations, it is best to lock them,
|
|
|
|
|
// otherwise there may be data race issues
|
|
|
|
|
func DoWithRetry(fn func() error, opts ...RetryOption) error {
|
|
|
|
|
return retry(func(errChan chan error, retryCount int) {
|
|
|
|
|
return retry(context.Background(), func(errChan chan error, retryCount int) {
|
|
|
|
|
errChan <- fn()
|
|
|
|
|
}, opts...)
|
|
|
|
|
}
|
|
|
|
@ -40,12 +37,12 @@ func DoWithRetry(fn func() error, opts ...RetryOption) error {
|
|
|
|
|
// otherwise there may be data race issues
|
|
|
|
|
func DoWithRetryCtx(ctx context.Context, fn func(ctx context.Context, retryCount int) error,
|
|
|
|
|
opts ...RetryOption) error {
|
|
|
|
|
return retry(func(errChan chan error, retryCount int) {
|
|
|
|
|
return retry(ctx, func(errChan chan error, retryCount int) {
|
|
|
|
|
errChan <- fn(ctx, retryCount)
|
|
|
|
|
}, opts...)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func retry(fn func(errChan chan error, retryCount int), opts ...RetryOption) error {
|
|
|
|
|
func retry(ctx context.Context, fn func(errChan chan error, retryCount int), opts ...RetryOption) error {
|
|
|
|
|
options := newRetryOptions()
|
|
|
|
|
for _, opt := range opts {
|
|
|
|
|
opt(options)
|
|
|
|
@ -53,7 +50,6 @@ func retry(fn func(errChan chan error, retryCount int), opts ...RetryOption) err
|
|
|
|
|
|
|
|
|
|
var berr errorx.BatchError
|
|
|
|
|
var cancelFunc context.CancelFunc
|
|
|
|
|
ctx := context.Background()
|
|
|
|
|
if options.timeout > 0 {
|
|
|
|
|
ctx, cancelFunc = context.WithTimeout(ctx, options.timeout)
|
|
|
|
|
defer cancelFunc()
|
|
|
|
@ -71,14 +67,14 @@ func retry(fn func(errChan chan error, retryCount int), opts ...RetryOption) err
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
berr.Add(errTimeout)
|
|
|
|
|
berr.Add(ctx.Err())
|
|
|
|
|
return berr.Err()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if options.interval > 0 {
|
|
|
|
|
select {
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
berr.Add(errTimeout)
|
|
|
|
|
berr.Add(ctx.Err())
|
|
|
|
|
return berr.Err()
|
|
|
|
|
case <-time.After(options.interval):
|
|
|
|
|
}
|
|
|
|
|