-
Notifications
You must be signed in to change notification settings - Fork 19
/
run.go
404 lines (329 loc) · 11.1 KB
/
run.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package runs
import (
"encoding/json"
"fmt"
"time"
"github.com/nyaruka/goflow/assets"
"github.com/nyaruka/goflow/excellent"
"github.com/nyaruka/goflow/excellent/types"
"github.com/nyaruka/goflow/flows"
"github.com/nyaruka/goflow/flows/events"
"github.com/nyaruka/goflow/flows/inputs"
"github.com/nyaruka/goflow/utils"
log "github.com/sirupsen/logrus"
)
type flowRun struct {
uuid flows.RunUUID
session flows.Session
environment flows.RunEnvironment
flow flows.Flow
context types.XValue
input flows.Input
parent flows.FlowRun
results flows.Results
path Path
events []flows.Event
status flows.RunStatus
createdOn time.Time
expiresOn *time.Time
exitedOn *time.Time
}
// NewRun initializes a new context and flow run for the passed in flow and contact
func NewRun(session flows.Session, flow flows.Flow, parent flows.FlowRun) flows.FlowRun {
r := &flowRun{
uuid: flows.RunUUID(utils.NewUUID()),
session: session,
flow: flow,
results: flows.NewResults(),
status: flows.RunStatusActive,
createdOn: utils.Now(),
}
r.environment = newRunEnvironment(session.Environment(), r)
r.context = newRunContext(r)
r.parent = parent
r.ResetExpiration(nil)
return r
}
func (r *flowRun) UUID() flows.RunUUID { return r.uuid }
func (r *flowRun) Session() flows.Session { return r.session }
func (r *flowRun) Environment() flows.RunEnvironment { return r.environment }
func (r *flowRun) Flow() flows.Flow { return r.flow }
func (r *flowRun) Contact() *flows.Contact { return r.session.Contact() }
func (r *flowRun) Context() types.XValue { return r.context }
func (r *flowRun) Results() flows.Results { return r.results }
func (r *flowRun) Events() []flows.Event { return r.events }
func (r *flowRun) Exit(status flows.RunStatus) {
r.SetStatus(status)
now := utils.Now()
r.exitedOn = &now
}
func (r *flowRun) Status() flows.RunStatus { return r.status }
func (r *flowRun) SetStatus(status flows.RunStatus) {
r.status = status
}
// ParentInSession returns the parent of the run within the same session if one exists
func (r *flowRun) ParentInSession() flows.FlowRun { return r.parent }
// Parent returns either the same session parent or if this session was triggered from a trigger_flow action
// in another session, that run
func (r *flowRun) Parent() flows.RunSummary {
if r.parent == nil {
return r.session.ParentRun()
}
return r.ParentInSession()
}
func (r *flowRun) Ancestors() []flows.FlowRun {
ancestors := make([]flows.FlowRun, 0)
if r.parent != nil {
run := r.parent.(*flowRun)
ancestors = append(ancestors, run)
for {
if run.parent != nil {
run = run.parent.(*flowRun)
ancestors = append(ancestors, run)
} else {
break
}
}
}
return ancestors
}
func (r *flowRun) Input() flows.Input { return r.input }
func (r *flowRun) SetInput(input flows.Input) {
r.input = input
// if we actually have new input, we can extend our expiration
if input != nil {
r.ResetExpiration(nil)
}
}
func (r *flowRun) LogEvent(s flows.Step, event flows.Event) {
if s != nil {
event.SetStepUUID(s.UUID())
r.events = append(r.events, event)
}
r.Session().LogEvent(event)
if log.GetLevel() >= log.DebugLevel {
eventEnvelope, _ := utils.EnvelopeFromTyped(event)
eventJSON, _ := json.Marshal(eventEnvelope)
log.WithField("event_type", event.Type()).WithField("payload", string(eventJSON)).WithField("run", r.UUID()).Debugf("event logged")
}
}
func (r *flowRun) LogError(step flows.Step, err error) {
r.LogEvent(step, events.NewErrorEvent(err))
}
func (r *flowRun) LogFatalError(step flows.Step, err error) {
r.Exit(flows.RunStatusErrored)
r.LogEvent(step, events.NewFatalErrorEvent(err))
}
func (r *flowRun) Path() []flows.Step { return r.path }
func (r *flowRun) CreateStep(node flows.Node) flows.Step {
now := utils.Now()
step := &step{stepUUID: flows.StepUUID(utils.NewUUID()), nodeUUID: node.UUID(), arrivedOn: now}
r.path = append(r.path, step)
return step
}
func (r *flowRun) PathLocation() (flows.Step, flows.Node, error) {
if r.Path() == nil {
return nil, nil, fmt.Errorf("run has no location as path is empty")
}
step := r.Path()[len(r.Path())-1]
// check that we still have a node for this step
node := r.Flow().GetNode(step.NodeUUID())
if node == nil {
return nil, nil, fmt.Errorf("run is located at a flow node that no longer exists")
}
return step, node, nil
}
func (r *flowRun) CreatedOn() time.Time { return r.createdOn }
func (r *flowRun) ExpiresOn() *time.Time { return r.expiresOn }
func (r *flowRun) ResetExpiration(from *time.Time) {
if r.Flow().ExpireAfterMinutes() >= 0 {
if from == nil {
now := utils.Now()
from = &now
}
expiresAfterMinutes := time.Duration(r.Flow().ExpireAfterMinutes())
expiresOn := from.Add(expiresAfterMinutes * time.Minute)
r.expiresOn = &expiresOn
}
if r.ParentInSession() != nil {
r.ParentInSession().ResetExpiration(r.expiresOn)
}
}
func (r *flowRun) ExitedOn() *time.Time { return r.exitedOn }
// EvaluateTemplate evaluates the given template in the context of this run
func (r *flowRun) EvaluateTemplate(template string) (types.XValue, error) {
return excellent.EvaluateTemplate(r.Environment(), r.Context(), template, RunContextTopLevels)
}
// EvaluateTemplateAsString evaluates the given template as a string in the context of this run
func (r *flowRun) EvaluateTemplateAsString(template string, urlEncode bool) (string, error) {
return excellent.EvaluateTemplateAsString(r.Environment(), r.Context(), template, urlEncode, RunContextTopLevels)
}
func (r *flowRun) GetText(uuid utils.UUID, key string, native string) string {
textArray := r.GetTextArray(uuid, key, []string{native})
return textArray[0]
}
func (r *flowRun) GetTextArray(uuid utils.UUID, key string, native []string) []string {
return r.GetTranslatedTextArray(uuid, key, native, r.environment.Languages())
}
func (r *flowRun) GetTranslatedTextArray(uuid utils.UUID, key string, native []string, languages utils.LanguageList) []string {
for _, lang := range languages {
if lang == r.Flow().Language() {
return native
}
translations := r.Flow().Localization().GetTranslations(lang)
if translations != nil {
textArray := translations.GetTextArray(uuid, key)
if textArray == nil {
return native
}
merged := make([]string, len(native))
for s := range native {
if textArray[s] != "" {
merged[s] = textArray[s]
} else {
merged[s] = native[s]
}
}
return merged
}
}
return native
}
// Resolve resolves the given key when this run is referenced in an expression
func (r *flowRun) Resolve(env utils.Environment, key string) types.XValue {
switch key {
case "uuid":
return types.NewXText(string(r.UUID()))
case "contact":
return r.Contact()
case "flow":
return r.Flow()
case "input":
return r.Input()
case "status":
return types.NewXText(string(r.Status()))
case "results":
return r.Results()
case "path":
return r.path
case "created_on":
return types.NewXDateTime(r.CreatedOn())
case "exited_on":
if r.exitedOn != nil {
return types.NewXDateTime(*r.exitedOn)
}
return nil
}
return types.NewXResolveError(r, key)
}
// Describe returns a representation of this type for error messages
func (r *flowRun) Describe() string { return "run" }
// Reduce is called when this object needs to be reduced to a primitive
func (r *flowRun) Reduce(env utils.Environment) types.XPrimitive {
return types.NewXText(string(r.uuid))
}
func (r *flowRun) ToXJSON(env utils.Environment) types.XText {
return types.ResolveKeys(env, r, "uuid", "contact", "flow", "input", "status", "results", "created_on", "exited_on").ToXJSON(env)
}
func (r *flowRun) Snapshot() flows.RunSummary {
return newRunSummaryFromRun(r)
}
var _ flows.FlowRun = (*flowRun)(nil)
var _ flows.RunSummary = (*flowRun)(nil)
//------------------------------------------------------------------------------------------
// JSON Encoding / Decoding
//------------------------------------------------------------------------------------------
type runEnvelope struct {
UUID flows.RunUUID `json:"uuid" validate:"required,uuid4"`
Flow *assets.FlowReference `json:"flow" validate:"required,dive"`
Path []*step `json:"path" validate:"dive"`
Events []*utils.TypedEnvelope `json:"events,omitempty"`
Status flows.RunStatus `json:"status"`
ParentUUID flows.RunUUID `json:"parent_uuid,omitempty" validate:"omitempty,uuid4"`
Results flows.Results `json:"results,omitempty" validate:"omitempty,dive"`
Input *utils.TypedEnvelope `json:"input,omitempty" validate:"omitempty,dive"`
Webhook *flows.WebhookCall `json:"webhook,omitempty" validate:"omitempty,dive"`
CreatedOn time.Time `json:"created_on"`
ExpiresOn *time.Time `json:"expires_on"`
ExitedOn *time.Time `json:"exited_on"`
}
// ReadRun decodes a run from the passed in JSON. Parent run UUID is returned separately as the
// run in question might be loaded yet from the session.
func ReadRun(session flows.Session, data json.RawMessage) (flows.FlowRun, error) {
r := &flowRun{}
var envelope runEnvelope
var err error
if err = utils.UnmarshalAndValidate(data, &envelope); err != nil {
return nil, fmt.Errorf("unable to read run: %s", err)
}
r.session = session
r.uuid = envelope.UUID
r.status = envelope.Status
r.createdOn = envelope.CreatedOn
r.expiresOn = envelope.ExpiresOn
r.exitedOn = envelope.ExitedOn
// lookup flow
if r.flow, err = session.Assets().Flows().Get(envelope.Flow.UUID); err != nil {
return nil, fmt.Errorf("unable to load flow[uuid=%s]: %s", envelope.Flow.UUID, err)
}
// lookup parent run
if envelope.ParentUUID != "" {
if r.parent, err = session.GetRun(envelope.ParentUUID); err != nil {
return nil, err
}
}
if envelope.Input != nil {
if r.input, err = inputs.ReadInput(session, envelope.Input); err != nil {
return nil, fmt.Errorf("unable to read input[type=%s]: %s", envelope.Input.Type, err)
}
}
if envelope.Results != nil {
r.results = envelope.Results
} else {
r.results = flows.NewResults()
}
// read in our path
r.path = make([]flows.Step, len(envelope.Path))
for i, step := range envelope.Path {
r.path[i] = step
}
// read in our events
r.events = make([]flows.Event, len(envelope.Events))
for i := range r.events {
if r.events[i], err = events.ReadEvent(envelope.Events[i]); err != nil {
return nil, fmt.Errorf("unable to read event[type=%s]: %s", envelope.Events[i].Type, err)
}
}
// create a run specific environment and context
r.environment = newRunEnvironment(session.Environment(), r)
r.context = newRunContext(r)
return r, nil
}
// MarshalJSON marshals this flow run into JSON
func (r *flowRun) MarshalJSON() ([]byte, error) {
var re runEnvelope
var err error
re.UUID = r.uuid
re.Flow = r.flow.Reference()
re.Status = r.status
re.CreatedOn = r.createdOn
re.ExpiresOn = r.expiresOn
re.ExitedOn = r.exitedOn
re.Results = r.results
if r.parent != nil {
re.ParentUUID = r.parent.UUID()
}
re.Input, err = utils.EnvelopeFromTyped(r.input)
if err != nil {
return nil, err
}
re.Path = make([]*step, len(r.path))
for i, s := range r.path {
re.Path[i] = s.(*step)
}
re.Events, err = events.EventsToEnvelopes(r.events)
if err != nil {
return nil, err
}
return json.Marshal(re)
}