-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathretry.go
97 lines (84 loc) · 2.04 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package routines
import "sync/atomic"
// Recorded creates a function that remembers how many times it is called
//
// for example:
//
// x := Recorded(f)
// x() // equals f(0)
// x() // equals f(1)
// x() // equals f(2)
func Recorded(f func(idx uint64) error) (ret func() error) {
x := uint64(0)
tries := &x
return func() (err error) {
err = f(atomic.LoadUint64(tries))
atomic.AddUint64(tries, 1)
return
}
}
// Retry runs f() until it returns nil
//
// err is closed when f() returns nil
//
// common usacase:
//
// ch := Retry(RunAtLeast(time.Minute, f)) // retries every minute
// idx := 1
// for e := range ch {
// log.Printf("#%d attempt is failed: %v", idx, err)
// idx++
// }
// log.Print("#%d attempt is successfully done", idx)
//
// WARNING: err is not buffered, so it won't execute before error in err is consumed
func Retry(f func() error) (err chan error) {
err = make(chan error)
go func(err chan error) {
defer close(err)
for {
e := f()
if e == nil {
return
}
err <- e
}
}(err)
return
}
// TriesAtMost retries f for at most n times
//
// suppose your f() costs 1s to run and always fail, TriesAtMost(10, f) will run f()
// 10 times (which costs you 10s), and err is closed at 10s
func TriesAtMost(n uint64, f func() error) (err chan error) {
return Retry(Recorded(func(idx uint64) error {
if idx >= n {
return nil
}
return f()
}))
}
// TryAtMost wraps TriesAtMost, returns last error iff all attempts failed.
func TryAtMost(n uint64, f func() error) (err error) {
ch := TriesAtMost(n, f)
cnt := uint64(0)
for err = range ch {
cnt++
}
if cnt < n {
err = nil
}
return
}
// IgnoreErr drops all errors in ch asynchronously
//
// If you need it synchronously, just use "for range ch {}".
func IgnoreErr(ch chan error) {
go func() {
for range ch {
}
}()
}