-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathhttp_server.go
More file actions
408 lines (363 loc) · 12.1 KB
/
http_server.go
File metadata and controls
408 lines (363 loc) · 12.1 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
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
package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"runtime"
"strconv"
"time"
"github.com/feast-dev/feast/go/internal/feast"
"github.com/feast-dev/feast/go/internal/feast/model"
"github.com/feast-dev/feast/go/internal/feast/onlineserving"
"github.com/feast-dev/feast/go/internal/feast/server/logging"
"github.com/feast-dev/feast/go/protos/feast/serving"
prototypes "github.com/feast-dev/feast/go/protos/feast/types"
"github.com/feast-dev/feast/go/types"
"github.com/rs/zerolog/log"
"github.com/feast-dev/feast/go/internal/feast/metrics"
)
type httpServer struct {
fs *feast.FeatureStore
loggingService *logging.LoggingService
server *http.Server
}
// Some Feast types aren't supported during JSON conversion
type repeatedValue struct {
stringVal []string
int64Val []int64
doubleVal []float64
boolVal []bool
stringListVal [][]string
int64ListVal [][]int64
doubleListVal [][]float64
boolListVal [][]bool
}
func (u *repeatedValue) UnmarshalJSON(data []byte) error {
isString := false
isDouble := false
isInt64 := false
isArray := false
openBraketCounter := 0
for _, b := range data {
if b == '"' {
isString = true
}
if b == '.' {
isDouble = true
}
if b >= '0' && b <= '9' {
isInt64 = true
}
if b == '[' {
openBraketCounter++
if openBraketCounter > 1 {
isArray = true
}
}
}
var err error
if !isArray {
if isString {
err = json.Unmarshal(data, &u.stringVal)
} else if isDouble {
err = json.Unmarshal(data, &u.doubleVal)
} else if isInt64 {
err = json.Unmarshal(data, &u.int64Val)
} else {
err = json.Unmarshal(data, &u.boolVal)
}
} else {
if isString {
err = json.Unmarshal(data, &u.stringListVal)
} else if isDouble {
err = json.Unmarshal(data, &u.doubleListVal)
} else if isInt64 {
err = json.Unmarshal(data, &u.int64ListVal)
} else {
err = json.Unmarshal(data, &u.boolListVal)
}
}
return err
}
func (u *repeatedValue) ToProto() *prototypes.RepeatedValue {
proto := new(prototypes.RepeatedValue)
if u.stringVal != nil {
for _, val := range u.stringVal {
proto.Val = append(proto.Val, &prototypes.Value{Val: &prototypes.Value_StringVal{StringVal: val}})
}
}
if u.int64Val != nil {
for _, val := range u.int64Val {
proto.Val = append(proto.Val, &prototypes.Value{Val: &prototypes.Value_Int64Val{Int64Val: val}})
}
}
if u.doubleVal != nil {
for _, val := range u.doubleVal {
proto.Val = append(proto.Val, &prototypes.Value{Val: &prototypes.Value_DoubleVal{DoubleVal: val}})
}
}
if u.boolVal != nil {
for _, val := range u.boolVal {
proto.Val = append(proto.Val, &prototypes.Value{Val: &prototypes.Value_BoolVal{BoolVal: val}})
}
}
if u.stringListVal != nil {
for _, val := range u.stringListVal {
proto.Val = append(proto.Val, &prototypes.Value{Val: &prototypes.Value_StringListVal{StringListVal: &prototypes.StringList{Val: val}}})
}
}
if u.int64ListVal != nil {
for _, val := range u.int64ListVal {
proto.Val = append(proto.Val, &prototypes.Value{Val: &prototypes.Value_Int64ListVal{Int64ListVal: &prototypes.Int64List{Val: val}}})
}
}
if u.doubleListVal != nil {
for _, val := range u.doubleListVal {
proto.Val = append(proto.Val, &prototypes.Value{Val: &prototypes.Value_DoubleListVal{DoubleListVal: &prototypes.DoubleList{Val: val}}})
}
}
if u.boolListVal != nil {
for _, val := range u.boolListVal {
proto.Val = append(proto.Val, &prototypes.Value{Val: &prototypes.Value_BoolListVal{BoolListVal: &prototypes.BoolList{Val: val}}})
}
}
return proto
}
type getOnlineFeaturesRequest struct {
FeatureService *string `json:"feature_service"`
Features []string `json:"features"`
Entities map[string]repeatedValue `json:"entities"`
FullFeatureNames bool `json:"full_feature_names"`
RequestContext map[string]repeatedValue `json:"request_context"`
}
func NewHttpServer(fs *feast.FeatureStore, loggingService *logging.LoggingService) *httpServer {
return &httpServer{fs: fs, loggingService: loggingService}
}
func (s *httpServer) getOnlineFeatures(w http.ResponseWriter, r *http.Request) {
var err error
ctx := r.Context()
ctx, span := tracer.Start(r.Context(), "server.getOnlineFeatures")
defer span.End()
logSpanContext := LogWithSpanContext(span)
if r.Method != "POST" {
http.NotFound(w, r)
return
}
statusQuery := r.URL.Query().Get("status")
status := false
if statusQuery != "" {
status, err = strconv.ParseBool(statusQuery)
if err != nil {
logSpanContext.Error().Err(err).Msg("Error parsing status query parameter")
writeJSONError(w, fmt.Errorf("Error parsing status query parameter: %+v", err), http.StatusBadRequest)
return
}
}
decoder := json.NewDecoder(r.Body)
var request getOnlineFeaturesRequest
err = decoder.Decode(&request)
if err != nil {
logSpanContext.Error().Err(err).Msg("Error decoding JSON request data")
writeJSONError(w, fmt.Errorf("Error decoding JSON request data: %+v", err), http.StatusInternalServerError)
return
}
var featureService *model.FeatureService
if request.FeatureService != nil {
featureService, err = s.fs.GetFeatureService(*request.FeatureService)
if err != nil {
logSpanContext.Error().Err(err).Msg("Error getting feature service from registry")
writeJSONError(w, fmt.Errorf("Error getting feature service from registry: %+v", err), http.StatusInternalServerError)
return
}
}
entitiesProto := make(map[string]*prototypes.RepeatedValue)
for key, value := range request.Entities {
entitiesProto[key] = value.ToProto()
}
requestContextProto := make(map[string]*prototypes.RepeatedValue)
for key, value := range request.RequestContext {
requestContextProto[key] = value.ToProto()
}
featureVectors, err := s.fs.GetOnlineFeatures(
ctx,
request.Features,
featureService,
entitiesProto,
requestContextProto,
request.FullFeatureNames)
if err != nil {
logSpanContext.Error().Err(err).Msg("Error getting feature vector")
writeJSONError(w, fmt.Errorf("Error getting feature vector: %+v", err), http.StatusInternalServerError)
return
}
var featureNames []string
var results []map[string]interface{}
for _, vector := range featureVectors {
featureNames = append(featureNames, vector.Name)
result := make(map[string]interface{})
if status {
var statuses []string
for _, status := range vector.Statuses {
statuses = append(statuses, status.String())
}
var timestamps []string
for _, timestamp := range vector.Timestamps {
timestamps = append(timestamps, timestamp.AsTime().Format(time.RFC3339))
}
result["statuses"] = statuses
result["event_timestamps"] = timestamps
}
// Note, that vector.Values is an Arrow Array, but this type implements JSON Marshaller.
// So, it's not necessary to pre-process it in any way.
result["values"] = vector.Values
results = append(results, result)
}
response := map[string]interface{}{
"metadata": map[string]interface{}{
"feature_names": featureNames,
},
"results": results,
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(response)
if err != nil {
logSpanContext.Error().Err(err).Msg("Error encoding response")
writeJSONError(w, fmt.Errorf("Error encoding response: %+v", err), http.StatusInternalServerError)
return
}
if featureService != nil && featureService.LoggingConfig != nil && s.loggingService != nil {
logger, err := s.loggingService.GetOrCreateLogger(featureService)
if err != nil {
logSpanContext.Error().Err(err).Msgf("Couldn't instantiate logger for feature service %s", featureService.Name)
writeJSONError(w, fmt.Errorf("Couldn't instantiate logger for feature service %s: %+v", featureService.Name, err), http.StatusInternalServerError)
return
}
requestId := GenerateRequestId()
// Note: we're converting arrow to proto for feature logging. In the future we should
// base feature logging on arrow so that we don't have to do this extra conversion.
var featureVectorProtos []*serving.GetOnlineFeaturesResponse_FeatureVector
for _, vector := range featureVectors[len(request.Entities):] {
values, err := types.ArrowValuesToProtoValues(vector.Values)
if err != nil {
logSpanContext.Error().Err(err).Msg("Couldn't convert arrow values into protobuf")
writeJSONError(w, fmt.Errorf("Couldn't convert arrow values into protobuf: %+v", err), http.StatusInternalServerError)
return
}
featureVectorProtos = append(featureVectorProtos, &serving.GetOnlineFeaturesResponse_FeatureVector{
Values: values,
Statuses: vector.Statuses,
EventTimestamps: vector.Timestamps,
})
}
err = logger.Log(entitiesProto, featureVectorProtos, featureNames[len(request.Entities):], requestContextProto, requestId)
if err != nil {
writeJSONError(w, fmt.Errorf("LoggerImpl error[%s]: %+v", featureService.Name, err), http.StatusInternalServerError)
return
}
}
go releaseCGOMemory(featureVectors)
}
func releaseCGOMemory(featureVectors []*onlineserving.FeatureVector) {
for _, vector := range featureVectors {
vector.Values.Release()
}
}
func logStackTrace() {
// Start with a small buffer and grow it until the full stack trace fits.
buf := make([]byte, 1024)
for {
stackSize := runtime.Stack(buf, false)
if stackSize < len(buf) {
// The stack trace fits in the buffer, so we can log it now.
log.Error().Str("stack_trace", string(buf[:stackSize])).Msg("")
return
}
// The stack trace doesn't fit in the buffer, so we need to grow the buffer and try again.
buf = make([]byte, 2*len(buf))
}
}
func writeJSONError(w http.ResponseWriter, err error, statusCode int) {
errMap := map[string]interface{}{
"error": fmt.Sprintf("%+v", err),
"status_code": statusCode,
}
errJSON, _ := json.Marshal(errMap)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
w.Write(errJSON)
}
func recoverMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if r := recover(); r != nil {
log.Error().Err(fmt.Errorf("Panic recovered: %v", r)).Msg("A panic occurred in the server")
// Log the stack trace
logStackTrace()
writeJSONError(w, fmt.Errorf("Internal Server Error: %v", r), http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(status int) {
if w.status == 0 {
w.status = status
}
w.ResponseWriter.WriteHeader(status)
}
func (w *statusWriter) Write(b []byte) (int, error) {
if w.status == 0 {
w.status = 200
}
n, err := w.ResponseWriter.Write(b)
return n, err
}
func metricsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t0 := time.Now()
sw := &statusWriter{ResponseWriter: w}
next.ServeHTTP(sw, r)
duration := time.Since(t0)
if sw.status == 0 {
sw.status = 200
}
metrics.HttpMetrics.Duration(metrics.HttpLabels{
Method: r.Method,
Status: sw.status,
Path: r.URL.Path,
}).Duration(duration)
metrics.HttpMetrics.RequestsTotal(metrics.HttpLabels{
Method: r.Method,
Status: sw.status,
Path: r.URL.Path,
}).Inc()
})
}
func (s *httpServer) Serve(host string, port int) error {
mux := http.NewServeMux()
mux.Handle("/get-online-features", metricsMiddleware(recoverMiddleware(http.HandlerFunc(s.getOnlineFeatures))))
mux.Handle("/health", metricsMiddleware(http.HandlerFunc(healthCheckHandler)))
s.server = &http.Server{Addr: fmt.Sprintf("%s:%d", host, port), Handler: mux, ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 15 * time.Second}
err := s.server.ListenAndServe()
// Don't return the error if it's caused by graceful shutdown using Stop()
if err == http.ErrServerClosed {
return nil
}
log.Fatal().Stack().Err(err).Msg("Failed to start HTTP server")
return err
}
func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Healthy")
}
func (s *httpServer) Stop() error {
if s.server != nil {
return s.server.Shutdown(context.Background())
}
return nil
}