-
Notifications
You must be signed in to change notification settings - Fork 1
/
coordinator.go
219 lines (179 loc) · 6.42 KB
/
coordinator.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
// Package choreograph contains sequentially executing processor.
// Such a way that subsequent steps are executed only when the preceding step has succeeded (job finished successfully).
// Each step also has a function that checks if the step should be executed, if so, the work
// specified in the step is executed, otherwise the step is skipped and the next step in the queue is passed.
package choreograph
import (
"context"
"reflect"
"runtime"
"sync"
"github.com/pkg/errors"
)
type contextKey string
const DataBagContextKey contextKey = "_coordinator_data_bag"
const (
bufferSize = 100
jobDataPostfix = "_job"
preCheckDataPostfix = "_preCheck"
)
var (
// ErrJobFailed implies that job execution failed.
ErrJobFailed = errors.New("job failed")
// ErrUnassignableParameter implies that input cannot be used as a parameter in callback function.
ErrUnassignableParameter = errors.New("cannot assign input to callback")
// ErrExecutionCanceled implies that execution was stopped intentionally by developer.
ErrExecutionCanceled = errors.New("execution canceled by callback")
// ErrInputMustBeSlice implies that input data set should be a slice of any type.
ErrInputMustBeSlice = errors.New("input data should be a slice")
)
// Coordinator is an executing processor of defined steps.
//
// Coordinator uses DataBag to store output from all run pre-check and job functions (if more than error was returned).
// To retrieve DataBag you can get it from context using DataBagContextKey, it is always cleared with start of Run.
//
// Use NewCoordinator to create new instance.
// Coordinator implements ProcessExecutioner interface.
type Coordinator struct {
workerCount int
workers []*worker
inputs chan interface{}
inputsLock sync.Locker
results chan Result
resultsLock sync.Locker
wg *sync.WaitGroup
addStepLock sync.Locker
steps Steps
err []error
}
// NewCoordinator creates new executing processor which uses passed context.
// It returns error if context is nil.
func NewCoordinator(opts ...Option) *Coordinator {
coordinator := &Coordinator{
workerCount: runtime.NumCPU(),
inputsLock: new(sync.Mutex),
resultsLock: new(sync.Mutex),
addStepLock: new(sync.Mutex),
wg: new(sync.WaitGroup),
steps: nil,
inputs: nil,
results: nil,
workers: nil,
err: nil,
}
for _, o := range opts {
o(coordinator)
}
if coordinator.workerCount < 1 {
coordinator.workerCount = 1
}
return coordinator
}
// AddStep adds another step to the queue.
//
// It does a step validation and can return one of following errors:
// - ErrJobIsNotAFunction
// - ErrJobContextAsFirstParameter
// - ErrJobErrorOnOutputRequired
// - ErrJobFuncIsRequired
// - ErrJobTooManyOutputParameters
// - ErrJobErrorAsLastParameterRequired
// - ErrPreCheckIsNotAFunction
// - ErrPreCheckContextAsFirstParameter
// - ErrPreCheckErrorOnOutputRequired
// - ErrPreCheckFuncIsRequired
// - ErrPreCheckTooManyOutputParameters
// - ErrPreCheckLastParamTypeErrorRequired
// Those are step validation errors.
func (c *Coordinator) AddStep(s *Step) error {
c.addStepLock.Lock()
defer c.addStepLock.Unlock()
if err := checkStep(s); err != nil {
return errors.Wrap(err, "add step")
}
c.steps = append(c.steps, s)
return nil
}
// Run executes the process. Use input to pass immutable data for a run.
//
// Runtime of the process is following, pre-check function is always run before job function,
// if pre-check returns error then job function is skipped and next step is run, in case job returns error
// no further step is being run. First return parameters are execution errors returned by jobs/pre-checks,
// second parameter is runtime error. In case run returns a runtime error you should probably retry the same event.
//
// Possible runtime errors:
// - ErrJobFailed
// - ErrExecutionCanceled
// - context.Canceled
func (c *Coordinator) Run(ctx context.Context, input interface{}) ([]error, error) {
// as RunConcurrent can return only ErrInputMustBeSlice as error it's safe to skip it
resultsChan, _ := c.RunConcurrent(ctx, []interface{}{input})
result := <-resultsChan
c.err = result.ExecutionErrors
return result.ExecutionErrors, result.RuntimeError
}
// RunConcurrent executes the process for set of data (same as running Run for each of input).
// This method starts the process in concurrent way, so it will be much faster than regular running.
//
// Runtime of the process is following, pre-check function is always run before job function,
// if pre-check returns error then job function is skipped and next step is run, in case job returns error
// no further step is being run. First return parameters are execution errors returned by jobs/pre-checks,
// second parameter is runtime error. In case run returns a runtime error you should probably retry the same event.
//
// Possible runtime errors:
// - ErrJobFailed
// - ErrExecutionCanceled
// - context.Canceled.
//
// Possible errors:
// - ErrInputMustBeSlice
func (c *Coordinator) RunConcurrent(ctx context.Context, inputs interface{}) (<-chan Result, error) {
inSlice, ok := toInterfaceSlice(inputs)
if !ok {
return c.results, ErrInputMustBeSlice
}
c.inputsLock.Lock()
c.resultsLock.Lock()
c.init(ctx)
c.wg.Add(len(inSlice))
go func(localInputs []interface{}) {
for i := range localInputs {
c.inputs <- localInputs[i]
}
close(c.inputs)
c.inputsLock.Unlock()
}(inSlice)
go func(waitGroup *sync.WaitGroup) {
waitGroup.Wait()
close(c.results)
c.resultsLock.Unlock()
}(c.wg)
return c.results, nil
}
// GetExecutionErrors returns all errors received during the process execution.
// [DEPRECATED] Instead check first return parameter from Run method.
func (c *Coordinator) GetExecutionErrors() []error {
return c.err
}
func (c *Coordinator) init(ctx context.Context) {
c.inputs = make(chan interface{}, bufferSize)
c.results = make(chan Result, bufferSize)
c.workers = make([]*worker, c.workerCount)
for workerIdx := 0; workerIdx < c.workerCount; workerIdx++ {
c.workers[workerIdx] = new(worker)
c.workers[workerIdx].steps = c.steps
go c.workers[workerIdx].StartWorker(ctx, c.inputs, c.results, c.wg)
}
}
func toInterfaceSlice(in interface{}) ([]interface{}, bool) {
sliceValue := reflect.ValueOf(in)
if sliceValue.Kind() != reflect.Slice {
return []interface{}{}, false
}
c := sliceValue.Len()
out := make([]interface{}, c)
for i := 0; i < c; i++ {
out[i] = sliceValue.Index(i).Interface()
}
return out, true
}