Skip to content

Commit

Permalink
[retry] support pointer Stop error
Browse files Browse the repository at this point in the history
Change-Id: Ie2013aac9ea6950ff47642c6ee54345cf22f3adf
  • Loading branch information
jxskiss committed Oct 10, 2024
1 parent 2d7d854 commit 3c688e4
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
9 changes: 8 additions & 1 deletion utils/retry/retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ func retry(opt options, f func() error, opts ...Option) (r Result) {
if _, ok := err.(Stop); ok {
break
}
if s, ok := err.(*Stop); ok && s != nil {
break
}
// attempts <= 0 means retry forever.
if opt.Attempts > 0 && r.Attempts >= opt.Attempts {
break
Expand Down Expand Up @@ -119,10 +122,14 @@ func retry(opt options, f func() error, opts ...Option) (r Result) {
if err != nil {
if s, ok := err.(Stop); ok {
// Return the original error for later checking.
// Stop error from caller don't count for circuit breaker.
merr.Append(s.Err)
opt.Hook(r.Attempts, s.Err)

} else if s, ok := err.(*Stop); ok && s != nil {
// Return the original error for later checking.
// Stop error from caller don't count for circuit breaker.
merr.Append(s.Err)
opt.Hook(r.Attempts, s.Err)
} else {
merr.Append(err)
opt.Hook(r.Attempts, err)
Expand Down
42 changes: 42 additions & 0 deletions utils/retry/retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,48 @@ func Test_Retry(t *testing.T) {
is.Equal(merrors[2].Error(), "error 1")
}

func Test_Stop(t *testing.T) {
is := assert.New(t)

t.Run("struct Stop", func(t *testing.T) {
fakeErrFunc := fakeErrors(1)
r := Retry(3, 100*time.Millisecond, func() error {
err := fakeErrFunc()
if err != nil {
return err
}
return Stop{Err: fmt.Errorf("stop")}
})
is.True(!r.Ok)
is.Equal(r.Attempts, 2)
merr, ok := r.Error.(*SizedError)
is.True(ok)
merrors := merr.Errors()
is.Equal(len(merrors), 2)
is.Equal(merrors[0].Error(), "stop")
is.Equal(merrors[1].Error(), "error 1")
})

t.Run("pointer of struct Stop", func(t *testing.T) {
fakeErrFunc := fakeErrors(1)
r := Retry(3, 100*time.Millisecond, func() error {
err := fakeErrFunc()
if err != nil {
return err
}
return &Stop{Err: fmt.Errorf("stop")}
})
is.True(!r.Ok)
is.Equal(r.Attempts, 2)
merr, ok := r.Error.(*SizedError)
is.True(ok)
merrors := merr.Errors()
is.Equal(len(merrors), 2)
is.Equal(merrors[0].Error(), "stop")
is.Equal(merrors[1].Error(), "error 1")
})
}

func Test_Hook(t *testing.T) {
is := assert.New(t)
target := fakeErrors(3)
Expand Down

0 comments on commit 3c688e4

Please sign in to comment.