forked from avast/retry-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathretry.go
More file actions
355 lines (313 loc) · 8.89 KB
/
retry.go
File metadata and controls
355 lines (313 loc) · 8.89 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
// Package retry provides a simple and flexible retry mechanism for Go.
// It allows executing functions with automatic retry on failure, with configurable
// backoff strategies, retry conditions, and error handling.
//
// The package is safe for concurrent use.
//
// The package is inspired by Try::Tiny::Retry from Perl.
//
// Basic usage:
//
// url := "http://example.com"
// var body []byte
//
// err := retry.Do(
// func() error {
// resp, err := http.Get(url)
// if err != nil {
// return err
// }
// defer resp.Body.Close()
// body, err = io.ReadAll(resp.Body)
// if err != nil {
// return err
// }
// return nil
// },
// )
//
// With data return:
//
// body, err := retry.DoWithData(
// func() ([]byte, error) {
// resp, err := http.Get(url)
// if err != nil {
// return nil, err
// }
// defer resp.Body.Close()
// return io.ReadAll(resp.Body)
// },
// )
package retry
import (
"context"
"errors"
"fmt"
"math"
"strings"
"time"
)
// RetryableFunc is the function signature for retryable functions used with Do.
type RetryableFunc func() error
// RetryableFuncWithData is the function signature for retryable functions that return data.
// Used with DoWithData.
type RetryableFuncWithData[T any] func() (T, error)
type defaultTimer struct{}
func (defaultTimer) After(d time.Duration) <-chan time.Time {
return time.After(d)
}
// Do executes the retryable function with the provided options.
// It returns nil if the function succeeds, or an error if all retry attempts fail.
//
// By default, it will retry up to 10 times with exponential backoff and jitter.
// The behavior can be customized using Option functions.
func Do(retryableFunc RetryableFunc, opts ...Option) error {
retryableFuncWithData := func() (any, error) {
return nil, retryableFunc()
}
_, err := DoWithData(retryableFuncWithData, opts...)
return err
}
// DoWithData executes the retryable function with the provided options and returns the function's data.
// It returns the data and nil error if the function succeeds, or zero value and error if all retry attempts fail.
//
// By default, it will retry up to 10 times with exponential backoff and jitter.
// The behavior can be customized using Option functions.
//
//nolint:gocognit,gocyclo // Complexity is necessary for retry logic
func DoWithData[T any](retryableFunc RetryableFuncWithData[T], opts ...Option) (T, error) {
var attempt uint
var emptyT T
const (
defaultAttempts = 10
defaultDelay = 100 * time.Millisecond
defaultJitter = 100 * time.Millisecond
)
// default config
config := &Config{
attempts: defaultAttempts,
attemptsForError: make(map[error]uint),
delay: defaultDelay,
maxJitter: defaultJitter,
onRetry: func(_ uint, _ error) {},
retryIf: IsRecoverable,
delayType: CombineDelay(BackOffDelay, RandomDelay),
lastErrorOnly: false,
context: context.Background(),
timer: defaultTimer{},
}
// apply opts
for _, opt := range opts {
opt(config)
}
// Validate configuration
if err := config.validate(); err != nil {
return emptyT, err
}
// Check if context is already done
if err := context.Cause(config.context); err != nil {
return emptyT, err
}
// Pre-allocate error slice with bounded capacity to prevent memory exhaustion.
const maxErrors = 1000 // Limit to prevent DoS through memory consumption.
capacity := config.attempts
if capacity == 0 || capacity > maxErrors {
capacity = maxErrors
}
errorLog := make(Error, 0, capacity)
// Copy map to avoid modifying the original.
attemptsForError := make(map[error]uint, len(config.attemptsForError))
for err, attempts := range config.attemptsForError {
attemptsForError[err] = attempts
}
for {
// Check context before each attempt.
if err := context.Cause(config.context); err != nil {
if config.lastErrorOnly {
return emptyT, err
}
if len(errorLog) < cap(errorLog) {
errorLog = append(errorLog, err)
}
return emptyT, errorLog
}
t, err := retryableFunc()
if err == nil {
return t, nil
}
// Only append if we haven't hit the cap to prevent unbounded growth.
if len(errorLog) < cap(errorLog) {
// Unpack unrecoverable errors to store the underlying error.
var u unrecoverableError
if errors.As(err, &u) {
errorLog = append(errorLog, u.error)
} else {
errorLog = append(errorLog, err)
}
}
// Check if we should stop retrying.
if !IsRecoverable(err) || !config.retryIf(err) {
if config.lastErrorOnly {
return emptyT, err
}
// For unrecoverable errors on first attempt, return the error directly.
if len(errorLog) == 1 && !IsRecoverable(err) {
return emptyT, err
}
return emptyT, errorLog
}
// Check error-specific attempt limits.
stop := false
for errToCheck, attempts := range attemptsForError {
if errors.Is(err, errToCheck) {
attempts--
attemptsForError[errToCheck] = attempts
if attempts <= 0 {
stop = true
break
}
}
}
if stop {
break
}
// Check if this is the last attempt (when attempts > 0).
if config.attempts > 0 && attempt >= config.attempts-1 {
break
}
// Call onRetry callback.
config.onRetry(attempt, err)
// Increment attempt counter.
if attempt == math.MaxUint {
break
}
attempt++
// Calculate delay.
delay := config.delayType(attempt, err, config)
if delay < 0 {
delay = 0
}
if config.maxDelay > 0 && delay > config.maxDelay {
delay = config.maxDelay
}
// Protect against timer implementations that might return nil channel.
timer := config.timer.After(delay)
if timer == nil {
return emptyT, errors.New("retry: timer.After returned nil channel")
}
select {
case <-timer:
case <-config.context.Done():
contextErr := context.Cause(config.context)
if config.lastErrorOnly {
if config.wrapLastErr {
return emptyT, fmt.Errorf("%w: %w", contextErr, err)
}
return emptyT, contextErr
}
if len(errorLog) < cap(errorLog) {
errorLog = append(errorLog, contextErr)
}
return emptyT, errorLog
}
}
if config.lastErrorOnly {
if len(errorLog) > 0 {
return emptyT, errorLog.Unwrap()
}
return emptyT, nil
}
return emptyT, errorLog
}
// Error represents a collection of errors that occurred during retry attempts.
// It implements the error interface and provides compatibility with errors.Is,
// errors.As, and errors.Unwrap.
type Error []error
// Error returns a string representation of all errors that occurred during retry attempts.
// Each error is prefixed with its attempt number.
func (e Error) Error() string {
if len(e) == 0 {
return "retry: all attempts failed"
}
// Pre-size builder for better performance
// Estimate: prefix (30) + each error (~50 chars avg)
var b strings.Builder
b.Grow(30 + len(e)*50)
b.WriteString("retry: all attempts failed:")
for i, err := range e {
if err != nil {
fmt.Fprintf(&b, "\n#%d: %s", i+1, err.Error())
}
}
return b.String()
}
// Is reports whether any error in e matches target.
// It implements support for errors.Is.
func (e Error) Is(target error) bool {
for _, err := range e {
if errors.Is(err, target) {
return true
}
}
return false
}
// As finds the first error in e that matches target, and if so,
// sets target to that error value and returns true.
// It implements support for errors.As.
func (e Error) As(target any) bool {
for _, err := range e {
if errors.As(err, target) {
return true
}
}
return false
}
// Unwrap returns the last error for compatibility with errors.Unwrap.
// When you need to unwrap all errors, you should use WrappedErrors instead.
//
// Example:
//
// err := Do(
// func() error {
// return errors.New("original error")
// },
// Attempts(1),
// )
// fmt.Println(errors.Unwrap(err)) // "original error" is printed
func (e Error) Unwrap() error {
return e[len(e)-1]
}
// WrappedErrors returns the list of errors that this Error is wrapping.
// It is an implementation of the `errwrap.Wrapper` interface
// in package [errwrap](https://github.com/hashicorp/errwrap) so that
// `retry.Error` can be used with that library.
func (e Error) WrappedErrors() []error {
return e
}
type unrecoverableError struct {
error
}
func (ue unrecoverableError) Error() string {
if ue.error == nil {
return "retry: unrecoverable error with nil value"
}
return ue.error.Error()
}
func (ue unrecoverableError) Unwrap() error {
return ue.error
}
// Unrecoverable wraps an error to mark it as unrecoverable.
// When an unrecoverable error is returned, the retry mechanism will stop immediately.
func Unrecoverable(err error) error {
return unrecoverableError{err}
}
// IsRecoverable reports whether err is recoverable.
// It returns false if err is or wraps an unrecoverable error.
func IsRecoverable(err error) bool {
return !errors.Is(err, unrecoverableError{})
}
// Is implements error matching for unrecoverableError.
func (unrecoverableError) Is(err error) bool {
_, ok := err.(unrecoverableError)
return ok
}