-
Notifications
You must be signed in to change notification settings - Fork 0
/
unmarshal.go
222 lines (203 loc) · 6.83 KB
/
unmarshal.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
package chalk
import (
"fmt"
"github.com/apache/arrow/go/v16/arrow"
"github.com/chalk-ai/chalk-go/internal"
"github.com/pkg/errors"
"reflect"
"strconv"
"strings"
)
type fqnToFields map[string][]reflect.Value
var FieldNotFoundError = errors.New("field not found")
func (f fqnToFields) addField(fqn string, field reflect.Value) {
if _, ok := f[fqn]; !ok {
f[fqn] = []reflect.Value{}
}
f[fqn] = append(f[fqn], field)
}
func setFeatureSingle(field reflect.Value, fqn string, value any) error {
if field.Type().Kind() == reflect.Ptr {
rVal, err := internal.GetReflectValue(&value, field.Type())
if err != nil {
return errors.Wrapf(err, "error getting reflect value for feature '%s'", fqn)
}
field.Set(*rVal)
return nil
} else if field.Kind() == reflect.Map {
// We are handling maps differently because they are typed as `map`
// instead of a pointer to a `map` like all other types are.
//
// And handling it in setFeaturesSingleNew instead of in the recursive
// GetReflectValue function checks out because we never encounter
// maps in slices, other maps, or structs.
sections := strings.Split(fqn, ".")
lastSection := sections[len(sections)-1]
lastSectionSplit := strings.Split(lastSection, "__")
formatErr := fmt.Errorf(
"error unmarshalling value for windowed bucket feature %s: "+
"expected windowed bucket feature to have fqn of the format "+
"`{fqn}__{bucket seconds}__` ",
fqn,
)
if len(lastSectionSplit) < 2 {
return formatErr
}
secondsStr := lastSectionSplit[1]
seconds, err := strconv.Atoi(secondsStr)
if err != nil {
return formatErr
}
tagValue := reflect.ValueOf(internal.FormatBucketDuration(seconds))
rVal, err := internal.GetReflectValue(value, field.Type().Elem().Elem())
if err != nil {
return errors.Wrapf(err, "error unmarshalling value for windowed bucket feature %s", fqn)
}
field.SetMapIndex(tagValue, internal.ReflectPtr(*rVal))
return nil
} else {
return fmt.Errorf("expected a pointer type for feature '%s', found %s", fqn, field.Type().Kind())
}
}
func (f fqnToFields) setFeature(fqn string, value any) error {
fields, ok := f[fqn]
if !ok {
return FieldNotFoundError
}
// Versioned features can have multiple fields with the same FQN.
// We need to set the value for each field.
for _, field := range fields {
if err := setFeatureSingle(field, fqn, value); err != nil {
return err
}
}
return nil
}
func (result *OnlineQueryResult) unmarshal(resultHolder any) (returnErr *ClientError) {
fqnToValue := map[Fqn]any{}
for _, featureResult := range result.Data {
fqnToValue[featureResult.Field] = featureResult.Value
}
return UnmarshalInto(resultHolder, fqnToValue, result.expectedOutputs)
}
func unmarshalTableInto(table arrow.Table, resultHolders any) (returnErr error) {
defer func() {
if panicContents := recover(); panicContents != nil {
detail := "details irretrievable"
switch typedContents := panicContents.(type) {
case *reflect.ValueError:
detail = typedContents.Error()
case string:
detail = typedContents
}
returnErr = fmt.Errorf("exception occurred while unmarshalling result: %s", detail)
}
}()
slicePtr := reflect.ValueOf(resultHolders)
if slicePtr.Kind() != reflect.Ptr {
return fmt.Errorf(
"result holder should be a pointer to a slice of structs, "+
"got '%s' instead",
slicePtr.Kind(),
)
}
slice := reflect.Indirect(slicePtr)
if slice.Kind() != reflect.Slice {
return fmt.Errorf(
"result holder should be a pointer to a slice of structs, "+
"got '%s' instead",
slice.Kind(),
)
}
sliceElemType := slice.Type().Elem()
if sliceElemType.Kind() != reflect.Struct {
return fmt.Errorf(
"result holder should be a pointer to a slice of structs, "+
"got a pointer to a slice of '%s' instead",
sliceElemType.Kind(),
)
}
rows, scalarsErr := internal.ExtractFeaturesFromTable(table)
if scalarsErr != nil {
return scalarsErr
}
for _, row := range rows {
res := reflect.New(sliceElemType)
if err := UnmarshalInto(res.Interface(), row, nil); err != nil {
return err
}
internal.SliceAppend(resultHolders, res.Elem())
}
return nil
}
// UnmarshalTableInto unmarshals the given Arrow table into the given result holders.
// The result holders should be a pointer to a slice of structs.
//
// Usage:
//
// func printNumRelatives(chalkClient chalk.Client) {
// result, _ := chalkClient.OnlineQueryBulk(chalk.OnlineQueryParams{}.WithOutputs(
// Features.User.Relatives,
// ).WithInput(Features.User.Id, []int{1, 2}), nil)
//
// relatives := make([]Relative, 0)
// result.UnmarshalInto(&relatives)
//
// feature, _ := chalk.UnwrapFeature(Features.User.Relatives)
// fmt.Println("Number of relatives for all users: ", len(result.GroupsTable[feature.Fqn]))
//
// }
func UnmarshalTableInto(table arrow.Table, resultHolders any) *ClientError {
if err := unmarshalTableInto(table, resultHolders); err != nil {
return &ClientError{err.Error()}
}
return nil
}
func UnmarshalInto(resultHolder any, fqnToValue map[Fqn]any, expectedOutputs []string) (returnErr *ClientError) {
fieldMap := make(fqnToFields)
structValue := reflect.ValueOf(resultHolder).Elem()
// Has a side effect: fieldMap will be populated.
initErr := initFeatures(structValue, "", make(map[string]bool), fieldMap)
if initErr != nil {
return &ClientError{Message: errors.Wrap(initErr, "exception occurred while initializing result holder").Error()}
}
for fqn, value := range fqnToValue {
if value == nil {
// Some fields are optional, so we leave the field as nil
// TODO: Add validation for optional fields
continue
}
err := fieldMap.setFeature(fqn, value)
if err != nil {
structName := structValue.Type().String()
outputNamespace := "unknown namespace"
sections := strings.Split(fqn, ".")
if len(sections) > 0 {
outputNamespace = sections[0]
}
if errors.Is(err, FieldNotFoundError) {
fieldError := fmt.Sprintf("Error unmarshaling feature '%s' into the struct '%s'. ", fqn, structName)
fieldError += fmt.Sprintf("First, check if you are passing a pointer to a struct that represents the output namespace '%s'. ", outputNamespace)
fieldError += fmt.Sprintf("Also, make sure the feature name can be traced to a field in the struct '%s' and or its nested structs.", structName)
return &ClientError{Message: fieldError}
} else {
return &ClientError{Message: errors.Wrapf(err, "error unmarshaling feature '%s' into the struct '%s'", fqn, structName).Error()}
}
}
}
for _, expectedOutput := range expectedOutputs {
if fields, ok := fieldMap[expectedOutput]; ok {
for _, field := range fields {
if field.IsNil() {
// TODO: Handle optional fields
//return &ClientError{Message: fmt.Sprintf(
// "Unexpected error unmarshaling output feature '%s'. "+
// "Feature is still nil after unmarshaling",
// expectedOutput,
//)}
}
}
}
}
return nil
}