-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathapi_gomux.go
More file actions
1493 lines (1315 loc) · 46.9 KB
/
api_gomux.go
File metadata and controls
1493 lines (1315 loc) · 46.9 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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017-2020, Square, Inc.
// Package api provides API endpoints and controllers.
package api
import (
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"runtime"
"strconv"
"strings"
"time"
"github.com/gorilla/websocket"
httpSwagger "github.com/swaggo/http-swagger"
"go.mongodb.org/mongo-driver/v2/bson"
"github.com/square/etre"
"github.com/square/etre/app"
"github.com/square/etre/auth"
"github.com/square/etre/cdc/changestream"
"github.com/square/etre/docs"
"github.com/square/etre/entity"
"github.com/square/etre/metrics"
"github.com/square/etre/query"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
const reqKey = "rc"
type req struct {
ctx context.Context
caller auth.Caller
wo entity.WriteOp
gm metrics.Metrics
inst app.Instrument
entityType string
entityId string
write bool
}
// API provides controllers for endpoints it registers with a router.
type API struct {
addr string
crt string
key string
es entity.Store
validate entity.Validator
auth auth.Plugin
metricsStore metrics.Store
cdcDisabled bool
streamFactory changestream.StreamerFactory
metricsFactory metrics.Factory
systemMetrics metrics.Metrics
queryTimeout time.Duration
queryLatencySLA time.Duration
queryProfSampleRate int
queryProfReportThreshold time.Duration
srv *http.Server
}
// NewAPI godoc
// @title Etre API
// @version 1
// @description Etre is an entity API for managing primitive entities with labels.
// @contact.url https://github.com/square/etre
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0
func NewAPI(appCtx app.Context) *API {
queryLatencySLA, _ := time.ParseDuration(appCtx.Config.Metrics.QueryLatencySLA)
queryProfReportThreshold, _ := time.ParseDuration(appCtx.Config.Metrics.QueryProfileReportThreshold)
queryTimeout, _ := time.ParseDuration(appCtx.Config.Datasource.QueryTimeout)
api := &API{
addr: appCtx.Config.Server.Addr,
crt: appCtx.Config.Server.TLSCert,
key: appCtx.Config.Server.TLSKey,
es: appCtx.EntityStore,
validate: appCtx.EntityValidator,
auth: appCtx.Auth,
cdcDisabled: appCtx.Config.CDC.Disabled,
streamFactory: appCtx.StreamerFactory,
metricsFactory: appCtx.MetricsFactory,
metricsStore: appCtx.MetricsStore,
systemMetrics: appCtx.SystemMetrics,
queryTimeout: queryTimeout,
queryLatencySLA: queryLatencySLA,
queryProfSampleRate: int(appCtx.Config.Metrics.QueryProfileSampleRate * 100),
queryProfReportThreshold: queryProfReportThreshold,
}
mux := http.NewServeMux()
// /////////////////////////////////////////////////////////////////////
// Query
// /////////////////////////////////////////////////////////////////////
mux.Handle("GET "+etre.API_ROOT+"/entities/{type}", api.requestWrapper(http.HandlerFunc(api.getEntitiesHandler)))
// /////////////////////////////////////////////////////////////////////
// Bulk Write
// /////////////////////////////////////////////////////////////////////
mux.Handle("POST "+etre.API_ROOT+"/entities/{type}", api.requestWrapper(http.HandlerFunc(api.postEntitiesHandler)))
mux.Handle("PUT "+etre.API_ROOT+"/entities/{type}", api.requestWrapper(http.HandlerFunc(api.putEntitiesHandler)))
mux.Handle("DELETE "+etre.API_ROOT+"/entities/{type}", api.requestWrapper(http.HandlerFunc(api.deleteEntitiesHandler)))
// /////////////////////////////////////////////////////////////////////
// Single Entity
// /////////////////////////////////////////////////////////////////////
mux.Handle("POST "+etre.API_ROOT+"/entity/{type}", api.requestWrapper(http.HandlerFunc(api.postEntityHandler)))
mux.Handle("GET "+etre.API_ROOT+"/entity/{type}/{id}", api.requestWrapper(api.id(http.HandlerFunc(api.getEntityHandler))))
mux.Handle("PUT "+etre.API_ROOT+"/entity/{type}/{id}", api.requestWrapper(api.id(http.HandlerFunc(api.putEntityHandler))))
mux.Handle("DELETE "+etre.API_ROOT+"/entity/{type}/{id}", api.requestWrapper(api.id(http.HandlerFunc(api.deleteEntityHandler))))
mux.Handle("GET "+etre.API_ROOT+"/entity/{type}/{id}/labels", api.requestWrapper(api.id(http.HandlerFunc(api.getLabelsHandler))))
mux.Handle("DELETE "+etre.API_ROOT+"/entity/{type}/{id}/labels/{label}", api.requestWrapper(api.id(http.HandlerFunc(api.deleteLabelHandler))))
// /////////////////////////////////////////////////////////////////////
// Metrics and status
// /////////////////////////////////////////////////////////////////////
mux.HandleFunc("GET "+etre.API_ROOT+"/metrics", api.metricsHandler)
mux.HandleFunc("GET "+etre.API_ROOT+"/status", api.statusHandler)
// /////////////////////////////////////////////////////////////////////
// Changes
// /////////////////////////////////////////////////////////////////////
mux.Handle("GET "+etre.API_ROOT+"/changes", api.cdcWrapper(http.HandlerFunc(api.changesHandler)))
// /////////////////////////////////////////////////////////////////////
// OpenAPI docs
// /////////////////////////////////////////////////////////////////////
docs.SwaggerInfo.BasePath = etre.API_ROOT
mux.Handle("GET /apidocs/", httpSwagger.Handler())
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
err := ErrEndpointNotFound
write := isWriteRequest(r.Method)
if write {
wr := etre.WriteResult{Error: &err}
json.NewEncoder(w).Encode(wr)
} else {
json.NewEncoder(w).Encode(err)
}
return
})
api.srv = &http.Server{
Addr: appCtx.Config.Server.Addr,
Handler: mux,
}
return api
}
func (api *API) ServeHTTP(w http.ResponseWriter, r *http.Request) {
api.srv.Handler.ServeHTTP(w, r)
}
func (api *API) Run() error {
if api.crt != "" && api.key != "" {
log.Printf("Listening on %s with TLS", api.addr)
return api.srv.ListenAndServeTLS(api.crt, api.key)
}
log.Printf("Listening on %s", api.addr)
return api.srv.ListenAndServe()
}
func (api *API) Stop() error {
return api.srv.Shutdown(context.TODO())
}
// requestWrapper adds auth and metrics middleware to the endpoint handler for
// entity read/write endpoints. CDC should use cdcWrapper instead.
func (api *API) requestWrapper(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
write := isWriteRequest(r.Method)
// Etre request context passed to endpoint handler
rc := &req{
entityType: r.PathValue("type"),
write: write,
}
// requests passed to requestWrapper should always have an entity type
if rc.entityType == "" {
etreErr := etre.Error{
Message: "missing entity type in request path: " + r.URL.String(),
Type: "bad-request",
HTTPStatus: http.StatusBadRequest,
}
if write {
api.WriteResult(rc, w, nil, etreErr)
} else {
api.readError(rc, w, etreErr)
}
return
}
defer func() {
if r := recover(); r != nil {
err, ok := r.(error)
if !ok {
err = fmt.Errorf("%v", r)
}
b := make([]byte, 4096)
n := runtime.Stack(b, false)
etreErr := etre.Error{
Message: fmt.Sprintf("PANIC: %s\n%s", err, string(b[0:n])),
Type: "panic",
HTTPStatus: http.StatusInternalServerError,
}
log.Printf("PANIC: %s\n%s\n\n", err, string(b[0:n]))
if write {
api.WriteResult(rc, w, nil, etreErr)
} else {
api.readError(rc, w, etreErr)
}
}
}()
api.systemMetrics.Inc(metrics.Load, 1)
defer api.systemMetrics.Inc(metrics.Load, -1)
api.systemMetrics.Inc(metrics.Query, 1)
// Instrument query_profile_sample_rate% of queries
if rand.Intn(100) < api.queryProfSampleRate {
rc.inst = app.NewTimerInstrument()
} else {
rc.inst = app.NopInstrument
}
// --------------------------------------------------------------
// Query timeout
// --------------------------------------------------------------
var ctx context.Context
var cancel context.CancelFunc
queryTimeout := api.queryTimeout
if qth := r.Header.Get(etre.QUERY_TIMEOUT_HEADER); qth != "" {
d, err := time.ParseDuration(qth)
if err != nil {
err := etre.Error{
Message: fmt.Sprintf("invalid %s header: %s: %s", etre.QUERY_TIMEOUT_HEADER, qth, err),
Type: "invalid-query-timeout",
HTTPStatus: http.StatusBadRequest,
}
if write {
api.WriteResult(rc, w, nil, err)
} else {
api.readError(rc, w, err)
}
return
}
queryTimeout = d
}
ctx, cancel = context.WithTimeout(r.Context(), queryTimeout)
defer cancel() // don't leak
t0 := time.Now()
// --------------------------------------------------------------
// Authenticate
// --------------------------------------------------------------
rc.inst.Start("authenticate")
caller, err := api.auth.Authenticate(r)
rc.inst.Stop("authenticate")
if err != nil {
log.Printf("AUTH: failed to authenticate: %s (caller: %+v request: %+v)", err, caller, r)
api.systemMetrics.Inc(metrics.AuthenticationFailed, 1)
authErr := auth.Error{
Err: err,
Type: "access-denied",
HTTPStatus: http.StatusUnauthorized,
}
if write {
api.WriteResult(rc, w, nil, authErr)
} else {
api.readError(rc, w, authErr)
}
return
}
rc.caller = caller
// --------------------------------------------------------------
// Metrics
// --------------------------------------------------------------
// This makes a metrics.Group which is a 1-to-many proxy for every
// metric group in caller.MetricGroups. E.g. if the groups are "ods"
// and "finch", then every metric is recorded in both groups.
gm := api.metricsFactory.Make(caller.MetricGroups)
rc.gm = gm
if err := api.validate.EntityType(rc.entityType); err != nil {
log.Printf("Invalid entity type: '%s': caller=%+v request=%+v", rc.entityType, caller, r)
gm.Inc(metrics.InvalidEntityType, 1)
if write {
api.WriteResult(rc, w, nil, err)
} else {
api.readError(rc, w, err)
}
return
}
// Bind group metrics to entity type
gm.EntityType(rc.entityType)
gm.Inc(metrics.Query, 1) // all queries (QPS)
// auth.Manager extracts trace values from X-Etre-Trace header
if caller.Trace != nil {
gm.Trace(caller.Trace)
}
// --------------------------------------------------------------
// Authorize
// --------------------------------------------------------------
rc.inst.Start("authorize")
if write {
gm.Inc(metrics.Write, 1) // all writes (write QPS)
// Don't allow empty PUT or POST, client must provide entities for these
if r.Method != "DELETE" && r.ContentLength == 0 {
api.WriteResult(rc, w, nil, ErrNoContent)
return
}
// All writes require a write op
rc.wo = writeOp(r, caller)
if err := api.validate.WriteOp(rc.wo); err != nil {
api.WriteResult(rc, w, nil, err)
return
}
if rc.wo.SetOp != "" {
gm.Inc(metrics.SetOp, 1)
}
if err := api.auth.Authorize(caller, auth.Action{EntityType: rc.entityType, Op: auth.OP_WRITE}); err != nil {
log.Printf("AUTH: not authorized: %s (caller: %+v request: %+v)", err, caller, r)
gm.Inc(metrics.AuthorizationFailed, 1)
authErr := auth.Error{
Err: err,
Type: "not-authorized",
HTTPStatus: http.StatusForbidden,
}
api.WriteResult(rc, w, nil, authErr)
return
}
} else {
gm.Inc(metrics.Read, 1) // all reads (read QPS)
if err := api.auth.Authorize(caller, auth.Action{EntityType: rc.entityType, Op: auth.OP_READ}); err != nil {
log.Printf("AUTH: not authorized: %s (caller: %+v request: %+v)", err, caller, r)
gm.Inc(metrics.AuthorizationFailed, 1)
authErr := auth.Error{
Err: err,
Type: "not-authorized",
HTTPStatus: http.StatusForbidden,
}
api.readError(rc, w, authErr)
return
}
}
rc.inst.Stop("authorize")
// //////////////////////////////////////////////////////////////////////
// Endpoint
// //////////////////////////////////////////////////////////////////////
next.ServeHTTP(w, r.WithContext(context.WithValue(ctx, reqKey, rc)))
// //////////////////////////////////////////////////////////////////////
// After
// //////////////////////////////////////////////////////////////////////
// Record query latency (response time) in milliseconds
queryLatency := time.Now().Sub(t0)
gm.Val(metrics.LatencyMs, int64(queryLatency/time.Millisecond))
// Did the query take too long (miss SLA)?
if api.queryLatencySLA > 0 && queryLatency > api.queryLatencySLA {
gm.Inc(metrics.MissSLA, 1)
profile := rc.inst != app.NopInstrument
log.Printf("Missed SLA: %s %s %s (profile: %t caller=%+v request=%+v)", r.Method, r.URL.String(), queryLatency,
profile, caller, r)
}
// Print query profile if it was timed and exceeds the report threshold
if rc.inst != app.NopInstrument && queryLatency > api.queryProfReportThreshold {
log.Printf("Query profile: %s %s %s %+v (caller=%+v)", r.Method, r.URL.String(), queryLatency, rc.inst.Report(), caller)
}
})
}
// cdcWrapper auth and metrics middleware for the changes endpoint. This endpoint is
// unique because it does not have an entity type and is a long-lived connection that
// should not use query timeout and long running query instrumentation.
func (api *API) cdcWrapper(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// Etre request context passed to endpoint handler
rc := &req{}
defer func() {
if r := recover(); r != nil {
err, ok := r.(error)
if !ok {
err = fmt.Errorf("%v", r)
}
b := make([]byte, 4096)
n := runtime.Stack(b, false)
etreErr := etre.Error{
Message: fmt.Sprintf("PANIC: %s\n%s", err, string(b[0:n])),
Type: "panic",
HTTPStatus: http.StatusInternalServerError,
}
log.Printf("PANIC: %s\n%s\n\n", err, string(b[0:n]))
api.readError(rc, w, etreErr)
}
}()
api.systemMetrics.Inc(metrics.Load, 1)
defer api.systemMetrics.Inc(metrics.Load, -1)
api.systemMetrics.Inc(metrics.Query, 1)
// --------------------------------------------------------------
// Authenticate
// --------------------------------------------------------------
caller, err := api.auth.Authenticate(r)
if err != nil {
log.Printf("AUTH: failed to authenticate: %s (caller: %+v request: %+v)", err, caller, r)
api.systemMetrics.Inc(metrics.AuthenticationFailed, 1)
authErr := auth.Error{
Err: err,
Type: "access-denied",
HTTPStatus: http.StatusUnauthorized,
}
api.readError(rc, w, authErr)
return
}
rc.caller = caller
// --------------------------------------------------------------
// Metrics
// --------------------------------------------------------------
// This makes a metrics.Group which is a 1-to-many proxy for every
// metric group in caller.MetricGroups. E.g. if the groups are "ods"
// and "finch", then every metric is recorded in both groups.
//
// Note that CDC does not have an entity type, so entity type specific
// metrics should not be recorded.
gm := api.metricsFactory.Make(caller.MetricGroups)
rc.gm = gm
// --------------------------------------------------------------
// Authorize
// --------------------------------------------------------------
if err := api.auth.Authorize(caller, auth.Action{Op: auth.OP_CDC}); err != nil {
log.Printf("AUTH: not authorized: %s (caller: %+v request: %+v)", err, caller, r)
gm.Inc(metrics.AuthorizationFailed, 1)
authErr := auth.Error{
Err: err,
Type: "not-authorized",
HTTPStatus: http.StatusForbidden,
}
api.readError(rc, w, authErr)
return
}
// //////////////////////////////////////////////////////////////////////
// Endpoint
// //////////////////////////////////////////////////////////////////////
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), reqKey, rc)))
})
}
func (api *API) id(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
rc := ctx.Value(reqKey).(*req)
var err error
var entityId bson.ObjectID
id := r.PathValue("id") // 1. from URL
if id == "" {
err = ErrMissingParam.New("missing id param")
} else {
entityId, err = bson.ObjectIDFromHex(id) // 2. convert to/validate as ObjectID
if err != nil {
err = ErrInvalidParam.New("id '%s' is not a valid ObjectID: %v", id, err)
}
}
if err != nil {
if rc.write {
api.WriteResult(rc, w, nil, err)
} else {
api.readError(rc, w, err)
}
return
}
rc.entityId = entityId.Hex() // 3. ObjectID to hex value (string)
next.ServeHTTP(w, r)
})
}
// //////////////////////////////////////////////////////////////////////////
// Query
// //////////////////////////////////////////////////////////////////////////
// getEntitiesHandler godoc
// @Summary Query a set of entities
// @Description Query entities of a type specified by the :type endpoint.
// @Description Returns a set of entities matching the labels in the `query` query parameter.
// @Description All labels of each entity are returned, unless specific labels are specified in the `labels` query parameter.
// @Description The result set is reduced to distinct values if the request includes the `distinct` query parameter (requires `lables` name a single label).
// @Description If the query is longer than 2000 characters, use the POST /query endpoint (to be implemented).
// @ID getEntitiesHandler
// @Produce json
// @Param type path string true "Entity type"
// @Param query query string true "Selector"
// @Param labels query string false "Comma-separated list of labels to return"
// @Param distinct query boolean false "Reduce results to one per distinct value"
// @Param limit query integer false "Maximum number of results to return" (0 for no limit)
// @Success 200 {array} etre.Entity "OK"
// @Failure 400,404 {object} etre.Error
// @Router /entities/:type [get]
func (api *API) getEntitiesHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context() // query timeout
rc := ctx.Value(reqKey).(*req) // Etre request context
rc.inst.Start("handler")
defer rc.inst.Stop("handler")
rc.gm.Inc(metrics.ReadQuery, 1) // specific read type
// Parse query (label selector) from URL
q, err := parseQuery(r)
if err != nil {
api.readError(rc, w, err)
return
}
// Label metrics
rc.gm.Val(metrics.Labels, int64(len(q.Predicates)))
for _, p := range q.Predicates {
rc.gm.IncLabel(metrics.LabelRead, p.Label)
}
// Query Filter
f := etre.QueryFilter{}
qv := r.URL.Query() // ?x=1&y=2&z -> https://godoc.org/net/url#Values
if csv, ok := qv["labels"]; ok {
f.ReturnLabels = strings.Split(csv[0], ",")
}
if _, ok := qv["distinct"]; ok {
f.Distinct = true
}
if f.Distinct && len(f.ReturnLabels) > 1 {
api.readError(rc, w, ErrInvalidQuery.New("distinct requires only 1 return label but %d specified: %v", len(f.ReturnLabels), f.ReturnLabels))
return
}
if v, ok := qv["limit"]; ok {
limit, err := strconv.ParseInt(v[0], 10, 64)
if err != nil || limit < 0 {
api.readError(rc, w, ErrInvalidQuery.New("invalid limit: %s", v[0]))
return
}
f.Limit = limit
}
// Query data store (instrumented)
rc.inst.Start("db")
entities := api.es.StreamEntities(ctx, rc.entityType, q, f)
rc.inst.Stop("db")
rc.inst.Start("encode-response")
// FinalWriter is where we will write the data. If we're using gzip compression, this will be the gzip writer. If not, it will just be the original response writer.
var finalWriter io.Writer
finalWriter = w
// gzip writer, only initialized if client accepts gzip encoding.
var gzw *gzip.Writer
// encoder is the JSON encoder writing to finalWriter. We initialize it after we know whether we're using gzip or not.
var encoder *json.Encoder
// Number of non-error records sent to the client
count := 0
for e := range entities {
// Handle errors returned by the database
if e.Err != nil {
api.readError(rc, w, e.Err)
return
}
// Handle context timeouts
if err := ctx.Err(); err != nil {
api.readError(rc, w, err)
return
}
// Initialize gzip writer and JSON encoder on the first record, after we know there is data to return to the client.
// We also check the client's Accept-Encoding header to see if gzip is supported.
if count == 0 && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
w.Header().Set("Content-Encoding", "gzip")
gzw = gzip.NewWriter(w)
defer gzw.Close()
finalWriter = gzw
}
// Start the JSON array if this is the first record, or put a comma separator if not the first record
// We don't do this before the for loop because we don't want to write the opening bracket if there is a database
// error in the first record returned.
if count == 0 {
finalWriter.Write([]byte("["))
encoder = json.NewEncoder(finalWriter)
} else {
finalWriter.Write([]byte(","))
}
// Write the record and handle the error.
// encoder.Encode will add a newline, which is fine (nice for human readable output)
err = encoder.Encode(e.Entity)
if err != nil {
// api.readError will mangle the response, but if the encoder failed then the response is already mangled and there's not much else we can do.
api.readError(rc, w, err)
log.Println("ERROR: Read error while encoding response: ", err)
return
}
// Count the record
count++
// If we're compressing, flush every 100 records to ensure data is sent to the client in a timely manner and not buffered in memory.
// Otherwise, the gzip flusher may buffer all the data instead of chunking.
if gzw != nil && count%100 == 0 {
gzw.Flush()
}
}
// One final check of the context timeout. If the store closed the channel because the context was canceled,
// we want to return an error instead of partial results.
if err := ctx.Err(); err != nil {
api.readError(rc, w, err)
return
}
// Clean up the JSON array
if count == 0 {
// Never saw any data. Write an empty array.
finalWriter.Write([]byte("[]"))
} else {
// We wrote some data, now we need to close the array
finalWriter.Write([]byte("]")) // end of JSON array
}
if gzw != nil {
gzw.Flush() // flush any remaining compressed data to the client
}
rc.gm.Val(metrics.ReadMatch, int64(count))
rc.inst.Stop("encode-response")
}
// //////////////////////////////////////////////////////////////////////////
// Bulk Write
// //////////////////////////////////////////////////////////////////////////
// postEntitiesHandler godoc
// @Summary Create entities in bulk
// @Description Given JSON payload, create new entities of the given :type.
// @Description Some meta-labels are filled in by Etre, e.g. `_id`.
// @Description Optionally specify `setOp`, `setId`, and `setSize` together to define a SetOp.
// @ID postEntitiesHandler
// @Accept json
// @Produce json
// @Param type path string true "Entity type"
// @Param setOp query string false "SetOp"
// @Param setId query string false "SetId"
// @Param setSize query int false "SetSize"
// @Success 201 {array} string "List of new entity id's"
// @Failure 400 {object} etre.Error
// @Router /entities/:type [post]
func (api *API) postEntitiesHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context() // query timeout
rc := ctx.Value(reqKey).(*req) // Etre request context
rc.inst.Start("handler")
defer rc.inst.Stop("handler")
rc.gm.Inc(metrics.CreateMany, 1) // specific write type
// Return values at reply (not mutually exclusive)
var ids []string
var err error
// Read new entities from client. Should be an array of entities like:
// [{a:1,b:"foo"},{a:2,b:"bar"}]
// Must have >= 1 entity; we're strict to guard against client bugs.
var entities []etre.Entity
if err = json.NewDecoder(r.Body).Decode(&entities); err != nil {
err = ErrInvalidContent
goto reply
}
if len(entities) == 0 {
err = ErrNoContent
goto reply
}
// Validate new entities before attempting to write
rc.gm.Val(metrics.CreateBulk, int64(len(entities))) // inc before validating
if err = api.validate.Entities(entities, entity.VALIDATE_ON_CREATE); err != nil {
goto reply
}
// Write new entities to data store
ids, err = api.es.CreateEntities(ctx, rc.wo, entities)
rc.gm.Inc(metrics.Created, int64(len(ids)))
reply:
api.WriteResult(rc, w, ids, err)
}
// putEntitiesHandler godoc
// @Summary Update matching entities in bulk
// @Description Given JSON payload, update labels in matching entities of the given :type.
// @Description Applies update to the set of entities matching the labels in the `query` query parameter.
// @Description Optionally specify `setOp`, `setId`, and `setSize` together to define a SetOp.
// @ID putEntitiesHandler
// @Accept json
// @Produce json
// @Param type path string true "Entity type"
// @Param query query string true "Selector"
// @Param setOp query string false "SetOp"
// @Param setId query string false "SetId"
// @Param setSize query int false "SetSize"
// @Success 200 {array} etre.Entity "Set of matching entities after update applied."
// @Failure 400 {object} etre.Error
// @Router /entities/:type [put]
func (api *API) putEntitiesHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context() // query timeout
rc := ctx.Value(reqKey).(*req) // Etre request context
rc.inst.Start("handler")
defer rc.inst.Stop("handler")
rc.gm.Inc(metrics.UpdateQuery, 1) // specific write type
// Return values at reply (not mutually exclusive)
var entities []etre.Entity
var err error
var patch etre.Entity
// Parse query (label selector) from URL
var q query.Query
q, err = parseQuery(r)
if err != nil {
goto reply
}
// Read and validate patch entity
if err = json.NewDecoder(r.Body).Decode(&patch); err != nil {
err = ErrInvalidContent
goto reply
}
if len(patch) == 0 {
err = ErrNoContent
goto reply
}
if err = api.validate.Entities([]etre.Entity{patch}, entity.VALIDATE_ON_UPDATE); err != nil {
goto reply
}
// Label metrics (read and update)
rc.gm.Val(metrics.Labels, int64(len(q.Predicates)))
for _, p := range q.Predicates {
rc.gm.IncLabel(metrics.LabelRead, p.Label)
}
for label := range patch {
rc.gm.IncLabel(metrics.LabelUpdate, label)
}
// Patch all entities matching query
entities, err = api.es.UpdateEntities(ctx, rc.wo, q, patch)
rc.gm.Val(metrics.UpdateBulk, int64(len(entities)))
rc.gm.Inc(metrics.Updated, int64(len(entities)))
reply:
api.WriteResult(rc, w, entities, err)
}
// deleteEntitiesHandler godoc
// @Summary Remove matching entities in bulk
// @Description Deletes the set of entities of the given :type, matching the labels in the `query` query parameter.
// @ID deleteEntitiesHandler
// @Produce json
// @Param type path string true "Entity type"
// @Param query query string true "Selector"
// @Param setOp query string false "SetOp"
// @Param setId query string false "SetId"
// @Param setSize query int false "SetSize"
// @Success 200 {array} etre.Entity "OK"
// @Failure 400 {object} etre.Error
// @Router /entities/:type [delete]
func (api *API) deleteEntitiesHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context() // query timeout
rc := ctx.Value(reqKey).(*req) // Etre request context
rc.inst.Start("handler")
defer rc.inst.Stop("handler")
rc.gm.Inc(metrics.DeleteQuery, 1) // specific write type
// Return values at reply (not mutually exclusive)
var entities []etre.Entity
var err error
// Parse query (label selector) from URL
var q query.Query
q, err = parseQuery(r)
if err != nil {
goto reply
}
// Label metrics
rc.gm.Val(metrics.Labels, int64(len(q.Predicates)))
for _, p := range q.Predicates {
rc.gm.IncLabel(metrics.LabelRead, p.Label)
}
// Delete entities, returns the deleted entities
entities, err = api.es.DeleteEntities(ctx, rc.wo, q)
rc.gm.Val(metrics.DeleteBulk, int64(len(entities)))
rc.gm.Inc(metrics.Deleted, int64(len(entities)))
reply:
api.WriteResult(rc, w, entities, err)
}
// //////////////////////////////////////////////////////////////////////////
// Single Entity
// //////////////////////////////////////////////////////////////////////////
// getEntityHandler godoc
// @Summary Get one entity by id
// @Description Return one entity of the given :type, identified by the path parameter :id.
// @Description All labels of each entity are returned, unless specific labels are specified in the `labels` query parameter.
// @ID getEntityHandler
// @Produce json
// @Param type path string true "Entity type"
// @Param id path string true "Entity ID"
// @Param labels query string false "Comma-separated list of labels to return"
// @Success 200 {object} etre.Entity "OK"
// @Failure 400,404 {object} etre.Error
// @Router /entity/:type/:id [get]
func (api *API) getEntityHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context() // query timeout
rc := ctx.Value(reqKey).(*req) // Etre request context
rc.inst.Start("handler")
defer rc.inst.Stop("handler")
rc.gm.Inc(metrics.ReadId, 1) // specific read type
// Query Filter
f := etre.QueryFilter{}
qv := r.URL.Query() // ?x=1&y=2&z -> https://godoc.org/net/url#Values
if csv, ok := qv["labels"]; ok {
f.ReturnLabels = strings.Split(csv[0], ",")
}
// Read the entity by ID
entity, err := api.es.ReadEntity(ctx, rc.entityType, rc.entityId, f)
if err != nil {
api.readError(rc, w, err)
return
}
if entity == nil {
w.WriteHeader(http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(entity)
}
// getLabelsHandler godoc
// @Summary Return the labels for a single entity.
// @Description Return an array of label names used by a single entity of the given :type, identified by the path parameter :id.
// @Description The values of these labels are not returned.
// @ID getLabelsHandler
// @Produce json
// @Param type path string true "Entity type"
// @Param id path string true "Entity ID"
// @Success 200 {array} string "OK"
// @Failure 400,404 {object} etre.Error
// @Router /entity/:type/:id/labels [get]
func (api *API) getLabelsHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context() // query timeout
rc := ctx.Value(reqKey).(*req) // Etre request context
rc.inst.Start("handler")
defer rc.inst.Stop("handler")
rc.gm.Inc(metrics.ReadLabels, 1) // specific read type
entity, err := api.es.ReadEntity(ctx, rc.entityType, rc.entityId, etre.QueryFilter{})
if err != nil {
api.readError(rc, w, err)
return
}
if entity == nil {
w.WriteHeader(http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(entity.Labels())
}
// --------------------------------------------------------------------------
// Single entity writes
// --------------------------------------------------------------------------
// postEntityHandler godoc
// @Summary Create one entity
// @Description Given JSON payload, create one new entity of the given :type.
// @Description Some meta-labels are filled in by Etre, e.g. `_id`.
// @Description Optionally specify `setOp`, `setId`, and `setSize` together to define a SetOp.
// @ID postEntityHandler
// @Accept json
// @Produce json
// @Param type path string true "Entity type"
// @Param setOp query string false "SetOp"
// @Param setId query string false "SetId"
// @Param setSize query int false "SetSize"
// @Success 201 {array} string "List of new entity id's"
// @Failure 400,404 {object} etre.Error
// @Router /entity/:type [post]
func (api *API) postEntityHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context() // query timeout
rc := ctx.Value(reqKey).(*req) // Etre request context
rc.inst.Start("handler")
defer rc.inst.Stop("handler")
rc.gm.Inc(metrics.CreateOne, 1)
var newEntity etre.Entity
var ids []string
var err error
// Read and validate new entity
if err = json.NewDecoder(r.Body).Decode(&newEntity); err != nil {
err = ErrInvalidContent
goto reply
}
if err = api.validate.Entities([]etre.Entity{newEntity}, entity.VALIDATE_ON_CREATE); err != nil {
goto reply
}
// Create new entity
ids, err = api.es.CreateEntities(ctx, rc.wo, []etre.Entity{newEntity})
if err == nil {
rc.gm.Inc(metrics.Created, 1)
}
reply:
api.WriteResult(rc, w, ids, err)
}
// putEntityHandler godoc
// @Summary Patch one entity by _id
// @Description Given JSON payload, update labels in the entity of the given :type and :id.
// @Description Optionally specify `setOp`, `setId`, and `setSize` together to define a SetOp.
// @ID putEntityHandler
// @Accept json
// @Produce json
// @Param type path string true "Entity type"
// @Param id path string true "Entity ID"
// @Param setOp query string false "SetOp"
// @Param setId query string false "SetId"
// @Param setSize query int false "SetSize"
// @Success 200 {array} etre.Entity "Entity after update applied."
// @Failure 400,404 {object} etre.Error
// @Router /entity/:type/:id [put]
func (api *API) putEntityHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context() // query timeout
rc := ctx.Value(reqKey).(*req) // Etre request context