-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add retry with backoff function
- Loading branch information
Showing
4 changed files
with
67 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package algorithms | ||
|
||
import ( | ||
"time" | ||
|
||
"github.com/cenkalti/backoff" | ||
) | ||
|
||
func Retry(op func() error, maxTries uint64) (err error) { | ||
b := backoff.NewExponentialBackOff() | ||
br := withMaxRetries(b, maxTries) | ||
return backoff.Retry(op, br) | ||
} | ||
|
||
func withMaxRetries(b backoff.BackOff, max uint64) backoff.BackOff { | ||
return &backOffTries{delegate: b, maxTries: max} | ||
} | ||
|
||
type backOffTries struct { | ||
delegate backoff.BackOff | ||
maxTries uint64 | ||
numTries uint64 | ||
} | ||
|
||
func (b *backOffTries) NextBackOff() time.Duration { | ||
if b.maxTries > 0 { | ||
b.numTries++ | ||
if b.maxTries <= b.numTries { | ||
return backoff.Stop | ||
} | ||
} | ||
return b.delegate.NextBackOff() | ||
} | ||
|
||
func (b *backOffTries) Reset() { | ||
b.numTries = 0 | ||
b.delegate.Reset() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
package algorithms | ||
|
||
import ( | ||
"fmt" | ||
"github.com/stretchr/testify/assert" | ||
"testing" | ||
) | ||
|
||
func TestRetryAlwaysFails(t *testing.T) { | ||
var counter int | ||
err := Retry(func() error { | ||
counter++ | ||
return fmt.Errorf("some error") | ||
}, 2) | ||
|
||
assert.Error(t, err, "expected error") | ||
assert.Equal(t, "some error", err.Error()) | ||
assert.Equal(t, counter, 2) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters