-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathretry.go
More file actions
75 lines (64 loc) · 2.1 KB
/
retry.go
File metadata and controls
75 lines (64 loc) · 2.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
package skedulr
import (
"math"
"math/rand"
"time"
)
// RetryStrategy defines how a failed task should be retried.
type RetryStrategy interface {
// NextDelay returns the delay before the next retry, and whether to continue retrying.
NextDelay(attempt int) (time.Duration, bool)
}
// ExponentialBackoff implements a retry strategy with exponential backoff and jitter.
type ExponentialBackoff struct {
// MaxAttempts is the maximum number of retries.
MaxAttempts int
// BaseDelay is the delay for the first retry.
BaseDelay time.Duration
// MaxDelay is the upper bound for any retry delay.
MaxDelay time.Duration
// Jitter is a factor (0-1) to randomize the delay.
Jitter float64 // Jitter factor (0-1), e.g., 0.1 for 10% jitter
}
// NextDelay calculates the next retry interval.
func (e *ExponentialBackoff) NextDelay(attempt int) (time.Duration, bool) {
if attempt >= e.MaxAttempts {
return 0, false
}
delay := time.Duration(float64(e.BaseDelay) * math.Pow(2, float64(attempt)))
if delay > e.MaxDelay {
delay = e.MaxDelay
}
if e.Jitter > 0 {
// Apply random jitter
jitterAmount := float64(delay) * e.Jitter
randomJitter := (rand.Float64()*2 - 1) * jitterAmount // Between -jitterAmount and +jitterAmount
delay += time.Duration(randomJitter)
}
return delay, true
}
// LinearRetry implements a simple retry strategy with a fixed delay.
type LinearRetry struct {
MaxAttempts int
Delay time.Duration
}
// NextDelay returns the fixed delay.
func (l *LinearRetry) NextDelay(attempt int) (time.Duration, bool) {
if attempt >= l.MaxAttempts {
return 0, false
}
return l.Delay, true
}
// NewLinearRetry creates a new linear retry strategy.
func NewLinearRetry(maxAttempts int, delay time.Duration) *LinearRetry {
return &LinearRetry{MaxAttempts: maxAttempts, Delay: delay}
}
// NewExponentialBackoff creates a new exponential backoff strategy.
func NewExponentialBackoff(maxAttempts int, baseDelay, maxDelay time.Duration, jitter float64) *ExponentialBackoff {
return &ExponentialBackoff{
MaxAttempts: maxAttempts,
BaseDelay: baseDelay,
MaxDelay: maxDelay,
Jitter: jitter,
}
}