-
Notifications
You must be signed in to change notification settings - Fork 0
/
init_features.go
215 lines (196 loc) · 6.79 KB
/
init_features.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
package chalk
import (
"fmt"
"github.com/chalk-ai/chalk-go/internal"
"reflect"
"strconv"
"strings"
"time"
)
func InitFeatures[T any](t *T) error {
structValue := reflect.ValueOf(t).Elem()
return initFeatures(structValue, "", make(map[string]bool), nil)
}
// initFeatures is a recursive function that initializes all features
// in the struct that is passed in. Each feature is initialized as
// a pointer to a Feature struct with the appropriate FQN.
func initFeatures(structValue reflect.Value, fqn string, visited map[string]bool, fieldMap fqnToFields) error {
if structValue.Kind() != reflect.Struct {
return fmt.Errorf("feature initialization function argument must be a reflect.Value of the kind reflect.Struct, found %s instead", structValue.Kind().String())
}
namespace := structValue.Type().Name()
if fqn == "" && namespace != "" {
fqn = snakeCase(namespace) + "."
}
if isVisited, ok := visited[namespace]; ok && isVisited {
// This is not memoization. Simply a cycle checker while DFSing.
return nil
} else {
visited[namespace] = true
}
for i := 0; i < structValue.NumField(); i++ {
f := structValue.Field(i)
fieldMeta := structValue.Type().Field(i)
attributeName := snakeCase(fieldMeta.Name)
nameOverride := fieldMeta.Tag.Get("name")
if nameOverride != "" {
attributeName = nameOverride
}
updatedFqn := fqn + attributeName
if !f.CanSet() {
continue
}
if f.Type().Elem().Kind() == reflect.Struct && f.Type().Elem() != reflect.TypeOf(time.Time{}) {
// RECURSIVE CASE.
// Create new Feature Set instance and point to it.
// The equivalent way of doing it without 'reflect':
//
// Features.User.CreditReport = new(CreditReport)
//
if ptrErr := pointerCheck(f); ptrErr != nil {
return ptrErr
}
featureSet := reflect.New(f.Type().Elem())
ptrInDisguiseToFeatureSet := reflect.NewAt(f.Type().Elem(), featureSet.UnsafePointer())
f.Set(ptrInDisguiseToFeatureSet)
featureSetInDisguise := f.Elem()
initErr := initFeatures(featureSetInDisguise, updatedFqn+".", visited, fieldMap)
if initErr != nil {
return initErr
}
if fieldMap != nil {
fieldMap.addField(updatedFqn, f)
}
} else if f.Kind() == reflect.Map {
// Creates a map of tag values to pointers to Features.
// For example, if we have the tag "windows=6h,12h,1d",
// then the map will be:
//
// map[string]*int64{
// "6h": &Feature{Fqn: "user.clicks__21600__"},
// "12h": &Feature{Fqn: "user.clicks__43200__"},
// "1d": &Feature{Fqn: "user.clicks__86400__"},
// }
//
// Notice that while the values is typed as *int64, it is
// actually a pointer to a Feature struct. See BASE CASE
// section below.
mapValueType := f.Type().Elem()
if mapValueType.Kind() != reflect.Pointer {
return fmt.Errorf("the map type for Windowed features should a pointer as its value type, but found %s instead", mapValueType.Kind())
}
newMap := reflect.MakeMap(f.Type())
windows := fieldMeta.Tag.Get("windows")
for _, tag := range strings.Split(windows, ",") {
seconds, parseErr := internal.ParseBucketDuration(tag)
if parseErr != nil {
return fmt.Errorf("error parsing bucket duration: %s", parseErr)
}
windowFqn := updatedFqn + fmt.Sprintf("__%d__", seconds)
if fieldMap == nil {
feature := Feature{Fqn: windowFqn}
ptrInDisguiseToFeature := reflect.NewAt(mapValueType.Elem(), reflect.ValueOf(&feature).UnsafePointer())
newMap.SetMapIndex(reflect.ValueOf(tag), ptrInDisguiseToFeature)
} else {
nilPointer := reflect.New(f.Type().Elem()).Elem()
nilPointer.Set(reflect.Zero(nilPointer.Type()))
newMap.SetMapIndex(reflect.ValueOf(tag), nilPointer)
}
if fieldMap != nil {
fieldMap.addField(windowFqn, f)
}
}
f.Set(newMap)
if fieldMap != nil {
fieldMap.addField(updatedFqn, f)
}
} else {
// BASE CASE.
if ptrErr := pointerCheck(f); ptrErr != nil {
return ptrErr
}
versioned := fieldMeta.Tag.Get("versioned")
if versioned == "true" {
parts := strings.Split(updatedFqn, "_")
nameErr := fmt.Errorf("versioned feature must have a version suffix `VN` at the end of the attribute name, but found '%s' instead", fieldMeta.Name)
if len(parts) == 1 {
return nameErr
}
lastPart := parts[len(parts)-1]
if !strings.HasPrefix(lastPart, "v") {
return nameErr
}
version := lastPart[1:]
baseFqn := strings.Join(parts[:len(parts)-1], "_")
if version == "1" {
updatedFqn = baseFqn
} else {
updatedFqn = baseFqn + "@" + version
}
} else if strings.HasPrefix(versioned, "default(") && strings.HasSuffix(versioned, ")") {
version := versioned[len("default(") : len(versioned)-len(")")]
_, convertErr := strconv.Atoi(version)
if convertErr != nil {
return fmt.Errorf("Expected struct tag `versioned:\"default(N)\"` where N is an integer, but found %s instead", versioned)
}
if version != "1" {
updatedFqn = updatedFqn + "@" + version
}
} else if versioned != "" {
return fmt.Errorf("Expected struct tag `versioned:\"true\"` or `versioned:\"default(N)\"` where N is an integer, but found '%s' instead", versioned)
}
if fieldMap != nil {
fieldMap.addField(updatedFqn, f)
} else {
// Create new Feature instance and point to it.
// The equivalent way of doing it without 'reflect':
//
// Features.User.CreditReport.Id = (*string)(unsafe.Pointer(&Feature{"user.credit_report.id"}))
//
// Dataclass fields are not actually real features,
// so when we are initializing the root Features struct (fieldMap == nil),
// we want to return the parent (real) feature FQN
// instead of the fake FQN of the dataclass field.
if internal.IsDataclass(structValue) {
updatedFqn = DesuffixFqn(updatedFqn)
}
feature := Feature{Fqn: updatedFqn}
ptrInDisguiseToFeature := reflect.NewAt(f.Type().Elem(), reflect.ValueOf(&feature).UnsafePointer())
f.Set(ptrInDisguiseToFeature)
}
}
}
visited[namespace] = false
return nil
}
func pointerCheck(field reflect.Value) error {
if field.Kind() != reflect.Ptr {
return fmt.Errorf("expected a pointer type but found %s -- make sure the generated feature structs are unchanged, and that every field is of a pointer type except for Windowed feature types", field.Kind())
}
return nil
}
func snakeCase(s string) string {
var b []byte
for i := 0; i < len(s); i++ {
c := s[i]
if isASCIIUpper(c) {
if i > 0 && s[i-1] != '.' {
b = append(b, '_')
}
c += 'a' - 'A'
} else if isASCIIDigit(c) && i > 0 && isASCIILower(s[i-1]) {
b = append(b, '_')
}
b = append(b, c)
}
return string(b)
}
func isASCIILower(c byte) bool {
return 'a' <= c && c <= 'z'
}
func isASCIIDigit(c byte) bool {
return '0' <= c && c <= '9'
}
func isASCIIUpper(c byte) bool {
return 'A' <= c && c <= 'Z'
}