|
| 1 | +// Copyright (c) HashiCorp, Inc. |
| 2 | +// SPDX-License-Identifier: MPL-2.0 |
| 3 | + |
| 4 | +package backoff |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "math" |
| 9 | + "math/rand" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +// Inspired by https://github.com/ServiceWeaver/weaver and https://github.com/avast/retry-go. |
| 14 | + |
| 15 | +// Timer represents the timer used to track time for a retry. |
| 16 | +type Timer interface { |
| 17 | + After(time.Duration) <-chan time.Time |
| 18 | +} |
| 19 | + |
| 20 | +// DelayFunc returns the duration to wait before the next retry attempt. |
| 21 | +type DelayFunc func(uint) time.Duration |
| 22 | + |
| 23 | +// FixedDelay returns a delay. The first retry attempt has no delay (0), and subsequent attempts use the fixed delay. |
| 24 | +func FixedDelay(delay time.Duration) DelayFunc { |
| 25 | + return func(n uint) time.Duration { |
| 26 | + if n == 0 { |
| 27 | + return 0 |
| 28 | + } |
| 29 | + |
| 30 | + return delay |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +// Do not use the default RNG since we do not want different provider instances |
| 35 | +// to pick the same deterministic random sequence. |
| 36 | +var rng = rand.New(rand.NewSource(time.Now().UnixNano())) |
| 37 | + |
| 38 | +// ExponentialJitterBackoff returns a duration of backoffMinDuration * backoffMultiplier**n, with added jitter. |
| 39 | +func ExponentialJitterBackoff(backoffMinDuration time.Duration, backoffMultiplier float64) DelayFunc { |
| 40 | + return func(n uint) time.Duration { |
| 41 | + if n == 0 { |
| 42 | + return 0 |
| 43 | + } |
| 44 | + |
| 45 | + mult := math.Pow(backoffMultiplier, float64(n)) |
| 46 | + return applyJitter(time.Duration(float64(backoffMinDuration) * mult)) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +func applyJitter(base time.Duration) time.Duration { |
| 51 | + const jitterFactor = 0.4 |
| 52 | + jitter := 1 - jitterFactor*rng.Float64() // Subtract up to 40%. |
| 53 | + return time.Duration(float64(base) * jitter) |
| 54 | +} |
| 55 | + |
| 56 | +type sdkv2HelperRetryCompatibleDelay struct { |
| 57 | + minTimeout time.Duration |
| 58 | + pollInterval time.Duration |
| 59 | + wait time.Duration |
| 60 | +} |
| 61 | + |
| 62 | +func (d *sdkv2HelperRetryCompatibleDelay) delay() time.Duration { |
| 63 | + wait := d.wait |
| 64 | + |
| 65 | + // First round had no wait. |
| 66 | + if wait == 0 { |
| 67 | + wait = 100 * time.Millisecond |
| 68 | + } |
| 69 | + |
| 70 | + wait *= 2 |
| 71 | + |
| 72 | + // If a poll interval has been specified, choose that interval. |
| 73 | + // Otherwise bound the default value. |
| 74 | + if d.pollInterval > 0 && d.pollInterval < 180*time.Second { |
| 75 | + wait = d.pollInterval |
| 76 | + } else { |
| 77 | + if wait < d.minTimeout { |
| 78 | + wait = d.minTimeout |
| 79 | + } else if wait > 10*time.Second { |
| 80 | + wait = 10 * time.Second |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + d.wait = wait |
| 85 | + |
| 86 | + return wait |
| 87 | +} |
| 88 | + |
| 89 | +// SDKv2HelperRetryCompatibleDelay returns a Terraform Plugin SDK v2 helper/retry-compatible delay. |
| 90 | +func SDKv2HelperRetryCompatibleDelay(initialDelay, pollInterval, minTimeout time.Duration) DelayFunc { |
| 91 | + delay := &sdkv2HelperRetryCompatibleDelay{ |
| 92 | + minTimeout: minTimeout, |
| 93 | + pollInterval: pollInterval, |
| 94 | + } |
| 95 | + |
| 96 | + return func(n uint) time.Duration { |
| 97 | + if n == 0 { |
| 98 | + return initialDelay |
| 99 | + } |
| 100 | + |
| 101 | + return delay.delay() |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +// DefaultSDKv2HelperRetryCompatibleDelay returns a Terraform Plugin SDK v2 helper/retry-compatible delay |
| 106 | +// with default values (from the `RetryContext` function). |
| 107 | +func DefaultSDKv2HelperRetryCompatibleDelay() DelayFunc { |
| 108 | + return SDKv2HelperRetryCompatibleDelay(0, 0, 500*time.Millisecond) //nolint:mnd // 500ms is the Plugin SDKv2 default |
| 109 | +} |
| 110 | + |
| 111 | +// RetryConfig configures a retry loop. |
| 112 | +type RetryConfig struct { |
| 113 | + delay DelayFunc |
| 114 | + gracePeriod time.Duration |
| 115 | + timer Timer |
| 116 | +} |
| 117 | + |
| 118 | +// Option represents an option for retry. |
| 119 | +type Option func(*RetryConfig) |
| 120 | + |
| 121 | +func emptyOption(c *RetryConfig) {} |
| 122 | + |
| 123 | +func WithGracePeriod(d time.Duration) Option { |
| 124 | + return func(c *RetryConfig) { |
| 125 | + c.gracePeriod = d |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +func WithDelay(d DelayFunc) Option { |
| 130 | + if d == nil { |
| 131 | + return emptyOption |
| 132 | + } |
| 133 | + |
| 134 | + return func(c *RetryConfig) { |
| 135 | + c.delay = d |
| 136 | + } |
| 137 | +} |
| 138 | + |
| 139 | +// WithTimer provides a way to swap out timer module implementations. |
| 140 | +// This primarily is useful for mocking/testing, where you may not want to explicitly wait for a set duration |
| 141 | +// for retries. |
| 142 | +func WithTimer(t Timer) Option { |
| 143 | + return func(c *RetryConfig) { |
| 144 | + c.timer = t |
| 145 | + } |
| 146 | +} |
| 147 | + |
| 148 | +// Default timer is a wrapper around time.After |
| 149 | +type timerImpl struct{} |
| 150 | + |
| 151 | +func (t *timerImpl) After(d time.Duration) <-chan time.Time { |
| 152 | + return time.After(d) |
| 153 | +} |
| 154 | + |
| 155 | +// The default RetryConfig is backwards compatible with github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry. |
| 156 | +func defaultRetryConfig() RetryConfig { |
| 157 | + return RetryConfig{ |
| 158 | + delay: DefaultSDKv2HelperRetryCompatibleDelay(), |
| 159 | + gracePeriod: 30 * time.Second, |
| 160 | + timer: &timerImpl{}, |
| 161 | + } |
| 162 | +} |
| 163 | + |
| 164 | +// RetryLoop holds state for managing retry loops with a timeout. |
| 165 | +type RetryLoop struct { |
| 166 | + attempt uint |
| 167 | + config RetryConfig |
| 168 | + deadline deadline |
| 169 | + timedOut bool |
| 170 | +} |
| 171 | + |
| 172 | +// NewRetryLoopWithOptions returns a new retry loop configured with the provided options. |
| 173 | +func NewRetryLoopWithOptions(timeout time.Duration, opts ...Option) *RetryLoop { |
| 174 | + config := defaultRetryConfig() |
| 175 | + for _, opt := range opts { |
| 176 | + opt(&config) |
| 177 | + } |
| 178 | + |
| 179 | + return &RetryLoop{ |
| 180 | + config: config, |
| 181 | + deadline: NewDeadline(timeout + config.gracePeriod), |
| 182 | + } |
| 183 | +} |
| 184 | + |
| 185 | +// NewRetryLoop returns a new retry loop configured with the default options. |
| 186 | +func NewRetryLoop(timeout time.Duration) *RetryLoop { |
| 187 | + return NewRetryLoopWithOptions(timeout) |
| 188 | +} |
| 189 | + |
| 190 | +// Continue sleeps between retry attempts. |
| 191 | +// It returns false if the timeout has been exceeded. |
| 192 | +// The deadline is not checked on the first call to Continue. |
| 193 | +func (r *RetryLoop) Continue(ctx context.Context) bool { |
| 194 | + if r.attempt != 0 && r.deadline.Remaining() == 0 { |
| 195 | + r.timedOut = true |
| 196 | + |
| 197 | + return false |
| 198 | + } |
| 199 | + |
| 200 | + r.sleep(ctx, r.config.delay(r.attempt)) |
| 201 | + r.attempt++ |
| 202 | + |
| 203 | + return true |
| 204 | +} |
| 205 | + |
| 206 | +// Reset resets a RetryLoop to its initial state. |
| 207 | +func (r *RetryLoop) Reset() { |
| 208 | + r.attempt = 0 |
| 209 | +} |
| 210 | + |
| 211 | +// TimedOut return whether the retry timed out. |
| 212 | +func (r *RetryLoop) TimedOut() bool { |
| 213 | + return r.timedOut |
| 214 | +} |
| 215 | + |
| 216 | +// sleep sleeps for the specified duration or until the context is canceled, whichever occurs first. |
| 217 | +func (r *RetryLoop) sleep(ctx context.Context, d time.Duration) { |
| 218 | + if d == 0 { |
| 219 | + return |
| 220 | + } |
| 221 | + |
| 222 | + select { |
| 223 | + case <-ctx.Done(): |
| 224 | + return |
| 225 | + case <-r.config.timer.After(d): |
| 226 | + } |
| 227 | +} |
0 commit comments