-
Notifications
You must be signed in to change notification settings - Fork 20
/
run.go
500 lines (417 loc) · 14.4 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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package runs
import (
"encoding/json"
"time"
"github.com/nyaruka/gocommon/dates"
"github.com/nyaruka/gocommon/i18n"
"github.com/nyaruka/gocommon/jsonx"
"github.com/nyaruka/gocommon/stringsx"
"github.com/nyaruka/gocommon/uuids"
"github.com/nyaruka/goflow/assets"
"github.com/nyaruka/goflow/envs"
"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/utils"
"github.com/pkg/errors"
)
type run struct {
uuid flows.RunUUID
session flows.Session
flow flows.Flow
flowRef *assets.FlowReference
parent flows.Run
results flows.Results
path Path
events []flows.Event
status flows.RunStatus
createdOn time.Time
modifiedOn time.Time
exitedOn *time.Time
webhook types.XValue
legacyExtra *legacyExtra
}
// 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.Run) flows.Run {
now := dates.Now()
r := &run{
uuid: flows.RunUUID(uuids.New()),
session: session,
flow: flow,
flowRef: flow.Reference(true),
parent: parent,
results: flows.NewResults(),
status: flows.RunStatusActive,
events: make([]flows.Event, 0),
createdOn: now,
modifiedOn: now,
}
r.webhook = types.XObjectEmpty
r.legacyExtra = newLegacyExtra(r)
return r
}
func (r *run) UUID() flows.RunUUID { return r.uuid }
func (r *run) Session() flows.Session { return r.session }
func (r *run) Flow() flows.Flow { return r.flow }
func (r *run) FlowReference() *assets.FlowReference { return r.flowRef }
func (r *run) Contact() *flows.Contact { return r.session.Contact() }
func (r *run) Events() []flows.Event { return r.events }
func (r *run) Results() flows.Results { return r.results }
func (r *run) SaveResult(result *flows.Result) {
// truncate value if necessary
result.Value = stringsx.Truncate(result.Value, r.session.Engine().Options().MaxResultChars)
r.results.Save(result)
r.modifiedOn = dates.Now()
r.legacyExtra.addResult(result)
}
func (r *run) Exit(status flows.RunStatus) {
now := dates.Now()
r.status = status
r.exitedOn = &now
r.modifiedOn = now
}
func (r *run) Status() flows.RunStatus { return r.status }
func (r *run) SetStatus(status flows.RunStatus) {
r.status = status
r.modifiedOn = dates.Now()
}
func (r *run) Webhook() types.XValue {
return r.webhook
}
func (r *run) SetWebhook(value types.XValue) {
r.webhook = value
}
// ParentInSession returns the parent of the run within the same session if one exists
func (r *run) ParentInSession() flows.Run { 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 *run) Parent() flows.RunSummary {
if r.parent == nil {
return r.session.ParentRun()
}
return r.ParentInSession()
}
func (r *run) Ancestors() []flows.Run {
ancestors := make([]flows.Run, 0)
if r.parent != nil {
pr := r.parent.(*run)
ancestors = append(ancestors, pr)
for {
if pr.parent != nil {
pr = pr.parent.(*run)
ancestors = append(ancestors, pr)
} else {
break
}
}
}
return ancestors
}
func (r *run) LogEvent(s flows.Step, event flows.Event) {
if s != nil {
event.SetStepUUID(s.UUID())
}
r.events = append(r.events, event)
r.modifiedOn = dates.Now()
}
func (r *run) LogError(step flows.Step, err error) {
r.LogEvent(step, events.NewError(err))
}
// find the first event matching the given step UUID and type
func (r *run) findEvent(stepUUID flows.StepUUID, eType string) flows.Event {
for _, e := range r.events {
if (stepUUID == "" || e.StepUUID() == stepUUID) && e.Type() == eType {
return e
}
}
return nil
}
func (r *run) ReceivedInput() bool {
return r.findEvent("", events.TypeMsgReceived) != nil
}
func (r *run) Path() []flows.Step { return r.path }
func (r *run) CreateStep(node flows.Node) flows.Step {
now := dates.Now()
step := NewStep(node, now)
r.path = append(r.path, step)
r.modifiedOn = now
return step
}
func (r *run) PathLocation() (flows.Step, flows.Node, error) {
if r.Path() == nil {
return nil, nil, errors.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
var node flows.Node
if r.Flow() != nil {
node = r.Flow().GetNode(step.NodeUUID())
}
if node == nil {
return nil, nil, errors.Errorf("run is located at a flow node that no longer exists")
}
return step, node, nil
}
func (r *run) CreatedOn() time.Time { return r.createdOn }
func (r *run) ModifiedOn() time.Time { return r.modifiedOn }
func (r *run) ExitedOn() *time.Time { return r.exitedOn }
// RootContext returns the root context for expression evaluation
//
// contact:contact -> the contact
// fields:fields -> the custom field values of the contact
// urns:urns -> the URN values of the contact
// results:results -> the current run results
// input:input -> the current input from the contact
// run:run -> the current run
// child:related_run -> the last child run
// parent:related_run -> the parent of the run
// ticket:ticket -> the open ticket for the contact
// webhook:any -> the parsed JSON response of the last webhook call
// node:node -> the current node
// globals:globals -> the global values
// trigger:trigger -> the trigger that started this session
// resume:resume -> the current resume that continued this session
//
// @context root
func (r *run) RootContext(env envs.Environment) map[string]types.XValue {
var urns, fields, ticket, node types.XValue
if r.Contact() != nil {
urns = flows.ContextFunc(env, r.Contact().URNs().MapContext)
fields = flows.Context(env, r.Contact().Fields())
if r.Contact().Ticket() != nil {
ticket = flows.Context(env, r.Contact().Ticket())
}
}
var child = newRelatedRunContext(r.Session().GetCurrentChild(r))
var parent = newRelatedRunContext(r.Parent())
_, n, _ := r.PathLocation()
if n != nil {
node = flows.ContextFunc(env, r.nodeContext)
}
return map[string]types.XValue{
// the available runs
"run": flows.Context(env, r),
"child": flows.Context(env, child),
"parent": flows.Context(env, parent),
// shortcuts to things on the current run or contact
"contact": flows.Context(env, r.Contact()),
"results": flows.Context(env, r.Results()),
"urns": urns,
"fields": fields,
"ticket": ticket,
// other
"trigger": flows.Context(env, r.Session().Trigger()),
"resume": flows.Context(env, r.Session().CurrentResume()),
"input": flows.Context(env, r.Session().Input()),
"globals": flows.Context(env, r.Session().Assets().Globals()),
"webhook": r.webhook,
"node": node,
"legacy_extra": r.legacyExtra.ToXValue(env),
}
}
// Context returns the properties available in expressions
//
// __default__:text -> the contact name and flow UUID
// uuid:text -> the UUID of the run
// contact:contact -> the contact of the run
// flow:flow -> the flow of the run
// status:text -> the current status of the run
// results:results -> the results saved by the run
// created_on:datetime -> the creation date of the run
// exited_on:datetime -> the exit date of the run
//
// @context run
func (r *run) Context(env envs.Environment) map[string]types.XValue {
var exitedOn types.XValue
if r.exitedOn != nil {
exitedOn = types.NewXDateTime(*r.exitedOn)
}
return map[string]types.XValue{
"__default__": types.NewXText(FormatRunSummary(env, r)),
"uuid": types.NewXText(string(r.UUID())),
"contact": flows.Context(env, r.Contact()),
"flow": flows.Context(env, r.Flow()),
"status": types.NewXText(string(r.Status())),
"results": flows.Context(env, r.Results()),
"path": r.path.ToXValue(env),
"created_on": types.NewXDateTime(r.CreatedOn()),
"exited_on": exitedOn,
}
}
// returns the context representation of the current node
//
// uuid:text -> the UUID of the node
// visit_count:number -> the count of visits to the node in this run
//
// @context node
func (r *run) nodeContext(env envs.Environment) map[string]types.XValue {
_, node, _ := r.PathLocation()
visitCount := 0
for _, s := range r.path {
if s.NodeUUID() == node.UUID() {
visitCount++
}
}
return map[string]types.XValue{
"uuid": types.NewXText(string(node.UUID())),
"visit_count": types.NewXNumberFromInt(visitCount),
}
}
// EvaluateTemplate evaluates the given template in the context of this run
func (r *run) EvaluateTemplateValue(template string) (types.XValue, error) {
ctx := types.NewXObject(r.RootContext(r.session.MergedEnvironment()))
return excellent.EvaluateTemplateValue(r.session.MergedEnvironment(), ctx, template)
}
// EvaluateTemplateText evaluates the given template as text in the context of this run
func (r *run) EvaluateTemplateText(template string, escaping excellent.Escaping, truncate bool) (string, error) {
ctx := types.NewXObject(r.RootContext(r.session.MergedEnvironment()))
value, err := excellent.EvaluateTemplate(r.session.MergedEnvironment(), ctx, template, escaping)
if truncate {
value = stringsx.TruncateEllipsis(value, r.Session().Engine().Options().MaxTemplateChars)
}
return value, err
}
// EvaluateTemplate is a convenience function for evaluating as text with no escaping
func (r *run) EvaluateTemplate(template string) (string, error) {
return r.EvaluateTemplateText(template, nil, true)
}
// get the ordered list of languages to be used for localization in this run
func (r *run) getLanguages() []i18n.Language {
languages := make([]i18n.Language, 0, 3)
// if contact has an allowed language, it takes priority
contactLanguage := r.session.MergedEnvironment().DefaultLanguage()
if contactLanguage != i18n.NilLanguage {
languages = append(languages, contactLanguage)
}
// next we include the default language if it's different to the contact language
defaultLanguage := r.session.Environment().DefaultLanguage()
if defaultLanguage != i18n.NilLanguage && defaultLanguage != contactLanguage {
languages = append(languages, defaultLanguage)
}
// finally we include the flow native language if it isn't an allowed language - because it's the only
// one guaranteed to have translations
return append(languages, r.flow.Language())
}
// GetText is a convenience version of GetTextArray for a single text values
func (r *run) GetText(uuid uuids.UUID, key string, native string) (string, i18n.Language) {
textArray, lang := r.getText(uuid, key, []string{native}, nil)
return textArray[0], lang
}
// GetTextArray returns the localized value for the given flow definition value
func (r *run) GetTextArray(uuid uuids.UUID, key string, native []string, languages []i18n.Language) ([]string, i18n.Language) {
return r.getText(uuid, key, native, languages)
}
func (r *run) getText(uuid uuids.UUID, key string, native []string, languages []i18n.Language) ([]string, i18n.Language) {
nativeLang := r.Flow().Language()
// if a preferred language list wasn't provided, default to the run preferred languages
if languages == nil {
languages = r.getLanguages()
}
for _, lang := range languages {
if lang == r.Flow().Language() {
return native, nativeLang
}
translated := r.Flow().Localization().GetItemTranslation(lang, uuid, key)
if len(translated) == 0 {
continue
}
return translated, lang
}
return native, nativeLang
}
func (r *run) Snapshot() flows.RunSummary {
return newRunSummaryFromRun(r)
}
var _ flows.RunSummary = (*run)(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 []json.RawMessage `json:"events,omitempty"`
Results flows.Results `json:"results,omitempty" validate:"omitempty,dive"`
Status flows.RunStatus `json:"status" validate:"required"`
ParentUUID flows.RunUUID `json:"parent_uuid,omitempty" validate:"omitempty,uuid4"`
CreatedOn time.Time `json:"created_on" validate:"required"`
ModifiedOn time.Time `json:"modified_on" validate:"required"`
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, missing assets.MissingCallback) (flows.Run, error) {
e := &runEnvelope{}
var err error
if err = utils.UnmarshalAndValidate(data, e); err != nil {
return nil, errors.Wrap(err, "unable to read run")
}
r := &run{
session: session,
uuid: e.UUID,
flowRef: e.Flow,
status: e.Status,
createdOn: e.CreatedOn,
modifiedOn: e.ModifiedOn,
exitedOn: e.ExitedOn,
}
// lookup actual flow
if r.flow, err = session.Assets().Flows().Get(e.Flow.UUID); err != nil {
missing(e.Flow, err)
}
// lookup parent run
if e.ParentUUID != "" {
if r.parent, err = session.GetRun(e.ParentUUID); err != nil {
return nil, err
}
}
if e.Results != nil {
r.results = e.Results
} else {
r.results = flows.NewResults()
}
// read in our path
r.path = make([]flows.Step, len(e.Path))
for i, step := range e.Path {
r.path[i] = step
}
// read in our events
r.events = make([]flows.Event, len(e.Events))
for i := range r.events {
if r.events[i], err = events.ReadEvent(e.Events[i]); err != nil {
return nil, errors.Wrap(err, "unable to read event")
}
}
// create context
r.webhook = lastWebhookSavedAsExtra(r)
r.legacyExtra = newLegacyExtra(r)
return r, nil
}
// MarshalJSON marshals this flow run into JSON
func (r *run) MarshalJSON() ([]byte, error) {
var err error
e := &runEnvelope{
UUID: r.uuid,
Flow: r.flowRef,
Status: r.status,
CreatedOn: r.createdOn,
ModifiedOn: r.modifiedOn,
ExitedOn: r.exitedOn,
Results: r.results,
}
if r.parent != nil {
e.ParentUUID = r.parent.UUID()
}
e.Path = make([]*step, len(r.path))
for i, s := range r.path {
e.Path[i] = s.(*step)
}
e.Events = make([]json.RawMessage, len(r.events))
for i := range r.events {
if e.Events[i], err = jsonx.Marshal(r.events[i]); err != nil {
return nil, errors.Wrapf(err, "unable to marshal event[type=%s]", r.events[i].Type())
}
}
return jsonx.Marshal(e)
}