-
Notifications
You must be signed in to change notification settings - Fork 0
/
retry.go
103 lines (85 loc) · 2.82 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Copyright 2024 itpey
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package retry
import (
"context"
"errors"
"time"
"github.com/bytedance/gopkg/lang/fastrand"
)
// Retry holds the configuration for retrying operations.
type Retry struct {
cfg Config
}
// New creates a new Retry instance with default settings.
func New(config ...Config) *Retry {
// Set default config
cfg := configDefault(config...)
return &Retry{
cfg: cfg,
}
}
// Do retries the provided function asynchronously until it either succeeds (returns nil error),
// decides not to retry (returns false), or reaches the maximum number of retries if specified.
func (r *Retry) Do(ctx context.Context, fn func() error) error {
maxRetries := r.cfg.MaxAttemptTimes
initialBackoff := r.cfg.InitialBackoff
maxBackoff := r.cfg.MaxBackoff
maxJitter := r.cfg.MaxJitter
backoff := initialBackoff
timer := time.NewTimer(0) // Initialize a timer
defer timer.Stop()
for attempt := uint(1); ; attempt++ {
select {
case <-ctx.Done():
return ctx.Err() // Context cancelled or deadline exceeded
case <-timer.C:
// Proceed with retry attempt
}
err := fn()
if err == nil {
return nil // Success, no error
}
if attempt >= maxRetries {
return errors.New("exceeded retry limit") // Exceeded max retries
}
// Calculate next backoff duration
backoff = calculateBackoff(backoff, maxBackoff, maxJitter)
timer.Reset(backoff) // Reset the timer for the next backoff duration
}
}
// calculateBackoff calculates the next backoff duration using truncated binary exponential backoff with jitter.
func calculateBackoff(backoff, maxBackoff, maxJitter time.Duration) time.Duration {
if backoff <= 0 {
return 0 * time.Millisecond
}
// Double the backoff duration
backoff *= 2
// Ensure the backoff duration does not exceed the maximum allowed
if maxBackoff > 0 && backoff > maxBackoff {
return maxBackoff
}
// Calculate jitter
if maxJitter > 0 {
// Generate random jitter within [0, jitter)
jitterValue := time.Duration(fastrand.Int63n(int64(maxJitter)))
// Apply jitter to the backoff duration
backoff += jitterValue
}
return backoff
}
// IsMaxRetriesError checks if the error indicates that the maximum number of retries has been reached.
func IsMaxRetriesError(err error) bool {
return err != nil && err.Error() == "exceeded retry limit"
}