Repository navigation
Expand file tree
/
Copy pathflow_context.go
More file actions
283 lines (251 loc) · 9.45 KB
/
Copy pathflow_context.go
File metadata and controls
283 lines (251 loc) · 9.45 KB
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
package gush
import (
"maps"
"time"
"go.temporal.io/sdk/workflow"
)
// abortedFlowErrorType is the ApplicationError type of a flow's Abort.
const abortedFlowErrorType = "FlowAborted"
// DefaultFlowVersion is what Version returns for an execution that passed the call before
// it was added.
const DefaultFlowVersion = int(workflow.DefaultVersion)
// FlowContext is what a flow receives. Its Context field is the Temporal SDK's own context,
// for SDK functions such as workflow.Sleep(ctx.Context, d).
//
// Temporal replays a flow's code to restore it, so flow code must be deterministic: no
// I/O, no time.Now and no time.Sleep. Do real work in steps. Logs written during a replay
// are dropped, so each line appears once.
//
// func OrderFulfillment(ctx *gush.FlowContext) (any, error) {
// var order Order
// err := ctx.Decode(&order)
// if err != nil {
// return nil, err
// }
//
// var payment Payment
// err = ctx.RunStep(ProcessPayment, order, &payment)
// if err != nil {
// return nil, err
// }
//
// var receipt Receipt
// err = ctx.RunStep(ShipOrder, payment, &receipt)
// return receipt, err
// }
type FlowContext struct {
// Context is the Temporal workflow context that RunStep and RunFlow run on.
Context workflow.Context
FlowInfo
*Logger
// Input is the raw input; Decode deserializes it.
Input []byte
// LogAttributes are inherited from the parent and passed on to child flows and steps.
LogAttributes map[string]any
}
// NewFlowContext creates a FlowContext from a Temporal workflow context.
func NewFlowContext(ctx workflow.Context, logAttributes map[string]any) *FlowContext {
info := workflow.GetInfo(ctx)
flowCtx := &FlowContext{Context: ctx, Logger: NewLogger(), LogAttributes: logAttributes}
flowCtx.ID = info.WorkflowExecution.ID
flowCtx.Queue = info.TaskQueueName
flowCtx.Priority = NewPriority(info.Priority.PriorityKey)
flowCtx.FairKey = info.Priority.FairnessKey
flowCtx.Attempt = info.Attempt
startTime := info.WorkflowStartTime
flowCtx.StartTime = &startTime
if info.ParentWorkflowExecution != nil {
flowCtx.ParentID = info.ParentWorkflowExecution.ID
}
flowCtx.Logger.muted = func() bool {
return workflow.IsReplaying(ctx)
}
flowCtx.Logger.now = func() time.Time {
return workflow.Now(ctx)
}
for key, value := range logAttributes {
flowCtx.Logger.SetAttributes(Attr(key, value))
}
flowCtx.Logger.SetAttributes(Attr("flow_id", flowCtx.ID))
return flowCtx
}
// WithContext returns a copy of this FlowContext that runs its steps and child flows on ctx.
// RunStep and RunFlow always use the FlowContext's own workflow.Context, so code holding a
// different one needs this, such as a goroutine started with workflow.Go or cleanup on a
// workflow.NewDisconnectedContext. StartFlow only checks that context for cancellation,
// because its child is independent.
//
// workflow.Go(ctx.Context, func(g workflow.Context) {
// err := ctx.WithContext(g).RunStep(Process, item, nil)
// ...
// })
func (flowCtx *FlowContext) WithContext(ctx workflow.Context) *FlowContext {
derived := *flowCtx
derived.Context = ctx
return &derived
}
// RunStep runs a step and waits for its result. The step inherits this flow's priority,
// fair key and log attributes unless options override them.
func (flowCtx *FlowContext) RunStep(step any, input, output any, options ...StepOption) error {
config := DefaultStepConfig()
config.Priority = flowCtx.Priority
config.FairKey = flowCtx.FairKey
maps.Copy(config.LogAttributes, flowCtx.LogAttributes)
config.Apply(options...)
stepName, err := handlerName("step", step)
if err != nil {
return flowCtx.Abort(err)
}
err = config.validate()
if err != nil {
return abortInvalidConfig(err)
}
payload, err := EncodePayload(input)
if err != nil {
return flowCtx.Abort(err)
}
stepContext := workflow.WithActivityOptions(flowCtx.Context, newActivityOptions(config))
future := workflow.ExecuteActivity(stepContext, stepName, payload, config.LogAttributes)
var result []byte
err = future.Get(stepContext, &result)
if err != nil {
return unwrapError(err)
}
err = DecodePayload(result, output)
if err != nil {
return flowCtx.Abort(err)
}
return nil
}
// RunFlow runs a child flow and waits for its result. The child inherits this flow's
// priority, fair key and log attributes unless options override them.
func (flowCtx *FlowContext) RunFlow(request FlowRequest, options ...FlowOption) error {
config := flowCtx.childFlowConfig(options)
err := config.validate()
if err != nil {
return abortInvalidConfig(err)
}
childOptions := newChildWorkflowOptions(request.Queue, config)
childContext := workflow.WithChildOptions(flowCtx.Context, childOptions)
future, err := executeChildFlow(childContext, request, config)
if err != nil {
return flowCtx.Abort(err)
}
var result []byte
err = future.Get(childContext, &result)
if err != nil {
return unwrapError(err)
}
err = DecodePayload(result, request.Output)
if err != nil {
return flowCtx.Abort(err)
}
return nil
}
// StartFlow starts a child flow and returns its ID once it has started, without waiting for
// it to finish. The child is independent: it keeps running when this flow ends or is
// canceled, and CancelFlow stops it by that ID. It inherits this flow's priority, fair key
// and log attributes unless options override them. It returns a canceled error if its own
// context is already canceled.
func (flowCtx *FlowContext) StartFlow(request FlowRequest, options ...FlowOption) (string, error) {
err := flowCtx.Context.Err()
if err != nil {
return "", err
}
config := flowCtx.childFlowConfig(options)
err = config.validate()
if err != nil {
return "", abortInvalidConfig(err)
}
// Canceling a context also cancels the children started on it.
detached, _ := workflow.NewDisconnectedContext(flowCtx.Context)
childOptions := newDetachedChildWorkflowOptions(request.Queue, config)
childContext := workflow.WithChildOptions(detached, childOptions)
future, err := executeChildFlow(childContext, request, config)
if err != nil {
return "", flowCtx.Abort(err)
}
var execution workflow.Execution
err = future.GetChildWorkflowExecution().Get(childContext, &execution)
if err != nil {
return "", unwrapError(err)
}
return execution.ID, nil
}
func (flowCtx *FlowContext) childFlowConfig(options []FlowOption) *FlowConfig {
config := DefaultFlowConfig()
config.Priority = flowCtx.Priority
config.FairKey = flowCtx.FairKey
maps.Copy(config.LogAttributes, flowCtx.LogAttributes)
config.Apply(options...)
return config
}
func executeChildFlow(ctx workflow.Context, request FlowRequest, config *FlowConfig) (workflow.ChildWorkflowFuture, error) {
flowName, err := handlerName("flow", request.Flow)
if err != nil {
return nil, err
}
payload, err := EncodePayload(request.Input)
if err != nil {
return nil, err
}
return workflow.ExecuteChildWorkflow(ctx, flowName, payload, config.LogAttributes), nil
}
// Version lets flow code change without breaking executions already running the old code.
// The first execution of a call records maxVersion in the flow's history, and replays
// return that recorded value. An execution that passed this point before the call existed
// gets DefaultFlowVersion, and one that reaches it later records maxVersion however long ago
// it started.
//
// To replace a step:
//
// v := ctx.Version("payment-provider", gush.DefaultFlowVersion, 1)
// if v == gush.DefaultFlowVersion {
// err = ctx.RunStep(OldCharge, input, &output)
// } else {
// err = ctx.RunStep(NewCharge, input, &output)
// }
//
// To change the same code again, keep the tag, raise maxVersion and add a branch. Once no
// execution can reach an old branch, delete it, keep the Version call and raise minVersion
// to the oldest version left. An execution that recorded an older version then stops making
// progress, with its flow tasks failing, until code that supports it is deployed. It never
// runs a branch it did not take.
func (flowCtx *FlowContext) Version(tag string, minVersion, maxVersion int) int {
version := workflow.GetVersion(flowCtx.Context, tag, workflow.Version(minVersion), workflow.Version(maxVersion))
return int(version)
}
// ContinueAsNew returns an error that ends this run and starts the same flow again with the
// given input, the same flow ID and log attributes, and an empty history. Temporal limits a
// flow's history, so a flow that loops for a long time returns this every so often.
//
// if batch.Done {
// return summary, nil
// }
// return nil, ctx.ContinueAsNew(batch.Next)
func (flowCtx *FlowContext) ContinueAsNew(input any) error {
payload, err := EncodePayload(input)
if err != nil {
return flowCtx.Abort(err)
}
flowName := workflow.GetInfo(flowCtx.Context).WorkflowType.Name
nextRun := workflow.WithWorkflowVersioningIntent(flowCtx.Context, defaultCommandVersioningIntent())
return workflow.NewContinueAsNewError(nextRun, flowName, payload, flowCtx.LogAttributes)
}
// Decode deserializes the flow's Input into target, aborting the flow if it cannot.
func (flowCtx *FlowContext) Decode(target any) error {
err := Decode(flowCtx.Input, target)
if err != nil {
return flowCtx.Abort(err)
}
return nil
}
// abortInvalidConfig fails the flow over settings validate rejected.
func abortInvalidConfig(err error) error {
cause := []error{err}
return abortError(invalidConfigErrorType, cause)
}
// Abort returns an error that fails the flow permanently, with no further retries.
func (flowCtx *FlowContext) Abort(cause ...error) error {
return abortError(abortedFlowErrorType, cause)
}