Skip to content

Commit

Permalink
doc for retry
Browse files Browse the repository at this point in the history
  • Loading branch information
DarienRaymond committed Dec 2, 2015
1 parent d45b867 commit e8e6cf1
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
8 changes: 6 additions & 2 deletions common/retry/retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,20 @@ import (
)

var (
RetryFailed = errors.New("All retry attempts failed.")
errorRetryFailed = errors.New("All retry attempts failed.")
)

// Strategy is a way to retry on a specific function.
type Strategy interface {
// On performs a retry on a specific function, until it doesn't return any error.
On(func() error) error
}

type retryer struct {
NextDelay func(int) int
}

// On implements Strategy.On.
func (r *retryer) On(method func() error) error {
attempt := 0
for {
Expand All @@ -26,13 +29,14 @@ func (r *retryer) On(method func() error) error {
}
delay := r.NextDelay(attempt)
if delay < 0 {
return RetryFailed
return errorRetryFailed
}
<-time.After(time.Duration(delay) * time.Millisecond)
attempt++
}
}

// Timed returns a retry strategy with fixed interval.
func Timed(attempts int, delay int) Strategy {
return &retryer{
NextDelay: func(attempt int) int {
Expand Down
10 changes: 5 additions & 5 deletions common/retry/retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
)

var (
TestError = errors.New("This is a fake error.")
errorTestOnly = errors.New("This is a fake error.")
)

func TestNoRetry(t *testing.T) {
Expand All @@ -33,7 +33,7 @@ func TestRetryOnce(t *testing.T) {
err := Timed(10, 1000).On(func() error {
if called == 0 {
called++
return TestError
return errorTestOnly
}
return nil
})
Expand All @@ -51,7 +51,7 @@ func TestRetryMultiple(t *testing.T) {
err := Timed(10, 1000).On(func() error {
if called < 5 {
called++
return TestError
return errorTestOnly
}
return nil
})
Expand All @@ -69,12 +69,12 @@ func TestRetryExhausted(t *testing.T) {
err := Timed(2, 1000).On(func() error {
if called < 5 {
called++
return TestError
return errorTestOnly
}
return nil
})
duration := time.Since(startTime)

assert.Error(err).Equals(RetryFailed)
assert.Error(err).Equals(errorRetryFailed)
assert.Int64(int64(duration / time.Millisecond)).AtLeast(1900)
}

0 comments on commit e8e6cf1

Please sign in to comment.