-
Notifications
You must be signed in to change notification settings - Fork 5
/
retrymanager.go
75 lines (64 loc) · 1.41 KB
/
retrymanager.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
package gocbcorex
import (
"context"
"errors"
"time"
)
type RetryController interface {
ShouldRetry(ctx context.Context, err error) (time.Duration, bool, error)
}
type RetryManager interface {
NewRetryController() RetryController
}
func OrchestrateRetries[RespT any](
ctx context.Context,
rs RetryManager,
fn func() (RespT, error),
) (RespT, error) {
var opRetryController RetryController
var lastErr error
for {
res, err := fn()
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return res, retrierDeadlineError{err, lastErr}
}
if opRetryController == nil {
opRetryController = rs.NewRetryController()
}
retryTime, shouldRetry, orchErr := opRetryController.ShouldRetry(ctx, err)
if orchErr != nil {
return res, &RetryOrchestrationError{
Cause: orchErr,
OriginalCause: err,
}
}
if shouldRetry {
select {
case <-time.After(retryTime):
case <-ctx.Done():
ctxErr := ctx.Err()
if errors.Is(ctxErr, context.DeadlineExceeded) {
return res, retrierDeadlineError{ctxErr, err}
} else {
return res, err
}
}
lastErr = err
continue
}
return res, err
}
return res, nil
}
}
func OrchestrateNoResponseRetries(
ctx context.Context,
rs RetryManager,
fn func() error,
) error {
_, err := OrchestrateRetries[struct{}](ctx, rs, func() (struct{}, error) {
return struct{}{}, fn()
})
return err
}