-
Notifications
You must be signed in to change notification settings - Fork 71
/
retry.go
76 lines (63 loc) · 1.45 KB
/
retry.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package utils
import (
"context"
"time"
nrErrors "github.com/newrelic/newrelic-client-go/v2/pkg/errors"
)
type RetryContext struct {
RetryCount int
Errors []error
Success bool
Canceled bool
}
func (c *RetryContext) MostRecentError() error {
if len(c.Errors) > 0 {
return c.Errors[len(c.Errors)-1]
}
return nil
}
type Retry struct {
MaxRetries int
retryDelayMs int
RetryFunc func() error
}
func NewRetry(maxRetries int, retryDelayMs int, retryFunc func() error) *Retry {
return &Retry{
MaxRetries: maxRetries,
retryDelayMs: retryDelayMs,
RetryFunc: retryFunc,
}
}
func (r *Retry) ExecWithRetries(ctx context.Context) *RetryContext {
retryCtx := RetryContext{}
for !retryCtx.Success {
retryCtx.RetryCount++
if err := r.RetryFunc(); err != nil {
if _, ok := err.(*nrErrors.PaymentRequiredError); ok {
retryCtx.Success = false
retryCtx.Errors = append(retryCtx.Errors, err)
return &retryCtx
}
retryCtx.Errors = append(retryCtx.Errors, err)
if retryCtx.RetryCount == r.MaxRetries {
retryCtx.Success = false
return &retryCtx
}
w := make(chan struct{}, 1)
go func() {
time.Sleep(time.Duration(r.retryDelayMs) * time.Millisecond)
w <- struct{}{}
}()
select {
case <-ctx.Done():
retryCtx.Canceled = true
retryCtx.Errors = append(retryCtx.Errors, context.Canceled)
return &retryCtx
case <-w:
}
} else {
retryCtx.Success = true
}
}
return &retryCtx
}