-
Notifications
You must be signed in to change notification settings - Fork 0
/
retry.go
54 lines (48 loc) · 959 Bytes
/
retry.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
package retry
import (
"context"
"iter"
"time"
)
type Steps []time.Duration
func (s Steps) Loop() (bool, time.Duration) {
if len(s)%2 == 1 {
return true, s[len(s)-1]
}
return false, 0
}
func (s Steps) Retry(ctx context.Context) iter.Seq2[int, time.Duration] {
return retry(ctx, s)
}
func Retry(ctx context.Context, steps ...time.Duration) iter.Seq2[int, time.Duration] {
return retry(ctx, steps)
}
func retry(ctx context.Context, s Steps) iter.Seq2[int, time.Duration] {
return func(yield func(int, time.Duration) bool) {
var err error
n := 0
for i := 0; i < (len(s)/2)*2; i += 2 {
duration := s[i+1]
for range s[i] {
if err = Sleep(ctx, duration); err != nil {
return
}
if !yield(n, duration) {
return
}
n++
}
}
if has, duration := s.Loop(); has {
for {
if err = Sleep(ctx, duration); err != nil {
return
}
if !yield(n, duration) {
return
}
n++
}
}
}
}