-
Notifications
You must be signed in to change notification settings - Fork 456
/
task.go
82 lines (73 loc) · 2.17 KB
/
task.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
package util
import (
"context"
"fmt"
"runtime/debug"
"sync"
)
// RunTasks executes all of the provided functions concurrently and waits for
// them all to complete. If a function returns an error, all other functions
// are canceled (i.e. the context they are passed is canceled) and the error is
// returned. If all functions finish to completion successfully, RunTasks
// returns nil. If the context passed to RunTasks is canceled then each
// function is canceled and RunTasks returns ctx.Err(). Tasks passed to
// RunTasks MUST support cancellation via the provided context for RunTasks to
// work properly.
func RunTasks(ctx context.Context, tasks ...func(context.Context) error) error {
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(ctx)
defer func() {
cancel()
wg.Wait()
}()
errch := make(chan error, len(tasks))
runTask := func(task func(context.Context) error) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v\n%s\n", r, string(debug.Stack())) //nolint: revive // newlines are intentional
}
wg.Done()
}()
return task(ctx)
}
wg.Add(len(tasks))
for _, task := range tasks {
task := task
go func() {
errch <- runTask(task)
}()
}
for complete := 0; complete < len(tasks); {
select {
case <-ctx.Done():
return ctx.Err()
case err := <-errch:
if err != nil {
return err
}
complete++
}
}
return nil
}
// SerialRun executes all of the provided functions serially.
// If all functions finish to completion successfully, SerialRun
// returns nil. If the context passed to SerialRun is canceled
// then each function is canceled and SerialRun returns ctx.Err().
// Tasks passed to SerialRun MUST support cancellation via the provided
// context for SerialRun to work properly.
func SerialRun(tasks ...func(context.Context) error) func(ctx context.Context) error {
return func(ctx context.Context) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v\n%s\n", r, string(debug.Stack())) //nolint: revive // newlines are intentional
}
}()
for _, task := range tasks {
if err := task(ctx); err != nil {
return err
}
}
return nil
}
}