Debian Codegraph @

net/backoff.go

raw symbols SCIP
1 package net
2
3 import "math"
4 import "math/rand"
5 import "time"
6
7 var randr *rand.Rand
8
9 func init() {
10 t := time.Now()
11 s := rand.NewSource(t.Unix() ^ t.UnixNano())
12 randr = rand.New(s)
13 }
14
15 // Expresses a backoff and retry specification.
16 //
17 // The nil value of this structure results in sensible defaults being used.
18 type Backoff struct {
19 // The maximum number of attempts which may be made.
20 // If this is 0, the number of attempts is unlimited.
21 MaxTries int
22
23 // The initial delay, in milliseconds. This is the delay used after the first
24 // failed attempt.
25 InitialDelay time.Duration // ms
26
27 // The maximum delay, in milliseconds. This is the maximum delay between
28 // attempts.
29 MaxDelay time.Duration // ms
30
31 // Determines when the maximum delay should be reached. If this is 5, the
32 // maximum delay will be reached after 5 attempts have been made.
33 MaxDelayAfterTries int
34
35 // Positive float expressing the maximum factor by which the delay value may
36 // be randomly inflated. e.g. specify 0.05 for a 5% variation. Set to zero to
37 // disable jitter.
38 Jitter float64
39
40 // The current try. You should not need to set this yourself.
41 CurrentTry int
42 }
43
44 // Initialises any nil field in Backoff with sensible defaults. You
45 // normally do not need to call this method yourself, as it will be called
46 // automatically.
47 func (rc *Backoff) InitDefaults() {
48 if rc.InitialDelay == 0 {
49 rc.InitialDelay = 5 * time.Second
50 }
51 if rc.MaxDelay == 0 {
52 rc.MaxDelay = 120 * time.Second
53 }
54 if rc.MaxDelayAfterTries == 0 {
55 rc.MaxDelayAfterTries = 10
56 }
57 }
58
59 // Gets the next delay in milliseconds and increments the internal try counter.
60 func (rc *Backoff) NextDelay() time.Duration {
61 rc.InitDefaults()
62
63 if rc.MaxTries != 0 && rc.CurrentTry >= rc.MaxTries {
64 return time.Duration(0)
65 }
66
67 initialDelay := float64(rc.InitialDelay)
68 maxDelay := float64(rc.MaxDelay)
69 maxDelayAfterTries := float64(rc.MaxDelayAfterTries)
70 currentTry := float64(rc.CurrentTry)
71
72 // [from backoff.c]
73 k := math.Log2(maxDelay/initialDelay) / maxDelayAfterTries
74 d := time.Duration(initialDelay * math.Exp2(currentTry*k))
75 rc.CurrentTry++
76
77 if d > rc.MaxDelay {
78 d = rc.MaxDelay
79 }
80
81 if rc.Jitter != 0 {
82 f := (randr.Float64() - 0.5) * 2 // random value in range [-1,1)
83 d = time.Duration(float64(d) * (1 + rc.Jitter*f))
84 }
85
86 return d
87 }
88
89 // Sleep for the duration returned by NextDelay().
90 func (rc *Backoff) Sleep() bool {
91 d := rc.NextDelay()
92 if d != 0 {
93 time.Sleep(d)
94 return true
95 }
96 return false
97 }
98
99 // Sets the internal try counter to zero; the next delay returned will be
100 // InitialDelay again.
101 func (rc *Backoff) Reset() {
102 rc.CurrentTry = 0
103 }