-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathgraphql_datasource.go
More file actions
2007 lines (1685 loc) · 70.3 KB
/
graphql_datasource.go
File metadata and controls
2007 lines (1685 loc) · 70.3 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 graphql_datasource
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"regexp"
"slices"
"strings"
"sync"
"time"
"unicode"
"github.com/buger/jsonparser"
"github.com/jensneuse/abstractlogger"
"github.com/pkg/errors"
"github.com/tidwall/sjson"
"google.golang.org/grpc"
"github.com/wundergraph/graphql-go-tools/v2/pkg/ast"
"github.com/wundergraph/graphql-go-tools/v2/pkg/astminify"
"github.com/wundergraph/graphql-go-tools/v2/pkg/astnormalization"
"github.com/wundergraph/graphql-go-tools/v2/pkg/astparser"
"github.com/wundergraph/graphql-go-tools/v2/pkg/astprinter"
"github.com/wundergraph/graphql-go-tools/v2/pkg/astvalidation"
grpcdatasource "github.com/wundergraph/graphql-go-tools/v2/pkg/engine/datasource/grpc_datasource"
"github.com/wundergraph/graphql-go-tools/v2/pkg/engine/datasource/httpclient"
"github.com/wundergraph/graphql-go-tools/v2/pkg/engine/plan"
"github.com/wundergraph/graphql-go-tools/v2/pkg/engine/resolve"
"github.com/wundergraph/graphql-go-tools/v2/pkg/internal/quotes"
"github.com/wundergraph/graphql-go-tools/v2/pkg/internal/unsafebytes"
"github.com/wundergraph/graphql-go-tools/v2/pkg/lexer/literal"
"github.com/wundergraph/graphql-go-tools/v2/pkg/operationreport"
)
var (
DefaultPostProcessingConfiguration = resolve.PostProcessingConfiguration{
SelectResponseDataPath: []string{"data"},
SelectResponseErrorsPath: []string{"errors"},
}
EntitiesPostProcessingConfiguration = resolve.PostProcessingConfiguration{
SelectResponseDataPath: []string{"data", "_entities"},
SelectResponseErrorsPath: []string{"errors"},
}
SingleEntityPostProcessingConfiguration = resolve.PostProcessingConfiguration{
SelectResponseDataPath: []string{"data", "_entities", "0"},
SelectResponseErrorsPath: []string{"errors"},
}
)
// Planner creates the subgraph operation.
type Planner[T Configuration] struct {
id int
debug bool
enableDebugPrintQueryPlan bool
includeQueryPlanInFetchConfiguration bool
queryPlan *resolve.QueryPlan
visitor *plan.Visitor
dataSourceConfig plan.DataSourceConfiguration[T]
dataSourcePlannerConfig plan.DataSourcePlannerConfiguration
config Configuration
upstreamOperation *ast.Document
upstreamVariables []byte
nodes []ast.Node
variables resolve.Variables
lastFieldEnclosingTypeName string
fetchClient *http.Client
subscriptionClient GraphQLSubscriptionClient
rootTypeName string // rootTypeName - holds name of top level type
rootFieldName string // rootFieldName - holds name of root type field
rootFieldRef int // rootFieldRef - holds ref of root type field
argTypeRef int // argTypeRef - holds current argument type ref from the definition
currentVariableDefinition int
addDirectivesToVariableDefinitions map[int][]int
insideCustomScalarField bool
customScalarFieldRef int
parentTypeNodes []ast.Node
// propagatedOperationName is non-empty when the operation name is propagated
// to the downstream subgraph fetch.
propagatedOperationName string
// federation
addedInlineFragments map[onTypeInlineFragment]struct{}
hasFederationRoot bool
minifier *astminify.Minifier
// gRPC
grpcClient grpc.ClientConnInterface
}
func (p *Planner[T]) EnableSubgraphRequestMinifier() {
p.minifier = astminify.NewMinifier()
}
type onTypeInlineFragment struct {
TypeCondition string
SelectionSet int
}
func (p *Planner[T]) SetID(id int) {
p.id = id
}
func (p *Planner[T]) ID() (id int) {
return p.id
}
func (p *Planner[T]) EnableDebug() {
p.debug = true
}
func (p *Planner[T]) EnableDebugQueryPlanLogging() {
p.enableDebugPrintQueryPlan = true
}
func (p *Planner[T]) IncludeQueryPlanInFetchConfiguration() {
p.includeQueryPlanInFetchConfiguration = true
}
func (p *Planner[T]) parentNodeIsAbstract() bool {
if len(p.parentTypeNodes) < 2 {
return false
}
parentTypeNode := p.parentTypeNodes[len(p.parentTypeNodes)-2]
return parentTypeNode.Kind.IsAbstractType()
}
func (p *Planner[T]) EnterVariableDefinition(ref int) {
p.currentVariableDefinition = ref
}
func (p *Planner[T]) LeaveVariableDefinition(_ int) {
p.currentVariableDefinition = -1
}
func (p *Planner[T]) EnterDirective(ref int) {
parent := p.nodes[len(p.nodes)-1]
if parent.Kind == ast.NodeKindOperationDefinition && p.currentVariableDefinition != -1 {
p.addDirectivesToVariableDefinitions[p.currentVariableDefinition] = append(p.addDirectivesToVariableDefinitions[p.currentVariableDefinition], ref)
return
}
p.addDirectiveToNode(ref, parent)
}
func (p *Planner[T]) addDirectiveToNode(directiveRef int, node ast.Node) {
directiveName := p.visitor.Operation.DirectiveNameString(directiveRef)
operationType := ast.OperationTypeQuery
if !p.dataSourcePlannerConfig.IsNested {
operationType = p.visitor.Operation.OperationDefinitions[p.visitor.Walker.Ancestors[0].Ref].OperationType
}
if !p.visitor.Definition.DirectiveIsAllowedOnNodeKind(directiveName, node.Kind, operationType) {
return
}
upstreamDirectiveName := p.dataSourceConfig.DirectiveConfigurations().RenameTypeNameOnMatchStr(directiveName)
upstreamSchema, err := p.config.UpstreamSchema()
if err != nil {
p.stopWithError(errors.WithStack(fmt.Errorf("failed to get upstream schema: %w", err)))
}
if !upstreamSchema.DirectiveIsAllowedOnNodeKind(upstreamDirectiveName, node.Kind, operationType) {
return
}
upstreamDirective := p.visitor.Importer.ImportDirectiveWithRename(directiveRef, upstreamDirectiveName, p.visitor.Operation, p.upstreamOperation)
p.upstreamOperation.AddDirectiveToNode(upstreamDirective, node)
// The directive is allowed on the node, so we know it exists.
directive := p.visitor.Operation.Directives[directiveRef]
var variables []ast.Value
// Collect all the variable arguments.
if directive.HasArguments {
for _, argument := range directive.Arguments.Refs {
value := p.visitor.Operation.ArgumentValue(argument)
// TODO: also handle literal values that CONTAIN variables
if value.Kind == ast.ValueKindVariable {
variables = append(variables, value)
}
}
}
// Process each variable, adding it to the upstream operation and
// variables, if it hasn't already been added. Note: instead of looking
// up the type of the corresponding argument on the directive definition,
// this code assumes the type of the variable as defined in the operation
// is correct and uses the same (possibly mapped) type for the upstream
// operation.
for _, value := range variables {
variableName := p.visitor.Operation.VariableValueNameBytes(value.Ref)
for _, i := range p.visitor.Operation.OperationDefinitions[p.visitor.Walker.Ancestors[0].Ref].VariableDefinitions.Refs {
// Find the variable declaration in the downstream operation.
ref := p.visitor.Operation.VariableDefinitions[i].VariableValue.Ref
if !p.visitor.Operation.VariableValueNameBytes(ref).Equals(variableName) {
continue
}
// Look up the variable type.
variableType := p.visitor.Operation.VariableDefinitions[i].Type
typeName := p.visitor.Operation.ResolveTypeNameString(variableType)
contextVariable := &resolve.ContextVariable{
Path: []string{string(variableName)},
Renderer: resolve.NewJSONVariableRenderer(),
}
// Try to add the variable to the set of upstream variables.
contextVariableName, exists := p.variables.AddVariable(contextVariable)
// If the variable already exists, it also already exists in the
// upstream operation; there's nothing to add!
if exists {
continue
}
// Add the variable to the upstream operation. Be sure to map the
// downstream type to the upstream type, if needed.
upstreamVariable := p.upstreamOperation.ImportVariableValue(variableName)
upstreamTypeName := p.visitor.Config.Types.RenameTypeNameOnMatchStr(typeName)
importedType := p.visitor.Importer.ImportTypeWithRename(p.visitor.Operation.VariableDefinitions[i].Type, p.visitor.Operation, p.upstreamOperation, upstreamTypeName)
p.upstreamOperation.AddVariableDefinitionToOperationDefinition(p.nodes[0].Ref, upstreamVariable, importedType)
// Also copy any variable directives in the downstream operation to
// the upstream operation.
if add, ok := p.addDirectivesToVariableDefinitions[i]; ok {
for _, directive := range add {
p.addDirectiveToNode(directive, ast.Node{Kind: ast.NodeKindVariableDefinition, Ref: i})
}
}
// And finally add the variable to the upstream variables JSON.
p.upstreamVariables, _ = sjson.SetRawBytes(p.upstreamVariables, string(variableName), []byte(contextVariableName))
}
}
}
func (p *Planner[T]) DownstreamResponseFieldAlias(downstreamFieldRef int) (alias string, exists bool) {
// If there's no alias but the downstream Query re-uses the same path on different root fields,
// we rewrite the downstream Query using an alias so that we can have an aliased Query to the upstream
// while keeping a non aliased Query to the downstream but with a path rewrite on an existing root field.
fieldName := p.visitor.Operation.FieldNameUnsafeString(downstreamFieldRef)
if p.visitor.Operation.FieldAliasIsDefined(downstreamFieldRef) {
return "", false
}
typeName := p.visitor.Walker.EnclosingTypeDefinition.NameString(p.visitor.Definition)
for i := range p.visitor.Config.Fields {
if p.visitor.Config.Fields[i].TypeName == typeName &&
p.visitor.Config.Fields[i].FieldName == fieldName &&
len(p.visitor.Config.Fields[i].Path) == 1 {
if p.visitor.Config.Fields[i].Path[0] != fieldName {
aliasBytes := p.visitor.Operation.FieldNameBytes(downstreamFieldRef)
return string(aliasBytes), true
}
break
}
}
return "", false
}
func (p *Planner[T]) Register(visitor *plan.Visitor, configuration plan.DataSourceConfiguration[T], dataSourcePlannerConfiguration plan.DataSourcePlannerConfiguration) error {
p.visitor = visitor
p.visitor.Walker.RegisterDocumentVisitor(p)
p.visitor.Walker.RegisterFieldVisitor(p)
p.visitor.Walker.RegisterOperationDefinitionVisitor(p)
p.visitor.Walker.RegisterSelectionSetVisitor(p)
p.visitor.Walker.RegisterEnterArgumentVisitor(p)
p.visitor.Walker.RegisterInlineFragmentVisitor(p)
p.visitor.Walker.RegisterEnterDirectiveVisitor(p)
p.visitor.Walker.RegisterVariableDefinitionVisitor(p)
p.dataSourcePlannerConfig = dataSourcePlannerConfiguration
p.dataSourceConfig = configuration
p.config = Configuration(configuration.CustomConfiguration())
return nil
}
func (p *Planner[T]) createInputForQuery() (input, operation []byte) {
opBytes, opVarsBytes := p.printOperation()
upstreamVariables := p.upstreamVariables
if opVarsBytes != nil {
err := jsonparser.ObjectEach(opVarsBytes, func(key, value []byte, dataType jsonparser.ValueType, offset int) (err error) {
if dataType == jsonparser.String {
upstreamVariables, err = sjson.SetRawBytes(upstreamVariables, string(key), quotes.WrapBytes(value))
} else {
upstreamVariables, err = sjson.SetRawBytes(upstreamVariables, string(key), value)
}
return err
})
if err != nil {
p.stopWithError(errors.WithStack(fmt.Errorf("createInputForQuery: failed to copy additional variables: %w", err)))
return nil, nil
}
}
input = httpclient.SetInputBodyWithPath(input, upstreamVariables, "variables")
input = httpclient.SetInputBodyWithPath(input, opBytes, "query")
return input, opBytes
}
func (p *Planner[T]) ConfigureFetch() resolve.FetchConfiguration {
if p.config.fetch == nil && p.config.grpc == nil {
p.stopWithError(errors.WithStack(errors.New("ConfigureFetch: fetch and grpc configuration is empty")))
return resolve.FetchConfiguration{}
}
input, operation := p.createInputForQuery()
if p.config.fetch != nil {
header, err := json.Marshal(p.config.fetch.Header)
if err != nil {
p.stopWithError(errors.WithStack(fmt.Errorf("ConfigureFetch: failed to marshal header: %w", err)))
return resolve.FetchConfiguration{}
}
if len(header) != 0 && !bytes.Equal(header, literal.NULL) {
input = httpclient.SetInputHeader(input, header)
}
input = httpclient.SetInputURL(input, []byte(p.config.fetch.URL))
input = httpclient.SetInputMethod(input, []byte(p.config.fetch.Method))
}
postProcessing := DefaultPostProcessingConfiguration
requiresEntityFetch := p.requiresEntityFetch()
requiresEntityBatchFetch := p.requiresEntityBatchFetch()
switch {
case requiresEntityFetch:
postProcessing = SingleEntityPostProcessingConfiguration
case requiresEntityBatchFetch:
postProcessing = EntitiesPostProcessingConfiguration
}
var dataSource resolve.DataSource
dataSource = &Source{httpClient: p.fetchClient}
if p.config.grpc != nil {
var err error
opDocument, opReport := astparser.ParseGraphqlDocumentBytes(operation)
if opReport.HasErrors() {
p.stopWithError(errors.WithStack(fmt.Errorf("failed to parse operation: %w", opReport)))
return resolve.FetchConfiguration{}
}
dataSource, err = grpcdatasource.NewDataSource(p.grpcClient, grpcdatasource.DataSourceConfig{
Operation: &opDocument,
Definition: p.config.schemaConfiguration.upstreamSchemaAst,
Mapping: p.config.grpc.Mapping,
Compiler: p.config.grpc.Compiler,
Disabled: p.config.grpc.Disabled,
FederationConfigs: p.dataSourcePlannerConfig.RequiredFields,
// TODO: remove fallback logic in visitor for subgraph name and
// add proper error handling if the subgraph name is not set in the mapping
SubgraphName: p.dataSourceConfig.Name(),
})
if err != nil {
p.stopWithError(errors.WithStack(fmt.Errorf("failed to create gRPC datasource: %w", err)))
return resolve.FetchConfiguration{}
}
}
return resolve.FetchConfiguration{
Input: string(input),
DataSource: dataSource,
Variables: p.variables,
RequiresEntityFetch: requiresEntityFetch,
RequiresEntityBatchFetch: requiresEntityBatchFetch,
PostProcessing: postProcessing,
SetTemplateOutputToNullOnVariableNull: requiresEntityFetch || requiresEntityBatchFetch,
QueryPlan: p.queryPlan,
OperationName: p.propagatedOperationName,
}
}
func (p *Planner[T]) shouldSelectSingleEntity() bool {
return p.dataSourcePlannerConfig.HasRequiredFields() &&
p.dataSourcePlannerConfig.PathType == plan.PlannerPathObject
}
func (p *Planner[T]) requiresEntityFetch() bool {
return p.hasFederationRoot && p.dataSourcePlannerConfig.HasRequiredFields() && p.dataSourcePlannerConfig.PathType == plan.PlannerPathObject
}
func (p *Planner[T]) requiresEntityBatchFetch() bool {
return p.hasFederationRoot && p.dataSourcePlannerConfig.HasRequiredFields() && p.dataSourcePlannerConfig.PathType != plan.PlannerPathObject
}
func (p *Planner[T]) ConfigureSubscription() plan.SubscriptionConfiguration {
if p.config.subscription == nil {
p.stopWithError(errors.WithStack(errors.New("ConfigureSubscription: subscription configuration is empty")))
return plan.SubscriptionConfiguration{}
}
input, _ := p.createInputForQuery()
input = httpclient.SetInputURL(input, []byte(p.config.subscription.URL))
if p.config.subscription.UseSSE {
input = httpclient.SetInputFlag(input, httpclient.USE_SSE)
if p.config.subscription.SSEMethodPost {
input = httpclient.SetInputFlag(input, httpclient.SSE_METHOD_POST)
}
}
input = httpclient.SetInputWSSubprotocol(input, []byte(p.config.subscription.WsSubProtocol))
header, err := json.Marshal(p.config.subscription.Header)
if err != nil {
p.stopWithError(errors.WithStack(fmt.Errorf("ConfigureSubscription: failed to marshal header: %w", err)))
return plan.SubscriptionConfiguration{}
}
if err == nil && len(header) != 0 && !bytes.Equal(header, literal.NULL) {
input = httpclient.SetInputHeader(input, header)
}
if len(p.config.subscription.ForwardedClientHeaderNames) > 0 {
headers, err := json.Marshal(p.config.subscription.ForwardedClientHeaderNames)
if err != nil {
p.stopWithError(errors.WithStack(fmt.Errorf("ConfigureSubscription: failed to marshal forwarded client header names: %w", err)))
return plan.SubscriptionConfiguration{}
}
input = httpclient.SetForwardedClientHeaderNames(input, headers)
}
if len(p.config.subscription.ForwardedClientHeaderRegularExpressions) > 0 {
headers, err := json.Marshal(p.config.subscription.ForwardedClientHeaderRegularExpressions)
if err != nil {
p.stopWithError(errors.WithStack(fmt.Errorf("ConfigureSubscription: failed to marshal forwarded client header regular expressions: %w", err)))
return plan.SubscriptionConfiguration{}
}
input = httpclient.SetForwardedClientHeaderRegularExpressions(input, headers)
}
return plan.SubscriptionConfiguration{
Input: string(input),
DataSource: &SubscriptionSource{
client: p.subscriptionClient,
subscriptionOnStartFns: p.config.subscription.StartupHooks,
},
Variables: p.variables,
PostProcessing: DefaultPostProcessingConfiguration,
QueryPlan: p.queryPlan,
}
}
func sanitize(element string) string {
// replace all invalid characters with underscore
return strings.Map(func(r rune) rune {
if !unicode.IsDigit(r) && !unicode.IsLetter(r) && r != '_' {
return '_'
}
return r
}, element)
}
func sanitizeKey(element string) string {
if element == "" {
return ""
}
sanitized := sanitize(element)
// remove consecutive underscores and leave only one
builder := strings.Builder{}
var prev rune
for _, r := range sanitized {
if r == '_' && prev == '_' {
continue
}
builder.WriteRune(r)
prev = r
}
return builder.String()
}
// buildUpstreamOperationName builds the name of the upstream operation.
// An operation name can only contain characters, digits and underscores. All other characters are replaced with underscores.
// As the subgraph name can contain special characters we need to make sure to sanitize it.
func (p *Planner[T]) buildUpstreamOperationName(ref int) string {
operationName := p.visitor.Operation.OperationDefinitionNameBytes(ref).String()
if operationName == "" {
return ""
}
builder := strings.Builder{}
operationName = strings.Trim(operationName, "_")
subgraphName := sanitizeKey(p.dataSourceConfig.Name())
subgraphName = strings.Trim(subgraphName, "_")
builder.Grow(len(operationName) + len(subgraphName) + 2) // 2 is for delimiters "__"
builder.WriteString(operationName + "__" + subgraphName)
return builder.String()
}
func (p *Planner[T]) EnterOperationDefinition(ref int) {
operationType := p.visitor.Operation.OperationDefinitions[ref].OperationType
if p.dataSourcePlannerConfig.IsNested {
operationType = ast.OperationTypeQuery
}
definition := p.upstreamOperation.AddOperationDefinitionToRootNodes(ast.OperationDefinition{
OperationType: operationType,
})
if p.dataSourcePlannerConfig.Options.EnableOperationNamePropagation {
operation := p.buildUpstreamOperationName(ref)
p.propagatedOperationName = operation
if operation != "" {
p.upstreamOperation.OperationDefinitions[definition.Ref].Name = p.upstreamOperation.Input.AppendInputString(operation)
}
}
p.nodes = append(p.nodes, definition)
}
func (p *Planner[T]) LeaveOperationDefinition(_ int) {
p.nodes = p.nodes[:len(p.nodes)-1]
}
func (p *Planner[T]) EnterSelectionSet(ref int) {
p.debugPrintOperationOnEnter(ast.NodeKindSelectionSet, ref)
p.parentTypeNodes = append(p.parentTypeNodes, p.visitor.Walker.EnclosingTypeDefinition)
if p.insideCustomScalarField {
return
}
parent := p.nodes[len(p.nodes)-1]
set := p.upstreamOperation.AddSelectionSet()
switch parent.Kind {
case ast.NodeKindSelectionSet:
// this happens when we're inside the root of a nested abstract federated query
// we want to walk into and out of the selection set because the root field is abstract
// this allows us to walk out of the inline fragment in the root
// however, as a nested operation always starts with an Operation Definition and a Selection Set
// we don't want to add the selection set to the root nodes
return
case ast.NodeKindOperationDefinition:
p.upstreamOperation.OperationDefinitions[parent.Ref].HasSelections = true
p.upstreamOperation.OperationDefinitions[parent.Ref].SelectionSet = set.Ref
case ast.NodeKindField:
p.upstreamOperation.Fields[parent.Ref].HasSelections = true
p.upstreamOperation.Fields[parent.Ref].SelectionSet = set.Ref
case ast.NodeKindInlineFragment:
p.upstreamOperation.InlineFragments[parent.Ref].HasSelections = true
p.upstreamOperation.InlineFragments[parent.Ref].SelectionSet = set.Ref
}
p.nodes = append(p.nodes, set)
if parent.Kind == ast.NodeKindOperationDefinition {
p.addRepresentationsQuery()
}
if p.visitor.Walker.EnclosingTypeDefinition.Kind != ast.NodeKindInterfaceTypeDefinition {
return
}
// handle adding typename for the InterfaceObject
// In case we are inside selection set which returns an interface object
// we need to add __typename field to the selection set to get an initial typename value
typeName := p.visitor.Walker.EnclosingTypeDefinition.NameString(p.visitor.Definition)
for _, interfaceObjectCfg := range p.dataSourceConfig.FederationConfiguration().InterfaceObjects {
if interfaceObjectCfg.InterfaceTypeName == typeName {
p.addTypenameToSelectionSet(set.Ref)
return
}
}
}
func (p *Planner[T]) addTypenameToSelectionSet(selectionSet int) {
field := p.upstreamOperation.AddField(ast.Field{
Name: p.upstreamOperation.Input.AppendInputString("__typename"),
})
p.upstreamOperation.AddSelection(selectionSet, ast.Selection{
Ref: field.Ref,
Kind: ast.SelectionKindField,
})
}
func (p *Planner[T]) LeaveSelectionSet(ref int) {
p.debugPrintOperationOnLeave(ast.NodeKindSelectionSet, ref)
p.parentTypeNodes = p.parentTypeNodes[:len(p.parentTypeNodes)-1]
if p.insideCustomScalarField {
return
}
lastIndex := len(p.nodes) - 1
if p.nodes[lastIndex].Kind == ast.NodeKindSelectionSet {
p.nodes = p.nodes[:lastIndex]
}
}
func (p *Planner[T]) EnterInlineFragment(ref int) {
p.debugPrintOperationOnEnter(ast.NodeKindInlineFragment, ref)
if p.insideCustomScalarField {
return
}
if p.config.IsFederationEnabled() && !p.hasFederationRoot && p.isNestedRequest() {
// if we're inside the nested root of a federated abstract query,
// we're walking into the inline fragment as the root
// however, as we're already handling the inline fragment when we walk into the root field,
// we can skip this one
return
}
hasTypeCondition := p.visitor.Operation.InlineFragmentHasTypeCondition(ref)
// after normalization the type condition is always present
IsOfTheSameType := p.visitor.Operation.InlineFragmentIsOfTheSameType(ref)
// create inline fragment and selection
inlineFragmentRef := p.upstreamOperation.AddInlineFragment(ast.InlineFragment{
TypeCondition: ast.TypeCondition{
Type: ast.InvalidRef,
},
})
currentSelectionSet := p.nodes[len(p.nodes)-1].Ref
// when fragment has type condition, and it is not of the same type
// we need to add __typename field to selection set
if hasTypeCondition && !IsOfTheSameType {
typeCondition := p.visitor.Operation.InlineFragmentTypeConditionName(ref)
onTypeName := p.visitor.Config.Types.RenameTypeNameOnMatchBytes(typeCondition)
// rename type name in case it is required by entity interface
shouldRenameInterfaceObjectType, newName := p.interfaceObjectTypeShouldBeRenamed(string(onTypeName))
if shouldRenameInterfaceObjectType {
onTypeName = []byte(newName)
}
fragmentTypeRef := p.upstreamOperation.AddNamedType(onTypeName)
p.upstreamOperation.InlineFragments[inlineFragmentRef].TypeCondition.Type = fragmentTypeRef
if !shouldRenameInterfaceObjectType {
// add __typename field to selection set which contains typeCondition
// so that the resolver can distinguish between the response types
p.addTypenameToSelectionSet(currentSelectionSet)
}
}
selection := ast.Selection{
Kind: ast.SelectionKindInlineFragment,
Ref: inlineFragmentRef,
}
p.upstreamOperation.AddSelection(currentSelectionSet, selection)
inlineFragmentNode := ast.Node{Kind: ast.NodeKindInlineFragment, Ref: inlineFragmentRef}
p.nodes = append(p.nodes, inlineFragmentNode)
}
func (p *Planner[T]) LeaveInlineFragment(ref int) {
p.debugPrintOperationOnLeave(ast.NodeKindInlineFragment, ref)
if p.insideCustomScalarField {
return
}
lastIndex := len(p.nodes) - 1
if p.nodes[lastIndex].Kind == ast.NodeKindInlineFragment {
p.nodes = p.nodes[:lastIndex]
}
}
func (p *Planner[T]) EnterField(ref int) {
p.debugPrintOperationOnEnter(ast.NodeKindField, ref)
p.lastFieldEnclosingTypeName = p.visitor.Walker.EnclosingTypeDefinition.NameString(p.visitor.Definition)
if !p.allowField(ref) {
return
}
if p.insideCustomScalarField {
return
}
fieldName := p.visitor.Operation.FieldNameString(ref)
typeName := p.lastFieldEnclosingTypeName
if shouldRenameInterfaceObjectType, newTypeName := p.interfaceObjectTypeShouldBeRenamed(typeName); shouldRenameInterfaceObjectType {
typeName = newTypeName
}
fieldConfiguration := p.visitor.Config.Fields.ForTypeField(typeName, fieldName)
for i := range p.config.customScalarTypeFields {
if p.config.customScalarTypeFields[i].TypeName == typeName && p.config.customScalarTypeFields[i].FieldName == fieldName {
p.insideCustomScalarField = true
p.customScalarFieldRef = ref
p.addFieldArguments(p.addCustomField(ref), ref, fieldConfiguration)
return
}
}
// store root field name and ref
if p.rootFieldName == "" {
p.rootFieldName = fieldName
p.rootFieldRef = ref
}
// store root type name
if p.rootTypeName == "" {
p.rootTypeName = p.lastFieldEnclosingTypeName
}
p.handleOnTypeInlineFragment()
p.addFieldArguments(p.addField(ref), ref, fieldConfiguration)
}
func (p *Planner[T]) addFieldArguments(upstreamFieldRef int, fieldRef int, fieldConfiguration *plan.FieldConfiguration) {
if fieldConfiguration != nil {
for i := range fieldConfiguration.Arguments {
argumentConfiguration := fieldConfiguration.Arguments[i]
p.configureArgument(upstreamFieldRef, fieldRef, *fieldConfiguration, argumentConfiguration)
}
}
}
func (p *Planner[T]) addCustomField(ref int) (upstreamFieldRef int) {
fieldName, alias := p.handleFieldAlias(ref)
fieldNode := p.upstreamOperation.AddField(ast.Field{
Name: p.upstreamOperation.Input.AppendInputString(fieldName),
Alias: alias,
})
selection := ast.Selection{
Kind: ast.SelectionKindField,
Ref: fieldNode.Ref,
}
p.upstreamOperation.AddSelection(p.nodes[len(p.nodes)-1].Ref, selection)
return fieldNode.Ref
}
func (p *Planner[T]) LeaveField(ref int) {
p.debugPrintOperationOnLeave(ast.NodeKindField, ref)
if !p.allowField(ref) {
return
}
if p.insideCustomScalarField {
if p.customScalarFieldRef == ref {
p.insideCustomScalarField = false
p.customScalarFieldRef = 0
}
return
}
p.nodes = p.nodes[:len(p.nodes)-1]
}
// allowField - allows processing a field if datasource has corresponding root or child node
// This check is required cause planner will add parent path as well, but we not always need to add fields from path.
// This is 3rd step of checks in addition to: planning path and skipFor functionality
// if field is __typename, it is always allowed
func (p *Planner[T]) allowField(ref int) bool {
fieldAliasOrName := p.visitor.Operation.FieldAliasOrNameString(ref)
// In addition, we skip field if its path are equal to planner parent path
// This is required to correctly plan on datasource which has corresponding child/root node,
// but we don't need to add it to the query as we are in the nested request
currentPath := fmt.Sprintf("%s.%s", p.visitor.Walker.Path.DotDelimitedString(), fieldAliasOrName)
if p.dataSourcePlannerConfig.ParentPath != "query" && p.dataSourcePlannerConfig.ParentPath == currentPath {
p.DebugPrint("allowField: false path:", currentPath, "is equal to parent path", p.dataSourcePlannerConfig.ParentPath)
return false
}
return true
}
func (p *Planner[T]) EnterArgument(_ int) {
if p.insideCustomScalarField {
return
}
}
func (p *Planner[T]) EnterDocument(_, _ *ast.Document) {
if p.upstreamOperation == nil {
p.upstreamOperation = ast.NewSmallDocument()
} else {
p.upstreamOperation.Reset()
}
p.nodes = p.nodes[:0]
p.parentTypeNodes = p.parentTypeNodes[:0]
p.upstreamVariables = nil
p.variables = p.variables[:0]
p.hasFederationRoot = false
p.queryPlan = nil
p.propagatedOperationName = ""
// reset information about root type
p.rootTypeName = ""
p.rootFieldName = ""
p.rootFieldRef = -1
// reset info about arg type
p.argTypeRef = -1
p.addDirectivesToVariableDefinitions = map[int][]int{}
p.addedInlineFragments = map[onTypeInlineFragment]struct{}{}
}
func (p *Planner[T]) LeaveDocument(_, _ *ast.Document) {
p.addRepresentationsVariable()
}
func (p *Planner[T]) addRepresentationsVariable() {
if !p.hasFederationRoot {
return
}
if !p.dataSourcePlannerConfig.HasRequiredFields() {
return
}
variable, _ := p.variables.AddVariable(p.buildRepresentationsVariable())
p.upstreamVariables, _ = sjson.SetRawBytes(p.upstreamVariables, "representations", []byte(fmt.Sprintf("[%s]", variable)))
}
func (p *Planner[T]) buildRepresentationsVariable() resolve.Variable {
objects := make([]*resolve.Object, 0, len(p.dataSourcePlannerConfig.RequiredFields))
for _, cfg := range p.dataSourcePlannerConfig.RequiredFields {
node, err := buildRepresentationVariableNode(p.visitor.Definition, cfg, p.dataSourceConfig.FederationConfiguration())
if err != nil {
p.stopWithError(errors.WithStack(fmt.Errorf("buildRepresentationsVariable: failed to build representation variable node: %w", err)))
return nil
}
objects = append(objects, node)
}
return resolve.NewResolvableObjectVariable(
mergeRepresentationVariableNodes(objects),
)
}
func (p *Planner[T]) addRepresentationsQuery() {
isNestedFederationRequest := p.dataSourcePlannerConfig.IsNested && p.config.IsFederationEnabled() && p.dataSourcePlannerConfig.HasRequiredFields()
if !isNestedFederationRequest {
return
}
p.hasFederationRoot = true
// query($representations: [_Any!]!){_entities(representations: $representations){... on Product
p.addRepresentationsVariableDefinition() // $representations: [_Any!]!
p.addEntitiesSelectionSet() // {_entities(representations: $representations)
}
func (p *Planner[T]) handleOnTypeInlineFragment() {
if p.hasFederationRoot {
if !p.isInEntitiesSelectionSet() {
// if we querying field of entity type, but we are not in the root of the query
// we should not add representations variable and should not add inline fragment
// e.g. query { _entities { ... on Product { price info {name} } } }
// where Info is an entity type, but it is used as a field of Product
//
// At the same time, we may need to update representations variables, but not to add an inline fragment
// cause, we could have a field which requires an additional field from entity type, which is not a key
return
}
// add inline fragment again, because it could be another entity type
// e.g. parallel request for a few entities
// ... on Product { price }
// ,,, on StockItem { stock }
if !p.isOnTypeInlineFragmentAllowed() {
return
}
p.addOnTypeInlineFragment() // ... on Product
return
}
}
func (p *Planner[T]) fieldDefinition(fieldName, typeName string) *ast.FieldDefinition {
node, ok := p.visitor.Definition.Index.FirstNodeByNameStr(typeName)
if !ok {
return nil
}
definition, ok := p.visitor.Definition.NodeFieldDefinitionByName(node, []byte(fieldName))
if !ok {
return nil
}
return &p.visitor.Definition.FieldDefinitions[definition]
}
// isOnTypeInlineFragmentAllowed returns false if we already have an entity fragment with the same type name
func (p *Planner[T]) isOnTypeInlineFragmentAllowed() bool {
p.DebugPrint("isOnTypeInlineFragmentAllowed")
if len(p.nodes) <= 1 || p.nodes[len(p.nodes)-1].Kind != ast.NodeKindSelectionSet {
return true
}
fragmentInfo := onTypeInlineFragment{
TypeCondition: p.lastFieldEnclosingTypeName,
SelectionSet: p.nodes[len(p.nodes)-1].Ref,
}
_, exists := p.addedInlineFragments[fragmentInfo]
return !exists
}
func (p *Planner[T]) isInEntitiesSelectionSet() bool {
if len(p.nodes) <= 2 {
return false
}
if p.nodes[len(p.nodes)-1].Kind != ast.NodeKindSelectionSet {
return false
}
if p.nodes[len(p.nodes)-2].Kind != ast.NodeKindField {
return false
}
fieldName := p.upstreamOperation.FieldNameBytes(p.nodes[len(p.nodes)-2].Ref)
return bytes.Equal(fieldName, []byte("_entities"))
}
func (p *Planner[T]) interfaceObjectTypeShouldBeRenamed(typeName string) (ok bool, newName string) {
for _, interfaceObjectCfg := range p.dataSourceConfig.FederationConfiguration().InterfaceObjects {
if slices.Contains(interfaceObjectCfg.ConcreteTypeNames, typeName) {
return true, interfaceObjectCfg.InterfaceTypeName
}
}
return false, ""
}
func (p *Planner[T]) addOnTypeInlineFragment() {
p.DebugPrint("addOnTypeInlineFragment")
shouldCopyDirectives := false
copyFromRef := ast.InvalidRef
if len(p.visitor.Walker.Ancestors) > 2 &&
p.visitor.Walker.Ancestors[len(p.visitor.Walker.Ancestors)-2].Kind == ast.NodeKindInlineFragment &&
p.visitor.Operation.InlineFragmentHasDirectives(p.visitor.Walker.Ancestors[len(p.visitor.Walker.Ancestors)-2].Ref) {
shouldCopyDirectives = true
copyFromRef = p.visitor.Walker.Ancestors[len(p.visitor.Walker.Ancestors)-2].Ref
// TODO: check whole ancestor tree for the inline fragment with directives
}
selectionSet := p.upstreamOperation.AddSelectionSet()
onTypeName := p.visitor.Config.Types.RenameTypeNameOnMatchBytes([]byte(p.lastFieldEnclosingTypeName))
// rename type name in case it is required by entity interface
shouldRenameInterfaceObjectType, newName := p.interfaceObjectTypeShouldBeRenamed(p.lastFieldEnclosingTypeName)
if shouldRenameInterfaceObjectType {
onTypeName = []byte(newName)
}
// we should not request a typename when we jump to an interface object
if !shouldRenameInterfaceObjectType {
// NOTE: we are adding __typename field to the selection set of the inline fragment,
// not the parent selection set, as it turns out that some subgraph implementations
// could not handle __typename field in the _entities selection set
p.addTypenameToSelectionSet(selectionSet.Ref)
}
typeRef := p.upstreamOperation.AddNamedType(onTypeName)
inlineFragment := p.upstreamOperation.AddInlineFragment(ast.InlineFragment{
HasSelections: true,
SelectionSet: selectionSet.Ref,
TypeCondition: ast.TypeCondition{
Type: typeRef,
},
})
if shouldCopyDirectives {
for _, ref := range p.visitor.Operation.InlineFragments[copyFromRef].Directives.Refs {
p.addDirectiveToNode(ref, ast.Node{Kind: ast.NodeKindInlineFragment, Ref: inlineFragment})
}
}