-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop.go
More file actions
101 lines (94 loc) · 1.9 KB
/
loop.go
File metadata and controls
101 lines (94 loc) · 1.9 KB
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
98
99
100
101
// 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 task
import (
"context"
)
// Loop creates a task that repeatedly runs t with same context until it returns an
// error.
func (t Task) Loop() Task {
return func(ctx context.Context) (err error) {
for {
err = t.Run(ctx)
if err != nil {
return
}
}
}
}
// Retry creates a task thats repeatedly runs t with same context until it returns
// nil.
//
// Retrying [Micro] task is resource-wasting as it never fail.
func (t Task) Retry() Task {
return func(ctx context.Context) (err error) {
for {
err = t.Run(ctx)
if err == nil {
return
}
}
}
}
// RetryN is like Retry, but retries no more than n times.
//
// In other words, RetryN(2) will run at most 3 times:
//
// - first try
// - first retry
// - second retry
//
// Retrying [Micro] task is resource-wasting as it never fail.
func (t Task) RetryN(n int) Task {
if n < 0 {
n = 0
}
n++
return func(ctx context.Context) (err error) {
for i := 0; i < n; i++ {
err = t.Run(ctx)
if err == nil {
return
}
}
return
}
}
// RetryNIf is like RetryN, but retries only if errf returns true.
//
// Error passed to errf can never be nil.
func (t Task) RetryNIf(errf func(error) bool, n int) Task {
if n < 0 {
n = 0
}
n++
return func(ctx context.Context) (err error) {
for i := 0; i < n; i++ {
err = t.Run(ctx)
if err == nil {
return
}
if !errf(err) {
return
}
}
return
}
}
// RetryIf is like Retry, but retries only if errf returns true.
//
// Error passed to errf can never be nil.
func (t Task) RetryIf(errf func(error) bool) Task {
return func(ctx context.Context) (err error) {
for {
err = t.Run(ctx)
if err == nil {
return
}
if !errf(err) {
return
}
}
}
}