-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathrouter.go
More file actions
2601 lines (2201 loc) · 81.1 KB
/
router.go
File metadata and controls
2601 lines (2201 loc) · 81.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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/tls"
"crypto/x509"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"os"
"path"
"sync"
"time"
"connectrpc.com/connect"
"github.com/mitchellh/mapstructure"
"github.com/nats-io/nuid"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/propagation"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.uber.org/zap"
"github.com/wundergraph/cosmo/router/gen/proto/wg/cosmo/graphqlmetrics/v1/graphqlmetricsv1connect"
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/debug"
"github.com/wundergraph/cosmo/router/internal/docker"
"github.com/wundergraph/cosmo/router/internal/exporter"
"github.com/wundergraph/cosmo/router/internal/graphiql"
"github.com/wundergraph/cosmo/router/internal/graphqlmetrics"
"github.com/wundergraph/cosmo/router/internal/persistedoperation"
"github.com/wundergraph/cosmo/router/internal/persistedoperation/apq"
"github.com/wundergraph/cosmo/router/internal/persistedoperation/operationstorage/cdn"
"github.com/wundergraph/cosmo/router/internal/persistedoperation/operationstorage/fs"
"github.com/wundergraph/cosmo/router/internal/persistedoperation/operationstorage/s3"
"github.com/wundergraph/cosmo/router/internal/persistedoperation/pqlmanifest"
rd "github.com/wundergraph/cosmo/router/internal/rediscloser"
"github.com/wundergraph/cosmo/router/internal/retrytransport"
"github.com/wundergraph/cosmo/router/internal/stringsx"
"github.com/wundergraph/cosmo/router/internal/track"
"github.com/wundergraph/cosmo/router/pkg/config"
"github.com/wundergraph/cosmo/router/pkg/connectrpc"
"github.com/wundergraph/cosmo/router/pkg/controlplane/configpoller"
"github.com/wundergraph/cosmo/router/pkg/controlplane/selfregister"
"github.com/wundergraph/cosmo/router/pkg/cors"
"github.com/wundergraph/cosmo/router/pkg/execution_config"
"github.com/wundergraph/cosmo/router/pkg/health"
"github.com/wundergraph/cosmo/router/pkg/mcpserver"
rmetric "github.com/wundergraph/cosmo/router/pkg/metric"
"github.com/wundergraph/cosmo/router/pkg/otel/otelconfig"
"github.com/wundergraph/cosmo/router/pkg/statistics"
rtrace "github.com/wundergraph/cosmo/router/pkg/trace"
"github.com/wundergraph/cosmo/router/pkg/trace/attributeprocessor"
"github.com/wundergraph/cosmo/router/pkg/watcher"
"github.com/wundergraph/graphql-go-tools/v2/pkg/netpoll"
)
type IPAnonymizationMethod string
const (
Hash IPAnonymizationMethod = "hash"
Redact IPAnonymizationMethod = "redact"
)
var CompressibleContentTypes = []string{
"text/html",
"text/css",
"text/plain",
"text/javascript",
"application/javascript",
"application/x-javascript",
"application/json",
"application/atom+xml",
"application/rss+xml",
"image/svg+xml",
"application/graphql",
"application/graphql-response+json",
"application/graphql+json",
}
type (
// Router is the main application instance.
Router struct {
Config
httpServer *server
modules []Module
EngineStats statistics.EngineStatistics
playgroundHandler func(http.Handler) http.Handler
proxy ProxyFunc
disableUsageTracking bool
usage UsageTracker
headerPropagation *HeaderPropagation
reloadPersistentState *ReloadPersistentState
}
UsageTracker interface {
Close()
TrackUptime(ctx context.Context)
TrackRouterConfigUsage(usage map[string]any)
TrackExecutionConfigUsage(usage map[string]any)
}
TransportRequestOptions struct {
RequestTimeout time.Duration
ResponseHeaderTimeout time.Duration
ExpectContinueTimeout time.Duration
KeepAliveIdleTimeout time.Duration
DialTimeout time.Duration
TLSHandshakeTimeout time.Duration
KeepAliveProbeInterval time.Duration
MaxConnsPerHost int
MaxIdleConns int
MaxIdleConnsPerHost int
}
SubgraphTransportOptions struct {
*TransportRequestOptions
SubgraphMap map[string]*TransportRequestOptions
}
GraphQLMetricsConfig struct {
Enabled bool
CollectorEndpoint string
}
BatchingConfig struct {
Enabled bool
MaxConcurrentRoutines int
MaxEntriesPerBatch int
OmitExtensions bool
}
IPAnonymizationConfig struct {
Enabled bool
Method IPAnonymizationMethod
}
TlsClientAuthConfig struct {
Required bool
CertFile string
}
TlsConfig struct {
Enabled bool
CertFile string
KeyFile string
ClientAuth *TlsClientAuthConfig
}
RouterConfigPollerConfig struct {
config.ExecutionConfig
PollInterval time.Duration
PollJitter time.Duration
GraphSignKey string
}
ExecutionConfig struct {
Watch bool
WatchInterval time.Duration
Path string
}
AccessLogsConfig struct {
Attributes []config.CustomAttribute
Logger *zap.Logger
SubgraphEnabled bool
SubgraphAttributes []config.CustomAttribute
IgnoreQueryParamsList []string
}
// Option defines the method to customize server.
Option func(svr *Router)
)
type SubgraphCircuitBreakerOptions struct {
CircuitBreaker circuit.CircuitBreakerConfig
SubgraphMap map[string]circuit.CircuitBreakerConfig
}
func (r *SubgraphCircuitBreakerOptions) IsEnabled() bool {
if r == nil {
return false
}
return r.CircuitBreaker.Enabled || len(r.SubgraphMap) > 0
}
// 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{
EngineStats: statistics.NewNoopEngineStats(),
}
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
}
// this is set via the deprecated method
if !r.playground {
r.playgroundConfig.Enabled = r.playground
r.logger.Warn("The playground_enabled option is deprecated. Use the /playground/enabled option in the config instead.")
}
if r.playgroundPath != "" && r.playgroundPath != "/" {
r.playgroundConfig.Path = r.playgroundPath
r.logger.Warn("The playground_path option is deprecated. Use the /playground/path option in the config instead.")
}
if r.playgroundConfig.Path == "" {
r.playgroundConfig.Path = "/"
}
// handle introspection config deprecation
// if either the old deprecated or the new config is set to false, introspection is disabled
if !r.introspection {
r.introspectionConfig.Enabled = r.introspection
r.logger.Warn("The introspection_enabled option is deprecated. Use the /introspection/enabled option in the config instead.")
} else if !r.introspectionConfig.Enabled {
r.introspection = r.introspectionConfig.Enabled
}
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.subscriptionHooks.onReceiveEvents.maxConcurrentHandlers == 0 {
r.subscriptionHooks.onReceiveEvents.maxConcurrentHandlers = 100
}
if r.subscriptionHooks.onReceiveEvents.timeout == 0 {
r.subscriptionHooks.onReceiveEvents.timeout = 5 * time.Second
}
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.fileUploadConfig == nil {
r.fileUploadConfig = DefaultFileUploadConfig()
}
if r.accessController != nil {
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"
}
r.headerRules = AddCacheControlPolicyToRules(r.headerRules, r.cacheControlPolicy)
var err error
r.headerPropagation, err = NewHeaderPropagation(r.headerRules)
if err != nil {
return nil, err
}
defaultCorsHeaders := []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-disable-tracing",
"x-wg-token",
"x-wg-skip-loader",
"x-wg-include-query-plan",
// Required for Trace Context propagation
"traceparent",
"tracestate",
// Required for feature flags
"x-feature-flag",
}
if r.clientHeader.Name != "" {
defaultCorsHeaders = append(defaultCorsHeaders, r.clientHeader.Name)
}
if r.clientHeader.Version != "" {
defaultCorsHeaders = append(defaultCorsHeaders, r.clientHeader.Version)
}
defaultMethods := []string{
"HEAD", "GET", "POST",
}
r.corsOptions.AllowHeaders = stringsx.RemoveDuplicates(append(r.corsOptions.AllowHeaders, defaultCorsHeaders...))
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)
}
graphqlEndpointURL, err := url.JoinPath(r.baseURL, r.graphqlPath)
if err != nil {
return nil, fmt.Errorf("failed to construct graphql endpoint url: %w", err)
}
r.graphqlEndpointURL = graphqlEndpointURL
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,
}
}
if r.traceConfig.Enabled {
if len(r.traceConfig.Propagators) > 0 {
propagators, err := rtrace.BuildPropagators(r.traceConfig.Propagators...)
if err != nil {
r.logger.Error("creating propagators", zap.Error(err))
return nil, err
}
r.tracePropagators = propagators
}
// Add default tracing exporter if needed
if len(r.traceConfig.Exporters) == 0 && r.traceConfig.TestMemoryExporter == nil {
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 && r.metricConfig.OpenTelemetry.TestReader == nil {
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 Cosmo Cloud features are disabled. Not recommended for Production.",
zap.Strings("features", disabledFeatures),
)
}
if r.persistedOperationsConfig.Safelist.Enabled && r.automaticPersistedQueriesConfig.Enabled {
return nil, errors.New("automatic persisted queries and safelist cannot be enabled at the same time (as APQ would permit queries that are not in the safelist)")
}
if r.securityConfiguration.BlockPersistedOperations.Enabled &&
r.securityConfiguration.BlockNonPersistedOperations.Enabled {
// Both have no condition, unusable state
if r.securityConfiguration.BlockPersistedOperations.Condition == "" &&
r.securityConfiguration.BlockNonPersistedOperations.Condition == "" {
return nil, errors.New("persisted and non-persisted operations are both unconditionally blocked")
}
// One or both have a condition, could be intentional for edge cases
r.logger.Warn("The security configuration fields 'block_persisted_operations' and 'block_non_persisted_operations' are both enabled. Take care to ensure this is intentional.")
}
if r.persistedOperationsConfig.Safelist.Enabled && r.securityConfiguration.BlockPersistedOperations.Enabled {
// Both have no condition, unusable state
if r.securityConfiguration.BlockPersistedOperations.Condition == "" {
return nil, errors.New("safelist cannot be enabled while persisted operations are unconditionally blocked")
}
// Has a condition, could be intentional for edge cases
r.logger.Warn("The security configuration field 'block_persisted_operations' is enabled alongside the persisted operations safelist. Take care to ensure this is intentional. Misconfiguration will result in safelisted queries being blocked.")
}
if r.engineExecutionConfiguration.EnableExecutionPlanCacheResponseHeader {
r.logger.Warn("The engine execution configuration field 'enable_execution_plan_cache_response_header' is deprecated, and will be removed. Use 'enable_cache_response_headers' instead.")
r.engineExecutionConfiguration.Debug.EnableCacheResponseHeaders = true
}
if r.engineExecutionConfiguration.Debug.EnablePersistedOperationsCacheResponseHeader {
r.logger.Warn("The engine execution configuration field 'enable_persisted_operations_cache_response_header' is deprecated, and will be removed. Use 'enable_cache_response_headers' instead.")
r.engineExecutionConfiguration.Debug.EnableCacheResponseHeaders = true
}
if r.engineExecutionConfiguration.Debug.EnableNormalizationCacheResponseHeader {
r.logger.Warn("The engine execution configuration field 'enable_normalization_cache_response_header' is deprecated, and will be removed. Use 'enable_cache_response_headers' instead.")
r.engineExecutionConfiguration.Debug.EnableCacheResponseHeaders = true
}
if r.securityConfiguration.DepthLimit != nil {
r.logger.Warn("The security configuration field 'depth_limit' is deprecated, and will be removed. Use 'security.complexity_limits.depth' instead.")
if r.securityConfiguration.ComplexityCalculationCache == nil {
r.securityConfiguration.ComplexityCalculationCache = &config.ComplexityCalculationCache{
Enabled: true,
CacheSize: r.securityConfiguration.DepthLimit.CacheSize,
}
}
if r.securityConfiguration.ComplexityLimits == nil {
r.securityConfiguration.ComplexityLimits = &config.ComplexityLimits{}
}
if r.securityConfiguration.ComplexityLimits.Depth == nil {
r.securityConfiguration.ComplexityLimits.Depth = &config.ComplexityLimit{
Enabled: r.securityConfiguration.DepthLimit.Enabled,
Limit: r.securityConfiguration.DepthLimit.Limit,
IgnorePersistedOperations: r.securityConfiguration.DepthLimit.IgnorePersistedOperations,
}
} else {
r.logger.Warn("Ignoring deprecated security configuration field 'depth_limit', in favor of the `security.complexity_limits.depth` configuration")
}
}
if r.developmentMode {
r.logger.Warn("Development mode enabled. This should only be used for testing purposes")
}
if r.healthcheck == nil {
r.healthcheck = health.New(&health.Options{
Logger: r.logger,
})
}
for _, source := range r.eventsConfig.Providers.Nats {
r.logger.Info("Nats Event source enabled", zap.String("provider_id", source.ID))
}
for _, source := range r.eventsConfig.Providers.Kafka {
r.logger.Info("Kafka Event source enabled", zap.String("provider_id", source.ID), zap.Strings("brokers", source.Brokers))
}
if !r.engineExecutionConfiguration.EnableNetPoll {
r.logger.Warn("Net poller is disabled by configuration. Falling back to less efficient connection handling method.")
} else if err := netpoll.Supported(); err != nil {
// Disable netPoll if it's not supported. This flag is used everywhere to decide whether to use netPoll or not.
r.engineExecutionConfiguration.EnableNetPoll = false
if errors.Is(err, netpoll.ErrUnsupported) {
r.logger.Warn(
"Net poller is only available on Linux and MacOS. Falling back to less efficient connection handling method.",
zap.Error(err),
)
} else {
r.logger.Warn(
"Net poller is not functional by the environment. Ensure that the system supports epoll/kqueue and that necessary syscall permissions are granted. Falling back to less efficient connection handling method.",
zap.Error(err),
)
}
}
if r.hostName == "" {
r.hostName, err = os.Hostname()
if err != nil {
r.logger.Warn("Failed to get hostname", zap.Error(err))
}
}
return r, nil
}
// newGraphServer creates a new server.
func (r *Router) newServer(ctx context.Context, cfg *nodev1.RouterConfig) error {
server, err := newGraphServer(ctx, r, cfg, r.proxy)
if err != nil {
r.logger.Error("Failed to create graph server. Keeping the old server", zap.Error(err))
return err
}
r.httpServer.SwapGraphServer(ctx, server)
// Cleanup any unused feature flags in case a feature flag was removed
r.reloadPersistentState.CleanupFeatureFlags(cfg)
return nil
}
// startPQLPoller starts the PQL manifest poller in a background goroutine if configured.
// Must be called after newServer so that SetOnUpdate has been registered on the store.
func (r *Router) startPQLPoller(ctx context.Context) {
if r.pqlPoller != nil {
go r.pqlPoller.Poll(ctx)
}
}
func (r *Router) listenAndServe() error {
go func() {
// Mark the server as not ready when the server is stopped
defer r.httpServer.healthcheck.SetReady(false)
// This is a blocking call
if err := r.httpServer.listenAndServe(); err != nil {
r.logger.Error("Failed to start new server", zap.Error(err))
}
}()
return nil
}
func (r *Router) initModules(ctx context.Context) error {
moduleList := make([]ModuleInfo, 0, len(modules)+len(r.customModules))
for _, module := range modules {
moduleList = append(moduleList, module)
}
for _, module := range r.customModules {
moduleList = append(moduleList, module.Module())
}
moduleList = sortModules(moduleList)
for _, moduleInfo := range moduleList {
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
// Propagate the writer so that when a module calls
// ctx.ResponseWriter() it receives the writer from the
// current middleware layer (e.g. a buffered writer from an
// outer module), not the one set by the pre-handler.
reqContext.responseWriter = writer
fn.Middleware(reqContext, handler)
})
})
}
if fn, ok := moduleInstance.(RouterOnRequestHandler); ok {
r.routerOnRequestHandlers = append(r.routerOnRequestHandlers, 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
// Propagate the writer so that when a module calls
// ctx.ResponseWriter() it receives the writer from the
// current middleware layer, not the one set by the pre-handler.
reqContext.responseWriter = writer
fn.RouterOnRequest(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)
}
if handler, ok := moduleInstance.(TracePropagationProvider); ok {
modulePropagators := handler.TracePropagators()
if len(modulePropagators) > 0 {
r.tracePropagators = append(r.tracePropagators, modulePropagators...)
}
}
if handler, ok := moduleInstance.(SubscriptionOnStartHandler); ok {
r.subscriptionHooks.onStart.handlers = append(r.subscriptionHooks.onStart.handlers, handler.SubscriptionOnStart)
}
if handler, ok := moduleInstance.(StreamPublishEventHandler); ok {
r.subscriptionHooks.onPublishEvents.handlers = append(r.subscriptionHooks.onPublishEvents.handlers, handler.OnPublishEvents)
}
if handler, ok := moduleInstance.(StreamReceiveEventHandler); ok {
r.subscriptionHooks.onReceiveEvents.handlers = append(r.subscriptionHooks.onReceiveEvents.handlers, handler.OnReceiveEvents)
}
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
}
func (r *Router) BaseURL() string {
return r.baseURL
}
// 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.WithExecutionConfig 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.newGraphServer().
func (r *Router) NewServer(ctx context.Context) (Server, error) {
if r.shutdown.Load() {
return nil, errors.New("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)
}
r.httpServer = newServer(&httpServerOptions{
addr: r.listenAddr,
logger: r.logger,
tlsConfig: r.tlsConfig,
tlsServerConfig: r.tlsServerConfig,
healthcheck: r.healthcheck,
baseURL: r.baseURL,
maxHeaderBytes: int(r.routerTrafficConfig.MaxHeaderBytes.Uint64()),
livenessCheckPath: r.livenessCheckPath,
readinessCheckPath: r.readinessCheckPath,
healthCheckPath: r.healthCheckPath,
})
r.configureUsageTracking(ctx)
if r.reloadPersistentState == nil {
r.reloadPersistentState = NewReloadPersistentState(r.logger)
}
r.reloadPersistentState.UpdateReloadPersistentState(&r.Config)
// Start the server with the static config without polling
if r.staticExecutionConfig != nil {
r.logger.Info("Static execution config provided. Polling is disabled. Updating execution config is only possible by providing a config.")
return r.httpServer, r.newServer(ctx, r.staticExecutionConfig)
}
// when no static config is provided and no poller is configured, we can't start the server
if r.configPoller == nil {
return nil, errors.New("config fetcher not provided. Please provide a static execution config instead")
}
cfg, err := r.configPoller.GetRouterConfig(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get initial execution config: %w", err)
}
if err := r.newServer(ctx, cfg.Config); err != nil {
r.logger.Error("Failed to start server with initial config", zap.Error(err))
return nil, err
}
return r.httpServer, nil
}
// bootstrap initializes the Router. It is called by Start() and NewServer().
// It should only be called once for a Router instance.
func (r *Router) bootstrap(ctx context.Context) error {
if !r.bootstrapped.CompareAndSwap(false, true) {
return fmt.Errorf("router is already bootstrapped")
}
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: &attributeprocessor.IPAnonymizationConfig{
Enabled: r.ipAnonymization.Enabled,
Method: attributeprocessor.IPAnonymizationMethod(r.ipAnonymization.Method),
},
SanitizeUTF8: r.traceConfig.SanitizeUTF8,
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
}
}
if r.graphqlMetricsConfig.Enabled {
client := graphqlmetricsv1connect.NewGraphQLMetricsServiceClient(
http.DefaultClient,
r.graphqlMetricsConfig.CollectorEndpoint,
connect.WithSendGzip(),
)
ge, err := graphqlmetrics.NewGraphQLMetricsExporter(
r.logger,
client,
r.graphApiToken,
exporter.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")
}
// Create Prometheus metrics exporter for schema field usage
// Note: This is separate from the Prometheus meter provider which handles OTEL metrics
// This exporter is specifically for schema field usage tracking via the Prometheus sink
if r.metricConfig.Prometheus.PromSchemaFieldUsage.Enabled {
// The metric store will be passed in later when building the graph mux
// because each mux has its own metric store
// We'll create the exporter when building the mux in buildGraphMux
r.logger.Info("Prometheus schema field usage metrics enabled",
zap.Bool("include_operation_sha", r.metricConfig.Prometheus.PromSchemaFieldUsage.IncludeOperationSha),
)
}
if r.rateLimit != nil && r.rateLimit.Enabled {
var err error
r.redisClient, err = rd.NewRedisCloser(&rd.RedisCloserOptions{
URLs: r.rateLimit.Storage.URLs,
ClusterEnabled: r.rateLimit.Storage.ClusterEnabled,
Logger: r.logger,
})
if err != nil {
return fmt.Errorf("failed to create redis client: %w", err)
}
}
if r.mcp.Enabled {
var operationsDir string
// If storage provider ID is set, resolve it to a directory path
if r.mcp.Storage.ProviderID != "" {
r.logger.Debug("Resolving storage provider for MCP operations",
zap.String("provider_id", r.mcp.Storage.ProviderID))
// Find the provider in storage_providers
// Check for file_system providers
for _, provider := range r.storageProviders.FileSystem {
if provider.ID == r.mcp.Storage.ProviderID {
r.logger.Debug("Found file_system storage provider for MCP",
zap.String("id", provider.ID),
zap.String("path", provider.Path))
// Use the resolved file system path
operationsDir = provider.Path
break
}
}
if operationsDir == "" {
return fmt.Errorf("storage provider with id '%s' for mcp server not found", r.mcp.Storage.ProviderID)
}
}
logFields := []zap.Field{
zap.String("storage_provider_id", r.mcp.Storage.ProviderID),
}
// Initialize the MCP server with the resolved operations directory
mcpOpts := []func(*mcpserver.Options){
mcpserver.WithGraphName(r.mcp.GraphName),
mcpserver.WithOperationsDir(operationsDir),
mcpserver.WithListenAddr(r.mcp.Server.ListenAddr),
mcpserver.WithLogger(r.logger.With(logFields...)),
mcpserver.WithExcludeMutations(r.mcp.ExcludeMutations),
mcpserver.WithEnableArbitraryOperations(r.mcp.EnableArbitraryOperations),
mcpserver.WithExposeSchema(r.mcp.ExposeSchema),
mcpserver.WithOmitToolNamePrefix(r.mcp.OmitToolNamePrefix),
mcpserver.WithStateless(r.mcp.Session.Stateless),
}
if r.corsOptions != nil {
mcpOpts = append(mcpOpts, mcpserver.WithCORS(*r.corsOptions))
}
mcpGraphQLEndpoint := r.graphqlEndpointURL
if r.mcp.RouterURL != "" {
mcpGraphQLEndpoint = r.mcp.RouterURL
}
mcpss, err := mcpserver.NewGraphQLSchemaServer(
mcpGraphQLEndpoint,
mcpOpts...,
)
if err != nil {
return fmt.Errorf("failed to create mcp server: %w", err)
}
err = mcpss.Start()
if err != nil {
// Cleanup the server if Start() fails to prevent resource leaks
if stopErr := mcpss.Stop(ctx); stopErr != nil {
r.logger.Warn("Failed to stop MCP server during error cleanup", zap.Error(stopErr))
}
return fmt.Errorf("failed to start MCP server: %w", err)