forked from rakyll/drive
-
Notifications
You must be signed in to change notification settings - Fork 424
/
exponential-backoff.go
65 lines (49 loc) · 1.13 KB
/
exponential-backoff.go
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
package expb
import (
"fmt"
"math/rand"
"time"
)
type StatusChecker func(q interface{}) (ok, retryable bool)
type ExponentialBacker struct {
Debug bool
Do Producer
RetryCount uint32
StatusCheck StatusChecker
}
type pair struct {
first interface{}
last interface{}
}
type Callback func(result interface{}, err error)
type Producer func() (result interface{}, err error)
func ExponentialBackOffSync(bk *ExponentialBacker) (interface{}, error) {
done := make(chan *pair)
go func() {
defer close(done)
retries := uint32(0)
for {
res, err := bk.Do()
ok, retryable := bk.StatusCheck(res)
if ok || !retryable || retries >= bk.RetryCount {
done <- &pair{first: res, last: err}
break
}
ms := time.Duration(1e9*rand.Float64()) + ((1 << retries) * time.Second)
if bk.Debug {
fmt.Printf("trying again in %v\n", ms)
}
duration := time.Duration(ms)
time.Sleep(duration)
retries += 1
}
}()
v := <-done
res := v.first
err, _ := v.last.(error)
return res, err
}
func ExponentialBackOff(bk *ExponentialBacker, cb Callback) {
res, err := ExponentialBackOffSync(bk)
cb(res, err)
}