forked from avast/retry-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptions.go
More file actions
392 lines (351 loc) · 11.1 KB
/
options.go
File metadata and controls
392 lines (351 loc) · 11.1 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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
package retry
import (
"context"
"errors"
"fmt"
"math"
"math/rand/v2"
"time"
)
// IfFunc is the signature for functions that determine whether to retry after an error.
// It returns true if the error is retryable, false otherwise.
type IfFunc func(error) bool
// RetryIfFunc is an alias for IfFunc for backwards compatibility.
// Deprecated: Use IfFunc instead.
type RetryIfFunc = IfFunc //nolint:revive // Keeping RetryIfFunc name for backwards compatibility
// OnRetryFunc is the signature for functions called after each retry attempt.
// The attempt parameter is the zero-based index of the attempt.
type OnRetryFunc func(attempt uint, err error)
// DelayTypeFunc calculates the delay duration before the next retry attempt.
// The attempt parameter is the zero-based index of the attempt.
type DelayTypeFunc func(attempt uint, err error, config *Config) time.Duration
// Timer provides an interface for time operations in retry logic.
// This abstraction allows for mocking time in tests and implementing
// custom timing behaviors. The standard implementation uses time.After.
//
// Security note: Custom Timer implementations must return a valid channel
// that either receives a time value or blocks. Returning nil will cause
// the retry to fail immediately.
type Timer interface {
// After returns a channel that sends the current time after the duration elapses.
// It should behave like time.After.
After(time.Duration) <-chan time.Time
}
// Config holds all configuration options for retry behavior.
// It is typically populated using Option functions and should not be
// constructed directly. Use the various Option functions like Attempts,
// Delay, and RetryIf to configure retry behavior.
//
//nolint:govet // Field alignment optimization would break API compatibility
type Config struct {
attemptsForError map[error]uint
context context.Context //nolint:containedctx // Required for backwards compatibility - context is part of the public API
delay time.Duration
maxDelay time.Duration
maxJitter time.Duration
onRetry OnRetryFunc
retryIf IfFunc
delayType DelayTypeFunc
timer Timer
attempts uint
lastErrorOnly bool
wrapLastErr bool // wrap context error with last function error
}
// validate checks if the configuration is valid and safe to use.
func (c *Config) validate() error {
// Ensure delay values are non-negative.
if c.delay < 0 {
return fmt.Errorf("retry: delay must be non-negative, got %v", c.delay)
}
if c.maxDelay < 0 {
return fmt.Errorf("retry: maxDelay must be non-negative, got %v", c.maxDelay)
}
if c.maxJitter < 0 {
return fmt.Errorf("retry: maxJitter must be non-negative, got %v", c.maxJitter)
}
// Ensure we have required functions.
if c.retryIf == nil {
return errors.New("retry: retryIf function cannot be nil")
}
if c.delayType == nil {
return errors.New("retry: delayType function cannot be nil")
}
if c.timer == nil {
return errors.New("retry: timer cannot be nil")
}
if c.context == nil {
return errors.New("retry: context cannot be nil")
}
// Ensure map is initialized.
if c.attemptsForError == nil {
c.attemptsForError = make(map[error]uint)
}
return nil
}
// Option configures retry behavior. Options are applied in the order provided
// to Do or DoWithData. Later options override earlier ones if they modify the
// same configuration field.
type Option func(*Config)
// LastErrorOnly configures whether to return only the last error that occurred,
// or wrap all errors together. Default is false (return all errors).
func LastErrorOnly(lastErrorOnly bool) Option {
return func(c *Config) {
c.lastErrorOnly = lastErrorOnly
}
}
// Attempts sets the maximum number of retry attempts.
// Setting to 0 enables infinite retries. Default is 10.
func Attempts(attempts uint) Option {
return func(c *Config) {
c.attempts = attempts
}
}
// UntilSucceeded configures infinite retry attempts until success.
// Equivalent to Attempts(0).
func UntilSucceeded() Option {
return func(c *Config) {
c.attempts = 0
}
}
// AttemptsForError sets a specific number of retry attempts for a particular error.
// These attempts are counted against the total retry limit.
// The retry stops when either the specific error limit or total limit is reached.
// Note: errors are compared using errors.Is for matching.
func AttemptsForError(attempts uint, err error) Option {
return func(c *Config) {
if err == nil {
return // Ignore nil errors.
}
if c.attemptsForError == nil {
c.attemptsForError = make(map[error]uint)
}
c.attemptsForError[err] = attempts
}
}
// Delay sets the base delay duration between retry attempts.
// Default is 100ms. The actual delay may be modified by the DelayType function.
func Delay(delay time.Duration) Option {
return func(c *Config) {
c.delay = delay
}
}
// MaxDelay sets the maximum delay duration between retry attempts.
// This caps the delay calculated by DelayType functions.
// By default, there is no maximum (0 means no limit).
func MaxDelay(maxDelay time.Duration) Option {
return func(c *Config) {
c.maxDelay = maxDelay
}
}
// MaxJitter sets the maximum random jitter duration for RandomDelay.
// Default is 100ms.
func MaxJitter(maxJitter time.Duration) Option {
return func(c *Config) {
c.maxJitter = maxJitter
}
}
// DelayType sets the delay calculation function between retries.
// Default is CombineDelay(BackOffDelay, RandomDelay).
func DelayType(delayType DelayTypeFunc) Option {
return func(c *Config) {
if delayType != nil {
c.delayType = delayType
}
}
}
const maxShiftAttempts = 62 // Maximum bit shift to prevent overflow
// BackOffDelay implements exponential backoff delay strategy.
// Each retry attempt doubles the delay, up to a maximum.
func BackOffDelay(attempt uint, _ error, config *Config) time.Duration {
// Adjust for zero-based indexing.
if attempt > 0 {
attempt--
}
// Cap attempt to prevent overflow.
if attempt > maxShiftAttempts {
attempt = maxShiftAttempts
}
// Simple exponential backoff.
delay := config.delay
if delay <= 0 {
delay = 1
}
// Check if shift would overflow.
if delay > time.Duration(math.MaxInt64)>>attempt {
return time.Duration(math.MaxInt64)
}
return delay << attempt
}
// FixedDelay implements a constant delay strategy.
// The delay is always config.delay regardless of attempt number.
func FixedDelay(_ uint, _ error, config *Config) time.Duration {
return config.delay
}
// RandomDelay implements a random delay strategy.
// Returns a random duration between 0 and config.maxJitter.
func RandomDelay(_ uint, _ error, config *Config) time.Duration {
// Ensure maxJitter is positive to avoid panic.
if config.maxJitter <= 0 {
return 0
}
return time.Duration(rand.Int64N(int64(config.maxJitter))) //nolint:gosec // Cryptographic randomness not needed for retry jitter
}
// CombineDelay creates a DelayTypeFunc that sums the delays from multiple strategies.
// The total delay is capped at math.MaxInt64 to prevent overflow.
func CombineDelay(delays ...DelayTypeFunc) DelayTypeFunc {
const maxDuration = time.Duration(math.MaxInt64)
return func(attempt uint, err error, config *Config) time.Duration {
var total time.Duration
for _, delayFunc := range delays {
d := delayFunc(attempt, err, config)
// Prevent overflow by checking if we can safely add.
if d > 0 && total > maxDuration-d {
return maxDuration
}
total += d
}
return total
}
}
// FullJitterBackoffDelay implements exponential backoff with full jitter.
// It returns a random delay between 0 and min(maxDelay, baseDelay * 2^attempt).
func FullJitterBackoffDelay(attempt uint, _ error, config *Config) time.Duration {
// Handle zero/negative base delay.
base := config.delay
if base <= 0 {
return 0
}
// Cap attempt to prevent overflow.
if attempt > maxShiftAttempts {
attempt = maxShiftAttempts
}
// Calculate ceiling with overflow check.
var ceiling time.Duration
if base > time.Duration(math.MaxInt64)>>attempt {
ceiling = time.Duration(math.MaxInt64)
} else {
ceiling = base << attempt
}
// Apply max delay cap if set.
if config.maxDelay > 0 && ceiling > config.maxDelay {
ceiling = config.maxDelay
}
// Return random delay up to ceiling.
if ceiling <= 0 {
return 0
}
return time.Duration(rand.Int64N(int64(ceiling))) //nolint:gosec // Cryptographic randomness not needed for retry jitter
}
// OnRetry sets a callback function that is called after each failed attempt.
// This is useful for logging or other side effects.
//
// Example:
//
// retry.Do(
// func() error {
// return errors.New("some error")
// },
// retry.OnRetry(func(attempt uint, err error) {
// log.Printf("#%d: %s\n", attempt, err)
// }),
// )
func OnRetry(onRetry OnRetryFunc) Option {
return func(c *Config) {
if onRetry != nil {
c.onRetry = onRetry
}
}
}
// RetryIf controls whether a retry should be attempted after an error
// (assuming there are any retry attempts remaining)
//
// skip retry if special error example:
//
// retry.Do(
// func() error {
// return errors.New("special error")
// },
// retry.RetryIf(func(err error) bool {
// if err.Error() == "special error" {
// return false
// }
// return true
// })
// )
//
// By default RetryIf stops execution if the error is wrapped using `retry.Unrecoverable`,
// so above example may also be shortened to:
//
// retry.Do(
// func() error {
// return retry.Unrecoverable(errors.New("special error"))
// }
// )
func RetryIf(retryIf IfFunc) Option { //nolint:revive // Keeping RetryIf name for backwards compatibility
return func(c *Config) {
if retryIf != nil {
c.retryIf = retryIf
}
}
}
// Context sets the context for retry operations.
// The retry loop will stop if the context is cancelled or times out.
// Default is context.Background().
//
// Example with timeout:
//
// ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
// defer cancel()
//
// retry.Do(
// func() error {
// return doSomething()
// },
// retry.Context(ctx),
// )
func Context(ctx context.Context) Option {
return func(c *Config) {
c.context = ctx //nolint:fatcontext // Required for backwards compatibility - users expect to set context via option
}
}
// WithTimer provides a way to swap out timer implementations.
// This is primarily useful for testing.
//
// Example:
//
// type mockTimer struct{}
//
// func (mockTimer) After(d time.Duration) <-chan time.Time {
// return time.After(0) // immediate return for tests
// }
//
// retry.Do(
// func() error { ... },
// retry.WithTimer(mockTimer{}),
// )
func WithTimer(t Timer) Option {
return func(c *Config) {
c.timer = t
}
}
// WrapContextErrorWithLastError configures whether to wrap context errors with the last function error.
// This is useful when using infinite retries (Attempts(0)) with context cancellation,
// as it preserves information about what error was occurring when the context expired.
// Default is false.
//
// ctx, cancel := context.WithCancel(context.Background())
// defer cancel()
//
// retry.Do(
// func() error {
// ...
// },
// retry.Context(ctx),
// retry.Attempts(0),
// retry.WrapContextErrorWithLastError(true),
// )
func WrapContextErrorWithLastError(wrap bool) Option {
return func(c *Config) {
c.wrapLastErr = wrap
}
}