Debian Codegraph @

exp/internal/github.com/efficientgo/core/backoff/backoff.go

raw
1 // Copyright (c) The EfficientGo Authors.
2 // Licensed under the Apache License 2.0.
3
4 // Initially copied from Cortex project.
5
6 // Package backoff implements backoff timers which increases wait time on every retry, incredibly useful
7 // in distributed system timeout functionalities.
8 package backoff
9
10 import (
11 "context"
12 "fmt"
13 "math/rand"
14 "time"
15 )
16
17 // Config configures a Backoff.
18 type Config struct {
19 Min time.Duration `yaml:"min_period"` // Start backoff at this level
20 Max time.Duration `yaml:"max_period"` // Increase exponentially to this level
21 MaxRetries int `yaml:"max_retries"` // Give up after this many; zero means infinite retries
22 }
23
24 // Backoff implements exponential backoff with randomized wait times.
25 type Backoff struct {
26 cfg Config
27 ctx context.Context
28 numRetries int
29 nextDelayMin time.Duration
30 nextDelayMax time.Duration
31 }
32
33 // New creates a Backoff object. Pass a Context that can also terminate the operation.
34 func New(ctx context.Context, cfg Config) *Backoff {
35 return &Backoff{
36 cfg: cfg,
37 ctx: ctx,
38 nextDelayMin: cfg.Min,
39 nextDelayMax: doubleDuration(cfg.Min, cfg.Max),
40 }
41 }
42
43 // Reset the Backoff back to its initial condition.
44 func (b *Backoff) Reset() {
45 b.numRetries = 0
46 b.nextDelayMin = b.cfg.Min
47 b.nextDelayMax = doubleDuration(b.cfg.Min, b.cfg.Max)
48 }
49
50 // Ongoing returns true if caller should keep going.
51 func (b *Backoff) Ongoing() bool {
52 // Stop if Context has errored or max retry count is exceeded.
53 return b.ctx.Err() == nil && (b.cfg.MaxRetries == 0 || b.numRetries < b.cfg.MaxRetries)
54 }
55
56 // Err returns the reason for terminating the backoff, or nil if it didn't terminate.
57 func (b *Backoff) Err() error {
58 if b.ctx.Err() != nil {
59 return b.ctx.Err()
60 }
61 if b.cfg.MaxRetries != 0 && b.numRetries >= b.cfg.MaxRetries {
62 return fmt.Errorf("terminated after %d retries", b.numRetries)
63 }
64 return nil
65 }
66
67 // NumRetries returns the number of retries so far.
68 func (b *Backoff) NumRetries() int {
69 return b.numRetries
70 }
71
72 // Wait sleeps for the backoff time then increases the retry count and backoff time.
73 // Returns immediately if Context is terminated.
74 func (b *Backoff) Wait() {
75 // Increase the number of retries and get the next delay.
76 sleepTime := b.NextDelay()
77
78 if b.Ongoing() {
79 select {
80 case <-b.ctx.Done():
81 case <-time.After(sleepTime):
82 }
83 }
84 }
85
86 func (b *Backoff) NextDelay() time.Duration {
87 b.numRetries++
88
89 // Handle the edge case the min and max have the same value
90 // (or due to some misconfig max is < min).
91 if b.nextDelayMin >= b.nextDelayMax {
92 return b.nextDelayMin
93 }
94
95 // Add a jitter within the next exponential backoff range.
96 sleepTime := b.nextDelayMin + time.Duration(rand.Int63n(int64(b.nextDelayMax-b.nextDelayMin)))
97
98 // Apply the exponential backoff to calculate the next jitter
99 // range, unless we've already reached the max.
100 if b.nextDelayMax < b.cfg.Max {
101 b.nextDelayMin = doubleDuration(b.nextDelayMin, b.cfg.Max)
102 b.nextDelayMax = doubleDuration(b.nextDelayMax, b.cfg.Max)
103 }
104
105 return sleepTime
106 }
107
108 func doubleDuration(value, maxValue time.Duration) time.Duration {
109 value = value * 2
110 if value <= maxValue {
111 return value
112 }
113 return maxValue
114 }