-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathretry.go
More file actions
336 lines (302 loc) · 10.3 KB
/
Copy pathretry.go
File metadata and controls
336 lines (302 loc) · 10.3 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
package goretry
import (
"context"
"errors"
"fmt"
"time"
)
// TransientErrorFunc is a function that determines if an error is transient and should trigger a retry.
// It receives an error and returns true if the error is considered transient (temporary/recoverable),
// false if the error is persistent and retries should not be attempted.
//
// Example:
//
// func isNetworkError(err error) bool {
// return strings.Contains(err.Error(), "connection refused") ||
// strings.Contains(err.Error(), "timeout")
// }
type TransientErrorFunc func(error) bool
// RetryPolicy defines the retry behavior and delay calculation strategy.
// Implementations determine how long to wait between retry attempts and whether to continue retrying.
//
// The NextDelay method receives the current attempt number (1-based) and returns:
// - delay: duration to wait before the next attempt
// - shouldContinue: whether to proceed with another attempt
//
// Common implementations include exponential backoff, fixed delays, and linear backoff.
type RetryPolicy interface {
// NextDelay calculates the delay before the next retry attempt.
// attempt is 1-based (first retry is attempt 1).
// Returns the delay duration and whether retrying should continue.
NextDelay(attempt int) (time.Duration, bool)
}
// Retrier provides retry functionality with configurable policies and transient error strategies.
// It encapsulates the retry logic and can be configured with various options such as
// maximum attempts, custom transient error detection, and retry callbacks.
//
// Retrier is safe for concurrent use by multiple goroutines.
//
// Example:
//
// retrier := NewRetrier(
// NewExponentialBackoffPolicy(100*time.Millisecond, 5*time.Second),
// WithMaxAttempts(5),
// WithTransientErrorFunc(func(err error) bool {
// return strings.Contains(err.Error(), "temporary")
// }),
// )
//
// err := retrier.Do(func() error {
// return riskyOperation()
// })
type Retrier struct {
policy RetryPolicy
isTransient TransientErrorFunc
maxAttempts int
onRetry func(attempt int, err error)
}
// OutOfRetriesError is returned when all retry attempts are exhausted without success.
// It contains information about all attempts made and provides access to both the last error
// encountered and all errors that occurred during the retry process.
//
// This error type implements the error interface and can be unwrapped to access the last error.
//
// Example:
//
// var outOfRetriesErr *OutOfRetriesError
// if errors.As(err, &outOfRetriesErr) {
// fmt.Printf("Failed after %d attempts\n", outOfRetriesErr.Attempts)
// fmt.Printf("Last error: %v\n", outOfRetriesErr.LastErr)
// }
type OutOfRetriesError struct {
// Attempts is the total number of attempts made
Attempts int
// LastErr is the error from the final attempt
LastErr error
// AllErrs contains all errors encountered during retry attempts
AllErrs []error
}
// Error returns a string representation of the OutOfRetriesError.
func (e *OutOfRetriesError) Error() string {
return fmt.Sprintf("retry failed after %d attempts: %v", e.Attempts, e.LastErr)
}
// Unwrap returns the last error, allowing for error unwrapping with errors.Is and errors.As.
func (e *OutOfRetriesError) Unwrap() error {
return e.LastErr
}
// NewRetrier creates a new Retrier with the specified retry policy and optional configuration.
// The retry policy determines the delay strategy between attempts.
// Additional options can be provided to customize behavior such as maximum attempts,
// transient error detection, and retry callbacks.
//
// Default configuration:
// - Maximum attempts: 3
// - Transient error function: DefaultTransientErrorFunc
// - No retry callback
//
// Example:
//
// retrier := NewRetrier(
// NewExponentialBackoffPolicy(100*time.Millisecond, 5*time.Second),
// WithMaxAttempts(5),
// WithTransientErrorFunc(customTransientFunc),
// )
func NewRetrier(policy RetryPolicy, options ...Option) *Retrier {
if policy == nil {
panic("policy cannot be nil")
}
r := &Retrier{
policy: policy,
maxAttempts: 3,
isTransient: DefaultTransientErrorFunc,
}
for _, opt := range options {
opt(r)
}
if r.maxAttempts <= 0 {
panic(fmt.Sprintf("maxAttempts must be positive, got %d", r.maxAttempts))
}
return r
}
// Option is a function that configures a Retrier instance.
// Options are applied during Retrier creation to customize its behavior.
type Option func(*Retrier)
// WithMaxAttempts sets the maximum number of retry attempts.
// The total number of function calls will be maxAttempts (including the initial attempt).
//
// Example:
//
// retrier := NewRetrier(policy, WithMaxAttempts(5)) // Will try up to 5 times total
func WithMaxAttempts(attempts int) Option {
return func(r *Retrier) {
if attempts <= 0 {
panic(fmt.Sprintf("maxAttempts must be positive, got %d", attempts))
}
r.maxAttempts = attempts
}
}
// WithTransientErrorFunc sets a custom function to determine if an error is transient.
// This function is called for each error encountered to decide whether a retry should be attempted.
// If the function returns true, the error is considered transient and a retry will be attempted
// (subject to other constraints like maximum attempts).
//
// Example:
//
// retrier := NewRetrier(policy, WithTransientErrorFunc(func(err error) bool {
// return strings.Contains(err.Error(), "temporary") ||
// strings.Contains(err.Error(), "timeout")
// }))
func WithTransientErrorFunc(fn TransientErrorFunc) Option {
return func(r *Retrier) {
r.isTransient = fn
}
}
// WithOnRetry sets a callback function that is called before each retry attempt.
// This can be useful for logging, metrics collection, or other side effects.
// The callback receives the attempt number (1-based) and the error that triggered the retry.
//
// Note: The callback is not called before the initial attempt, only before retries.
//
// Example:
//
// retrier := NewRetrier(policy, WithOnRetry(func(attempt int, err error) {
// log.Printf("Retry attempt %d due to error: %v", attempt, err)
// }))
func WithOnRetry(fn func(attempt int, err error)) Option {
return func(r *Retrier) {
r.onRetry = fn
}
}
// Do executes the given function with retry logic.
// The function will be retried according to the configured policy and options
// until it succeeds, a non-transient error occurs, or the maximum attempts are reached.
//
// The function should be idempotent as it may be called multiple times.
// If all retry attempts are exhausted, an OutOfRetriesError is returned.
//
// Example:
//
// err := retrier.Do(func() error {
// resp, err := http.Get("https://api.example.com/data")
// if err != nil {
// return err
// }
// defer resp.Body.Close()
// return processResponse(resp)
// })
func (r *Retrier) Do(fn func() error) error {
return r.DoWithContext(context.Background(), func(ctx context.Context) error {
return fn()
})
}
// DoWithContext executes the given function with retry logic and context support.
// This method provides the same retry functionality as Do, but with context support
// for cancellation and timeout handling.
//
// The context is checked before each retry attempt, and if cancelled or timed out,
// the context error is returned immediately without further retries.
//
// Example:
//
// ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
// defer cancel()
//
// err := retrier.DoWithContext(ctx, func(ctx context.Context) error {
// req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.example.com/data", nil)
// resp, err := client.Do(req)
// if err != nil {
// return err
// }
// defer resp.Body.Close()
// return processResponse(resp)
// })
func (r *Retrier) DoWithContext(ctx context.Context, fn func(context.Context) error) error {
var allErrors []error
var lastErr error
startTime := time.Now()
// Check if policy has duration limit (for StopPolicy)
var maxDuration time.Duration
if stopPolicy, ok := r.policy.(*StopPolicy); ok {
maxDuration = stopPolicy.GetMaxDuration()
}
for attempt := 1; attempt <= r.maxAttempts; attempt++ {
// Check duration limit before each attempt
if maxDuration > 0 && time.Since(startTime) >= maxDuration {
break
}
err := fn(ctx)
if err == nil {
return nil
}
lastErr = err
allErrors = append(allErrors, err)
// If error is not transient, return immediately
if !r.isTransient(err) {
return err
}
// If this was the last attempt, don't wait
if attempt == r.maxAttempts {
break
}
// Call retry callback if provided
if r.onRetry != nil {
r.onRetry(attempt, err)
}
// Calculate delay for next attempt
delay, shouldContinue := r.policy.NextDelay(attempt)
if !shouldContinue {
break
}
// Check duration limit before waiting
if maxDuration > 0 && time.Since(startTime)+delay >= maxDuration {
break
}
// Wait for the delay or context cancellation with proper timer cleanup
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
// Continue to next attempt
}
}
return &OutOfRetriesError{
Attempts: len(allErrors),
LastErr: lastErr,
AllErrs: allErrors,
}
}
// DefaultTransientErrorFunc provides a reasonable default implementation for transient error detection.
// It considers an error transient if it implements common Go network error interfaces:
// - Timeout() bool - for timeout errors
// - Temporary() bool - for temporary errors
//
// Context cancellation and deadline exceeded errors are explicitly NOT considered transient,
// as they indicate intentional cancellation rather than temporary failures.
//
// This function can be used as a starting point, but applications should consider
// implementing custom transient error logic based on their specific error types and requirements.
//
// Example usage:
//
// retrier := NewRetrier(policy, WithTransientErrorFunc(DefaultTransientErrorFunc))
func DefaultTransientErrorFunc(err error) bool {
if err == nil {
return false
}
// Context cancellation/timeout are not transient
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return false
}
// Check for common transient errors
var netErr interface{ Timeout() bool }
if errors.As(err, &netErr) && netErr.Timeout() {
return true
}
var tempErr interface{ Temporary() bool }
if errors.As(err, &tempErr) && tempErr.Temporary() {
return true
}
return false
}