-
Notifications
You must be signed in to change notification settings - Fork 55
/
execution.go
672 lines (585 loc) · 19.4 KB
/
execution.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
package bramble
import (
"context"
"errors"
"fmt"
"os"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/vektah/gqlparser/v2/ast"
"github.com/vektah/gqlparser/v2/gqlerror"
"golang.org/x/sync/errgroup"
)
var errNullBubbledToRoot = errors.New("bubbleUpNullValuesInPlace: null bubbled up to root")
type executionResult struct {
ServiceURL string
InsertionPoint []string
Data interface{}
Errors gqlerror.List
}
type queryExecution struct {
ctx context.Context
operationName string
schema *ast.Schema
requestCount int32
maxRequest int32
graphqlClient *GraphQLClient
boundaryFields BoundaryFieldsMap
group *errgroup.Group
results chan executionResult
}
func newQueryExecution(ctx context.Context, operationName string, client *GraphQLClient, schema *ast.Schema, boundaryFields BoundaryFieldsMap, maxRequest int32) *queryExecution {
group, ctx := errgroup.WithContext(ctx)
return &queryExecution{
ctx: ctx,
operationName: operationName,
schema: schema,
graphqlClient: client,
boundaryFields: boundaryFields,
maxRequest: maxRequest,
group: group,
results: make(chan executionResult),
}
}
func (q *queryExecution) Execute(queryPlan *QueryPlan) ([]executionResult, gqlerror.List) {
wg := &sync.WaitGroup{}
results := []executionResult{}
for _, step := range queryPlan.RootSteps {
if step.ServiceURL == internalServiceName {
reqStart := time.Now()
r, err := executeBrambleStep(step)
if err != nil {
return nil, q.createGQLErrors(step, err)
}
step.executionResult = &executionStepResult{
executed: true,
error: err,
timeTaken: time.Since(reqStart),
}
results = append(results, *r)
continue
}
step := step
q.group.Go(func() error {
return q.executeRootStep(step)
})
}
wg.Add(1)
go func() {
for result := range q.results {
results = append(results, result)
}
wg.Done()
}()
if err := q.group.Wait(); err != nil {
return nil, gqlerror.List{
&gqlerror.Error{
Message: err.Error(),
},
}
}
close(q.results)
wg.Wait()
return results, nil
}
func (q *queryExecution) executeRootStep(step *QueryPlanStep) error {
var document string
reqStart := time.Now()
var variables map[string]interface{}
switch step.ParentType {
case queryObjectName, mutationObjectName:
document, variables = formatDocument(q.ctx, q.schema, step.ParentType, step.SelectionSet)
default:
return errors.New("expected mutation or query root step")
}
req := NewRequest(document).
WithVariables(variables).
WithHeaders(GetOutgoingRequestHeadersFromContext(q.ctx)).
WithOperationName(q.operationName).
WithOperationType(step.ParentType)
var data map[string]interface{}
err := q.graphqlClient.Request(q.ctx, step.ServiceURL, req, &data)
q.writeExecutionResult(step, data, err)
step.executionResult = &executionStepResult{
executed: true,
error: err,
timeTaken: time.Since(reqStart),
}
if err != nil {
return nil
}
for _, childStep := range step.Then {
boundaryIDs, err := extractAndDedupeBoundaryIDs(data, childStep.InsertionPoint, childStep.ParentType)
if err != nil {
return err
}
if len(boundaryIDs) == 0 {
continue
}
childStep := childStep
q.group.Go(func() error {
return q.executeChildStep(childStep, boundaryIDs)
})
}
return nil
}
func (q *queryExecution) writeExecutionResult(step *QueryPlanStep, data interface{}, err error) {
result := executionResult{
ServiceURL: step.ServiceURL,
InsertionPoint: step.InsertionPoint,
Data: data,
}
if err != nil {
result.Errors = q.createGQLErrors(step, err)
}
q.results <- result
}
func (q *queryExecution) executeChildStep(step *QueryPlanStep, boundaryIDs []string) error {
newRequestCount := atomic.AddInt32(&q.requestCount, 1)
if newRequestCount > q.maxRequest {
return fmt.Errorf("exceeded max requests of %v", q.maxRequest)
}
reqStart := time.Now()
boundaryField, err := q.boundaryFields.Field(step.ServiceURL, step.ParentType)
if err != nil {
return err
}
documents, variables, err := buildBoundaryQueryDocuments(q.ctx, q.schema, step, boundaryIDs, boundaryField, 50)
if err != nil {
return err
}
data, err := q.executeBoundaryQuery(documents, step.ServiceURL, variables, boundaryField)
q.writeExecutionResult(step, data, err)
step.executionResult = &executionStepResult{
executed: true,
error: err,
timeTaken: time.Since(reqStart),
}
if err != nil {
return nil
}
nonNilBoundaryResults := extractNonNilBoundaryResults(data)
if len(nonNilBoundaryResults) > 0 {
for _, childStep := range step.Then {
boundaryResultInsertionPoint, err := trimInsertionPointForNestedBoundaryStep(nonNilBoundaryResults, childStep.InsertionPoint)
if err != nil {
return err
}
boundaryIDs, err := extractAndDedupeBoundaryIDs(nonNilBoundaryResults, boundaryResultInsertionPoint, childStep.ParentType)
if err != nil {
return err
}
if len(boundaryIDs) == 0 {
continue
}
childStep := childStep
q.group.Go(func() error {
return q.executeChildStep(childStep, boundaryIDs)
})
}
}
return nil
}
func extractNonNilBoundaryResults(data []interface{}) []interface{} {
var nonNilResults []interface{}
for _, d := range data {
if d == nil {
continue
}
nonNilResults = append(nonNilResults, d)
}
return nonNilResults
}
func (q *queryExecution) executeBoundaryQuery(documents []string, serviceURL string, variables map[string]interface{}, boundaryFieldGetter BoundaryField) ([]interface{}, error) {
output := make([]interface{}, 0)
if !boundaryFieldGetter.Array {
for _, document := range documents {
req := NewRequest(document).
WithVariables(variables).
WithHeaders(GetOutgoingRequestHeadersFromContext(q.ctx)).
WithOperationName(q.operationName).
WithOperationType(queryObjectName)
partialData := make(map[string]interface{})
err := q.graphqlClient.Request(q.ctx, serviceURL, req, &partialData)
if err != nil {
return nil, err
}
for _, value := range partialData {
output = append(output, value)
}
}
return output, nil
}
if len(documents) != 1 {
return nil, errors.New("there should only be a single document for array boundary field lookups")
}
data := struct {
Result []interface{} `json:"_result"`
}{}
req := NewRequest(documents[0]).
WithVariables(variables).
WithHeaders(GetOutgoingRequestHeadersFromContext(q.ctx)).
WithOperationName(q.operationName).
WithOperationType(queryObjectName)
err := q.graphqlClient.Request(q.ctx, serviceURL, req, &data)
return data.Result, err
}
func (q *queryExecution) createGQLErrors(step *QueryPlanStep, err error) gqlerror.List {
var path ast.Path
for _, p := range step.InsertionPoint {
path = append(path, ast.PathName(p))
}
var locs []gqlerror.Location
for _, f := range selectionSetToFields(step.SelectionSet) {
pos := f.GetPosition()
if pos == nil {
continue
}
locs = append(locs, gqlerror.Location{Line: pos.Line, Column: pos.Column})
// if the field has a selection set it's part of the path
if len(f.SelectionSet) > 0 {
path = append(path, ast.PathName(f.Alias))
}
}
var gqlErr GraphqlErrors
var outputErrs gqlerror.List
switch {
case errors.As(err, &gqlErr):
for _, ge := range gqlErr {
extensions := ge.Extensions
if extensions == nil {
extensions = make(map[string]interface{})
}
extensions["selectionSet"] = formatSelectionSetSingleLine(q.ctx, q.schema, step.SelectionSet)
extensions["selectionPath"] = path
extensions["serviceName"] = step.ServiceName
extensions["serviceUrl"] = step.ServiceURL
outputErrs = append(outputErrs, &gqlerror.Error{
Err: err,
Message: ge.Message,
Path: ge.Path,
Locations: locs,
Extensions: extensions,
Rule: "",
})
}
return outputErrs
case os.IsTimeout(err):
outputErrs = append(outputErrs, &gqlerror.Error{
Err: err,
Message: "downstream request timed out",
Path: path,
Locations: locs,
Extensions: map[string]interface{}{
"selectionSet": formatSelectionSetSingleLine(q.ctx, q.schema, step.SelectionSet),
},
Rule: "",
})
default:
outputErrs = append(outputErrs, &gqlerror.Error{
Err: err,
Message: err.Error(),
Path: path,
Locations: locs,
Extensions: map[string]interface{}{
"selectionSet": formatSelectionSetSingleLine(q.ctx, q.schema, step.SelectionSet),
},
Rule: "",
})
}
return outputErrs
}
// The insertionPoint represents the level a piece of data should be inserted at, relative to the root of the root step's data.
// However results from a boundary query only contain a portion of that tree. For example, you could
// have insertionPoint: ["foo", "bar", "movies", "movie", "compTitles"], with the below example as the boundary result we're
// crawling for ids:
// [
//
// {
// "_bramble_id": "MOVIE1",
// "compTitles": [
// {
// "_bramble_id": "1"
// }
// ]
// }
//
// ]
//
// We therefore cannot use the insertionPoint as is in order to extract the boundary ids for the next child step.
// This function trims the insertionPoint up until we find a key that exists in both the boundary result and insertionPoint.
// When a match is found, the remainder of the insertionPoint is used, which in this case is only ["compTitles"].
// This logic is only needed when we are already in a child step, which itself contains it's own child steps.
func trimInsertionPointForNestedBoundaryStep(data []interface{}, childInsertionPoint []string) ([]string, error) {
if len(data) == 0 {
return nil, fmt.Errorf("no boundary results to process")
}
firstBoundaryResult, ok := data[0].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("a single boundary result should be a map[string]interface{}")
}
for i, point := range childInsertionPoint {
_, ok := firstBoundaryResult[point]
if ok {
return childInsertionPoint[i:], nil
}
}
return nil, fmt.Errorf("could not find any insertion points inside boundary data")
}
func executeBrambleStep(queryPlanStep *QueryPlanStep) (*executionResult, error) {
result, err := buildTypenameResponseMap(queryPlanStep.SelectionSet, queryPlanStep.ParentType)
if err != nil {
return nil, err
}
return &executionResult{
ServiceURL: internalServiceName,
InsertionPoint: []string{},
Data: result,
}, nil
}
func buildTypenameResponseMap(selectionSet ast.SelectionSet, parentTypeName string) (map[string]interface{}, error) {
result := make(map[string]interface{})
for _, field := range selectionSetToFields(selectionSet) {
if field.SelectionSet != nil {
if field.Definition.Type.NamedType == "" {
return nil, fmt.Errorf("buildTypenameResponseMap: expected named type")
}
var err error
result[field.Alias], err = buildTypenameResponseMap(field.SelectionSet, field.Definition.Type.Name())
if err != nil {
return nil, err
}
} else {
if field.Name != "__typename" {
return nil, fmt.Errorf("buildTypenameResponseMap: expected __typename")
}
result[field.Alias] = parentTypeName
}
}
return result, nil
}
func extractAndDedupeBoundaryIDs(data interface{}, insertionPoint []string, parentType string) ([]string, error) {
boundaryIDs, err := extractBoundaryIDs(data, insertionPoint, parentType)
if err != nil {
return nil, err
}
dedupeMap := make(map[string]struct{}, len(boundaryIDs))
for _, boundaryID := range boundaryIDs {
dedupeMap[boundaryID] = struct{}{}
}
deduped := make([]string, 0, len(boundaryIDs))
for id := range dedupeMap {
deduped = append(deduped, id)
}
return deduped, nil
}
func extractBoundaryIDs(data interface{}, insertionPoint []string, parentType string) ([]string, error) {
ptr := data
if ptr == nil {
return nil, nil
}
if len(insertionPoint) == 0 {
switch ptr := ptr.(type) {
case map[string]interface{}:
tpe, err := boundaryTypeFromMap(ptr)
if err != nil {
return nil, err
}
if tpe != parentType {
return []string{}, nil
}
id, err := boundaryIDFromMap(ptr)
return []string{id}, err
case []interface{}:
var result []string
for _, innerPtr := range ptr {
ids, err := extractBoundaryIDs(innerPtr, insertionPoint, parentType)
if err != nil {
return nil, err
}
result = append(result, ids...)
}
return result, nil
default:
return nil, fmt.Errorf("extractBoundaryIDs: unexpected type: %T", ptr)
}
}
switch ptr := ptr.(type) {
case map[string]interface{}:
return extractBoundaryIDs(ptr[insertionPoint[0]], insertionPoint[1:], parentType)
case []interface{}:
var result []string
for _, innerPtr := range ptr {
ids, err := extractBoundaryIDs(innerPtr, insertionPoint, parentType)
if err != nil {
return nil, err
}
result = append(result, ids...)
}
return result, nil
default:
return nil, fmt.Errorf("extractBoundaryIDs: unexpected type: %T", ptr)
}
}
func buildBoundaryQueryDocuments(ctx context.Context, schema *ast.Schema, step *QueryPlanStep, ids []string, parentTypeBoundaryField BoundaryField, batchSize int) ([]string, map[string]interface{}, error) {
operation, variables := formatOperation(ctx, step.SelectionSet)
selectionSetQL := formatSelectionSetSingleLine(ctx, schema, step.SelectionSet)
if parentTypeBoundaryField.Array {
var qids []string
for _, id := range ids {
qids = append(qids, fmt.Sprintf("%q", id))
}
idsQL := fmt.Sprintf("[%s]", strings.Join(qids, ", "))
return []string{fmt.Sprintf(`query %s { _result: %s(%s: %s) %s }`, operation, parentTypeBoundaryField.Field, parentTypeBoundaryField.Argument, idsQL, selectionSetQL)}, variables, nil
}
var (
documents []string
selectionIndex int
)
for _, batch := range batchBy(ids, batchSize) {
var selections []string
for _, id := range batch {
selection := fmt.Sprintf("%s: %s(%s: %q) %s", fmt.Sprintf("_%d", selectionIndex), parentTypeBoundaryField.Field, parentTypeBoundaryField.Argument, id, selectionSetQL)
selections = append(selections, selection)
selectionIndex++
}
document := fmt.Sprintf("query %s { %s }", operation, strings.Join(selections, " "))
documents = append(documents, document)
}
return documents, variables, nil
}
func batchBy(items []string, batchSize int) (batches [][]string) {
for batchSize < len(items) {
items, batches = items[batchSize:], append(batches, items[0:batchSize:batchSize])
}
return append(batches, items)
}
// When formatting the response data, the shape of the selection set has to potentially be modified to more closely resemble the shape
// of the response. This only happens when running into fragments, there are two cases we need to deal with:
// 1. the selection set of the target fragment has to be unioned with the selection set at the level for which the target fragment is referenced
// 2. if the target fragments are an implementation of an abstract type, we need to use the __typename from the response body to check which
// implementation was resolved. Any fragments that do not match are dropped from the selection set.
func unionAndTrimSelectionSet(responseObjectTypeName string, schema *ast.Schema, selectionSet ast.SelectionSet) ast.SelectionSet {
filteredSelectionSet := eliminateUnwantedFragments(responseObjectTypeName, schema, selectionSet)
return mergeWithTopLevelFragmentFields(filteredSelectionSet)
}
func eliminateUnwantedFragments(responseObjectTypeName string, schema *ast.Schema, selectionSet ast.SelectionSet) ast.SelectionSet {
var filteredSelectionSet ast.SelectionSet
for _, selection := range selectionSet {
var (
fragmentObjectDefinition *ast.Definition
fragmentTypeCondition string
)
switch selection := selection.(type) {
case *ast.Field:
filteredSelectionSet = append(filteredSelectionSet, selection)
case *ast.InlineFragment:
fragmentObjectDefinition = selection.ObjectDefinition
fragmentTypeCondition = selection.TypeCondition
case *ast.FragmentSpread:
fragmentObjectDefinition = selection.ObjectDefinition
fragmentTypeCondition = selection.Definition.TypeCondition
}
if fragmentObjectDefinition != nil && includeFragment(responseObjectTypeName, schema, fragmentObjectDefinition, fragmentTypeCondition) {
filteredSelectionSet = append(filteredSelectionSet, selection)
}
}
return filteredSelectionSet
}
func includeFragment(responseObjectTypeName string, schema *ast.Schema, objectDefinition *ast.Definition, typeCondition string) bool {
return !(objectDefinition.IsAbstractType() &&
fragmentImplementsAbstractType(schema, objectDefinition.Name, typeCondition) &&
objectTypenameMatchesDifferentFragment(responseObjectTypeName, typeCondition))
}
func fragmentImplementsAbstractType(schema *ast.Schema, abstractObjectTypename, fragmentTypeDefinition string) bool {
for _, def := range schema.Implements[fragmentTypeDefinition] {
if def.Name == abstractObjectTypename {
return true
}
}
return false
}
func objectTypenameMatchesDifferentFragment(typename, fragmentTypeCondition string) bool {
return fragmentTypeCondition != typename
}
func mergeWithTopLevelFragmentFields(selectionSet ast.SelectionSet) ast.SelectionSet {
merged := newSelectionSetMerger()
for _, selection := range selectionSet {
switch selection := selection.(type) {
case *ast.Field:
merged.addField(selection)
case *ast.InlineFragment:
fragment := selection
merged.addInlineFragment(fragment)
case *ast.FragmentSpread:
fragment := selection
merged.addFragmentSpread(fragment)
}
}
return merged.selectionSet
}
type selectionSetMerger struct {
selectionSet ast.SelectionSet
seenFields map[string]*ast.Field
}
func newSelectionSetMerger() *selectionSetMerger {
return &selectionSetMerger{
selectionSet: []ast.Selection{},
seenFields: make(map[string]*ast.Field),
}
}
func (s *selectionSetMerger) addField(field *ast.Field) {
shouldAppend := s.shouldAppendField(field)
if shouldAppend {
s.selectionSet = append(s.selectionSet, field)
}
}
func (s *selectionSetMerger) shouldAppendField(field *ast.Field) bool {
if seenField, ok := s.seenFields[field.Alias]; ok {
if seenField.Name == field.Name && seenField.SelectionSet != nil && field.SelectionSet != nil {
seenField.SelectionSet = append(seenField.SelectionSet, field.SelectionSet...)
}
return false
} else {
s.seenFields[field.Alias] = field
return true
}
}
func (s *selectionSetMerger) addInlineFragment(fragment *ast.InlineFragment) {
dedupedSelectionSet := s.dedupeFragmentSelectionSet(fragment.SelectionSet)
if len(dedupedSelectionSet) > 0 {
fragment.SelectionSet = dedupedSelectionSet
s.selectionSet = append(s.selectionSet, fragment)
}
}
func (s *selectionSetMerger) addFragmentSpread(fragment *ast.FragmentSpread) {
dedupedSelectionSet := s.dedupeFragmentSelectionSet(fragment.Definition.SelectionSet)
if len(dedupedSelectionSet) > 0 {
fragment.Definition.SelectionSet = dedupedSelectionSet
s.selectionSet = append(s.selectionSet, fragment)
}
}
func (s *selectionSetMerger) dedupeFragmentSelectionSet(selectionSet ast.SelectionSet) ast.SelectionSet {
var filteredSelectionSet ast.SelectionSet
for _, selection := range selectionSet {
switch selection := selection.(type) {
case *ast.Field:
shouldAppend := s.shouldAppendField(selection)
if shouldAppend {
filteredSelectionSet = append(filteredSelectionSet, selection)
}
case *ast.InlineFragment, *ast.FragmentSpread:
filteredSelectionSet = append(filteredSelectionSet, selection)
}
}
return filteredSelectionSet
}
func extractAndCastTypenameField(result map[string]interface{}) string {
typeNameInterface, ok := result["_bramble__typename"]
if !ok {
return ""
}
return typeNameInterface.(string)
}