-
Notifications
You must be signed in to change notification settings - Fork 5
/
step.go
376 lines (348 loc) · 9.69 KB
/
step.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package flow
import (
"context"
"time"
)
// Steper describes the requirement for a Step, which is basic unit of a Workflow.
//
// Implement this interface to allow Workflow orchestrating your Steps.
//
// Notice Steper will be saved in Workflow as map key, so it's supposed to be 'comparable' type like pointer.
type Steper interface {
Do(context.Context) error
}
// Builder builds a Workflow by adding Steps.
type Builder interface {
AddToWorkflow() map[Steper]*StepConfig
}
// BeforeStep defines callback being called BEFORE step being executed.
type BeforeStep func(context.Context, Steper) (context.Context, error)
// AfterStep defines callback being called AFTER step being executed.
type AfterStep func(context.Context, Steper, error) error
type StepConfig struct {
Upstreams Set[Steper] // Upstreams of the Step, means these Steps should happen-before this Step
Before []BeforeStep // Before callbacks of the Step, will be called before Do
After []AfterStep // After callbacks of the Step, will be called before Do
Option []func(*StepOption) // Option customize the Step settings
}
type StepOption struct {
RetryOption *RetryOption // RetryOption customize how the Step should be retried, default (nil) means no retry.
Condition Condition // Condition decides whether Workflow should execute the Step, default to DefaultCondition.
Timeout *time.Duration // Timeout sets the Step level timeout, default (nil) means no timeout.
}
// Steps declares a series of Steps ready to be added into Workflow.
//
// The Steps declared are mutually independent.
//
// workflow.Add(
// Steps(a, b, c), // a, b, c will be executed in parallel
// Steps(a, b, c).DependsOn(d, e), // d, e will be executed in parallel, then a, b, c in parallel
// )
func Steps(steps ...Steper) AddSteps {
rv := make(AddSteps)
for _, step := range steps {
rv[step] = &StepConfig{Upstreams: make(Set[Steper])}
}
return rv
}
// Step declares Step ready to be added into Workflow.
//
// The main difference between Step() and Steps() is that,
// Step() allows to add Input for the Step.
//
// Step(a).Input(func(ctx context.Context, a *A) error {
// // fill a
// }))
func Step[S Steper](steps ...S) AddStep[S] {
return AddStep[S]{
AddSteps: Steps(ToSteps(steps)...),
Steps: steps,
}
}
// Pipe creates a pipeline in Workflow.
//
// workflow.Add(
// Pipe(a, b, c), // a -> b -> c
// )
//
// The above code is equivalent to:
//
// workflow.Add(
// Step(b).DependsOn(a),
// Step(c).DependsOn(b),
// )
func Pipe(steps ...Steper) AddSteps {
as := Steps(steps...)
for i := 0; i < len(steps)-1; i++ {
as.Merge(Steps(steps[i+1]).DependsOn(steps[i]))
}
return as
}
// BatchPipe creates a batched pipeline in Workflow.
//
// workflow.Add(
// BatchPipe(
// Steps(a, b),
// Steps(c, d, e),
// Steps(f),
// ),
// )
//
// The above code is equivalent to:
//
// workflow.Add(
// Steps(c, d, e).DependsOn(a, b),
// Steps(f).DependsOn(c, d, e),
// )
func BatchPipe(batch ...AddSteps) AddSteps {
as := Steps()
for _, other := range batch {
as.Merge(other)
}
for i := 0; i < len(batch)-1; i++ {
as.Merge(Steps(Keys(batch[i+1])...).DependsOn(Keys(batch[i])...))
}
return as
}
// DependsOn declares dependency on the given Steps.
//
// Step(a).DependsOn(b, c)
//
// Then b, c should happen-before a.
func (as AddSteps) DependsOn(ups ...Steper) AddSteps {
for down := range as {
as[down].Upstreams.Add(ups...)
}
return as
}
// Input adds BeforeStep callback for the Step(s).
//
// Input callbacks will be called before Do,
// and the order will respect the order of declarations.
//
// Step(a).
// Input(/* 1. this Input will be called first */).
// Input(/* 2. this Input will be called after 1. */)
// Step(a).Input(/* 3. this Input is after all */)
//
// The Input callbacks are executed at runtime and per-try.
func (as AddStep[S]) Input(fns ...func(context.Context, S) error) AddStep[S] {
for _, step := range as.Steps {
step := step // capture range variable
for _, fn := range fns {
if fn != nil {
fn := fn // capture range variable
as.AddSteps[step].Before = append(as.AddSteps[step].Before, func(ctx context.Context, _ Steper) (context.Context, error) {
return ctx, fn(ctx, step)
})
}
}
}
return as
}
// Output can pass the results of the Step to outer scope.
// Output is only triggered when the Step is successful (returns nil error).
//
// Output actually adds AfterStep callback for the Step(s).
//
// The Output callbacks are executed at runtime and per-try.
func (as AddStep[S]) Output(fns ...func(context.Context, S) error) AddStep[S] {
for _, step := range as.Steps {
step := step // capture range variable
for _, fn := range fns {
if fn != nil {
fn := fn // capture range variable
as.AddSteps[step].After = append(as.AddSteps[step].After, func(ctx context.Context, _ Steper, err error) error {
if err == nil {
return fn(ctx, step)
}
return err
})
}
}
}
return as
}
// BeforeStep adds BeforeStep callback for the Step(s).
//
// The BeforeStep callback will be called before Do, and return when first error occurs.
// The order of execution will respect the order of declarations.
// The BeforeStep callbacks are able to change the context.Context feed into Do.
// The BeforeStep callbacks are executed at runtime and per-try.
func (as AddSteps) BeforeStep(befores ...BeforeStep) AddSteps {
for step := range as {
as[step].Before = append(as[step].Before, befores...)
}
return as
}
// AfterStep adds AfterStep callback for the Step(s).
//
// The AfterStep callback will be called after Do, and pass the error to next AfterStep callback.
// The order of execution will respect the order of declarations.
// The AfterStep callbacks are able to change the error returned by Do.
// The AfterStep callbacks are executed at runtime and per-try.
func (as AddSteps) AfterStep(afters ...AfterStep) AddSteps {
for step := range as {
as[step].After = append(as[step].After, afters...)
}
return as
}
// Timeout sets the Step level timeout.
func (as AddSteps) Timeout(timeout time.Duration) AddSteps {
for step := range as {
as[step].Option = append(as[step].Option, func(so *StepOption) {
so.Timeout = &timeout
})
}
return as
}
// When set the Condition for the Step.
func (as AddSteps) When(cond Condition) AddSteps {
for step := range as {
as[step].Option = append(as[step].Option, func(so *StepOption) {
so.Condition = cond
})
}
return as
}
// Retry customize how the Step should be retried.
//
// Step will be retried as long as this option is configured.
//
// w.Add(
// Step(a), // not retry
// Step(b).Retry(func(opt *RetryOption) { // will retry 3 times
// opt.MaxAttempts = 3
// }),
// Step(c).Retry(nil), // will use DefaultRetryOption!
// )
func (as AddSteps) Retry(opts ...func(*RetryOption)) AddSteps {
for step := range as {
as[step].Option = append(as[step].Option, func(so *StepOption) {
if so.RetryOption == nil {
so.RetryOption = new(RetryOption)
*so.RetryOption = DefaultRetryOption
}
for _, opt := range opts {
if opt != nil {
opt(so.RetryOption)
}
}
})
}
return as
}
// AddToWorkflow implements Builder
func (as AddSteps) AddToWorkflow() map[Steper]*StepConfig { return as }
// Merge another AddSteps into one.
func (as AddSteps) Merge(others ...AddSteps) AddSteps {
for _, other := range others {
for k, v := range other {
if as[k] == nil {
as[k] = new(StepConfig)
}
as[k].Merge(v)
}
}
return as
}
func (as AddStep[S]) DependsOn(ups ...Steper) AddStep[S] {
as.AddSteps = as.AddSteps.DependsOn(ups...)
return as
}
func (as AddStep[S]) BeforeStep(befores ...BeforeStep) AddStep[S] {
as.AddSteps = as.AddSteps.BeforeStep(befores...)
return as
}
func (as AddStep[S]) AfterStep(afters ...AfterStep) AddStep[S] {
as.AddSteps = as.AddSteps.AfterStep(afters...)
return as
}
func (as AddStep[S]) Timeout(timeout time.Duration) AddStep[S] {
as.AddSteps = as.AddSteps.Timeout(timeout)
return as
}
func (as AddStep[S]) When(when Condition) AddStep[S] {
as.AddSteps = as.AddSteps.When(when)
return as
}
func (as AddStep[S]) Retry(fns ...func(*RetryOption)) AddStep[S] {
as.AddSteps = as.AddSteps.Retry(fns...)
return as
}
type AddStep[S Steper] struct {
AddSteps
Steps []S
}
type AddSteps map[Steper]*StepConfig
// ToSteps converts []<StepDoer implemention> to []StepDoer.
//
// steps := []someStepImpl{ ... }
// flow.Add(
// Steps(ToSteps(steps)...),
// )
func ToSteps[S Steper](steps []S) []Steper {
rv := []Steper{}
for _, s := range steps {
rv = append(rv, s)
}
return rv
}
func (sc *StepConfig) Merge(other *StepConfig) {
if other == nil {
return
}
if sc.Upstreams == nil {
sc.Upstreams = make(Set[Steper])
}
sc.Upstreams.Union(other.Upstreams)
sc.Before = append(sc.Before, other.Before...)
sc.After = append(sc.After, other.After...)
sc.Option = append(sc.Option, other.Option...)
}
type Set[T comparable] map[T]struct{}
func (s Set[T]) Has(v T) bool {
if s == nil {
return false
}
_, ok := s[v]
return ok
}
func (s *Set[T]) Add(vs ...T) {
if *s == nil {
*s = make(Set[T])
}
for _, v := range vs {
(*s)[v] = struct{}{}
}
}
func (s *Set[T]) Union(sets ...Set[T]) {
for _, set := range sets {
s.Add(set.Flatten()...)
}
}
func (s Set[T]) Flatten() []T {
r := make([]T, 0, len(s))
for v := range s {
r = append(r, v)
}
return r
}
// Keys returns the keys of the map m.
// The keys will be in an indeterminate order.
func Keys[M ~map[K]V, K comparable, V any](m M) []K {
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
return r
}
// Values returns the values of the map m.
// The values will be in an indeterminate order.
func Values[M ~map[K]V, K comparable, V any](m M) []V {
r := make([]V, 0, len(m))
for _, v := range m {
r = append(r, v)
}
return r
}