-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsafestep.go
229 lines (214 loc) · 6.36 KB
/
safestep.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package safestep
import (
"context"
"fmt"
"sync"
)
// SafeStep used for handling multiple layers goroutine execution
type SafeStep interface {
// AddInput add input which can be used by asyncFunc parameter
// it can also be called in previous function call step so it can acts like dependency
AddInput(code string, input interface{}) SafeStep
// GetInput will get input thar can be used inside asyncFunc
GetInput(code string) interface{}
// AddFunction adding asyncFunc with function code
// code must be unique, otherwise previous function result will be overwritten
AddFunction(code string, function asyncFunc) SafeStep
// Step appends async function step
Step() SafeStep
// Do execute all async functions according to their order
Do() (map[string]interface{}, error)
// Do execute all async functions according to their order(with maximum concurrency)
DoWithMaxConcurrency(maxConcurrency int) (map[string]interface{}, error)
}
// SafeStepStruct used for handling multiple layers goroutine execution
type SafeStepStruct struct {
ctx context.Context
input map[string]interface{}
step []map[string]asyncFunc
tempFuncs map[string]asyncFunc
result map[string]interface{}
mapLock sync.RWMutex
err error
}
type goRoutineResp struct {
code string
result interface{}
err error
}
type asyncFunc func() (interface{}, error)
// New initialization
func New() SafeStep {
return &SafeStepStruct{
ctx: context.Background(),
input: make(map[string]interface{}),
result: make(map[string]interface{}),
tempFuncs: make(map[string]asyncFunc),
step: make([]map[string]asyncFunc, 0),
}
}
// New initialization
func NewWithContext(ctx context.Context) SafeStep {
return &SafeStepStruct{
ctx: ctx,
input: make(map[string]interface{}),
result: make(map[string]interface{}),
tempFuncs: make(map[string]asyncFunc),
step: make([]map[string]asyncFunc, 0),
}
}
// GetInput will get input thar can be used inside asyncFunc
func (step *SafeStepStruct) GetInput(code string) interface{} {
step.mapLock.Lock()
input := step.input[code]
step.mapLock.Unlock()
return input
}
// AddInput add input which can be used by asyncFunc parameter, note that it can also be used in previous step so it can acts like dependency
func (step *SafeStepStruct) AddInput(code string, input interface{}) SafeStep {
step.mapLock.Lock()
step.input[code] = input
step.mapLock.Unlock()
return step
}
// AddFunction adding asyncFunc with function code (must be unique, otherwise previous function result will be overwritten)
func (step *SafeStepStruct) AddFunction(code string, function asyncFunc) SafeStep {
step.mapLock.Lock()
step.tempFuncs[code] = function
step.mapLock.Unlock()
return step
}
// Step appends async function step
func (step *SafeStepStruct) Step() SafeStep {
step.step = append(step.step, step.tempFuncs)
step.tempFuncs = make(map[string]asyncFunc)
return step
}
// Do execute all async functions according to their order
func (step *SafeStepStruct) Do() (map[string]interface{}, error) {
// check just in case there are still some function not appended
if len(step.tempFuncs) > 0 {
step.Step()
}
// execute async funcs in their respective order
for _, s := range step.step {
chGo := make(chan goRoutineResp, len(s)) // to get asyncFunc result
defer close(chGo)
var wg sync.WaitGroup // to wait all goroutine/timeout finish (whichever first)
var mu sync.RWMutex // prevent race condition
wg.Add(len(s))
for code, f := range s {
go func(code string, f asyncFunc) {
defer func() { // recover go routine in case of panic
if r := recover(); r != nil {
mu.Lock()
chGo <- goRoutineResp{
code: code,
err: fmt.Errorf("%v", r), // convert panic to err
}
mu.Unlock()
wg.Done()
}
}()
res, err := f()
mu.Lock()
chGo <- goRoutineResp{
code: code,
result: res,
err: err,
}
mu.Unlock()
wg.Done()
}(code, f)
}
step.err = waitTimeout(step.ctx, &wg)
if step.err != nil {
return step.result, step.err
}
for range s { // put all asyncFunc response to result based on function code
mu.RLock()
resp := <-chGo
mu.RUnlock()
if resp.err != nil {
step.err = resp.err
return step.result, step.err
}
step.result[resp.code] = resp.result
}
}
return step.result, step.err
}
// Do execute all async functions according to their order(with maximum concurrency)
func (step *SafeStepStruct) DoWithMaxConcurrency(maxConcurrency int) (map[string]interface{}, error) {
// check just in case there are still some function not appended
if len(step.tempFuncs) > 0 {
step.Step()
}
// execute async funcs in their respective order
for _, s := range step.step {
chGo := make(chan goRoutineResp, len(s)) // to get asyncFunc result
defer close(chGo)
var wg sync.WaitGroup // to wait all goroutine/timeout finish (whichever first)
var mu sync.RWMutex // prevent race condition
var counter = 0 // count total data has been executed
for code, f := range s {
wg.Add(1)
go func(code string, f asyncFunc) {
defer func() { // recover go routine in case of panic
if r := recover(); r != nil {
mu.Lock()
chGo <- goRoutineResp{
code: code,
err: fmt.Errorf("%v", r), // convert panic to err
}
mu.Unlock()
wg.Done()
}
}()
res, err := f()
mu.Lock()
chGo <- goRoutineResp{
code: code,
result: res,
err: err,
}
mu.Unlock()
wg.Done()
}(code, f)
// limit maximum concurrency that will be executed in this function
if ((counter + 1) == len(s)) ||
((counter+1)%maxConcurrency == 0) {
step.err = waitTimeout(step.ctx, &wg)
if step.err != nil {
return step.result, step.err
}
}
counter++ // add counter
}
for range s { // put all asyncFunc response to result based on function code
mu.RLock()
resp := <-chGo
mu.RUnlock()
if resp.err != nil {
step.err = resp.err
return step.result, step.err
}
step.result[resp.code] = resp.result
}
}
return step.result, step.err
}
// waitTimeout waits for the waitgroup for the specified max timeout, return error if context done
func waitTimeout(ctx context.Context, wg *sync.WaitGroup) error {
c := make(chan struct{})
go func() {
defer close(c)
wg.Wait()
}()
select {
case <-c:
return nil
case <-ctx.Done():
return ctx.Err()
}
}