forked from nautilus/gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plan.go
1007 lines (847 loc) · 32.4 KB
/
plan.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 gateway
import (
"errors"
"fmt"
"sync"
"github.com/vektah/gqlparser/v2"
"github.com/vektah/gqlparser/v2/ast"
"github.com/nautilus/graphql"
)
// QueryPlanStep represents a step in the plan required to fulfill a query.
type QueryPlanStep struct {
// execution meta data
InsertionPoint []string
Then []*QueryPlanStep
// required info to generate the query
Queryer graphql.Queryer
ParentType string
ParentID string
SelectionSet ast.SelectionSet
// pre-generated query stuff
QueryDocument *ast.QueryDocument
QueryString string
FragmentDefinitions ast.FragmentDefinitionList
Variables Set
}
// QueryPlan is the full plan to resolve a particular query
type QueryPlan struct {
Operation *ast.OperationDefinition
RootStep *QueryPlanStep
FragmentDefinitions ast.FragmentDefinitionList
FieldsToScrub map[string][][]string
}
type newQueryPlanStepPayload struct {
Plan *QueryPlan
Location string
SelectionSet ast.SelectionSet
ParentType string
Parent *QueryPlanStep
InsertionPoint []string
Fragments ast.FragmentDefinitionList
Wrapper ast.SelectionSet
}
// QueryPlanner is responsible for taking a string with a graphql query and returns
// the steps to fulfill it
type QueryPlanner interface {
Plan(*PlanningContext) (QueryPlanList, error)
}
// PlannerWithQueryerFactory is an interface for planners with configurable queryer factories
type PlannerWithQueryerFactory interface {
WithQueryerFactory(*QueryerFactory) QueryPlanner
}
// PlannerWithLocationFactory is an interface for planners with configurable location priorities
type PlannerWithLocationPriorities interface {
WithLocationPriorities(priorities []string) QueryPlanner
}
// QueryerFactory is a function that returns the queryer to use depending on the context
type QueryerFactory func(ctx *PlanningContext, url string) graphql.Queryer
// Planner is meant to be embedded in other QueryPlanners to share configuration
type Planner struct {
QueryerFactory *QueryerFactory
}
// MinQueriesPlanner does the most basic level of query planning
type MinQueriesPlanner struct {
Planner
LocationPriorities []string
}
// WithQueryerFactory returns a version of the planner with the factory set
func (p *MinQueriesPlanner) WithQueryerFactory(factory *QueryerFactory) QueryPlanner {
p.Planner.QueryerFactory = factory
return p
}
func (p *MinQueriesPlanner) WithLocationPriorities(priorities []string) QueryPlanner {
p.LocationPriorities = priorities
return p
}
// PlanningContext is the input struct to the Plan method
type PlanningContext struct {
Query string
Schema *ast.Schema
Locations FieldURLMap
Gateway *Gateway
}
// Plan computes the nested selections that will need to be performed
func (p *MinQueriesPlanner) Plan(ctx *PlanningContext) (QueryPlanList, error) {
// the first thing to do is to parse the query
parsedQuery, e := gqlparser.LoadQuery(ctx.Schema, ctx.Query)
if e != nil {
return nil, e
}
// generate the plan
plans, err := p.generatePlans(ctx, parsedQuery)
if err != nil {
return nil, err
}
flatSelection, err := graphql.ApplyFragments(parsedQuery.Operations[0].SelectionSet, parsedQuery.Fragments)
if err != nil {
return nil, err
}
// add the scrub fields
err = p.generateScrubFields(plans, flatSelection)
if err != nil {
return nil, err
}
// we're done
return plans, nil
}
func (p *MinQueriesPlanner) generatePlans(ctx *PlanningContext, query *ast.QueryDocument) (QueryPlanList, error) {
// an accumulator
plans := QueryPlanList{}
for _, operation := range query.Operations {
// each operation results in a new query
plan := &QueryPlan{
Operation: operation,
FragmentDefinitions: query.Fragments,
}
// add the plan to the top level list
plans = append(plans, plan)
// a channel to register new steps
const maxConcurrentSteps = 50
stepCh := make(chan *newQueryPlanStepPayload, maxConcurrentSteps)
// a chan to get errors
errCh := make(chan error)
defer close(errCh)
// a wait group to track the progress of goroutines
stepWg := &sync.WaitGroup{}
// get the type for the operation
var operationType string
switch operation.Operation {
case ast.Mutation:
operationType = typeNameMutation
case ast.Subscription:
operationType = typeNameSubscription
case ast.Query:
operationType = typeNameQuery
default:
operationType = typeNameQuery
}
// we are garunteed at least one query
stepWg.Add(1)
// start with an empty root step
stepCh <- &newQueryPlanStepPayload{
Plan: plan,
SelectionSet: operation.SelectionSet,
ParentType: operationType,
Location: "",
InsertionPoint: []string{},
Fragments: ast.FragmentDefinitionList{},
Wrapper: ast.SelectionSet{},
}
// start waiting for steps to be added
// NOTE: i dont think this closure is necessary ¯\_(ツ)_/¯
go func(newSteps chan *newQueryPlanStepPayload) {
SelectLoop:
// continuously drain the step channel
for payload := range newSteps {
step := &QueryPlanStep{
Queryer: p.GetQueryer(ctx, payload.Location),
ParentType: payload.ParentType,
SelectionSet: ast.SelectionSet{},
InsertionPoint: payload.InsertionPoint,
Variables: Set{},
FragmentDefinitions: payload.Fragments,
}
// if there is a parent to this query
if payload.Parent != nil {
ctx.Gateway.logger.Debug("Adding step as dependency")
// add the new step to the Then of the parent
payload.Parent.Then = append(payload.Parent.Then, step)
}
// if we don't yet have a root step
if plan.RootStep == nil {
// use this one
plan.RootStep = step
}
ctx.Gateway.logger.Debug(fmt.Sprintf(
"Encountered new step: \n"+
"\tParentType: %v \n"+
"\tInsertion Point: %v \n"+
"\tSelectionSet: \n%s",
step.ParentType,
payload.InsertionPoint,
graphql.FormatSelectionSet(payload.SelectionSet),
))
// we are going to start walking down the operations selection set and let
// the steps of the walk add any necessary selectedFields
newSelection, err := p.extractSelection(ctx, &extractSelectionConfig{
stepCh: stepCh,
stepWg: stepWg,
locations: ctx.Locations,
parentLocation: payload.Location,
parentType: step.ParentType,
selection: payload.SelectionSet,
step: step,
insertionPoint: payload.InsertionPoint,
plan: payload.Plan,
wrapper: payload.Wrapper,
})
if err != nil {
errCh <- err
continue SelectLoop
}
// if some of the fields are from the same location as the field on the operation
if newSelection != nil {
// we have a selection set from one of the root operation fields in the same location
// so add it to the query we are sending to the service
step.SelectionSet = newSelection
}
// now that we're done processing the step we need to preconstruct the query that we
// will be firing for this plan
// we need to grab the list of variable definitions
variableDefs := ast.VariableDefinitionList{}
// we need to grab the variable definitions and values for each variable in the step
for variable := range step.Variables {
// add the definition
variableDefs = append(variableDefs, plan.Operation.VariableDefinitions.ForName(variable))
}
// build up the query document
step.QueryDocument = plannerBuildQuery(ctx, plan.Operation.Name, step.ParentType, variableDefs, step.SelectionSet, step.FragmentDefinitions)
// we also need to turn the query into a string
queryString, err := graphql.PrintQuery(step.QueryDocument)
if err != nil {
errCh <- err
continue SelectLoop
}
step.QueryString = queryString
// we're done processing this step
stepWg.Done()
}
}(stepCh)
// there are 2 possible options:
// - either the wait group finishes
// - we get a messsage over the error chan
// in order to wait for either, let's spawn a go routine
// that waits until all of the steps are built and notifies us when its done
doneCh := make(chan bool)
defer close(doneCh)
go func() {
// when the wait group is finished
stepWg.Wait()
// push a value over the channel
doneCh <- true
}()
// wait for either the error channel or done channel
select {
// there was an error
case err := <-errCh:
// bubble the error up
return nil, err
// we are done
case <-doneCh:
close(stepCh)
}
}
// return the final plan
return plans, nil
}
type extractSelectionConfig struct {
stepCh chan *newQueryPlanStepPayload
stepWg *sync.WaitGroup
locations FieldURLMap
parentLocation string
parentType string
step *QueryPlanStep
plan *QueryPlan
selection ast.SelectionSet
insertionPoint []string
wrapper ast.SelectionSet
}
func (p *MinQueriesPlanner) extractSelection(ctx *PlanningContext, config *extractSelectionConfig) (ast.SelectionSet, error) {
ctx.Gateway.logger.Debug("--- Extracting Selection ---")
ctx.Gateway.logger.Debug("Parent location: ", config.parentLocation)
// in order to group together fields in as few queries as possible, we need to group
// the selection set by the location.
locationFields, locationFragments, err := p.groupSelectionSet(ctx, config)
if err != nil {
return nil, err
}
ctx.Gateway.logger.Debug("Fields By Location: ", locationFields)
// we only need to add an ID field if there are steps coming off of this insertion point
checkForID := false
// we have to make sure we spawn any more goroutines before this one terminates. This means that
// we first have to look at any locations that are not the current one
for location, selectionSet := range locationFields {
if location == config.parentLocation {
continue
}
// we are dealing with a selection to another location that isn't the current one
ctx.Gateway.logger.Debug(fmt.Sprintf(
"Adding the new step"+
"\n\tParent Type: %s"+
"\n\tLocation: %v"+
"\n\tInsertion point: %v",
config.parentType, location, config.insertionPoint))
// if there are selections in this bundle that are not from the parent location we need to add
// id to the selection set
checkForID = true
// if we have a wrapper to add
if config.wrapper != nil && len(config.wrapper) > 0 {
ctx.Gateway.logger.Debug("wrapping selection", config.wrapper)
// use the wrapped version
selectionSet, err = p.wrapSelectionSet(ctx, config, locationFragments, location, selectionSet)
if err != nil {
return nil, err
}
}
// since we're adding another step we need to wait for at least one more goroutine to finish processing
config.stepWg.Add(1)
// add the new step
config.stepCh <- &newQueryPlanStepPayload{
Plan: config.plan,
Parent: config.step,
InsertionPoint: config.insertionPoint,
Wrapper: config.wrapper,
ParentType: config.parentType,
Location: location,
SelectionSet: selectionSet,
Fragments: locationFragments[location],
}
}
// if we have to have an id field on this selection set
if checkForID {
// add the id field since duplicates are ignored
locationFields[config.parentLocation] = append(locationFields[config.parentLocation], &ast.Field{Name: "id"})
}
// now we have to generate a selection set for fields that are coming from the same location as the parent
currentLocationFields, ok := locationFields[config.parentLocation]
if !ok {
// there are no fields in the current location so we're done
return ast.SelectionSet{}, nil
}
// build up a selection set for the parent
finalSelection := ast.SelectionSet{}
// we need to repeat this process for each field in the current location selection set
for _, selection := range currentLocationFields {
switch selection := selection.(type) {
case *ast.Field:
// if the targetField has a selection, it cannot be added naively to the parent. We first have to
// modify its selection set to only include fields that are at the same location as the parent.
if len(selection.SelectionSet) > 0 {
// the insertion point for this field is the previous one with the new field name
insertionPoint := copyStrings(config.insertionPoint)
insertionPoint = append(insertionPoint, selection.Alias)
// if this field is being wrapped in a fragment then we need to make sure
// that any branches we kick off are still wrapped within the fragment.
// if the field is being wrapped in any inline fragments (above or below),
// we can get rid of them since the parent was responsible for handling
wrapper := ast.SelectionSet{}
if len(config.wrapper) > 0 {
wrapper = config.wrapper[:1]
if _, ok := wrapper[0].(*ast.InlineFragment); ok {
wrapper = ast.SelectionSet{}
}
}
ctx.Gateway.logger.Debug("found a thing with a selection. extracting to ", insertionPoint, ". Parent insertion", config.insertionPoint)
// add any possible selections provided by this fields selections
subSelection, err := p.extractSelection(ctx, &extractSelectionConfig{
stepCh: config.stepCh,
stepWg: config.stepWg,
step: config.step,
locations: config.locations,
parentLocation: config.parentLocation,
plan: config.plan,
parentType: coreFieldType(selection).Name(),
selection: selection.SelectionSet,
insertionPoint: insertionPoint,
wrapper: wrapper,
})
if err != nil {
return nil, err
}
ctx.Gateway.logger.Debug(fmt.Sprintf("final selection for %s.%s: %v\n", config.parentType, selection.Name, subSelection))
// overwrite the selection set for this selection
selection.SelectionSet = subSelection
} else {
ctx.Gateway.logger.Debug("found a scalar")
}
// the field is now safe to add to the parents selection set
// any variables that this field depends on need to be added to the steps list of variables
for _, variable := range graphql.ExtractVariables(selection.Arguments) {
config.step.Variables.Add(variable)
}
for _, directive := range selection.Directives {
for _, variable := range graphql.ExtractVariables(directive.Arguments) {
config.step.Variables.Add(variable)
}
}
// add it to the list
finalSelection = append(finalSelection, selection)
case *ast.FragmentSpread:
// we have to walk down the fragments definition and keep adding to the selection sets and fragment definitions
// add it to the list
finalSelection = append(finalSelection, selection)
// grab the official definition for the fragment.
// we could have overwritten the definition to fit the local needs of the top level
// ie if there is a branch off of one that happens mid-fragment.
defn := config.step.FragmentDefinitions.ForName(selection.Name)
addDefn := false
if defn == nil {
addDefn = true
defn = config.plan.FragmentDefinitions.ForName(selection.Name)
}
// compute the actual selection set for the fragment coming from this location
subSelection, err := p.extractSelection(ctx, &extractSelectionConfig{
stepCh: config.stepCh,
stepWg: config.stepWg,
step: config.step,
locations: config.locations,
parentLocation: config.parentLocation,
insertionPoint: config.insertionPoint,
plan: config.plan,
parentType: defn.TypeCondition,
selection: defn.SelectionSet,
// Children should now be wrapped by this fragment and nothing else
wrapper: ast.SelectionSet{selection},
})
if err != nil {
return nil, err
}
// if the step does not have a definition for this fragment
if addDefn {
// we're going to leave a different fragment definition behind for this step
config.step.FragmentDefinitions = append(config.step.FragmentDefinitions,
&ast.FragmentDefinition{
Name: selection.Name,
TypeCondition: defn.TypeCondition,
Directives: defn.Directives,
},
)
}
// we need to make sure that this steps fragment definitions always match our expecatations
config.step.FragmentDefinitions.ForName(selection.Name).SelectionSet = subSelection
case *ast.InlineFragment:
ctx.Gateway.logger.Debug("found an inline fragment. extracting to ", config.insertionPoint, ". Parent insertion", config.insertionPoint)
newWrapper := make(ast.SelectionSet, len(config.wrapper))
copy(newWrapper, config.wrapper)
newWrapper = append(newWrapper, selection)
// add any possible selections provided by selections
subSelection, err := p.extractSelection(ctx, &extractSelectionConfig{
stepCh: config.stepCh,
stepWg: config.stepWg,
step: config.step,
locations: config.locations,
parentLocation: config.parentLocation,
plan: config.plan,
insertionPoint: config.insertionPoint,
parentType: selection.TypeCondition,
selection: selection.SelectionSet,
wrapper: newWrapper,
})
if err != nil {
return nil, err
}
// overwrite the selection set for this selection
selection.SelectionSet = subSelection
// for now, just add it to the list
finalSelection = append(finalSelection, selection)
}
}
// we should have added every field that needs to be added to this list
return finalSelection, nil
}
func (p *MinQueriesPlanner) wrapSelectionSet(ctx *PlanningContext, config *extractSelectionConfig, locationFragments map[string]ast.FragmentDefinitionList, location string, selectionSet ast.SelectionSet) (ast.SelectionSet, error) {
ctx.Gateway.logger.Debug("wrapping selection", config.wrapper)
// pointers required to nest the
var selection ast.Selection
var innerSelection ast.Selection
for _, wrap := range config.wrapper {
var newSelection ast.Selection
switch wrap := wrap.(type) {
case *ast.InlineFragment:
// create a new inline fragment
newSelection = &ast.InlineFragment{
TypeCondition: wrap.TypeCondition,
Directives: wrap.Directives,
}
case *ast.FragmentSpread:
newSelection = &ast.FragmentSpread{
Name: wrap.Name,
Directives: wrap.Directives,
}
locationFragments[location] = append(locationFragments[location], &ast.FragmentDefinition{
Name: wrap.Name,
TypeCondition: config.parentType,
})
}
// if this is the first one then use the first object we create as the top level
if selection == nil {
selection = newSelection
} else if sel, ok := innerSelection.(*ast.InlineFragment); ok {
sel.SelectionSet = ast.SelectionSet{newSelection}
} else if sel, ok := innerSelection.(*ast.FragmentSpread); ok {
// look up the definition for the selection in the step
defn := locationFragments[location].ForName(sel.Name)
defn.SelectionSet = ast.SelectionSet{newSelection}
}
// this is the new inner-most selection
innerSelection = newSelection
}
if sel, ok := innerSelection.(*ast.InlineFragment); ok {
sel.SelectionSet = selectionSet
} else if sel, ok := innerSelection.(*ast.FragmentSpread); ok {
// look up the definition for the selection in the step
defn := locationFragments[location].ForName(sel.Name)
// if we couldn't find the definition
if defn == nil {
return nil, errors.New("Could not find defn")
}
// update its selection set
defn.SelectionSet = selectionSet
}
return ast.SelectionSet{selection}, nil
}
// selects one location out of possibleLocations, prioritizing the parent's location and the internal schema
func (p *MinQueriesPlanner) selectLocation(possibleLocations []string, config *extractSelectionConfig) string {
// if this field can only be found in one location
if len(possibleLocations) == 1 {
return possibleLocations[0]
}
// the field can be found in many locations
// locations to prioritize first
initialLocationPriorities := []string{config.parentLocation, internalSchemaLocation}
priorities := make([]string, len(p.LocationPriorities), len(p.LocationPriorities)+len(initialLocationPriorities))
copy(priorities, p.LocationPriorities)
priorities = append(priorities, initialLocationPriorities...)
for _, priority := range priorities {
// look to see if the current location is one of the possible locations
for _, location := range possibleLocations {
// if the location is the same as the parent
if location == priority {
// assign this field to the parents entry
return priority
}
}
}
// if we got here then this field can be found in multiple services and none of the top priority locations.
// for now, just use the first one
return possibleLocations[0]
}
func (p *MinQueriesPlanner) groupSelectionSet(ctx *PlanningContext, config *extractSelectionConfig) (map[string]ast.SelectionSet, map[string]ast.FragmentDefinitionList, error) {
locationFields := map[string]ast.SelectionSet{}
locationFragments := map[string]ast.FragmentDefinitionList{}
// split each selection into groups of selection sets to be sent to a single service
for _, selection := range config.selection {
// each kind of selection contributes differently to the final selection set
switch selection := selection.(type) {
case *ast.Field:
ctx.Gateway.logger.Debug("Encountered field ", selection.Name)
field := &ast.Field{
Name: selection.Name,
Alias: selection.Alias,
Directives: selection.Directives,
Arguments: selection.Arguments,
Definition: selection.Definition,
ObjectDefinition: selection.ObjectDefinition,
SelectionSet: selection.SelectionSet,
}
// look up the location for this field
possibleLocations, err := config.locations.URLFor(config.parentType, selection.Name)
if err != nil {
return nil, nil, err
}
location := p.selectLocation(possibleLocations, config)
locationFields[location] = append(locationFields[location], field)
case *ast.FragmentSpread:
ctx.Gateway.logger.Debug("Encountered fragment spread ", selection.Name)
// a fragments fields can span multiple services so a single fragment can result in many selections being added
fragmentLocations := map[string]ast.SelectionSet{}
// look up if we already have a definition for this fragment in the step
defn := config.step.FragmentDefinitions.ForName(selection.Name)
// if we don't have it
if defn == nil {
// look in the operation
defn = config.plan.FragmentDefinitions.ForName(selection.Name)
if defn == nil {
return nil, nil, fmt.Errorf("Could not find definition for directive: %s", selection.Name)
}
}
// each field in the fragment should be bundled with whats around it (still wrapped in fragment)
for _, fragmentSelection := range defn.SelectionSet {
switch fragmentSelection := fragmentSelection.(type) {
case *ast.Field:
field := &ast.Field{
Name: fragmentSelection.Name,
Alias: fragmentSelection.Alias,
Directives: fragmentSelection.Directives,
Arguments: fragmentSelection.Arguments,
Definition: fragmentSelection.Definition,
ObjectDefinition: fragmentSelection.ObjectDefinition,
SelectionSet: fragmentSelection.SelectionSet,
}
// look up the location of the field
fieldLocations, err := config.locations.URLFor(defn.TypeCondition, field.Name)
if err != nil {
return nil, nil, err
}
fieldLocation := p.selectLocation(fieldLocations, config)
fragmentLocations[fieldLocation] = append(fragmentLocations[fieldLocation], field)
case *ast.FragmentSpread, *ast.InlineFragment:
// non-field selections will be handled in the next tick
// add it to the current location so we don't create a new step if its not needed
fragmentLocations[config.parentLocation] = append(fragmentLocations[config.parentLocation], fragmentSelection)
}
}
// for each bundle under a fragment
for location, selectionSet := range fragmentLocations {
// add the fragment spread to the selection set for this location
locationFields[location] = append(locationFields[location], &ast.FragmentSpread{
Name: selection.Name,
Directives: selection.Directives,
})
// since the fragment can only refer to fields in the top level that are at
// the same location we need to add a new definition of the
locationFragments[location] = append(locationFragments[location], &ast.FragmentDefinition{
Name: selection.Name,
TypeCondition: defn.TypeCondition,
SelectionSet: selectionSet,
})
}
case *ast.InlineFragment:
ctx.Gateway.logger.Debug("Encountered inline fragment on ", selection.TypeCondition)
// we need to split the inline fragment into an inline fragment for each location that this cover
// and then add those inline fragments to the final selection
fragmentLocations := map[string]ast.SelectionSet{}
// each field in the fragment should be bundled with whats around it (still wrapped in fragment)
for _, fragmentSelection := range selection.SelectionSet {
switch fragmentSelection := fragmentSelection.(type) {
case *ast.Field:
// look up the location of the field
fieldLocations, err := config.locations.URLFor(selection.TypeCondition, fragmentSelection.Name)
if err != nil {
return nil, nil, err
}
// add the field to the location
fragmentLocations[fieldLocations[0]] = append(fragmentLocations[fieldLocations[0]], fragmentSelection)
case *ast.FragmentSpread, *ast.InlineFragment:
// non-field selections will be handled in the next tick
// add it to the current location so we don't create a new step if its not needed
fragmentLocations[config.parentLocation] = append(fragmentLocations[config.parentLocation], fragmentSelection)
}
}
// for each bundle under a fragment
for location, selectionSet := range fragmentLocations {
// add the fragment spread to the selection set for this location
locationFields[location] = append(locationFields[location], &ast.InlineFragment{
TypeCondition: selection.TypeCondition,
Directives: selection.Directives,
SelectionSet: selectionSet,
})
}
}
}
return locationFields, locationFragments, nil
}
// This plan results in a query that has fields that were not explicitly asked for.
// In order for the executor to know what to filter out of the final reply,
// we have to leave behind paths to objects that need to be scrubbed.
func (p *MinQueriesPlanner) generateScrubFields(plans QueryPlanList, requestSelection ast.SelectionSet) error {
for _, plan := range plans {
// the list of fields to scrub in this plan
fieldsToScrub := map[string][][]string{"id": {}}
// add all of the plans for the next step along with those from this step
for _, nextStep := range plan.RootStep.Then {
// compute the fields that our children have to add
childScrubs, err := p.generateScrubFieldsWalk(nextStep, requestSelection)
if err != nil {
return err
}
for field, values := range childScrubs {
fieldsToScrub[field] = append(fieldsToScrub[field], values...)
}
}
plan.FieldsToScrub = fieldsToScrub
}
return nil
}
func (p *MinQueriesPlanner) generateScrubFieldsWalk(step *QueryPlanStep, selection ast.SelectionSet) (map[string][][]string, error) {
// the acumulator of plans
acc := map[string][][]string{}
insertionPoint := step.InsertionPoint
targetSelection := selection
// we need to look if this steps insertion point artificially asked for the id
for _, point := range insertionPoint {
foundField := false
// look over the points in the selection
for _, field := range graphql.SelectedFields(targetSelection) {
// if the field name is what we expected
if field.Name == point || field.Alias == point {
// our next selection set is the fields selection set
targetSelection = field.SelectionSet
// we found the field for this point
foundField = true
break
}
}
if !foundField {
return nil, fmt.Errorf("error adding scrub fields: could not find field for point %s", point)
}
}
// look through the selection for a field named id
naturalID := false
for _, field := range graphql.SelectedFields(targetSelection) {
// if the field is for id
if field.Alias == "id" {
naturalID = true
}
}
// if the id was not natural and we were going to be inserted somewhere
if !naturalID && len(insertionPoint) > 0 {
// we have to add this insertion point to the list places to scrub
acc["id"] = append(acc["id"], insertionPoint)
}
// add all of the plans for the next step along with those from this step
for _, nextStep := range step.Then {
// compute the fields that our children have to add
childScrubs, err := p.generateScrubFieldsWalk(nextStep, selection)
if err != nil {
return nil, err
}
for id, values := range childScrubs {
acc[id] = append(acc[id], values...)
}
}
return acc, nil
}
func coreFieldType(source *ast.Field) *ast.Type {
// if we are looking at a
return source.Definition.Type
}
// Set is a set
type Set map[string]bool
// Add adds the item to the set
func (set Set) Add(k string) {
set[k] = true
}
// Remove removes the item from the set
func (set Set) Remove(k string) {
delete(set, k)
}
// Has returns wether or not the string is in the set
func (set Set) Has(k string) bool {
_, ok := set[k]
return ok
}
// GetQueryer returns the queryer that should be used to resolve the plan
func (p *Planner) GetQueryer(ctx *PlanningContext, url string) graphql.Queryer {
// if we are looking to query the local schema
if url == internalSchemaLocation {
return ctx.Gateway
}
// if there is a queryer factory defined
if p.QueryerFactory != nil {
// use the factory
return (*p.QueryerFactory)(ctx, url)
}
// return the queryer for the url
return graphql.NewSingleRequestQueryer(url)
}
func plannerBuildQuery(ctx *PlanningContext, operationName, parentType string, variables ast.VariableDefinitionList, selectionSet ast.SelectionSet, fragmentDefinitions ast.FragmentDefinitionList) *ast.QueryDocument {
ctx.Gateway.logger.Debug("Building Query: \n"+"\tParentType: ", parentType, " ")
// build up an operation for the query
operation := &ast.OperationDefinition{
VariableDefinitions: variables,
Name: operationName,
}
// assign the right operation
switch parentType {
case typeNameMutation:
operation.Operation = ast.Mutation
case typeNameSubscription:
operation.Operation = ast.Subscription
default:
operation.Operation = ast.Query
}
// if we are querying an operation all we need to do is add the selection set at the root
if parentType == typeNameQuery || parentType == typeNameMutation || parentType == typeNameSubscription {
operation.SelectionSet = selectionSet
} else {
// if we are not querying the top level then we have to embed the selection set
// under the node query with the right id as the argument
// we want the operation to have the equivalent of
// {
// node(id: $id) {
// ... on parentType {
// selection
// }
// }
// }
operation.SelectionSet = ast.SelectionSet{
&ast.Field{
Name: "node",
Arguments: ast.ArgumentList{
&ast.Argument{
Name: "id",
Value: &ast.Value{
Kind: ast.Variable,
Raw: "id",
},
},
},
SelectionSet: ast.SelectionSet{
&ast.InlineFragment{
TypeCondition: parentType,
SelectionSet: selectionSet,
},
},
},
}
// if the original query didn't have an id arg we need to add one
if variables.ForName("id") == nil {
operation.VariableDefinitions = append(operation.VariableDefinitions, &ast.VariableDefinition{
Variable: "id",
Type: ast.NonNullNamedType("ID", &ast.Position{}),
})
}
}
// add the operation to a QueryDocument
return &ast.QueryDocument{
Operations: ast.OperationList{operation},
Fragments: fragmentDefinitions,
}
}
// MockErrPlanner always returns the provided error. Useful in testing.
type MockErrPlanner struct {
Err error
}
func (p *MockErrPlanner) Plan(*PlanningContext) (QueryPlanList, error) {
return nil, p.Err
}
// MockPlanner always returns the provided list of plans. Useful in testing.
type MockPlanner struct {
Plans QueryPlanList
}
func (p *MockPlanner) Plan(*PlanningContext) (QueryPlanList, error) {
return p.Plans, nil
}
// QueryPlanList is a list of plans which can be indexed by operation name
type QueryPlanList []*QueryPlan
// ForOperation returns the query plan meant to satisfy the given operation name
func (l QueryPlanList) ForOperation(name string) (*QueryPlan, error) {
// look over every plan in the list for the operation with the matching name
for _, plan := range l {