@@ -19,18 +19,49 @@ func (e PermanentError) Is(err error) bool {
1919 return ok
2020}
2121
22+ // Same as Retry only that the functionToRetry can return a value upon correct execution
23+ func RetryWithData [T any ](functionToRetry func () (* T , error ), minDelay uint64 , factor float64 , maxTries uint64 ) (* T , error ) {
24+ i := 0
25+ f := func () (* T , error ) {
26+ val , err := functionToRetry ()
27+ i ++
28+ if perm , ok := err .(PermanentError ); err != nil && ok {
29+ return nil , backoff .Permanent (perm .Inner )
30+ }
31+ return val , err
32+ }
33+
34+ randomOption := backoff .WithRandomizationFactor (0 )
35+
36+ initialRetryOption := backoff .WithInitialInterval (time .Millisecond * time .Duration (minDelay ))
37+ multiplierOption := backoff .WithMultiplier (factor )
38+ expBackoff := backoff .NewExponentialBackOff (randomOption , multiplierOption , initialRetryOption )
39+ var maxRetriesBackoff backoff.BackOff
40+
41+ if maxTries > 0 {
42+ maxRetriesBackoff = backoff .WithMaxRetries (expBackoff , maxTries )
43+ } else {
44+ maxRetriesBackoff = expBackoff
45+ }
46+
47+ return backoff .RetryWithData (f , maxRetriesBackoff )
48+ }
49+
2250// Retries a given function in an exponential backoff manner.
23- // It will retry calling the function while it returns an error, until the max retries
51+ // It will retry calling the function while it returns an error, until the max retries.
52+ // If maxTries == 0 then the retry function will run indefinitely until success
2453// from the configuration are reached, or until a `PermanentError` is returned.
2554// The function to be retried should return `PermanentError` when the condition for stop retrying
2655// is met.
27- func Retry (functionToRetry func () (interface {}, error ), minDelay uint64 , factor float64 , maxTries uint64 ) (interface {}, error ) {
28- f := func () (interface {}, error ) {
29- val , err := functionToRetry ()
56+ func Retry (functionToRetry func () error , minDelay uint64 , factor float64 , maxTries uint64 ) error {
57+ i := 0
58+ f := func () error {
59+ err := functionToRetry ()
60+ i ++
3061 if perm , ok := err .(PermanentError ); err != nil && ok {
31- return nil , backoff .Permanent (perm .Inner )
62+ return backoff .Permanent (perm .Inner )
3263 }
33- return val , err
64+ return err
3465 }
3566
3667 randomOption := backoff .WithRandomizationFactor (0 )
@@ -40,5 +71,5 @@ func Retry(functionToRetry func() (interface{}, error), minDelay uint64, factor
4071 expBackoff := backoff .NewExponentialBackOff (randomOption , multiplierOption , initialRetryOption )
4172 maxRetriesBackoff := backoff .WithMaxRetries (expBackoff , maxTries )
4273
43- return backoff .RetryWithData (f , maxRetriesBackoff )
74+ return backoff .Retry (f , maxRetriesBackoff )
4475}
0 commit comments