-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathgraph_server.go
More file actions
2354 lines (2055 loc) · 88.6 KB
/
Copy pathgraph_server.go
File metadata and controls
2354 lines (2055 loc) · 88.6 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
package core
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/tls"
"errors"
"fmt"
"net/http"
"net/url"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/cespare/xxhash/v2"
"github.com/cloudflare/backoff"
"github.com/dgraph-io/ristretto/v2"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/golang-jwt/jwt/v5"
"github.com/klauspost/compress/gzhttp"
"github.com/klauspost/compress/gzip"
"github.com/wundergraph/cosmo/router/pkg/routerconfig"
"go.opentelemetry.io/otel/attribute"
otelmetric "go.opentelemetry.io/otel/metric"
oteltrace "go.opentelemetry.io/otel/trace"
"go.uber.org/atomic"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/exp/maps"
"golang.org/x/sync/errgroup"
"github.com/wundergraph/cosmo/router/gen/proto/wg/cosmo/common"
nodev1 "github.com/wundergraph/cosmo/router/gen/proto/wg/cosmo/node/v1"
"github.com/wundergraph/cosmo/router/internal/circuit"
"github.com/wundergraph/cosmo/router/internal/exporter"
"github.com/wundergraph/cosmo/router/internal/expr"
"github.com/wundergraph/cosmo/router/internal/graphqlmetrics"
rjwt "github.com/wundergraph/cosmo/router/internal/jwt"
rmiddleware "github.com/wundergraph/cosmo/router/internal/middleware"
"github.com/wundergraph/cosmo/router/internal/recoveryhandler"
"github.com/wundergraph/cosmo/router/internal/requestlogger"
"github.com/wundergraph/cosmo/router/pkg/config"
"github.com/wundergraph/cosmo/router/pkg/cors"
"github.com/wundergraph/cosmo/router/pkg/execution_config"
"github.com/wundergraph/cosmo/router/pkg/grpcconnector"
"github.com/wundergraph/cosmo/router/pkg/grpcconnector/grpccommon"
"github.com/wundergraph/cosmo/router/pkg/grpcconnector/grpcplugin"
"github.com/wundergraph/cosmo/router/pkg/grpcconnector/grpcpluginoci"
"github.com/wundergraph/cosmo/router/pkg/grpcconnector/grpcremote"
"github.com/wundergraph/cosmo/router/pkg/health"
"github.com/wundergraph/cosmo/router/pkg/logging"
rmetric "github.com/wundergraph/cosmo/router/pkg/metric"
"github.com/wundergraph/cosmo/router/pkg/otel"
"github.com/wundergraph/cosmo/router/pkg/pubsub/datasource"
"github.com/wundergraph/cosmo/router/pkg/slowplancache"
"github.com/wundergraph/cosmo/router/pkg/statistics"
rtrace "github.com/wundergraph/cosmo/router/pkg/trace"
"github.com/wundergraph/graphql-go-tools/v2/pkg/astparser"
)
const (
featureFlagHeader = "X-Feature-Flag"
featureFlagCookie = "feature_flag"
)
type (
// Server is the public interface of the server.
Server interface {
HttpServer() *http.Server
HealthChecks() health.Checker
}
// graphServer is the swappable implementation of a Graph instance which is an HTTP mux with middlewares.
// Everytime a schema is updated, the old graph server is shutdown and a new graph server is created.
// For feature flags, a graphql server has multiple mux and is dynamically switched based on the feature flag header or cookie.
// All fields are shared between all feature muxes. On shutdown, all graph instances are shutdown.
graphServer struct {
*Config
graphServerCtx context.Context
graphServerCancel context.CancelFunc
routerCtx context.Context
storageProviders *config.StorageProviders
engineStats statistics.EngineStatistics
playgroundHandler func(http.Handler) http.Handler
publicKey *ecdsa.PublicKey
baseTransport *http.Transport
subgraphTransports map[string]*http.Transport
baseOtelAttributes []attribute.KeyValue
baseRouterConfigVersion string
mux *chi.Mux
// inFlightRequests is used to track the number of requests currently being processed
// does not include websocket (hijacked) connections.
inFlightRequests *atomic.Uint64
// graphMuxList contains all graph muxes of this graph server.
// It's keyed by mux name (feature flag name or empty string for base graph).
graphMuxList map[string]*graphMux
graphMuxListLock sync.Mutex
runtimeMetrics *rmetric.RuntimeMetrics
otlpEngineMetrics *rmetric.EngineMetrics
prometheusEngineMetrics *rmetric.EngineMetrics
connectionMetrics *rmetric.ConnectionMetrics
instanceData InstanceData
pubSubProviders []datasource.Provider
traceDialer *TraceDialer
connector *grpcconnector.Connector
circuitBreakerManager *circuit.Manager
headerPropagation *HeaderPropagation
}
)
// BuildGraphMuxOptions contains the configuration options for building a graph mux.
type BuildGraphMuxOptions struct {
FeatureFlagName string
RouterConfigVersion string
EngineConfig *nodev1.EngineConfiguration
ConfigSubgraphs []*nodev1.Subgraph
RoutingUrlGroupings map[string]map[string]bool
ReloadPersistentState *ReloadPersistentState
defaultClientTLS *tls.Config
perSubgraphTLS map[string]*tls.Config
}
func (b BuildGraphMuxOptions) IsBaseGraph() bool {
return b.FeatureFlagName == ""
}
// buildMultiGraphHandlerOptions contains the configuration options for building a multi-graph handler.
type buildMultiGraphHandlerOptions struct {
baseMux *chi.Mux
featureFlagConfigs map[string]*nodev1.FeatureFlagRouterExecutionConfig
reloadPersistentState *ReloadPersistentState
currentGraphMuxes map[string]*graphMux
changes *routerconfig.Changes
defaultClientTLS *tls.Config
perSubgraphTLS map[string]*tls.Config
}
// reusedGraphMux holds a graph mux from the previous server that the new server
// intends to reuse. The reuse is bookkeeping is deferred (mux.reused flag and
// s.graphMuxList entry) until newGraphServer succeeds, so a failed construction
// leaves the previous server's muxes untouched.
type reusedGraphMux struct {
key string
mux *graphMux
}
// newGraphServer creates a new server instance.
func newGraphServer(routerCtx context.Context, r *Router, response *routerconfig.Response, proxy ProxyFunc) (*graphServer, error) {
/* Older versions of composition will not populate a compatibility version.
* Currently, all "old" router execution configurations are compatible as there have been no breaking
* changes.
* Upon the first breaking change to the execution config, an unpopulated compatibility version will
* also be unsupported (and the logic for IsRouterCompatibleWithExecutionConfig will need to be updated).
*/
if !execution_config.IsRouterCompatibleWithExecutionConfig(r.logger, response.Config.CompatibilityVersion) {
return nil, fmt.Errorf(`the compatibility version "%s" is not compatible with this router version`, response.Config.CompatibilityVersion)
}
isConnStoreEnabled := r.metricConfig.OpenTelemetry.ConnectionStats || r.metricConfig.Prometheus.ConnectionStats
var traceDialer *TraceDialer
if isConnStoreEnabled {
traceDialer = NewTraceDialer()
}
// Build subgraph client TLS configs (mTLS for outbound subgraph connections)
defaultClientTLS, perSubgraphTLS, err := buildSubgraphTLSConfigs(
r.logger,
&r.tls.settings.Client,
)
if err != nil {
return nil, fmt.Errorf("could not build subgraph client TLS config: %w", err)
}
// Build gRPC subgraph client TLS configs
defaultGRPCClientTLS, perSubgraphGRPCTLS, err := buildSubgraphTLSConfigs(
r.logger,
&r.tls.settings.ClientGRPC,
)
if err != nil {
return nil, fmt.Errorf("could not build gRPC subgraph client TLS config: %w", err)
}
// Base transport
baseTransport := newHTTPTransport(r.subgraphTransportOptions.TransportRequestOptions, proxy, traceDialer, "", defaultClientTLS)
// Subgraph transports
subgraphTransports := map[string]*http.Transport{}
for subgraph, subgraphOpts := range r.subgraphTransportOptions.SubgraphMap {
clientTLS := defaultClientTLS
if sgTLS, ok := perSubgraphTLS[subgraph]; ok {
clientTLS = sgTLS
}
subgraphBaseTransport := newHTTPTransport(subgraphOpts, proxy, traceDialer, subgraph, clientTLS)
subgraphTransports[subgraph] = subgraphBaseTransport
}
// Create transports for subgraphs with per-subgraph TLS configs that don't have
// per-subgraph transport options (they inherit the base transport options).
for subgraph, sgTLS := range perSubgraphTLS {
if _, exists := subgraphTransports[subgraph]; !exists {
subgraphBaseTransport := newHTTPTransport(r.subgraphTransportOptions.TransportRequestOptions, proxy, traceDialer, subgraph, sgTLS)
subgraphTransports[subgraph] = subgraphBaseTransport
}
}
graphServerCtx, graphServerCancel := context.WithCancel(routerCtx)
s := &graphServer{
graphServerCtx: graphServerCtx,
graphServerCancel: graphServerCancel,
routerCtx: routerCtx,
Config: &r.Config,
engineStats: r.EngineStats,
baseTransport: baseTransport,
subgraphTransports: subgraphTransports,
playgroundHandler: r.playgroundHandler,
traceDialer: traceDialer,
baseRouterConfigVersion: response.Config.GetVersion(),
inFlightRequests: &atomic.Uint64{},
graphMuxList: make(map[string]*graphMux, 1),
instanceData: InstanceData{
HostName: r.hostName,
ListenAddress: r.listenAddr,
},
storageProviders: &r.storageProviders,
headerPropagation: r.headerPropagation,
}
baseOtelAttributes := []attribute.KeyValue{
otel.WgRouterVersion.String(Version),
otel.WgRouterClusterName.String(r.clusterName),
}
if s.graphApiToken != "" {
claims, err := rjwt.ExtractFederatedGraphTokenClaims(s.graphApiToken)
if err != nil {
return nil, err
}
baseOtelAttributes = append(baseOtelAttributes, otel.WgFederatedGraphID.String(claims.FederatedGraphID))
}
s.baseOtelAttributes = baseOtelAttributes
baseDefaultMuxAttributes := append([]attribute.KeyValue{otel.WgRouterConfigVersion.String(s.baseRouterConfigVersion)}, baseOtelAttributes...)
mapper := newAttributeMapper(!rmetric.IsUsingDefaultCloudExporter(s.metricConfig), s.metricConfig.Attributes)
mappedMetricAttributes := mapper.mapAttributes(baseDefaultMuxAttributes)
if s.metricConfig.OpenTelemetry.RouterRuntime {
// We track runtime metrics with base router config version
s.runtimeMetrics = rmetric.NewRuntimeMetrics(
s.logger,
s.otlpMeterProvider,
mappedMetricAttributes,
s.processStartTime,
)
// Start runtime metrics
if err := s.runtimeMetrics.Start(); err != nil {
return nil, err
}
}
if isConnStoreEnabled {
connStore, err := rmetric.NewConnectionMetricStore(
s.logger,
nil,
s.otlpMeterProvider,
s.promMeterProvider,
s.metricConfig,
s.traceDialer.connectionPoolStats,
)
if err != nil {
return nil, err
}
s.connectionMetrics = connStore
}
if err := s.setupEngineStatistics(mappedMetricAttributes); err != nil {
return nil, fmt.Errorf("failed to setup engine statistics: %w", err)
}
if s.registrationInfo != nil {
publicKey, err := jwt.ParseECPublicKeyFromPEM([]byte(s.registrationInfo.GetGraphPublicKey()))
if err != nil {
return nil, fmt.Errorf("failed to parse router public key: %w", err)
}
s.publicKey = publicKey
}
httpRouter := chi.NewRouter()
/**
* Middlewares
*/
// This recovery handler is used for everything before the graph mux to ensure that
// we can recover from panics and log them properly.
httpRouter.Use(recoveryhandler.New(recoveryhandler.WithLogHandler(func(w http.ResponseWriter, r *http.Request, err any) {
s.logger.Error("[Recovery from panic]",
zap.Any("error", err),
)
})))
if s.routerTrafficConfig.DecompressionEnabled {
httpRouter.Use(rmiddleware.HandleCompression(s.logger))
}
// Request traffic shaping related middlewares, happens after decompression to prevent unbounded decompression attacks
httpRouter.Use(rmiddleware.RequestSize(int64(s.routerTrafficConfig.MaxRequestBodyBytes)))
httpRouter.Use(middleware.RequestID)
httpRouter.Use(middleware.RealIP)
if s.corsOptions.Enabled {
httpRouter.Use(cors.New(*s.corsOptions))
}
if s.subgraphCircuitBreakerOptions.IsEnabled() {
manager, err := circuit.NewManager(s.subgraphCircuitBreakerOptions.CircuitBreaker)
if err != nil {
return nil, err
}
s.circuitBreakerManager = manager
}
routingUrlGroupings, err := getRoutingUrlGroupingForCircuitBreakers(response.Config, s.overrideRoutingURLConfiguration, s.overrides)
if err != nil {
return nil, err
}
// reusedMuxes accumulates the muxes that the new server intends to inherit from
// the previous server. The reuse bookkeeping (gm.reused flag and s.graphMuxList
// entries) is committed at the end of this function, after every fallible step
// has succeeded. A failed construction therefore leaves the previous server's
// state untouched and the partially-built new server is discarded.
var reusedMuxes []reusedGraphMux
currentMuxes := currentGraphMuxes(r)
var gm *graphMux
mux, oldBaseGraphMuxExists := currentMuxes[""]
needNewBaseGraphMux := response.Changes == nil || response.Changes.BaseGraphChanged() || !oldBaseGraphMuxExists
if needNewBaseGraphMux {
// build new base grap mux
s.logger.Debug("Will build a new base graph mux for new graph server")
gm, err = s.buildGraphMux(BuildGraphMuxOptions{
RouterConfigVersion: s.baseRouterConfigVersion,
EngineConfig: response.Config.GetEngineConfig(),
ConfigSubgraphs: response.Config.GetSubgraphs(),
RoutingUrlGroupings: routingUrlGroupings,
ReloadPersistentState: r.reloadPersistentState,
defaultClientTLS: defaultGRPCClientTLS,
perSubgraphTLS: perSubgraphGRPCTLS,
})
if err != nil {
return nil, fmt.Errorf("failed to build base mux: %w", err)
}
} else {
s.logger.Debug("Will reuse old base graph mux for new graph server")
gm = mux
reusedMuxes = append(reusedMuxes, reusedGraphMux{key: "", mux: mux})
}
featureFlagConfigMap := response.Config.FeatureFlagConfigs.GetConfigByFeatureFlagName()
if len(featureFlagConfigMap) > 0 {
s.logger.Info("Feature flags enabled", zap.Strings("flags", maps.Keys(featureFlagConfigMap)))
}
multiGraphHandler, ffReusedMuxes, err := s.buildMultiGraphHandler(buildMultiGraphHandlerOptions{
baseMux: gm.mux,
featureFlagConfigs: featureFlagConfigMap,
reloadPersistentState: r.reloadPersistentState,
currentGraphMuxes: currentMuxes,
changes: response.Changes,
defaultClientTLS: defaultGRPCClientTLS,
perSubgraphTLS: perSubgraphGRPCTLS,
})
if err != nil {
return nil, fmt.Errorf("failed to build feature flag handler: %w", err)
}
reusedMuxes = append(reusedMuxes, ffReusedMuxes...)
wrapper, err := gzhttp.NewWrapper(
gzhttp.MinSize(int(s.routerTrafficConfig.ResponseCompressionMinSize)),
gzhttp.CompressionLevel(gzip.DefaultCompression),
gzhttp.ContentTypes(CompressibleContentTypes),
)
if err != nil {
return nil, fmt.Errorf("failed to create gzip wrapper: %w", err)
}
if s.traceConfig.Enabled {
handler := rtrace.NewTracingHandler(rtrace.TracingHandlerOpts{
TraceConfig: s.traceConfig,
HealthCheckPath: s.healthCheckPath,
ReadinessCheckPath: s.readinessCheckPath,
LivenessCheckPath: s.livenessCheckPath,
CompositePropagator: s.compositePropagator,
TracerProvider: s.tracerProvider,
SpanNameFormatter: func(_ string, r *http.Request) string {
return s.spanNameFormatter(r)
},
})
httpRouter.Use(handler)
}
if s.batchingConfig.Enabled {
if s.batchingConfig.MaxConcurrentRoutines <= 0 {
return nil, errors.New("maxConcurrent must be greater than 0")
}
if s.batchingConfig.MaxEntriesPerBatch <= 0 {
return nil, errors.New("maxEntriesPerBatch must be greater than 0")
}
}
/**
* A group where we can selectively apply middlewares to the graphql endpoint
*/
httpRouter.Group(func(cr chi.Router) {
// We are applying it conditionally because compressing 3MB playground is still slow even with stdlib gzip
cr.Use(func(h http.Handler) http.Handler {
return wrapper(h)
})
if s.headerRules != nil {
cr.Use(rmiddleware.CookieWhitelist(s.headerRules.CookieWhitelist, []string{featureFlagCookie}))
}
// Mount the feature flag handler. It calls the base mux if no feature flag is set.
if s.batchingConfig.Enabled {
handler := Handler(
HandlerOpts{
MaxEntriesPerBatch: s.batchingConfig.MaxEntriesPerBatch,
MaxRoutines: s.batchingConfig.MaxConcurrentRoutines,
OmitExtensions: s.batchingConfig.OmitExtensions,
HandlerSent: multiGraphHandler,
Tracer: r.tracerProvider.Tracer(
"wundergraph/cosmo/router/internal/batch",
oteltrace.WithInstrumentationVersion("0.0.1"),
),
Digest: xxhash.New(),
ClientHeader: s.clientHeader,
BaseOtelAttributes: s.baseOtelAttributes,
RouterConfigVersion: s.baseRouterConfigVersion,
Logger: s.logger,
},
)
cr.Handle(r.graphqlPath, handler)
} else {
cr.Handle(r.graphqlPath, multiGraphHandler)
}
if r.webSocketConfiguration != nil && r.webSocketConfiguration.Enabled && r.webSocketConfiguration.AbsintheProtocol.Enabled {
// Mount the Absinthe protocol handler for WebSockets
httpRouter.Handle(r.webSocketConfiguration.AbsintheProtocol.HandlerPath, multiGraphHandler)
}
})
/**
* Routes
*/
// We mount the playground once here when we don't have a conflict with the websocket handler
// If we have a conflict, we mount the playground during building the individual muxes
if s.playgroundHandler != nil && s.graphqlPath != s.playgroundConfig.Path {
httpRouter.Get(r.playgroundConfig.Path, s.playgroundHandler(nil).ServeHTTP)
}
httpRouter.Get(s.healthCheckPath, r.healthcheck.Liveness())
httpRouter.Get(s.livenessCheckPath, r.healthcheck.Liveness())
httpRouter.Get(s.readinessCheckPath, r.healthcheck.Readiness())
s.mux = httpRouter
// commitReusedMuxes MUST be the last call before returning success. If any
// step above returns early with an error, the previous server's muxes stay
// in their original state (reused=false, not in this server's graphMuxList)
// so a subsequent reload that no longer reuses them will still shut them
// down correctly.
s.commitReusedMuxes(reusedMuxes)
return s, nil
}
// commitReusedMuxes finalizes the reuse bookkeeping for muxes inherited from the
// previous server. For each entry it flips the mux's reused flag to true (so the
// previous server's Shutdown does not tear it down) and registers it under the
// new server's graphMuxList (so when this server is itself replaced, the reused
// mux is found and its flag is reset).
//
// It MUST only be called when the new server has been fully constructed; calling
// it earlier risks leaving the previous server's mux flagged for reuse without
// the new server actually being put into service, which would cause a subsequent
// non-reuse reload to skip the mux's shutdown and leak resources.
func (s *graphServer) commitReusedMuxes(reused []reusedGraphMux) {
if len(reused) == 0 {
return
}
s.graphMuxListLock.Lock()
defer s.graphMuxListLock.Unlock()
for _, rm := range reused {
rm.mux.reused.Store(true)
s.graphMuxList[rm.key] = rm.mux
}
}
func getRoutingUrlGroupingForCircuitBreakers(
routerConfig *nodev1.RouterConfig,
overrideRoutingURLConfiguration config.OverrideRoutingURLConfiguration,
overridesConfiguration config.OverridesConfiguration,
) (map[string]map[string]bool, error) {
routingUrlGroupings := make(map[string]map[string]bool)
overwrites, err := configureSubgraphOverwrites(
routerConfig.GetEngineConfig(),
routerConfig.GetSubgraphs(),
overrideRoutingURLConfiguration,
overridesConfiguration,
true,
)
if err != nil {
return nil, err
}
for _, subgraph := range overwrites {
if _, ok := routingUrlGroupings[subgraph.UrlString]; !ok {
routingUrlGroupings[subgraph.UrlString] = make(map[string]bool)
}
routingUrlGroupings[subgraph.UrlString][subgraph.Name] = true
}
if routerConfig.FeatureFlagConfigs != nil {
for _, ffConfig := range routerConfig.FeatureFlagConfigs.ConfigByFeatureFlagName {
ffOverwrites, err := configureSubgraphOverwrites(
ffConfig.GetEngineConfig(),
ffConfig.GetSubgraphs(),
overrideRoutingURLConfiguration,
overridesConfiguration,
true,
)
if err != nil {
return nil, err
}
for _, subgraph := range ffOverwrites {
if _, ok := routingUrlGroupings[subgraph.UrlString]; !ok {
routingUrlGroupings[subgraph.UrlString] = make(map[string]bool)
}
routingUrlGroupings[subgraph.UrlString][subgraph.Name] = true
}
}
}
return routingUrlGroupings, nil
}
// buildMultiGraphHandler assembles the feature-flag routing handler. The returned
// reusedGraphMux slice lists muxes inherited from the previous server; the caller
// is responsible for committing the reuse bookkeeping once construction has fully
// succeeded.
func (s *graphServer) buildMultiGraphHandler(
opts buildMultiGraphHandlerOptions,
) (http.HandlerFunc, []reusedGraphMux, error) {
if len(opts.featureFlagConfigs) == 0 {
return opts.baseMux.ServeHTTP, nil, nil
}
featureFlagToMux := make(map[string]*chi.Mux, len(opts.featureFlagConfigs))
var reused []reusedGraphMux
// Build all the muxes for the feature flags in serial to avoid any race conditions
for featureFlagName, executionConfig := range opts.featureFlagConfigs {
if opts.changes != nil {
// if the ff is unchanged and still needed, we reuse it
_, hasChanged := opts.changes.ChangedConfigs[featureFlagName]
_, wasAdded := opts.changes.AddedConfigs[featureFlagName]
if !hasChanged && !wasAdded {
oldGraphMux, exists := opts.currentGraphMuxes[featureFlagName]
if exists {
s.logger.Debug("will reuse feature flag mux for new graph server",
zap.String("flag", featureFlagName))
featureFlagToMux[featureFlagName] = oldGraphMux.mux
reused = append(reused, reusedGraphMux{key: featureFlagName, mux: oldGraphMux})
continue
}
}
}
s.logger.Debug("will create a new feature flag mux for new graph server",
zap.String("flag", featureFlagName))
gm, err := s.buildGraphMux(BuildGraphMuxOptions{
FeatureFlagName: featureFlagName,
RouterConfigVersion: executionConfig.GetVersion(),
EngineConfig: executionConfig.GetEngineConfig(),
ConfigSubgraphs: executionConfig.Subgraphs,
ReloadPersistentState: opts.reloadPersistentState,
defaultClientTLS: opts.defaultClientTLS,
perSubgraphTLS: opts.perSubgraphTLS,
})
if err != nil {
return nil, nil, fmt.Errorf("failed to build mux for feature flag '%s': %w", featureFlagName, err)
}
featureFlagToMux[featureFlagName] = gm.mux
}
return func(w http.ResponseWriter, r *http.Request) {
// Extract the feature flag and run the corresponding mux
// 1. From the request header
// 2. From the cookie
ff := strings.TrimSpace(r.Header.Get(featureFlagHeader))
if ff == "" {
cookie, err := r.Cookie(featureFlagCookie)
if err == nil && cookie != nil {
ff = strings.TrimSpace(cookie.Value)
}
}
if mux, ok := featureFlagToMux[ff]; ok {
w.Header().Set(featureFlagHeader, ff)
mux.ServeHTTP(w, r)
return
}
opts.baseMux.ServeHTTP(w, r)
}, reused, nil
}
// setupEngineStatistics creates the engine statistics for the server.
// It creates the OTLP and Prometheus metrics for the engine statistics.
func (s *graphServer) setupEngineStatistics(baseAttributes []attribute.KeyValue) (err error) {
// We only include the base router config version in the attributes for the engine statistics.
// Same approach is used for the runtime metrics.
s.otlpEngineMetrics, err = rmetric.NewEngineMetrics(
s.logger,
baseAttributes,
s.otlpMeterProvider,
s.engineStats,
&s.metricConfig.OpenTelemetry.EngineStats,
)
if err != nil {
return err
}
s.prometheusEngineMetrics, err = rmetric.NewEngineMetrics(
s.logger,
baseAttributes,
s.promMeterProvider,
s.engineStats,
&s.metricConfig.Prometheus.EngineStats,
)
if err != nil {
return err
}
return nil
}
type graphMux struct {
ctx context.Context
cancel context.CancelFunc
mux *chi.Mux
reused atomic.Bool
planCache *ristretto.Cache[uint64, *planWithMetaData]
planFallbackCache *slowplancache.Cache[*planWithMetaData]
persistedOperationCache *ristretto.Cache[uint64, NormalizationCacheEntry]
normalizationCache *ristretto.Cache[uint64, NormalizationCacheEntry]
complexityCalculationCache *ristretto.Cache[uint64, ComplexityCacheEntry]
variablesNormalizationCache *ristretto.Cache[uint64, VariablesNormalizationCacheEntry]
remapVariablesCache *ristretto.Cache[uint64, RemapVariablesCacheEntry]
validationCache *ristretto.Cache[uint64, bool]
operationHashCache *ristretto.Cache[uint64, string]
accessLogsFileLogger *logging.BufferedLogger
metricStore rmetric.Store
prometheusCacheMetrics *rmetric.CacheMetrics
otelCacheMetrics *rmetric.CacheMetrics
streamMetricStore rmetric.StreamMetricStore
prometheusMetricsExporter *graphqlmetrics.PrometheusMetricsExporter
}
// buildOperationCaches creates the caches for the graph mux.
// The caches are created based on the engine configuration.
func (s *graphMux) buildOperationCaches(srv *graphServer) (computeSha256 bool, err error) {
// We create a new execution plan cache for each operation planner which is coupled to
// the specific engine configuration. This is necessary because otherwise we would return invalid plans.
//
// when an execution plan was generated, which can be quite expensive, we want to cache it
// this means that we can hash the input and cache the generated plan
// the next time we get the same input, we can just return the cached plan
// the engine is smart enough to first do normalization and then hash the input
// this means that we can cache the normalized input and don't have to worry about
// different inputs that would generate the same execution plan
if srv.engineExecutionConfiguration.ExecutionPlanCacheSize > 0 {
planCacheConfig := &ristretto.Config[uint64, *planWithMetaData]{
Metrics: srv.metricConfig.OpenTelemetry.GraphqlCache || srv.metricConfig.Prometheus.GraphqlCache,
MaxCost: srv.engineExecutionConfiguration.ExecutionPlanCacheSize,
NumCounters: srv.engineExecutionConfiguration.ExecutionPlanCacheSize * 10,
IgnoreInternalCost: true,
BufferItems: 64,
}
if srv.cacheWarmup != nil && srv.cacheWarmup.Enabled && srv.cacheWarmup.InMemoryFallback {
planCacheConfig.OnEvict = func(item *ristretto.Item[*planWithMetaData]) {
// This could be called before planFallbackCache is set, but it's not a problem
// because there is a nil guard inside, as well as items should not really be evicted
// on startup
s.planFallbackCache.Set(item.Key, item.Value, item.Value.planningDuration)
}
}
s.planCache, err = ristretto.NewCache[uint64, *planWithMetaData](planCacheConfig)
if err != nil {
return computeSha256, fmt.Errorf("failed to create planner cache: %w", err)
}
}
if srv.engineExecutionConfiguration.EnablePersistedOperationsCache || srv.automaticPersistedQueriesConfig.Enabled {
cacheSize := int64(1024)
persistedOperationCacheConfig := &ristretto.Config[uint64, NormalizationCacheEntry]{
MaxCost: cacheSize,
NumCounters: cacheSize * 10,
IgnoreInternalCost: true,
BufferItems: 64,
Metrics: true,
}
s.persistedOperationCache, _ = ristretto.NewCache[uint64, NormalizationCacheEntry](persistedOperationCacheConfig)
}
if srv.engineExecutionConfiguration.EnableNormalizationCache && srv.engineExecutionConfiguration.NormalizationCacheSize > 0 {
normalizationCacheConfig := &ristretto.Config[uint64, NormalizationCacheEntry]{
Metrics: srv.metricConfig.OpenTelemetry.GraphqlCache || srv.metricConfig.Prometheus.GraphqlCache,
MaxCost: srv.engineExecutionConfiguration.NormalizationCacheSize,
NumCounters: srv.engineExecutionConfiguration.NormalizationCacheSize * 10,
IgnoreInternalCost: true,
BufferItems: 64,
}
s.normalizationCache, err = ristretto.NewCache[uint64, NormalizationCacheEntry](normalizationCacheConfig)
if err != nil {
return computeSha256, fmt.Errorf("failed to create normalization cache: %w", err)
}
variablesNormalizationCacheConfig := &ristretto.Config[uint64, VariablesNormalizationCacheEntry]{
Metrics: srv.metricConfig.OpenTelemetry.GraphqlCache || srv.metricConfig.Prometheus.GraphqlCache,
MaxCost: srv.engineExecutionConfiguration.NormalizationCacheSize,
NumCounters: srv.engineExecutionConfiguration.NormalizationCacheSize * 10,
IgnoreInternalCost: true,
BufferItems: 64,
}
s.variablesNormalizationCache, err = ristretto.NewCache[uint64, VariablesNormalizationCacheEntry](variablesNormalizationCacheConfig)
if err != nil {
return computeSha256, fmt.Errorf("failed to create variables normalization cache: %w", err)
}
remapVariablesCacheConfig := &ristretto.Config[uint64, RemapVariablesCacheEntry]{
Metrics: srv.metricConfig.OpenTelemetry.GraphqlCache || srv.metricConfig.Prometheus.GraphqlCache,
MaxCost: srv.engineExecutionConfiguration.NormalizationCacheSize,
NumCounters: srv.engineExecutionConfiguration.NormalizationCacheSize * 10,
IgnoreInternalCost: true,
BufferItems: 64,
}
s.remapVariablesCache, err = ristretto.NewCache[uint64, RemapVariablesCacheEntry](remapVariablesCacheConfig)
if err != nil {
return computeSha256, fmt.Errorf("failed to create remap variables cache: %w", err)
}
}
if srv.engineExecutionConfiguration.EnableValidationCache && srv.engineExecutionConfiguration.ValidationCacheSize > 0 {
validationCacheConfig := &ristretto.Config[uint64, bool]{
Metrics: srv.metricConfig.OpenTelemetry.GraphqlCache || srv.metricConfig.Prometheus.GraphqlCache,
MaxCost: srv.engineExecutionConfiguration.ValidationCacheSize,
NumCounters: srv.engineExecutionConfiguration.ValidationCacheSize * 10,
IgnoreInternalCost: true,
BufferItems: 64,
}
s.validationCache, err = ristretto.NewCache[uint64, bool](validationCacheConfig)
if err != nil {
return computeSha256, fmt.Errorf("failed to create validation cache: %w", err)
}
}
if srv.securityConfiguration.ComplexityCalculationCache != nil && srv.securityConfiguration.ComplexityCalculationCache.Enabled && srv.securityConfiguration.ComplexityCalculationCache.CacheSize > 0 {
complexityCalculationCacheConfig := &ristretto.Config[uint64, ComplexityCacheEntry]{
Metrics: srv.metricConfig.OpenTelemetry.GraphqlCache || srv.metricConfig.Prometheus.GraphqlCache,
MaxCost: srv.securityConfiguration.ComplexityCalculationCache.CacheSize,
NumCounters: srv.securityConfiguration.ComplexityCalculationCache.CacheSize * 10,
IgnoreInternalCost: true,
BufferItems: 64,
}
s.complexityCalculationCache, err = ristretto.NewCache[uint64, ComplexityCacheEntry](complexityCalculationCacheConfig)
if err != nil {
return computeSha256, fmt.Errorf("failed to create query depth cache: %w", err)
}
}
// Currently, we only support custom attributes from the context for OTLP metrics
if !computeSha256 && len(srv.metricConfig.Attributes) > 0 {
for _, customAttribute := range srv.metricConfig.Attributes {
if customAttribute.ValueFrom != nil && customAttribute.ValueFrom.ContextField == ContextFieldOperationSha256 {
computeSha256 = true
break
}
}
}
if !computeSha256 && srv.accessLogsConfig != nil {
for _, customAttribute := range append(srv.accessLogsConfig.Attributes, srv.accessLogsConfig.SubgraphAttributes...) {
if customAttribute.ValueFrom != nil && customAttribute.ValueFrom.ContextField == ContextFieldOperationSha256 {
computeSha256 = true
break
}
}
}
if srv.persistedOperationsConfig.Safelist.Enabled || srv.persistedOperationsConfig.LogUnknown {
// In these case, we'll want to compute the sha256 for every operation, in order to check that the operation
// is present in the Persisted Operation cache
computeSha256 = true
}
// Prometheus schema field usage metrics can use sha256, so we need to ensure it is computed
if srv.metricConfig.Prometheus.PromSchemaFieldUsage.Enabled && srv.metricConfig.Prometheus.PromSchemaFieldUsage.IncludeOperationSha {
computeSha256 = true
}
if computeSha256 {
operationHashCacheConfig := &ristretto.Config[uint64, string]{
MaxCost: srv.engineExecutionConfiguration.OperationHashCacheSize,
NumCounters: srv.engineExecutionConfiguration.OperationHashCacheSize * 10,
IgnoreInternalCost: true,
BufferItems: 64,
Metrics: srv.metricConfig.OpenTelemetry.GraphqlCache || srv.metricConfig.Prometheus.GraphqlCache,
}
s.operationHashCache, err = ristretto.NewCache[uint64, string](operationHashCacheConfig)
if err != nil {
return computeSha256, fmt.Errorf("failed to create operation hash cache: %w", err)
}
}
return computeSha256, nil
}
// waitForCaches blocks until all pending ristretto async writes have been applied.
// This ensures that items stored during one warmup pass are visible to the next pass.
func (s *graphMux) waitForCaches() {
if s.planCache != nil {
s.planCache.Wait()
}
if s.persistedOperationCache != nil {
s.persistedOperationCache.Wait()
}
if s.normalizationCache != nil {
s.normalizationCache.Wait()
}
if s.variablesNormalizationCache != nil {
s.variablesNormalizationCache.Wait()
}
if s.remapVariablesCache != nil {
s.remapVariablesCache.Wait()
}
if s.validationCache != nil {
s.validationCache.Wait()
}
if s.operationHashCache != nil {
s.operationHashCache.Wait()
}
}
// configureCacheMetrics sets up the cache metrics for this mux if enabled in the config.
func (s *graphMux) configureCacheMetrics(srv *graphServer, baseOtelAttributes []attribute.KeyValue) error {
if srv.metricConfig.OpenTelemetry.GraphqlCache {
cacheMetrics, err := rmetric.NewCacheMetrics(
srv.logger,
baseOtelAttributes,
srv.otlpMeterProvider)
if err != nil {
return fmt.Errorf("failed to create cache metrics for OTLP: %w", err)
}
s.otelCacheMetrics = cacheMetrics
}
if srv.metricConfig.Prometheus.GraphqlCache {
cacheMetrics, err := rmetric.NewCacheMetrics(
srv.logger,
baseOtelAttributes,
srv.promMeterProvider)
if err != nil {
return fmt.Errorf("failed to create cache metrics for Prometheus: %w", err)
}
s.prometheusCacheMetrics = cacheMetrics
}
var metricInfos []rmetric.CacheMetricInfo
if s.planCache != nil {
metricInfos = append(metricInfos, rmetric.NewCacheMetricInfo("plan", srv.engineExecutionConfiguration.ExecutionPlanCacheSize, s.planCache.Metrics))
}
if s.normalizationCache != nil {
metricInfos = append(metricInfos, rmetric.NewCacheMetricInfo("query_normalization", srv.engineExecutionConfiguration.NormalizationCacheSize, s.normalizationCache.Metrics))
}
if s.variablesNormalizationCache != nil {
metricInfos = append(metricInfos, rmetric.NewCacheMetricInfo("variables_normalization", srv.engineExecutionConfiguration.NormalizationCacheSize, s.variablesNormalizationCache.Metrics))
}
if s.remapVariablesCache != nil {
metricInfos = append(metricInfos, rmetric.NewCacheMetricInfo("remap_variables", srv.engineExecutionConfiguration.NormalizationCacheSize, s.remapVariablesCache.Metrics))
}
if s.persistedOperationCache != nil {
metricInfos = append(metricInfos, rmetric.NewCacheMetricInfo("persisted_query_normalization", 1024, s.persistedOperationCache.Metrics))
}
if s.validationCache != nil {
metricInfos = append(metricInfos, rmetric.NewCacheMetricInfo("validation", srv.engineExecutionConfiguration.ValidationCacheSize, s.validationCache.Metrics))
}
if s.operationHashCache != nil {
metricInfos = append(metricInfos, rmetric.NewCacheMetricInfo("query_hash", srv.engineExecutionConfiguration.OperationHashCacheSize, s.operationHashCache.Metrics))
}
if s.otelCacheMetrics != nil {
if err := s.otelCacheMetrics.RegisterObservers(metricInfos); err != nil {
return fmt.Errorf("failed to register observer for OTLP cache metrics: %w", err)
}
}
if s.prometheusCacheMetrics != nil {
if err := s.prometheusCacheMetrics.RegisterObservers(metricInfos); err != nil {
return fmt.Errorf("failed to register observer for Prometheus cache metrics: %w", err)
}
}
return nil
}
func (s *graphMux) Shutdown(ctx context.Context) error {
// cancel the graph muxes context to close its resources like websocket connections, resolvers, etc.
s.cancel()
s.planCache.Close()
s.planFallbackCache.Close()
s.persistedOperationCache.Close()
s.normalizationCache.Close()
s.variablesNormalizationCache.Close()
s.remapVariablesCache.Close()
s.complexityCalculationCache.Close()
s.validationCache.Close()
s.operationHashCache.Close()
var err error
if s.accessLogsFileLogger != nil {
if aErr := s.accessLogsFileLogger.Close(); aErr != nil {
err = errors.Join(err, aErr)
}
}
if s.otelCacheMetrics != nil {
if aErr := s.otelCacheMetrics.Shutdown(); aErr != nil {
err = errors.Join(err, aErr)
}
}
if s.prometheusCacheMetrics != nil {
if aErr := s.prometheusCacheMetrics.Shutdown(); aErr != nil {
err = errors.Join(err, aErr)
}
}
if s.metricStore != nil {
if aErr := s.metricStore.Shutdown(ctx); aErr != nil {
err = errors.Join(err, aErr)
}
}
if s.streamMetricStore != nil {
if aErr := s.streamMetricStore.Shutdown(ctx); aErr != nil {
err = errors.Join(err, aErr)
}
}
if s.prometheusMetricsExporter != nil {
if aErr := s.prometheusMetricsExporter.Shutdown(ctx); aErr != nil {
err = errors.Join(err, aErr)
}
}
if err != nil {
return fmt.Errorf("shutdown graph mux: %w", err)