-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorchestration.go
358 lines (313 loc) · 8.15 KB
/
orchestration.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// Copyright 2024 Outreach Corporation. All Rights Reserved.
// Description: This file contains task orchestration code
package plumber
import (
"context"
"errors"
"sync"
"golang.org/x/sync/errgroup"
)
// DoneFunc is a func used to report that worker has finished
type DoneFunc func(error)
// ReadyFunc is a func used to report that worker is ready
type ReadyFunc func()
// Done reports back runner status using given error
func (f DoneFunc) Done(do func() error) {
f(do())
}
// Finish reports back runner status using given error
func (f DoneFunc) Finish(err error) {
if f != nil {
f(err)
}
}
// Success reports back runner status as success. It is preferred then running Done(nil) to increase code readability.
func (f DoneFunc) Success() {
f(nil)
}
// ErrorCh is a channel of errors
type ErrorCh chan error
// Errors returns errors accumulated in the channel. This function blockes until the channel is closed
func (ec ErrorCh) Errors() []error {
errs := []error{}
for err := range ec {
errs = append(errs, err)
}
return errs
}
// WaitTill waits till channel is not close or till given context is ended and then returns all accumulated errors.
func (ec ErrorCh) WaitTill(ctx context.Context) []error {
var (
errs = []error{}
)
for {
select {
case <-ctx.Done():
if !errors.Is(ctx.Err(), context.Canceled) {
errs = append(errs, ctx.Err())
}
return errs
case err, ok := <-ec:
if err != nil {
errs = append(errs, err)
}
if !ok {
return errs
}
}
}
}
// Wait waits till channel is not close and returns all accumulated errors.
func (ec ErrorCh) Wait() []error {
var (
errs = []error{}
)
for {
err, ok := <-ec
if err != nil {
errs = append(errs, err)
}
if !ok {
return errs
}
}
}
// CallbackFunc a callback function type for graceful runner
type CallbackFunc func(context.Context) error
// ReadyRunner creates a Runner based on supplied run function with callback to signal ready state
func ReadyRunner(run func(ctx context.Context, ready ReadyFunc) error) Runner {
signal := NewSignal()
return NewRunner(func(ctx context.Context) error {
return run(ctx, func() {
signal.Notify()
})
}, WithReady(signal))
}
// Closer creates a runner implementing Closer interface based on supplied close function with noop Run method
// run method will block until context is done or close function is invoked
func Closer(closeFunc CallbackFunc) Runner {
signal := NewSignal()
return NewRunner(func(ctx context.Context) error {
select {
case <-ctx.Done():
case <-signal.C():
}
return nil
}, WithClose(func(ctx context.Context) error {
err := closeFunc(ctx)
signal.Notify()
return err
}))
}
// PipelineRunner creates a pipeline runner so the pipeline it self can be started and closed
func PipelineRunner(runner Runner, opts ...Option) RunnerCloser {
var (
signal = NewSignal()
)
opts = append(opts, SignalChannelCloser(signal))
return NewRunner(
func(ctx context.Context) error {
err := Start(ctx, runner, opts...)
return err
},
WithClose(func(ctx context.Context) error {
// trigger close sequence
signal.Notify()
return nil
}),
)
}
// eventRun is a event run event type for runner state machine
type eventRun struct {
}
// eventReady is a event runner ready event type for runner state machine
type eventReady struct {
}
// eventClosed is a event all runner closed event type for runner state machine
type eventClosed struct {
err error
}
// eventRunnerStart is a event start event type for runner state machine
type eventRunnerStart struct {
}
// eventRunnerClose is a event runner close event type for runner state machine
type eventRunnerClose struct {
id int
}
// eventClose is a event close event type for runner state machine
type eventClose struct {
closerContext context.Context
done chan error
}
// eventFinished is a event finish event type for runner state machine
type eventFinished struct {
err error
}
// eventError is a event error event type for runner state machine
type eventError struct {
err error
}
// Start will execute given runner with optional configuration
func Start(xctx context.Context, runner Runner, opts ...Option) error {
var (
options = &Options{}
messages = make(chan any, 10)
onceClose sync.Once
)
startCtx := options.apply(xctx, opts...)
defer options.finalize()
runCtx, runCancel := context.WithCancelCause(startCtx)
closers := newCloserContext(runCtx)
defer closers.cancel()
options.close = func() {
onceClose.Do(func() {
messages <- &eventClose{}
})
}
go closers.startClosers(messages, options.closers...)
if propagator, ok := runner.(ErrorNotifier); ok {
go func() {
select {
case <-startCtx.Done():
return
case <-propagator.Errored():
onceClose.Do(func() {
messages <- &eventClose{}
})
}
}()
}
// lets try to start the runner
go func() {
messages <- &eventRun{}
}()
// main event loop
return errors.Join(func() []error {
defer func() {
// drain the close signal
onceClose.Do(func() {})
}()
var running bool
var closing bool
errs := []error{}
for m := range messages {
switch m := m.(type) {
// close requested
case *eventClose:
// we are not running so we are safe to exit
if !running {
return errs
}
if closing {
continue
}
closing = true
go func() {
closeCtx, closeCancel := options.closeContext(startCtx, runCancel)
defer closeCancel()
// start the close sequence
messages <- &eventError{err: RunnerClose(closeCtx, runner)}
}()
// starting runner
case *eventRun:
// already started
if running || closing {
continue
}
running = true
// runner go routine
go func() {
// notify about pipeline readiness
if options.readySignal != nil {
ready := RunnerReady(runner)
go func() {
select {
case <-ready:
options.readySignal.Notify()
case <-runCtx.Done():
}
}()
}
err := runner.Run(runCtx)
messages <- &eventFinished{err: err}
}()
// runner has finished running
case *eventFinished:
if m.err != nil {
errs = append(errs, m.err)
}
return errs
// some error occurred
case *eventError:
if m.err != nil {
errs = append(errs, m.err)
}
}
}
return errs
}()...)
}
// newCloserContext return instance of *closerContext
func newCloserContext(startCtx context.Context) *closerContext {
var erg, closerCtx = errgroup.WithContext(startCtx)
closerCtx, closerCancel := context.WithCancel(closerCtx)
return &closerContext{
erg: erg,
cancel: closerCancel,
ctx: closerCtx,
}
}
// closerContext a helper struct managing pipeline closers
type closerContext struct {
erg *errgroup.Group
ctx context.Context
cancel func()
}
// startClosers starts closers functions and captures an error
func (c *closerContext) startClosers(messages chan any, closers ...func(context.Context) error) {
for _, closer := range closers {
c.erg.Go(func() error {
return closer(c.ctx)
})
}
// closers go routine
go func() {
err := c.erg.Wait()
if !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) {
messages <- &eventError{err: err}
}
}()
}
// PipelineOptions holds a pipeline options
type PipelineOptions struct {
ErrorNotifier ErrorNotifierStrategy
KeepRunningOnError bool
}
// NewPipelineOptions creates a default instance of PipelineOptions
func NewPipelineOptions() *PipelineOptions {
return &PipelineOptions{
ErrorNotifier: NotifyingErrorNotifier{},
}
}
// PipelineOption is a option patter struct for PipelineOptions
type PipelineOption func(*PipelineOptions)
// apply given PipelineOption
func (o *PipelineOptions) apply(oo ...PipelineOption) {
for _, op := range oo {
op(o)
}
}
// WithErrorNotifier overrides default error notifier strategy
func WithErrorNotifier(errorNotifier ErrorNotifierStrategy) func(*PipelineOptions) {
return func(o *PipelineOptions) {
o.ErrorNotifier = errorNotifier
}
}
// UnlessCanceled returns nil if error is context.Canceled
// The pipeline might return context.Canceled error when it is closed
func UnlessCanceled(err error) error {
if errors.Is(err, context.Canceled) {
return nil
}
return err
}