-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathredisonlinestore.go
More file actions
340 lines (297 loc) · 10.8 KB
/
Copy pathredisonlinestore.go
File metadata and controls
340 lines (297 loc) · 10.8 KB
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
package onlinestore
import (
"context"
"crypto/tls"
"encoding/binary"
"errors"
"fmt"
"strconv"
"strings"
"github.com/feast-dev/feast/go/internal/feast/registry"
//"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
"github.com/redis/go-redis/v9"
"github.com/spaolacci/murmur3"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/feast-dev/feast/go/protos/feast/serving"
"github.com/feast-dev/feast/go/protos/feast/types"
"github.com/rs/zerolog/log"
//redistrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/redis/go-redis.v9"
)
type redisType int
const (
redisNode redisType = 0
redisCluster redisType = 1
)
type RedisOnlineStore struct {
// Feast project name
// TODO (woop): Should we remove project as state that is tracked at the store level?
project string
// Redis database type, either a single node server (RedisType.Redis) or a cluster (RedisType.RedisCluster)
t redisType
// Redis client connector
client *redis.Client
// Redis cluster client connector
clusterClient *redis.ClusterClient
config *registry.RepoConfig
}
func NewRedisOnlineStore(project string, config *registry.RepoConfig, onlineStoreConfig map[string]interface{}) (*RedisOnlineStore, error) {
store := RedisOnlineStore{
project: project,
config: config,
}
var address []string
var password string
var tlsConfig *tls.Config
var db int // Default to 0
// Parse redis_type and write it into conf.redisStoreType
redisStoreType, err := getRedisType(onlineStoreConfig)
if err != nil {
return nil, err
}
store.t = redisStoreType
// Parse connection_string and write it into conf.address, conf.password, and conf.ssl
redisConnJson, ok := onlineStoreConfig["connection_string"]
if !ok {
// Default to "localhost:6379"
redisConnJson = "localhost:6379"
}
if redisConnStr, ok := redisConnJson.(string); !ok {
return nil, fmt.Errorf("failed to convert connection_string to string: %+v", redisConnJson)
} else {
parts := strings.Split(redisConnStr, ",")
for _, part := range parts {
if strings.Contains(part, ":") {
address = append(address, part)
} else if strings.Contains(part, "=") {
kv := strings.SplitN(part, "=", 2)
if kv[0] == "password" {
password = kv[1]
} else if kv[0] == "ssl" {
result, err := strconv.ParseBool(kv[1])
if err != nil {
return nil, err
} else if result {
tlsConfig = &tls.Config{}
}
} else if kv[0] == "db" {
db, err = strconv.Atoi(kv[1])
if err != nil {
return nil, err
}
} else {
return nil, fmt.Errorf("unrecognized option in connection_string: %s. Must be one of 'password', 'ssl'", kv[0])
}
} else {
return nil, fmt.Errorf("unable to parse a part of connection_string: %s. Must contain either ':' (addresses) or '=' (options", part)
}
}
}
// Metrics are not showing up when the service name is set to DD_SERVICE
//redisTraceServiceName := os.Getenv("DD_SERVICE") + "-redis"
//if redisTraceServiceName == "" {
// redisTraceServiceName = "redis.client" // default service name if DD_SERVICE is not set
//}
if redisStoreType == redisNode {
log.Info().Msgf("Using Redis: %s", address[0])
store.client = redis.NewClient(&redis.Options{
Addr: address[0],
Password: password,
DB: db,
TLSConfig: tlsConfig,
})
//if strings.ToLower(os.Getenv("ENABLE_DATADOG_REDIS_TRACING")) == "true" {
// redistrace.WrapClient(store.client, redistrace.WithServiceName(redisTraceServiceName))
//}
} else if redisStoreType == redisCluster {
log.Info().Msgf("Using Redis Cluster: %s", address)
store.clusterClient = redis.NewClusterClient(&redis.ClusterOptions{
Addrs: address,
Password: password,
TLSConfig: tlsConfig,
ReadOnly: true,
})
//if strings.ToLower(os.Getenv("ENABLE_DATADOG_REDIS_TRACING")) == "true" {
// redistrace.WrapClient(store.clusterClient, redistrace.WithServiceName(redisTraceServiceName))
//}
}
return &store, nil
}
func getRedisType(onlineStoreConfig map[string]interface{}) (redisType, error) {
var t redisType
redisTypeJson, ok := onlineStoreConfig["redis_type"]
if !ok {
// Default to "redis"
redisTypeJson = "redis"
} else if redisTypeStr, ok := redisTypeJson.(string); !ok {
return -1, fmt.Errorf("failed to convert redis_type to string: %+v", redisTypeJson)
} else {
if redisTypeStr == "redis" {
t = redisNode
} else if redisTypeStr == "redis_cluster" {
t = redisCluster
} else {
return -1, fmt.Errorf("failed to convert redis_type to enum: %s. Must be one of 'redis', 'redis_cluster'", redisTypeStr)
}
}
return t, nil
}
func (r *RedisOnlineStore) buildFeatureViewIndices(featureViewNames []string, featureNames []string) (map[string]int, map[int]string, int) {
featureViewIndices := make(map[string]int)
indicesFeatureView := make(map[int]string)
index := len(featureNames)
for _, featureViewName := range featureViewNames {
if _, ok := featureViewIndices[featureViewName]; !ok {
featureViewIndices[featureViewName] = index
indicesFeatureView[index] = featureViewName
index += 1
}
}
return featureViewIndices, indicesFeatureView, index
}
func (r *RedisOnlineStore) buildRedisHashSetKeys(featureViewNames []string, featureNames []string, indicesFeatureView map[int]string, index int) ([]string, []string) {
featureCount := len(featureNames)
var hsetKeys = make([]string, index)
h := murmur3.New32()
intBuffer := h.Sum32()
byteBuffer := make([]byte, 4)
for i := 0; i < featureCount; i++ {
h.Write([]byte(fmt.Sprintf("%s:%s", featureViewNames[i], featureNames[i])))
intBuffer = h.Sum32()
binary.LittleEndian.PutUint32(byteBuffer, intBuffer)
hsetKeys[i] = string(byteBuffer)
h.Reset()
}
for i := featureCount; i < index; i++ {
view := indicesFeatureView[i]
tsKey := fmt.Sprintf("_ts:%s", view)
hsetKeys[i] = tsKey
featureNames = append(featureNames, tsKey)
}
return hsetKeys, featureNames
}
func (r *RedisOnlineStore) buildRedisKeys(entityKeys []*types.EntityKey) ([]*[]byte, map[string]int, error) {
redisKeys := make([]*[]byte, len(entityKeys))
redisKeyToEntityIndex := make(map[string]int)
for i := 0; i < len(entityKeys); i++ {
var key, err = buildRedisKey(r.project, entityKeys[i], r.config.EntityKeySerializationVersion)
if err != nil {
return nil, nil, err
}
redisKeys[i] = key
redisKeyToEntityIndex[string(*key)] = i
}
return redisKeys, redisKeyToEntityIndex, nil
}
func (r *RedisOnlineStore) OnlineRead(ctx context.Context, entityKeys []*types.EntityKey, featureViewNames []string, featureNames []string) ([][]FeatureData, error) {
//span, _ := tracer.StartSpanFromContext(ctx, "redis.OnlineRead")
//defer span.Finish()
featureCount := len(featureNames)
featureViewIndices, indicesFeatureView, index := r.buildFeatureViewIndices(featureViewNames, featureNames)
hsetKeys, featureNamesWithTimeStamps := r.buildRedisHashSetKeys(featureViewNames, featureNames, indicesFeatureView, index)
redisKeys, redisKeyToEntityIndex, err := r.buildRedisKeys(entityKeys)
if err != nil {
return nil, err
}
results := make([][]FeatureData, len(entityKeys))
commands := map[string]*redis.SliceCmd{}
if r.t == redisNode {
pipe := r.client.Pipeline()
for _, redisKey := range redisKeys {
keyString := string(*redisKey)
commands[keyString] = pipe.HMGet(ctx, keyString, hsetKeys...)
}
_, err = pipe.Exec(ctx)
if err != nil {
return nil, err
}
} else if r.t == redisCluster {
pipe := r.clusterClient.Pipeline()
for _, redisKey := range redisKeys {
keyString := string(*redisKey)
commands[keyString] = pipe.HMGet(ctx, keyString, hsetKeys...)
}
_, err = pipe.Exec(ctx)
if err != nil {
return nil, err
}
}
var entityIndex int
var resContainsNonNil bool
for redisKey, values := range commands {
entityIndex = redisKeyToEntityIndex[redisKey]
resContainsNonNil = false
results[entityIndex] = make([]FeatureData, featureCount)
res, err := values.Result()
if err != nil {
return nil, err
}
var timeStamp timestamppb.Timestamp
for featureIndex, resString := range res {
if featureIndex == featureCount {
break
}
if resString == nil {
// TODO (Ly): Can there be nil result within each feature or they will all be returned as string proto of types.Value_NullVal proto?
featureName := featureNamesWithTimeStamps[featureIndex]
featureViewName := featureViewNames[featureIndex]
timeStampIndex := featureViewIndices[featureViewName]
timeStampInterface := res[timeStampIndex]
if timeStampInterface != nil {
if timeStampString, ok := timeStampInterface.(string); !ok {
return nil, errors.New("error parsing value from redis")
} else {
if err := proto.Unmarshal([]byte(timeStampString), &timeStamp); err != nil {
return nil, errors.New("error converting parsed redis value to timestamppb.Timestamp")
}
}
}
results[entityIndex][featureIndex] = FeatureData{Reference: serving.FeatureReferenceV2{FeatureViewName: featureViewName, FeatureName: featureName},
Timestamp: timestamppb.Timestamp{Seconds: timeStamp.Seconds, Nanos: timeStamp.Nanos},
Value: types.Value{Val: &types.Value_NullVal{NullVal: types.Null_NULL}},
}
} else if valueString, ok := resString.(string); !ok {
return nil, errors.New("error parsing Value from redis")
} else {
resContainsNonNil = true
var value types.Value
if err := proto.Unmarshal([]byte(valueString), &value); err != nil {
return nil, errors.New("error converting parsed redis Value to types.Value")
} else {
featureName := featureNamesWithTimeStamps[featureIndex]
featureViewName := featureViewNames[featureIndex]
timeStampIndex := featureViewIndices[featureViewName]
timeStampInterface := res[timeStampIndex]
if timeStampInterface != nil {
if timeStampString, ok := timeStampInterface.(string); !ok {
return nil, errors.New("error parsing Value from redis")
} else {
if err := proto.Unmarshal([]byte(timeStampString), &timeStamp); err != nil {
return nil, errors.New("error converting parsed redis Value to timestamppb.Timestamp")
}
}
}
results[entityIndex][featureIndex] = FeatureData{Reference: serving.FeatureReferenceV2{FeatureViewName: featureViewName, FeatureName: featureName},
Timestamp: timestamppb.Timestamp{Seconds: timeStamp.Seconds, Nanos: timeStamp.Nanos},
Value: types.Value{Val: value.Val},
}
}
}
}
if !resContainsNonNil {
results[entityIndex] = nil
}
}
return results, nil
}
// Dummy destruct function to conform with plugin OnlineStore interface
func (r *RedisOnlineStore) Destruct() {
}
func buildRedisKey(project string, entityKey *types.EntityKey, entityKeySerializationVersion int64) (*[]byte, error) {
serKey, err := serializeEntityKey(entityKey, entityKeySerializationVersion)
if err != nil {
return nil, err
}
fullKey := append(*serKey, []byte(project)...)
return &fullKey, nil
}