-
Notifications
You must be signed in to change notification settings - Fork 20
/
legacy.go
97 lines (79 loc) · 2.59 KB
/
legacy.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
package runs
import (
"regexp"
"sort"
"strconv"
"strings"
"github.com/nyaruka/goflow/excellent/types"
"github.com/nyaruka/goflow/flows"
"github.com/nyaruka/goflow/utils"
)
var invalidLegacyExtraKeyChars = regexp.MustCompile(`[^a-zA-Z0-9_]`)
// keys in legacy @extra have non-word chars replaced with underscores and are limited to 255 chars
func legacyExtraKey(key string) string {
key = invalidLegacyExtraKeyChars.ReplaceAllString(strings.ToLower(key), "_")
return key[0:utils.MinInt(len(key), 255)]
}
type legacyExtra struct {
values map[string]types.XValue
}
// creates a new legacy extra which will be lazily initialized on first call to .update()
func newLegacyExtra(run flows.FlowRun) *legacyExtra {
e := &legacyExtra{values: make(map[string]types.XValue)}
// if trigger params is a JSON object, we include it in @extra
triggerParams := run.Session().Trigger().Params()
asDict, isDict := triggerParams.(*types.XDict)
if isDict && asDict != nil {
e.addValues(asDict)
}
// if trigger has results (i.e. a flow_action type trigger with a parent run) use them too
asExtraContrib, isExtraContrib := run.Session().Trigger().(flows.LegacyExtraContributor)
if isExtraContrib {
e.addResults(asExtraContrib.LegacyExtra())
}
// add any existing results from this run
e.addResults(run.Results())
return e
}
func (e *legacyExtra) ToXValue(env utils.Environment) types.XValue {
return types.NewXDict(e.values)
}
func (e *legacyExtra) addResults(results flows.Results) {
// sort by created time
sortedResults := make([]*flows.Result, 0)
for _, result := range results {
sortedResults = append(sortedResults, result)
}
sort.SliceStable(sortedResults, func(i, j int) bool { return sortedResults[i].CreatedOn.Before(sortedResults[j].CreatedOn) })
// add each result in order
for _, result := range sortedResults {
e.addResult(result)
}
}
// adds any extra from the given result
func (e *legacyExtra) addResult(result *flows.Result) {
if result.Extra == nil {
return
}
e.values[utils.Snakify(result.Name)] = types.NewXText(string(result.Extra))
values := types.JSONToXValue(result.Extra)
e.addValues(values)
}
func (e *legacyExtra) addValues(values types.XValue) {
switch typed := values.(type) {
case *types.XDict:
for _, key := range typed.Keys() {
value, _ := typed.Get(key)
e.values[legacyExtraKey(key)] = value
}
case *types.XArray:
e.addValues(arrayToDict(typed))
}
}
func arrayToDict(array *types.XArray) *types.XDict {
m := make(map[string]types.XValue, array.Length())
for i := 0; i < array.Length(); i++ {
m[strconv.Itoa(i)] = array.Get(i)
}
return types.NewXDict(m)
}