-
Notifications
You must be signed in to change notification settings - Fork 2
/
awaiter.go
97 lines (76 loc) · 1.72 KB
/
awaiter.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
package async
import (
"context"
)
type Awaiter interface {
// Add add an action
Add(action Action)
// Wait wail for all actions to completed
Wait(context.Context) ([]error, error)
// WaitAny wait for any action to completed without error, can cancel other tasks
WaitAny(context.Context) ([]error, error)
// WaitN wait for N actions to completed without error
WaitN(context.Context, int) ([]error, error)
}
type awaiter struct {
actions []Action
}
func (a *awaiter) Add(action Action) {
a.actions = append(a.actions, action)
}
func (a *awaiter) Wait(ctx context.Context) ([]error, error) {
wait := make(chan error)
for _, action := range a.actions {
go func(action Action) {
wait <- action(ctx)
}(action)
}
var taskErrs []error
tt := len(a.actions)
for i := 0; i < tt; i++ {
select {
case err := <-wait:
if err != nil {
taskErrs = append(taskErrs, err)
}
case <-ctx.Done():
return taskErrs, ctx.Err()
}
}
if len(taskErrs) > 0 {
return taskErrs, ErrTooLessDone
}
return taskErrs, nil
}
func (a *awaiter) WaitN(ctx context.Context, n int) ([]error, error) {
wait := make(chan error)
cancelCtx, cancel := context.WithCancel(ctx)
defer cancel()
for _, action := range a.actions {
go func(action Action) {
wait <- action(cancelCtx)
}(action)
}
var taskErrs []error
tt := len(a.actions)
var done int
for i := 0; i < tt; i++ {
select {
case err := <-wait:
if err != nil {
taskErrs = append(taskErrs, err)
} else {
done++
if done == n {
return taskErrs, nil
}
}
case <-ctx.Done():
return taskErrs, ctx.Err()
}
}
return taskErrs, ErrTooLessDone
}
func (a *awaiter) WaitAny(ctx context.Context) ([]error, error) {
return a.WaitN(ctx, 1)
}