-
Notifications
You must be signed in to change notification settings - Fork 9
/
errgroup.go
117 lines (95 loc) · 2.24 KB
/
errgroup.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package executor
import (
"context"
"errors"
"fmt"
"sync"
"namespacelabs.dev/go-ids"
)
type ExecutorLike interface {
Go(func(context.Context) error)
GoCancelable(func(context.Context) error) func()
Wait() error
CancelAndWait() error
}
func New(ctx context.Context, name string) *Executor {
ctxWithCancel, cancel := context.WithCancel(ctx)
return &Executor{ctx: ctxWithCancel, cancel: cancel, name: name, id: ids.NewRandomBase32ID(8)}
}
func Newf(ctx context.Context, format string, args ...interface{}) *Executor {
return New(ctx, fmt.Sprintf(format, args...))
}
func NewSerial(ctx context.Context) *Serial {
return &Serial{ctx: ctx}
}
type Executor struct {
ctx context.Context
cancel func()
name string
id string
wg sync.WaitGroup
errOnce sync.Once
err error
}
func (exec *Executor) Wait() error {
exec.wg.Wait()
exec.cancel()
return exec.err
}
func (exec *Executor) CancelAndWait() error {
exec.cancel()
exec.wg.Wait()
return exec.err
}
func (exec *Executor) Cancel() {
exec.cancel()
}
func (exec *Executor) lowlevelGo(f func() error) {
exec.wg.Add(1)
go func() {
defer exec.wg.Done()
if err := f(); err != nil {
exec.errOnce.Do(func() {
exec.err = err
exec.cancel()
})
}
}()
}
func (exec *Executor) Go(f func(context.Context) error) {
exec.lowlevelGo(func() error {
return f(exec.ctx)
})
}
func (exec *Executor) GoCancelable(f func(context.Context) error) func() {
ctxWithCancel, cancel := context.WithCancel(exec.ctx)
exec.lowlevelGo(func() error {
if err := f(ctxWithCancel); err != nil {
// Don't let individual cancelation lead to the cancelation of the whole group.
if !errors.Is(err, context.Canceled) {
return err
}
}
return nil
})
return cancel
}
type Serial struct {
ctx context.Context
err error
}
func (s *Serial) Go(f func(context.Context) error) {
if s.err == nil {
s.err = f(s.ctx)
}
}
func (s *Serial) GoCancelable(f func(context.Context) error) func() {
if s.err == nil {
s.err = f(s.ctx)
}
return func() {}
}
func (s *Serial) Wait() error { return s.err }