-
Notifications
You must be signed in to change notification settings - Fork 10
/
kitchen_sink.go
331 lines (309 loc) · 10.5 KB
/
kitchen_sink.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
package kitchensink
import (
"context"
"errors"
"fmt"
"time"
"github.com/temporalio/omes/loadgen/kitchensink"
"go.temporal.io/api/common/v1"
"go.temporal.io/sdk/temporal"
"go.temporal.io/sdk/workflow"
)
type KSWorkflowState struct {
workflowState *kitchensink.WorkflowState
}
func KitchenSinkWorkflow(ctx workflow.Context, params *kitchensink.WorkflowInput) (*common.Payload, error) {
workflow.GetLogger(ctx).Debug("Started kitchen sink workflow")
state := KSWorkflowState{
workflowState: &kitchensink.WorkflowState{},
}
queryErr := workflow.SetQueryHandler(ctx, "report_state",
func(input interface{}) (*kitchensink.WorkflowState, error) {
return state.workflowState, nil
})
if queryErr != nil {
return nil, queryErr
}
updateErr := workflow.SetUpdateHandlerWithOptions(ctx, "do_actions_update",
func(ctx workflow.Context, actions *kitchensink.DoActionsUpdate) (rval interface{}, err error) {
rval, err = state.handleActionSet(ctx, actions.GetDoActions())
if rval == nil {
rval = &state.workflowState
}
return rval, err
}, workflow.UpdateHandlerOptions{
Validator: func(ctx workflow.Context, actions *kitchensink.DoActionsUpdate) error {
if actions.GetRejectMe() != nil {
return errors.New("rejected")
}
return nil
},
})
if updateErr != nil {
return nil, updateErr
}
// Handle initial set
if params != nil && params.InitialActions != nil {
for _, actionSet := range params.InitialActions {
if ret, err := state.handleActionSet(ctx, actionSet); ret != nil || err != nil {
workflow.GetLogger(ctx).Debug("Finishing early", "ret", ret, "err", err)
return ret, err
}
}
}
// Handle signal action sets
signalActionsChan := workflow.GetSignalChannel(ctx, "do_actions_signal")
retOrErrChan := workflow.NewChannel(ctx)
workflow.Go(ctx, func(ctx workflow.Context) {
for {
var sigActions kitchensink.DoSignal_DoSignalActions
signalActionsChan.Receive(ctx, &sigActions)
actionSet := sigActions.GetDoActionsInMain()
if actionSet == nil {
actionSet = sigActions.GetDoActions()
}
workflow.Go(ctx, func(ctx workflow.Context) {
ret, err := state.handleActionSet(ctx, actionSet)
if ret != nil || err != nil {
retOrErrChan.Send(ctx, ReturnOrErr{ret, err})
}
})
}
})
for {
var retOrErr ReturnOrErr
retOrErrChan.Receive(ctx, &retOrErr)
workflow.GetLogger(ctx).Info("Finishing workflow", "retOrErr", retOrErr)
return retOrErr.retme, retOrErr.err
}
}
func (ws *KSWorkflowState) handleActionSet(
ctx workflow.Context,
set *kitchensink.ActionSet,
) (returnValue *common.Payload, err error) {
// If these are non-concurrent, just execute and return if requested
if !set.Concurrent {
for _, action := range set.Actions {
if returnValue, err = ws.handleAction(ctx, action); returnValue != nil || err != nil {
return
}
}
return
}
// With a concurrent set, we'll use a coroutine for each, only updating the
// return values if we should return, then awaiting on that or completion
var actionsCompleted int
for _, action := range set.Actions {
action := action
workflow.Go(ctx, func(ctx workflow.Context) {
if maybeReturnValue, maybeErr := ws.handleAction(ctx, action); maybeReturnValue != nil || maybeErr != nil {
returnValue, err = maybeReturnValue, maybeErr
}
actionsCompleted++
})
}
awaitErr := workflow.Await(ctx, func() bool {
return (returnValue != nil || err != nil) || actionsCompleted == len(set.Actions)
})
if awaitErr != nil {
return nil, fmt.Errorf("failed waiting on actions: %w", err)
}
return
}
func (ws *KSWorkflowState) handleAction(
ctx workflow.Context,
action *kitchensink.Action,
) (*common.Payload, error) {
if rr := action.GetReturnResult(); rr != nil {
return rr.ReturnThis, nil
} else if re := action.GetReturnError(); re != nil {
return nil, temporal.NewApplicationError(re.Failure.Message, "")
} else if can := action.GetContinueAsNew(); can != nil {
// Use string arg to avoid the SDK trying to convert payload to input type
return nil, workflow.NewContinueAsNewError(ctx, "kitchenSink", can.GetArguments()[0])
} else if timer := action.GetTimer(); timer != nil {
return nil, withAwaitableChoice(ctx, func(ctx workflow.Context) workflow.Future {
fut, setter := workflow.NewFuture(ctx)
workflow.Go(ctx, func(ctx workflow.Context) {
_ = workflow.Sleep(ctx, time.Duration(timer.Milliseconds)*time.Millisecond)
setter.Set(struct{}{}, nil)
})
return fut
}, timer.AwaitableChoice)
} else if act := action.GetExecActivity(); act != nil {
return nil, launchActivity(ctx, action.GetExecActivity())
} else if child := action.GetExecChildWorkflow(); child != nil {
// Use name if present, otherwise use this one
childType := "kitchenSink"
if child.WorkflowType != "" {
childType = child.WorkflowType
}
err := withAwaitableChoiceCustom(ctx, func(ctx workflow.Context) workflow.ChildWorkflowFuture {
return workflow.ExecuteChildWorkflow(ctx, childType, child.GetInput()[0])
}, child.AwaitableChoice,
func(ctx workflow.Context, fut workflow.ChildWorkflowFuture) error {
return fut.GetChildWorkflowExecution().Get(ctx, nil)
},
func(ctx workflow.Context, fut workflow.ChildWorkflowFuture) error {
return fut.Get(ctx, nil)
},
)
return nil, err
} else if patch := action.GetSetPatchMarker(); patch != nil {
if workflow.GetVersion(ctx, patch.GetPatchId(), workflow.DefaultVersion, 1) == 1 {
return ws.handleAction(ctx, patch.GetInnerAction())
}
} else if setWfState := action.GetSetWorkflowState(); setWfState != nil {
ws.workflowState = setWfState
} else if awaitState := action.GetAwaitWorkflowState(); awaitState != nil {
err := workflow.Await(ctx, func() bool {
if val, ok := ws.workflowState.Kvs[awaitState.Key]; ok {
return val == awaitState.Value
}
return false
})
return nil, err
} else if upsertMemo := action.GetUpsertMemo(); upsertMemo != nil {
convertedMap := make(map[string]interface{}, len(upsertMemo.GetUpsertedMemo().Fields))
for k, v := range upsertMemo.GetUpsertedMemo().Fields {
convertedMap[k] = v
}
err := workflow.UpsertMemo(ctx, convertedMap)
return nil, err
} else if upsertSA := action.GetUpsertSearchAttributes(); upsertSA != nil {
convertedMap := make(map[string]interface{}, len(upsertSA.GetSearchAttributes()))
for k, v := range upsertSA.GetSearchAttributes() {
convertedMap[k] = v
}
err := workflow.UpsertSearchAttributes(ctx, convertedMap)
return nil, err
} else if action.GetNestedActionSet() != nil {
return ws.handleActionSet(ctx, action.GetNestedActionSet())
} else {
return nil, fmt.Errorf("unrecognized action")
}
return nil, nil
}
func launchActivity(ctx workflow.Context, act *kitchensink.ExecuteActivityAction) error {
actType := "noop"
args := make([]interface{}, 0)
if delay := act.GetDelay(); delay != nil {
actType = "delay"
args = append(args, delay.AsDuration())
}
if act.GetIsLocal() != nil {
opts := workflow.LocalActivityOptions{
ScheduleToCloseTimeout: act.ScheduleToCloseTimeout.AsDuration(),
StartToCloseTimeout: act.StartToCloseTimeout.AsDuration(),
RetryPolicy: convertFromPBRetryPolicy(act.GetRetryPolicy()),
}
actCtx := workflow.WithLocalActivityOptions(ctx, opts)
return withAwaitableChoice(actCtx, func(ctx workflow.Context) workflow.Future {
return workflow.ExecuteLocalActivity(ctx, actType, args...)
}, act.GetAwaitableChoice())
} else {
waitForCancel := false
if remote := act.GetRemote(); remote != nil {
if remote.GetCancellationType() == kitchensink.ActivityCancellationType_WAIT_CANCELLATION_COMPLETED {
waitForCancel = true
}
}
opts := workflow.ActivityOptions{
TaskQueue: act.TaskQueue,
ScheduleToCloseTimeout: act.ScheduleToCloseTimeout.AsDuration(),
StartToCloseTimeout: act.StartToCloseTimeout.AsDuration(),
ScheduleToStartTimeout: act.ScheduleToStartTimeout.AsDuration(),
WaitForCancellation: waitForCancel,
HeartbeatTimeout: act.HeartbeatTimeout.AsDuration(),
RetryPolicy: convertFromPBRetryPolicy(act.GetRetryPolicy()),
}
actCtx := workflow.WithActivityOptions(ctx, opts)
return withAwaitableChoice(actCtx, func(ctx workflow.Context) workflow.Future {
return workflow.ExecuteActivity(ctx, actType, args...)
}, act.GetAwaitableChoice())
}
}
func withAwaitableChoice[F workflow.Future](
ctx workflow.Context,
starter func(workflow.Context) F,
awaitChoice *kitchensink.AwaitableChoice,
) error {
return withAwaitableChoiceCustom(ctx, starter, awaitChoice,
func(ctx workflow.Context, fut F) error {
_ = workflow.Sleep(ctx, 1)
return nil
},
func(ctx workflow.Context, fut F) error {
return fut.Get(ctx, nil)
})
}
func withAwaitableChoiceCustom[F workflow.Future](
ctx workflow.Context,
starter func(workflow.Context) F,
awaitChoice *kitchensink.AwaitableChoice,
afterStartedWaiter func(workflow.Context, F) error,
afterCompletedWaiter func(workflow.Context, F) error,
) error {
cancelCtx, cancel := workflow.WithCancel(ctx)
fut := starter(cancelCtx)
var err error
didCancel := false
if awaitChoice.GetAbandon() != nil {
return nil
} else if awaitChoice.GetCancelBeforeStarted() != nil {
cancel()
didCancel = true
err = fut.Get(ctx, nil)
} else if awaitChoice.GetCancelAfterStarted() != nil {
err = afterStartedWaiter(ctx, fut)
if err != nil {
return err
}
cancel()
didCancel = true
err = fut.Get(ctx, nil)
} else if awaitChoice.GetCancelAfterCompleted() != nil {
res := afterCompletedWaiter(ctx, fut)
cancel()
err = res
} else {
err = fut.Get(ctx, nil)
}
// If we intentionally cancelled we want to swallow the cancel error to avoid bombing out the
// whole workflow
var canceledErr *temporal.CanceledError
if didCancel && errors.As(err, &canceledErr) {
err = nil
}
return err
}
// Noop is used as a no-op activity
func Noop(_ context.Context, _ []*common.Payload) error {
return nil
}
// Delay runs for the provided delay period
func Delay(_ context.Context, delayFor time.Duration) error {
time.Sleep(delayFor)
return nil
}
func convertFromPBRetryPolicy(retryPolicy *common.RetryPolicy) *temporal.RetryPolicy {
if retryPolicy == nil {
return nil
}
p := temporal.RetryPolicy{
BackoffCoefficient: retryPolicy.BackoffCoefficient,
MaximumAttempts: retryPolicy.MaximumAttempts,
NonRetryableErrorTypes: retryPolicy.NonRetryableErrorTypes,
}
if v := retryPolicy.MaximumInterval; v != nil {
p.MaximumInterval = v.AsDuration()
}
if v := retryPolicy.InitialInterval; v != nil {
p.InitialInterval = v.AsDuration()
}
return &p
}
type ReturnOrErr struct {
retme *common.Payload
err error
}