-
Notifications
You must be signed in to change notification settings - Fork 69
/
router.go
1854 lines (1549 loc) · 56.5 KB
/
router.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
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 (
"context"
"crypto/ecdsa"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"github.com/wundergraph/cosmo/router/pkg/pubsub"
"github.com/wundergraph/cosmo/router/pkg/pubsub/kafka"
pubsubNats "github.com/wundergraph/cosmo/router/pkg/pubsub/nats"
"github.com/wundergraph/graphql-go-tools/v2/pkg/engine/datasource/pubsub_datasource"
"net"
"net/http"
"net/url"
"os"
"sync"
"time"
"github.com/nats-io/nuid"
"github.com/redis/go-redis/v9"
"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/health"
rmetric "github.com/wundergraph/cosmo/router/pkg/metric"
"github.com/wundergraph/cosmo/router/pkg/otel"
"github.com/wundergraph/cosmo/router/pkg/otel/otelconfig"
rtrace "github.com/wundergraph/cosmo/router/pkg/trace"
"connectrpc.com/connect"
"github.com/golang-jwt/jwt/v5"
brotli "go.withmatt.com/connect-brotli"
"github.com/wundergraph/cosmo/router/gen/proto/wg/cosmo/graphqlmetrics/v1/graphqlmetricsv1connect"
"github.com/wundergraph/cosmo/router/internal/cdn"
"github.com/wundergraph/cosmo/router/internal/controlplane/configpoller"
"github.com/wundergraph/cosmo/router/internal/controlplane/selfregister"
"github.com/wundergraph/cosmo/router/internal/debug"
"github.com/wundergraph/cosmo/router/internal/docker"
"github.com/wundergraph/cosmo/router/internal/graphqlmetrics"
rjwt "github.com/wundergraph/cosmo/router/internal/jwt"
"github.com/dgraph-io/ristretto"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/mitchellh/mapstructure"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel/attribute"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
oteltrace "go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
nodev1 "github.com/wundergraph/cosmo/router/gen/proto/wg/cosmo/node/v1"
"github.com/wundergraph/cosmo/router/internal/graphiql"
"github.com/wundergraph/cosmo/router/internal/retrytransport"
"github.com/wundergraph/cosmo/router/internal/stringsx"
)
type IPAnonymizationMethod string
const (
Hash IPAnonymizationMethod = "hash"
Redact IPAnonymizationMethod = "redact"
)
type (
// Router is the main application instance.
Router struct {
Config
activeServer *server
modules []Module
WebsocketStats WebSocketsStatistics
}
SubgraphTransportOptions struct {
RequestTimeout time.Duration
ResponseHeaderTimeout time.Duration
ExpectContinueTimeout time.Duration
KeepAliveIdleTimeout time.Duration
DialTimeout time.Duration
TLSHandshakeTimeout time.Duration
KeepAliveProbeInterval time.Duration
}
GraphQLMetricsConfig struct {
Enabled bool
CollectorEndpoint string
}
IPAnonymizationConfig struct {
Enabled bool
Method IPAnonymizationMethod
}
TlsClientAuthConfig struct {
Required bool
CertFile string
}
TlsConfig struct {
Enabled bool
CertFile string
KeyFile string
ClientAuth *TlsClientAuthConfig
}
EnginePubSubProviders struct {
nats map[string]pubsub_datasource.NatsPubSub
kafka map[string]pubsub_datasource.KafkaPubSub
}
// Config defines the configuration options for the Router.
Config struct {
clusterName string
instanceID string
logger *zap.Logger
traceConfig *rtrace.Config
metricConfig *rmetric.Config
tracerProvider *sdktrace.TracerProvider
otlpMeterProvider *sdkmetric.MeterProvider
promMeterProvider *sdkmetric.MeterProvider
gqlMetricsExporter graphqlmetrics.SchemaUsageExporter
corsOptions *cors.Config
routerConfig *nodev1.RouterConfig
gracePeriod time.Duration
awsLambda bool
shutdown bool
bootstrapped bool
ipAnonymization *IPAnonymizationConfig
listenAddr string
baseURL string
graphqlWebURL string
playgroundPath string
graphqlPath string
playground bool
introspection bool
graphApiToken string
healthCheckPath string
healthChecks health.Checker
readinessCheckPath string
livenessCheckPath string
cdnConfig config.CDNConfiguration
cdnPersistentOpClient *cdn.PersistentOperationClient
eventsConfig config.EventsConfiguration
prometheusServer *http.Server
modulesConfig map[string]interface{}
routerMiddlewares []func(http.Handler) http.Handler
preOriginHandlers []TransportPreHandler
postOriginHandlers []TransportPostHandler
headerRuleEngine *HeaderRuleEngine
headerRules config.HeaderRules
subgraphTransportOptions *SubgraphTransportOptions
graphqlMetricsConfig *GraphQLMetricsConfig
routerTrafficConfig *config.RouterTrafficConfiguration
accessController *AccessController
retryOptions retrytransport.RetryOptions
redisClient *redis.Client
processStartTime time.Time
developmentMode bool
// If connecting to localhost inside Docker fails, fallback to the docker internal address for the host
localhostFallbackInsideDocker bool
tlsServerConfig *tls.Config
tlsConfig *TlsConfig
// Poller
configPoller configpoller.ConfigPoller
selfRegister selfregister.SelfRegister
registrationInfo *nodev1.RegistrationInfo
securityConfiguration config.SecurityConfiguration
engineExecutionConfiguration config.EngineExecutionConfiguration
overrideRoutingURLConfiguration config.OverrideRoutingURLConfiguration
authorization *config.AuthorizationConfiguration
rateLimit *config.RateLimitConfiguration
webSocketConfiguration *config.WebSocketConfiguration
subgraphErrorPropagation config.SubgraphErrorPropagationConfiguration
}
Server interface {
HttpServer() *http.Server
HealthChecks() health.Checker
BaseURL() string
}
// server is the main router instance.
server struct {
Config
httpServer *http.Server
metricStore rmetric.Store
routerConfig *nodev1.RouterConfig
healthChecks health.Checker
pubSubProviders *EnginePubSubProviders
}
// Option defines the method to customize server.
Option func(svr *Router)
)
func (s *server) BaseURL() string {
return s.baseURL
}
// NewRouter creates a new Router instance. Router.Start() must be called to start the server.
// Alternatively, use Router.NewServer() to create a new server instance without starting it.
func NewRouter(opts ...Option) (*Router, error) {
r := &Router{
WebsocketStats: NewNoopWebSocketStats(),
}
for _, opt := range opts {
opt(r)
}
if r.logger == nil {
r.logger = zap.NewNop()
}
// Default value for graphql path
if r.graphqlPath == "" {
r.graphqlPath = "/graphql"
}
if r.graphqlWebURL == "" {
r.graphqlWebURL = r.graphqlPath
}
if r.playgroundPath == "" {
r.playgroundPath = "/"
}
if r.instanceID == "" {
r.instanceID = nuid.Next()
}
r.processStartTime = time.Now()
// Create noop tracer and meter to avoid nil pointer panics and to avoid checking for nil everywhere
r.tracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSampler(sdktrace.NeverSample()))
r.otlpMeterProvider = sdkmetric.NewMeterProvider()
r.promMeterProvider = sdkmetric.NewMeterProvider()
// Default values for trace and metric config
if r.traceConfig == nil {
r.traceConfig = rtrace.DefaultConfig(Version)
}
if r.metricConfig == nil {
r.metricConfig = rmetric.DefaultConfig(Version)
}
if r.corsOptions == nil {
r.corsOptions = CorsDefaultOptions()
}
if r.subgraphTransportOptions == nil {
r.subgraphTransportOptions = DefaultSubgraphTransportOptions()
}
if r.graphqlMetricsConfig == nil {
r.graphqlMetricsConfig = DefaultGraphQLMetricsConfig()
}
if r.routerTrafficConfig == nil {
r.routerTrafficConfig = DefaultRouterTrafficConfig()
}
if r.accessController == nil {
r.accessController = DefaultAccessController()
} else {
if len(r.accessController.authenticators) == 0 && r.accessController.authenticationRequired {
r.logger.Warn("authentication is required but no authenticators are configured")
}
}
if r.ipAnonymization == nil {
r.ipAnonymization = &IPAnonymizationConfig{
Enabled: true,
Method: Redact,
}
}
// Default values for health check paths
if r.healthCheckPath == "" {
r.healthCheckPath = "/health"
}
if r.readinessCheckPath == "" {
r.readinessCheckPath = "/health/ready"
}
if r.livenessCheckPath == "" {
r.livenessCheckPath = "/health/live"
}
hr, err := NewHeaderTransformer(r.headerRules)
if err != nil {
return nil, err
}
r.headerRuleEngine = hr
r.preOriginHandlers = append(r.preOriginHandlers, r.headerRuleEngine.OnOriginRequest)
defaultHeaders := []string{
// Common headers
"authorization",
"origin",
"content-length",
"content-type",
// Semi standard client info headers
"graphql-client-name",
"graphql-client-version",
// Apollo client info headers
"apollographql-client-name",
"apollographql-client-version",
// Required for WunderGraph ART
"x-wg-trace",
"x-wg-token",
// Required for Trace Context propagation
"traceparent",
"tracestate",
}
defaultMethods := []string{
"HEAD", "GET", "POST",
}
r.corsOptions.AllowHeaders = stringsx.RemoveDuplicates(append(r.corsOptions.AllowHeaders, defaultHeaders...))
r.corsOptions.AllowMethods = stringsx.RemoveDuplicates(append(r.corsOptions.AllowMethods, defaultMethods...))
if r.tlsConfig != nil && r.tlsConfig.Enabled {
r.baseURL = fmt.Sprintf("https://%s", r.listenAddr)
} else {
r.baseURL = fmt.Sprintf("http://%s", r.listenAddr)
}
if r.tlsConfig != nil && r.tlsConfig.Enabled {
if r.tlsConfig.CertFile == "" {
return nil, errors.New("tls cert file not provided")
}
if r.tlsConfig.KeyFile == "" {
return nil, errors.New("tls key file not provided")
}
var caCertPool *x509.CertPool
clientAuthMode := tls.NoClientCert
if r.tlsConfig.ClientAuth != nil && r.tlsConfig.ClientAuth.CertFile != "" {
caCert, err := os.ReadFile(r.tlsConfig.ClientAuth.CertFile)
if err != nil {
return nil, fmt.Errorf("failed to read cert file: %w", err)
}
// Create a CA an empty cert pool and add the CA cert to it to serve as authority to validate client certs
caPool := x509.NewCertPool()
if ok := caPool.AppendCertsFromPEM(caCert); !ok {
return nil, errors.New("failed to append cert to pool")
}
caCertPool = caPool
if r.tlsConfig.ClientAuth.Required {
clientAuthMode = tls.RequireAndVerifyClientCert
} else {
clientAuthMode = tls.VerifyClientCertIfGiven
}
r.logger.Debug("Client auth enabled", zap.String("mode", clientAuthMode.String()))
}
// Load the server cert and private key
cer, err := tls.LoadX509KeyPair(r.tlsConfig.CertFile, r.tlsConfig.KeyFile)
if err != nil {
return nil, fmt.Errorf("failed to load tls cert and key: %w", err)
}
r.tlsServerConfig = &tls.Config{
ClientCAs: caCertPool,
Certificates: []tls.Certificate{cer},
ClientAuth: clientAuthMode,
}
}
// Add default tracing exporter if needed
if r.traceConfig.Enabled && len(r.traceConfig.Exporters) == 0 {
if endpoint := otelconfig.DefaultEndpoint(); endpoint != "" {
r.logger.Debug("Using default trace exporter", zap.String("endpoint", endpoint))
r.traceConfig.Exporters = append(r.traceConfig.Exporters, &rtrace.ExporterConfig{
Endpoint: endpoint,
Exporter: otelconfig.ExporterOLTPHTTP,
HTTPPath: "/v1/traces",
Headers: otelconfig.DefaultEndpointHeaders(r.graphApiToken),
})
}
}
// Add default metric exporter if none are configured
if r.metricConfig.OpenTelemetry.Enabled && len(r.metricConfig.OpenTelemetry.Exporters) == 0 {
if endpoint := otelconfig.DefaultEndpoint(); endpoint != "" {
r.logger.Debug("Using default metrics exporter", zap.String("endpoint", endpoint))
r.metricConfig.OpenTelemetry.Exporters = append(r.metricConfig.OpenTelemetry.Exporters, &rmetric.OpenTelemetryExporter{
Endpoint: endpoint,
Exporter: otelconfig.ExporterOLTPHTTP,
HTTPPath: "/v1/metrics",
Headers: otelconfig.DefaultEndpointHeaders(r.graphApiToken),
})
}
}
var disabledFeatures []string
// The user might want to start the server with a static config
// Disable all features that requires a valid graph token and inform the user
if r.graphApiToken == "" {
r.graphqlMetricsConfig.Enabled = false
disabledFeatures = append(disabledFeatures, "Schema Usage Tracking", "Persistent operations")
if !r.developmentMode {
disabledFeatures = append(disabledFeatures, "Advanced Request Tracing")
}
if r.traceConfig.Enabled {
defaultExporter := rtrace.DefaultExporter(r.traceConfig)
if defaultExporter != nil {
disabledFeatures = append(disabledFeatures, "Cosmo Cloud Tracing")
defaultExporter.Disabled = true
}
}
if r.metricConfig.OpenTelemetry.Enabled {
defaultExporter := rmetric.GetDefaultExporter(r.metricConfig)
if defaultExporter != nil {
disabledFeatures = append(disabledFeatures, "Cosmo Cloud Metrics")
defaultExporter.Disabled = true
}
}
r.logger.Warn("No graph token provided. The following features are disabled. Not recommended for Production.", zap.Strings("features", disabledFeatures))
}
if r.graphApiToken != "" {
routerCDN, err := cdn.NewPersistentOperationClient(r.cdnConfig.URL, r.graphApiToken, cdn.PersistentOperationsOptions{
CacheSize: r.cdnConfig.CacheSize.Uint64(),
Logger: r.logger,
})
if err != nil {
return nil, err
}
r.cdnPersistentOpClient = routerCDN
}
if r.developmentMode {
r.logger.Warn("Development mode enabled. This should only be used for testing purposes")
}
for _, source := range r.eventsConfig.Providers.Nats {
r.logger.Info("Nats Event source enabled", zap.String("providerID", source.ID), zap.String("url", source.URL))
}
for _, source := range r.eventsConfig.Providers.Kafka {
r.logger.Info("Kafka Event source enabled", zap.String("providerID", source.ID), zap.Strings("brokers", source.Brokers))
}
return r, nil
}
func (r *Router) configureSubgraphOverwrites(cfg *nodev1.RouterConfig) ([]Subgraph, error) {
subgraphs := make([]Subgraph, 0, len(cfg.Subgraphs))
for _, sg := range cfg.Subgraphs {
subgraph := Subgraph{
Id: sg.Id,
Name: sg.Name,
}
// Validate subgraph url. Note that it can be empty if the subgraph is virtual
parsedURL, err := url.Parse(sg.RoutingUrl)
if err != nil {
return nil, fmt.Errorf("failed to parse subgraph url '%s': %w", sg.RoutingUrl, err)
}
subgraph.Url = parsedURL
overrideURL, ok := r.overrideRoutingURLConfiguration.Subgraphs[sg.Name]
// check if the subgraph is overridden
if ok && overrideURL != "" {
parsedURL, err := url.Parse(overrideURL)
if err != nil {
return nil, fmt.Errorf("failed to parse override url '%s': %w", overrideURL, err)
}
subgraph.Url = parsedURL
// Override datasource urls
for _, conf := range cfg.EngineConfig.DatasourceConfigurations {
if conf.Id == sg.Id {
conf.CustomGraphql.Fetch.Url.StaticVariableContent = overrideURL
conf.CustomGraphql.Subscription.Url.StaticVariableContent = overrideURL
sg.RoutingUrl = overrideURL
break
}
}
}
subgraphs = append(subgraphs, subgraph)
}
return subgraphs, nil
}
// UpdateServer creates a new server and swaps the active server with the new one. The old server is shutdown gracefully.
// When the router can't be swapped due to an error the old server kept running. Not safe for concurrent use.
func (r *Router) UpdateServer(ctx context.Context, cfg *nodev1.RouterConfig) (Server, error) {
// Rebuild server with new router config
// In case of an error, we return early and keep the old server running
newServer, err := r.newServer(ctx, cfg)
if err != nil {
r.logger.Error("Failed to create a new router instance. Keeping old router running", zap.Error(err))
return nil, err
}
// Shutdown old server
if r.activeServer != nil {
// Respect grace period
if r.gracePeriod > 0 {
ctxWithTimer, cancel := context.WithTimeout(ctx, r.gracePeriod)
defer cancel()
ctx = ctxWithTimer
}
if err := r.activeServer.Shutdown(ctx); err != nil {
r.logger.Error("Could not shutdown router", zap.Error(err))
if errors.Is(err, context.DeadlineExceeded) {
r.logger.Warn(
"Shutdown deadline exceeded. Router took too long to shutdown. Consider increasing the grace period",
zap.Duration("grace_period", r.gracePeriod),
)
}
return nil, err
}
}
// Swap active server
r.activeServer = newServer
return newServer, nil
}
func (r *Router) updateServerAndStart(ctx context.Context, cfg *nodev1.RouterConfig) error {
if _, err := r.UpdateServer(ctx, cfg); err != nil {
return err
}
// read here to avoid race condition
version := r.activeServer.routerConfig.GetVersion()
// Start new server
go func() {
r.logger.Info("Server listening and serving",
zap.String("listen_addr", r.listenAddr),
zap.Bool("playground", r.playground),
zap.Bool("introspection", r.introspection),
zap.String("config_version", cfg.GetVersion()),
)
r.activeServer.healthChecks.SetReady(true)
// This is a blocking call
if err := r.activeServer.listenAndServe(); err != nil {
r.activeServer.healthChecks.SetReady(false)
r.logger.Error("Failed to start new server", zap.Error(err))
}
r.logger.Info("Server stopped", zap.String("config_version", version))
}()
return nil
}
func (r *Router) initModules(ctx context.Context) error {
for _, moduleInfo := range modules {
now := time.Now()
moduleInstance := moduleInfo.New()
mc := &ModuleContext{
Context: ctx,
Module: moduleInstance,
Logger: r.logger.With(zap.String("module", string(moduleInfo.ID))),
}
moduleConfig, ok := r.modulesConfig[string(moduleInfo.ID)]
if ok {
if err := mapstructure.Decode(moduleConfig, &moduleInstance); err != nil {
return fmt.Errorf("failed to decode module config from module %s: %w", moduleInfo.ID, err)
}
} else {
r.logger.Debug("No config found for module", zap.String("id", string(moduleInfo.ID)))
}
if fn, ok := moduleInstance.(Provisioner); ok {
if err := fn.Provision(mc); err != nil {
return fmt.Errorf("failed to provision module '%s': %w", moduleInfo.ID, err)
}
}
if fn, ok := moduleInstance.(RouterMiddlewareHandler); ok {
r.routerMiddlewares = append(r.routerMiddlewares, func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
reqContext := getRequestContext(request.Context())
// Ensure we work with latest request in the chain to work with the right context
reqContext.request = request
fn.Middleware(reqContext, handler)
})
})
}
if handler, ok := moduleInstance.(EnginePreOriginHandler); ok {
r.preOriginHandlers = append(r.preOriginHandlers, handler.OnOriginRequest)
}
if handler, ok := moduleInstance.(EnginePostOriginHandler); ok {
r.postOriginHandlers = append(r.postOriginHandlers, handler.OnOriginResponse)
}
r.modules = append(r.modules, moduleInstance)
r.logger.Info("Module registered",
zap.String("id", string(moduleInfo.ID)),
zap.String("duration", time.Since(now).String()),
)
}
return nil
}
// NewServer prepares a new server instance but does not start it. The method should only be used when you want to bootstrap
// the server manually otherwise you can use Router.Start(). You're responsible for setting health checks status to ready with Server.HealthChecks().
// The server can be shutdown with Router.Shutdown(). Use core.WithStaticRouterConfig to pass the initial config otherwise the Router will
// try to fetch the config from the control plane. You can swap the router config by using Router.UpdateServer().
func (r *Router) NewServer(ctx context.Context) (Server, error) {
if r.shutdown {
return nil, fmt.Errorf("router is shutdown. Create a new instance with router.NewRouter()")
}
if err := r.bootstrap(ctx); err != nil {
return nil, fmt.Errorf("failed to bootstrap application: %w", err)
}
// Start the server with the static config without polling
if r.routerConfig != nil {
r.logger.Info("Static router config provided. Polling is disabled. Updating router config is only possible by providing a config.")
return r.UpdateServer(ctx, r.routerConfig)
}
// when no static config is provided and no poller is configured, we can't start the server
if r.configPoller == nil {
return nil, fmt.Errorf("config fetcher not provided. Please provide a static router config instead")
}
routerConfig, err := r.configPoller.GetRouterConfig(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get initial router config: %w", err)
}
if _, err := r.UpdateServer(ctx, routerConfig); err != nil {
r.logger.Error("Failed to start server with initial config", zap.Error(err))
return nil, err
}
return r.activeServer, nil
}
// bootstrap initializes the Router. It is called by Start() and NewServer().
// It should only be called once for a Router instance. Not safe for concurrent use.
func (r *Router) bootstrap(ctx context.Context) error {
if r.bootstrapped {
return fmt.Errorf("router is already bootstrapped")
}
r.bootstrapped = true
cosmoCloudTracingEnabled := r.traceConfig.Enabled && rtrace.DefaultExporter(r.traceConfig) != nil
artInProductionEnabled := r.engineExecutionConfiguration.EnableRequestTracing && !r.developmentMode
needsRegistration := cosmoCloudTracingEnabled || artInProductionEnabled
if needsRegistration && r.selfRegister != nil {
r.logger.Info("Registering router with control plane because you opted in to send telemetry to Cosmo Cloud or advanced request tracing (ART) in production")
ri, registerErr := r.selfRegister.Register(ctx)
if registerErr != nil {
r.logger.Warn("Failed to register router on the control plane. If this warning persists, please contact support.")
} else {
r.registrationInfo = ri
// Only ensure sampling rate if the user exports traces to Cosmo Cloud
if cosmoCloudTracingEnabled {
if r.traceConfig.Sampler > float64(r.registrationInfo.AccountLimits.TraceSamplingRate) {
r.logger.Warn("Trace sampling rate is higher than account limit. Using account limit instead. Please contact support to increase your account limit.",
zap.Float64("limit", r.traceConfig.Sampler),
zap.String("account_limit", fmt.Sprintf("%.2f", r.registrationInfo.AccountLimits.TraceSamplingRate)),
)
r.traceConfig.Sampler = float64(r.registrationInfo.AccountLimits.TraceSamplingRate)
}
}
}
}
if r.traceConfig.Enabled {
tp, err := rtrace.NewTracerProvider(ctx, &rtrace.ProviderConfig{
Logger: r.logger,
Config: r.traceConfig,
ServiceInstanceID: r.instanceID,
IPAnonymization: &rtrace.IPAnonymizationConfig{
Enabled: r.ipAnonymization.Enabled,
Method: rtrace.IPAnonymizationMethod(r.ipAnonymization.Method),
},
MemoryExporter: r.traceConfig.TestMemoryExporter,
})
if err != nil {
return fmt.Errorf("failed to start trace agent: %w", err)
}
r.tracerProvider = tp
}
// Prometheus metrics rely on OTLP metrics
if r.metricConfig.IsEnabled() {
if r.metricConfig.Prometheus.Enabled {
mp, registry, err := rmetric.NewPrometheusMeterProvider(ctx, r.metricConfig, r.instanceID)
if err != nil {
return fmt.Errorf("failed to create Prometheus exporter: %w", err)
}
r.promMeterProvider = mp
r.prometheusServer = rmetric.NewPrometheusServer(r.logger, r.metricConfig.Prometheus.ListenAddr, r.metricConfig.Prometheus.Path, registry)
go func() {
if err := r.prometheusServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
r.logger.Error("Failed to start Prometheus server", zap.Error(err))
}
}()
}
if r.metricConfig.OpenTelemetry.Enabled {
mp, err := rmetric.NewOtlpMeterProvider(ctx, r.logger, r.metricConfig, r.instanceID)
if err != nil {
return fmt.Errorf("failed to start trace agent: %w", err)
}
r.otlpMeterProvider = mp
}
}
r.gqlMetricsExporter = graphqlmetrics.NewNoopExporter()
if r.graphqlMetricsConfig.Enabled {
client := graphqlmetricsv1connect.NewGraphQLMetricsServiceClient(
http.DefaultClient,
r.graphqlMetricsConfig.CollectorEndpoint,
brotli.WithCompression(),
// Compress requests with Brotli.
connect.WithSendCompression(brotli.Name),
)
ge, err := graphqlmetrics.NewExporter(
r.logger,
client,
r.graphApiToken,
graphqlmetrics.NewDefaultExporterSettings(),
)
if err != nil {
return fmt.Errorf("failed to validate graphql metrics exporter: %w", err)
}
r.gqlMetricsExporter = ge
r.logger.Info("GraphQL schema coverage metrics enabled")
}
if r.Config.rateLimit != nil && r.Config.rateLimit.Enabled {
options, err := redis.ParseURL(r.Config.rateLimit.Storage.Url)
if err != nil {
return fmt.Errorf("failed to parse the redis connection url: %w", err)
}
r.redisClient = redis.NewClient(options)
}
if r.engineExecutionConfiguration.Debug.ReportWebSocketConnections {
r.WebsocketStats = NewWebSocketStats(ctx, r.logger)
}
if r.engineExecutionConfiguration.Debug.ReportMemoryUsage {
debug.ReportMemoryUsage(ctx, r.logger)
}
// Modules are only initialized once and not on every config change
if err := r.initModules(ctx); err != nil {
return fmt.Errorf("failed to init user modules: %w", err)
}
return nil
}
// Start starts the server. It does not block. The server can be shutdown with Router.Shutdown().
// Not safe for concurrent use.
func (r *Router) Start(ctx context.Context) error {
if r.shutdown {
return fmt.Errorf("router is shutdown. Create a new instance with router.NewRouter()")
}
if err := r.bootstrap(ctx); err != nil {
return fmt.Errorf("failed to bootstrap application: %w", err)
}
// Start the server with the static config without polling
if r.routerConfig != nil {
r.logger.Info("Static router config provided. Polling is disabled. Updating router config is only possible by providing a config.")
return r.updateServerAndStart(ctx, r.routerConfig)
}
// when no static config is provided and no poller is configured, we can't start the server
if r.configPoller == nil {
return fmt.Errorf("config fetcher not provided. Please provide a static router config instead")
}
routerConfig, err := r.configPoller.GetRouterConfig(ctx)
if err != nil {
return fmt.Errorf("failed to get initial router config: %w", err)
}
if err := r.updateServerAndStart(ctx, routerConfig); err != nil {
r.logger.Error("Failed to start server with initial config", zap.Error(err))
return err
}
r.logger.Info("Polling for router config updates in the background")
r.configPoller.Subscribe(ctx, func(newConfig *nodev1.RouterConfig, oldVersion string) error {
r.logger.Info("Router execution config has changed, upgrading server",
zap.String("old_version", oldVersion),
zap.String("new_version", newConfig.GetVersion()),
)
if err := r.updateServerAndStart(ctx, newConfig); err != nil {
r.logger.Error("Failed to start server with new config. Trying again on the next update cycle.", zap.Error(err))
return err
}
return nil
})
return nil
}
func (r *Router) buildPubSubConfiguration(ctx context.Context, routerCfg *nodev1.RouterConfig, routerEngineCfg *RouterEngineConfiguration) (*EnginePubSubProviders, error) {
natsPubSubByProviderID := make(map[string]pubsub_datasource.NatsPubSub)
kafkaPubSubByProviderID := make(map[string]pubsub_datasource.KafkaPubSub)
datasourceConfigurations := routerCfg.EngineConfig.GetDatasourceConfigurations()
for _, datasourceConfiguration := range datasourceConfigurations {
if datasourceConfiguration.CustomEvents == nil {
continue
}
for _, eventConfiguration := range datasourceConfiguration.GetCustomEvents().GetNats() {
providerID := eventConfiguration.EngineEventConfiguration.GetProviderId()
// if this source name's provider has already been initiated, do not try to initiate again
_, ok := natsPubSubByProviderID[providerID]
if ok {
continue
}
for _, eventSource := range routerEngineCfg.Events.Providers.Nats {
if eventSource.ID == eventConfiguration.EngineEventConfiguration.GetProviderId() {
options, err := buildNatsOptions(eventSource)
if err != nil {
return nil, fmt.Errorf("failed to build options for Nats provider with ID \"%s\": %w", providerID, err)
}
natsConnection, err := nats.Connect(eventSource.URL, options...)
if err != nil {
return nil, fmt.Errorf("failed to create connection for Nats provider with ID \"%s\": %w", providerID, err)
}
js, err := jetstream.New(natsConnection)
if err != nil {
return nil, err
}
natsPubSubByProviderID[providerID] = pubsubNats.NewConnector(r.logger, natsConnection, js).New(ctx)
break
}
}
}
for _, eventConfiguration := range datasourceConfiguration.GetCustomEvents().GetKafka() {
providerID := eventConfiguration.EngineEventConfiguration.GetProviderId()
// if this source name's provider has already been initiated, do not try to initiate again
_, ok := kafkaPubSubByProviderID[providerID]
if ok {
continue
}
for _, eventSource := range routerEngineCfg.Events.Providers.Kafka {
if eventSource.ID == providerID {
options, err := buildKafkaOptions(eventSource)
if err != nil {
return nil, fmt.Errorf("failed to build options for Kafka provider with ID \"%s\": %w", providerID, err)
}
ps, err := kafka.NewConnector(r.logger, options)
if err != nil {
return nil, fmt.Errorf("failed to create connection for Kafka provider with ID \"%s\": %w", providerID, err)
}
kafkaPubSubByProviderID[providerID] = ps.New(ctx)
break
}
}
}
}
return &EnginePubSubProviders{
nats: natsPubSubByProviderID,
kafka: kafkaPubSubByProviderID,
}, nil
}
// newServer creates a new server instance.
// All stateful data is copied from the Router over to the new server instance. Not safe for concurrent use.
func (r *Router) newServer(ctx context.Context, routerConfig *nodev1.RouterConfig) (*server, error) {
subgraphs, err := r.configureSubgraphOverwrites(routerConfig)
if err != nil {
return nil, err
}
ro := &server{
routerConfig: routerConfig,
Config: r.Config,
metricStore: rmetric.NewNoopMetrics(),
}
baseAttributes := []attribute.KeyValue{
otel.WgRouterConfigVersion.String(routerConfig.GetVersion()),
otel.WgRouterVersion.String(Version),
otel.WgRouterClusterName.String(r.clusterName),
}
if r.graphApiToken != "" {
claims, err := rjwt.ExtractFederatedGraphTokenClaims(r.graphApiToken)
if err != nil {
return nil, err
}
baseAttributes = append(baseAttributes, otel.WgFederatedGraphID.String(claims.FederatedGraphID))
}
recoveryHandler := recoveryhandler.New(recoveryhandler.WithLogger(r.logger), recoveryhandler.WithPrintStack())
var traceHandler *rtrace.Middleware
if r.traceConfig.Enabled {
spanStartOptions := []oteltrace.SpanStartOption{
oteltrace.WithAttributes(
baseAttributes...,
),
oteltrace.WithAttributes(
otel.RouterServerAttribute,
otel.WgRouterRootSpan.Bool(true),
),
}
if r.traceConfig.WithNewRoot {
spanStartOptions = append(spanStartOptions, oteltrace.WithNewRoot())
}
traceHandler = rtrace.NewMiddleware(
otelhttp.WithSpanOptions(spanStartOptions...),
otelhttp.WithFilter(rtrace.CommonRequestFilter),
otelhttp.WithFilter(rtrace.PrefixRequestFilter(