...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package jsonclient
16
17 import (
18 "sync"
19 "time"
20 )
21
22 type backoff struct {
23 mu sync.RWMutex
24 multiplier uint
25 notBefore time.Time
26 }
27
28 const (
29
30 maxMultiplier = 8
31 )
32
33 func (b *backoff) set(override *time.Duration) time.Duration {
34 b.mu.Lock()
35 defer b.mu.Unlock()
36 if b.notBefore.After(time.Now()) {
37 if override != nil {
38
39
40 notBefore := time.Now().Add(*override)
41 if notBefore.After(b.notBefore) {
42 b.notBefore = notBefore
43 }
44 }
45 return time.Until(b.notBefore)
46 }
47 var wait time.Duration
48 if override != nil {
49 wait = *override
50 } else {
51 if b.multiplier < maxMultiplier {
52 b.multiplier++
53 }
54 wait = time.Second * time.Duration(1<<(b.multiplier-1))
55 }
56 b.notBefore = time.Now().Add(wait)
57 return wait
58 }
59
60 func (b *backoff) decreaseMultiplier() {
61 b.mu.Lock()
62 defer b.mu.Unlock()
63 if b.multiplier > 0 {
64 b.multiplier--
65 }
66 }
67
68 func (b *backoff) until() time.Time {
69 b.mu.RLock()
70 defer b.mu.RUnlock()
71 return b.notBefore
72 }
73
View as plain text