forked from sethvargo/go-retry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackoff_fibonacci.go
50 lines (42 loc) · 1.14 KB
/
backoff_fibonacci.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
package retry
import (
"context"
"fmt"
"sync/atomic"
"time"
"unsafe"
)
type state [2]time.Duration
type fibonacciBackoff struct {
state unsafe.Pointer
}
// Fibonacci is a wrapper around Retry that uses a Fibonacci backoff.
func Fibonacci(ctx context.Context, base time.Duration, f RetryFunc) error {
b, err := NewFibonacci(base)
if err != nil {
return err
}
return Do(ctx, b, f)
}
// NewFibonacci creates a new Fibonacci backoff using the starting value of
// base. The wait time is the sum of the previous two wait times on each failed
// attempt (1, 1, 2, 3, 5, 8, 13...).
func NewFibonacci(base time.Duration) (Backoff, error) {
if base <= 0 {
return nil, fmt.Errorf("base must be greater than 0")
}
return &fibonacciBackoff{
state: unsafe.Pointer(&state{0, base}),
}, nil
}
// Next implements Backoff. It is safe for concurrent use.
func (b *fibonacciBackoff) Next() (time.Duration, bool) {
for {
curr := atomic.LoadPointer(&b.state)
currState := (*state)(curr)
next := currState[0] + currState[1]
if atomic.CompareAndSwapPointer(&b.state, curr, unsafe.Pointer(&state{currState[1], next})) {
return next, false
}
}
}