-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathretry.go
44 lines (41 loc) · 1.05 KB
/
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
package iters
import (
"context"
"iter"
"time"
)
// Retry returns sequence that allows to retry with specified delays.
// The first iteration occurs immediately (retry, delay, retry, delay, retry).
func Retry[R int, D time.Duration](ctx context.Context, delays iter.Seq[time.Duration]) iter.Seq2[int, time.Duration] {
return func(yield func(int, time.Duration) bool) {
if !yield(0, 0) {
return
}
for attempt, delay := range RetryAfterDelay(ctx, delays) {
if !yield(attempt, delay) {
return
}
}
}
}
// RetryAfterDelay returns sequence that allows to retry with specified delays.
// Started from delay (delay, retry, delay, retry).
func RetryAfterDelay[R int, D time.Duration](ctx context.Context, delays iter.Seq[time.Duration]) iter.Seq2[int, time.Duration] {
return func(yield func(int, time.Duration) bool) {
if delays == nil {
return
}
attempts := 1
for delay := range delays {
select {
case <-ctx.Done():
return
case <-time.After(delay):
}
if !yield(attempts, delay) {
return
}
attempts++
}
}
}