-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackoff.go
More file actions
274 lines (235 loc) · 6.86 KB
/
Copy pathbackoff.go
File metadata and controls
274 lines (235 loc) · 6.86 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// Package backoff implements backoff logic for loop controls.
package backoff
import (
"context"
"iter"
"math"
"math/rand/v2"
"time"
)
// StepFunc is the signature of the function that
// generates step values for a [Generator].
type StepFunc func(base time.Duration, count int) time.Duration
// Generator generates a sequence of duration values using a step function.
//
// A Generator is not safe for concurrent use by multiple goroutines.
type Generator struct {
base time.Duration
ceiling time.Duration
iter int
fn StepFunc
}
// Base returns the base duration used by the generator.
func (g *Generator) Base() time.Duration {
return g.base
}
// Ceiling returns the maximum duration that can be yielded.
func (g *Generator) Ceiling() time.Duration {
return g.ceiling
}
// Delays returns an infinite iterator that yields the 1-based attempt
// number and the delay duration. Unlike [Generator.Attempts], this iterator
// does not sleep—the caller is responsible for sleeping the returned duration.
//
// The iterator stops when the context is cancelled.
func (g *Generator) Delays(ctx context.Context) iter.Seq2[int, time.Duration] {
return func(yield func(int, time.Duration) bool) {
for attempt := 1; ; attempt++ {
select {
case <-ctx.Done():
return
default:
if !yield(attempt, g.next()) {
return
}
}
}
}
}
// Attempts returns an iterator that yields attempt numbers (1-based),
// sleeping the backoff duration after each iteration before yielding
// the next attempt. The sleep respects context cancellation.
//
// The iterator stops when the context is cancelled or maxAttempts is reached.
func (g *Generator) Attempts(ctx context.Context, maxAttempts int) iter.Seq[int] {
return func(yield func(int) bool) {
t := time.NewTimer(0)
t.Stop()
defer t.Stop()
for attempt := 1; attempt <= maxAttempts; attempt++ {
select {
case <-ctx.Done():
return
default:
}
if !yield(attempt) {
return
}
if attempt < maxAttempts {
t.Reset(g.next())
select {
case <-ctx.Done():
return
case <-t.C:
}
}
}
}
}
// next generates and returns the next duration.
func (g *Generator) next() time.Duration {
val := g.fn(g.base, g.iter)
if g.ceiling > 0 {
val = min(val, g.ceiling)
}
g.iter++
return val
}
// Reset resets the generator to its initial state.
func (g *Generator) Reset() {
g.iter = 0
}
// New returns a new generator that uses the given step function.
//
// Base is the first value that will be returned, and the one from which
// the next values will be derived. Ceiling is the maximum value that can
// be generated. A ceiling of 0 disables the ceiling check.
func New(base, ceiling time.Duration, fn StepFunc) *Generator {
return &Generator{
base: base,
ceiling: ceiling,
fn: fn,
iter: 0,
}
}
// Delays returns an infinite iterator that yields the 1-based attempt
// number and the delay duration. The caller is responsible for sleeping
// the returned duration. The iterator stops when the context is cancelled.
func Delays(ctx context.Context, base, ceiling time.Duration, fn StepFunc) iter.Seq2[int, time.Duration] {
return New(base, ceiling, fn).Delays(ctx)
}
// Attempts returns an iterator that yields attempt numbers (1-based),
// sleeping the backoff duration after each iteration before yielding
// the next attempt. The sleep respects context cancellation.
// The iterator stops when the context is cancelled or maxAttempts is reached.
func Attempts(ctx context.Context, base, ceiling time.Duration, fn StepFunc, maxAttempts int) iter.Seq[int] {
return New(base, ceiling, fn).Attempts(ctx, maxAttempts)
}
// Fixed returns a StepFunc that always returns the base duration.
// It is equivalent to Linear(0).
func Fixed() StepFunc {
return Linear(0)
}
var _ StepFunc = Fixed()
// Incremental returns a step function that scales the base by the given multiple
// each retry.
func Incremental(multiplier int) StepFunc {
return func(base time.Duration, count int) time.Duration {
if count == 0 {
return base
}
factor := saturatingMulInt64(int64(multiplier), int64(count))
return saturatingMulDuration(base, factor)
}
}
var _ StepFunc = Incremental(0)
// Linear returns a step function that adds d each retry.
func Linear(d time.Duration) StepFunc {
return func(base time.Duration, count int) time.Duration {
if count == 0 {
return base
}
increment := saturatingMulDurationInt(d, count)
return saturatingAddDuration(base, increment)
}
}
var _ StepFunc = Linear(0)
// Exponential returns an exponential step function.
func Exponential(factor int) StepFunc {
if factor <= 0 {
panic("backoff: exponential factor must be greater than 0")
}
return func(base time.Duration, count int) time.Duration {
if count == 0 {
return base
}
return saturatingExp(base, factor, count)
}
}
var _ StepFunc = Exponential(2)
// Jitter wraps a StepFunc and returns a new StepFunc that applies
// "full-range" jitter in the range [d - factor*d, d].
//
// For example, with d=1s and factor=0.5, the result is uniformly
// distributed in [500ms, 1s]. Factor should be in [0, 1].
func Jitter(fn StepFunc, factor float64) StepFunc {
if factor < 0 || factor > 1 {
panic("backoff: jitter factor must be in [0, 1]")
}
return func(base time.Duration, count int) time.Duration {
d := fn(base, count)
j := time.Duration(float64(d) * rand.Float64() * factor) //nolint:gosec // jitter doesn't need crypto rand
return d - j
}
}
var _ StepFunc = Jitter(Linear(0), 1)
func saturatingMulDuration(d time.Duration, m int64) time.Duration {
if d == 0 || m == 0 {
return 0
}
d64 := int64(d)
ad := absInt64(d64)
am := absInt64(m)
if am != 0 && ad > uint64(math.MaxInt64)/am {
if (d64 < 0) == (m < 0) {
return time.Duration(math.MaxInt64)
}
return time.Duration(math.MinInt64)
}
return time.Duration(d64 * m)
}
func saturatingMulDurationInt(d time.Duration, m int) time.Duration {
return saturatingMulDuration(d, int64(m))
}
func saturatingMulInt64(a, b int64) int64 {
if a == 0 || b == 0 {
return 0
}
aa := absInt64(a)
bb := absInt64(b)
if bb != 0 && aa > uint64(math.MaxInt64)/bb {
if (a < 0) == (b < 0) {
return math.MaxInt64
}
return math.MinInt64
}
return a * b
}
func saturatingAddDuration(a, b time.Duration) time.Duration {
if b > 0 && a > time.Duration(math.MaxInt64)-b {
return time.Duration(math.MaxInt64)
}
if b < 0 && a < time.Duration(math.MinInt64)-b {
return time.Duration(math.MinInt64)
}
return a + b
}
func saturatingExp(base time.Duration, factor, count int) time.Duration {
result := base
for i := 0; i < count; i++ {
result = saturatingMulDurationInt(result, factor)
if result == time.Duration(math.MaxInt64) || result == time.Duration(math.MinInt64) {
return result
}
}
return result
}
func absInt64(v int64) uint64 {
if v >= 0 {
return uint64(v)
}
if v == math.MinInt64 {
return uint64(math.MaxInt64) + 1
}
return uint64(-v)
}