-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
resolver.go
2290 lines (2036 loc) · 69.6 KB
/
resolver.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
/*
* Copyright 2019 Dgraph Labs, Inc. and Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package resolve
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/dgraph-io/dgraph/graphql/authorization"
"github.com/dgraph-io/dgraph/edgraph"
"github.com/dgraph-io/dgraph/graphql/dgraph"
"github.com/dgraph-io/dgraph/types"
dgoapi "github.com/dgraph-io/dgo/v200/protos/api"
"github.com/dgraph-io/dgraph/graphql/api"
"github.com/dgraph-io/dgraph/x"
"github.com/pkg/errors"
"go.opencensus.io/trace"
otrace "go.opencensus.io/trace"
"github.com/golang/glog"
"github.com/dgraph-io/dgraph/graphql/schema"
)
type resolveCtxKey string
const (
methodResolve = "RequestResolver.Resolve"
resolveStartTime resolveCtxKey = "resolveStartTime"
resolverFailed = false
resolverSucceeded = true
errExpectedScalar = "A scalar type was returned, but GraphQL was expecting an object. " +
"This indicates an internal error - " +
"probably a mismatch between the GraphQL and Dgraph/remote schemas. " +
"The value was resolved as null (which may trigger GraphQL error propagation) " +
"and as much other data as possible returned."
errExpectedObject = "A list was returned, but GraphQL was expecting just one item. " +
"This indicates an internal error - " +
"probably a mismatch between the GraphQL and Dgraph/remote schemas. " +
"The value was resolved as null (which may trigger GraphQL error propagation) " +
"and as much other data as possible returned."
errExpectedList = "An object was returned, but GraphQL was expecting a list of objects. " +
"This indicates an internal error - " +
"probably a mismatch between the GraphQL and Dgraph/remote schemas. " +
"The value was resolved as null (which may trigger GraphQL error propagation) " +
"and as much other data as possible returned."
errInternal = "Internal error"
errExpectedNonNull = "Non-nullable field '%s' (type %s) was not present in result from Dgraph. " +
"GraphQL error propagation triggered."
)
// A ResolverFactory finds the right resolver for a query/mutation.
type ResolverFactory interface {
queryResolverFor(query schema.Query) QueryResolver
mutationResolverFor(mutation schema.Mutation) MutationResolver
// WithQueryResolver adds a new query resolver. Each time query name is resolved
// resolver is called to create a new instance of a QueryResolver to resolve the
// query.
WithQueryResolver(name string, resolver func(schema.Query) QueryResolver) ResolverFactory
// WithMutationResolver adds a new query resolver. Each time mutation name is resolved
// resolver is called to create a new instance of a MutationResolver to resolve the
// mutation.
WithMutationResolver(
name string, resolver func(schema.Mutation) MutationResolver) ResolverFactory
// WithConventionResolvers adds a set of our convention based resolvers to the
// factory. The registration happens only once.
WithConventionResolvers(s schema.Schema, fns *ResolverFns) ResolverFactory
// WithQueryMiddlewareConfig adds the configuration to use to apply middlewares before resolving
// queries. The config should be a mapping of the name of query to its middlewares.
WithQueryMiddlewareConfig(config map[string]QueryMiddlewares) ResolverFactory
// WithMutationMiddlewareConfig adds the configuration to use to apply middlewares before
// resolving mutations. The config should be a mapping of the name of mutation to its
// middlewares.
WithMutationMiddlewareConfig(config map[string]MutationMiddlewares) ResolverFactory
// WithSchemaIntrospection adds schema introspection capabilities to the factory.
// So __schema and __type queries can be resolved.
WithSchemaIntrospection() ResolverFactory
}
// A ResultCompleter can take a []byte slice representing an intermediate result
// in resolving field and applies a completion step - for example, apply GraphQL
// error propagation or massaging error paths.
type ResultCompleter interface {
Complete(ctx context.Context, resolved *Resolved)
}
// RequestResolver can process GraphQL requests and write GraphQL JSON responses.
// A schema.Request may contain any number of queries or mutations (never both).
// RequestResolver.Resolve() resolves all of them by finding the resolved answers
// of the component queries/mutations and joining into a single schema.Response.
type RequestResolver struct {
schema schema.Schema
resolvers ResolverFactory
}
// A resolverFactory is the main implementation of ResolverFactory. It stores a
// map of all the resolvers that have been registered and returns a resolver that
// just returns errors if it's asked for a resolver for a field that it doesn't
// know about.
type resolverFactory struct {
sync.RWMutex
queryResolvers map[string]func(schema.Query) QueryResolver
mutationResolvers map[string]func(schema.Mutation) MutationResolver
queryMiddlewareConfig map[string]QueryMiddlewares
mutationMiddlewareConfig map[string]MutationMiddlewares
// returned if the factory gets asked for resolver for a field that it doesn't
// know about.
queryError QueryResolverFunc
mutationError MutationResolverFunc
}
// ResolverFns is a convenience struct for passing blocks of rewriters and executors.
type ResolverFns struct {
Qrw QueryRewriter
Arw func() MutationRewriter
Urw func() MutationRewriter
Drw MutationRewriter
Ex DgraphExecutor
}
// dgraphExecutor is an implementation of both QueryExecutor and MutationExecutor
// that proxies query/mutation resolution through Query method in dgraph server.
type dgraphExecutor struct {
dg *dgraph.DgraphEx
}
// adminExecutor is an implementation of both QueryExecutor and MutationExecutor
// that proxies query resolution through Query method in dgraph server, and
// it doesn't require authorization. Currently it's only used for querying
// gqlschema during init.
type adminExecutor struct {
dg *dgraph.DgraphEx
}
// A Resolved is the result of resolving a single field - generally a query or mutation.
type Resolved struct {
Data interface{}
Field schema.Field
Err error
Extensions *schema.Extensions
}
// restErr is Error returned from custom REST endpoint
type restErr struct {
Errors x.GqlErrorList `json:"errors,omitempty"`
}
// CompletionFunc is an adapter that allows us to compose completions and build a
// ResultCompleter from a function. Based on the http.HandlerFunc pattern.
type CompletionFunc func(ctx context.Context, resolved *Resolved)
// Complete calls cf(ctx, resolved)
func (cf CompletionFunc) Complete(ctx context.Context, resolved *Resolved) {
cf(ctx, resolved)
}
// NewDgraphExecutor builds a DgraphExecutor for proxying requests through dgraph.
func NewDgraphExecutor() DgraphExecutor {
return newDgraphExecutor(&dgraph.DgraphEx{})
}
func newDgraphExecutor(dg *dgraph.DgraphEx) DgraphExecutor {
return &dgraphExecutor{dg: dg}
}
// NewAdminExecutor builds a DgraphExecutor for proxying requests through dgraph.
func NewAdminExecutor() DgraphExecutor {
return &adminExecutor{dg: &dgraph.DgraphEx{}}
}
func (aex *adminExecutor) Execute(ctx context.Context, req *dgoapi.Request) (
*dgoapi.Response, error) {
ctx = context.WithValue(ctx, edgraph.Authorize, false)
return aex.dg.Execute(ctx, req)
}
func (aex *adminExecutor) CommitOrAbort(ctx context.Context, tc *dgoapi.TxnContext) error {
return aex.dg.CommitOrAbort(ctx, tc)
}
func (de *dgraphExecutor) Execute(ctx context.Context, req *dgoapi.Request) (
*dgoapi.Response, error) {
return de.dg.Execute(ctx, req)
}
func (de *dgraphExecutor) CommitOrAbort(ctx context.Context, tc *dgoapi.TxnContext) error {
return de.dg.CommitOrAbort(ctx, tc)
}
func (rf *resolverFactory) WithQueryResolver(
name string, resolver func(schema.Query) QueryResolver) ResolverFactory {
rf.Lock()
defer rf.Unlock()
rf.queryResolvers[name] = resolver
return rf
}
func (rf *resolverFactory) WithMutationResolver(
name string, resolver func(schema.Mutation) MutationResolver) ResolverFactory {
rf.Lock()
defer rf.Unlock()
rf.mutationResolvers[name] = resolver
return rf
}
func (rf *resolverFactory) WithSchemaIntrospection() ResolverFactory {
return rf.
WithQueryResolver("__schema",
func(q schema.Query) QueryResolver {
return QueryResolverFunc(resolveIntrospection)
}).
WithQueryResolver("__type",
func(q schema.Query) QueryResolver {
return QueryResolverFunc(resolveIntrospection)
}).
WithQueryResolver("__typename",
func(q schema.Query) QueryResolver {
return QueryResolverFunc(resolveIntrospection)
})
}
func (rf *resolverFactory) WithConventionResolvers(
s schema.Schema, fns *ResolverFns) ResolverFactory {
queries := append(s.Queries(schema.GetQuery), s.Queries(schema.FilterQuery)...)
queries = append(queries, s.Queries(schema.PasswordQuery)...)
queries = append(queries, s.Queries(schema.AggregateQuery)...)
for _, q := range queries {
rf.WithQueryResolver(q, func(q schema.Query) QueryResolver {
return NewQueryResolver(fns.Qrw, fns.Ex, StdQueryCompletion())
})
}
rf.WithQueryResolver("_entities", func(q schema.Query) QueryResolver {
return QueryResolverFunc(func(ctx context.Context, query schema.Query) *Resolved {
// Input Argument to the Query is a List of "__typename" and "keyField" pair.
// For this type Extension:-
// extend type Product @key(fields: "upc") {
// upc: String @external
// reviews: [Review]
// }
// Input to the Query will be
// "_representations": [
// {
// "__typename": "Product",
// "upc": "B00005N5PF"
// },
// ...
// ]
representations := query.ArgValue("representations").([]interface{})
typeNames := make([]string, 0)
keyFieldValueList := make([]string, 0)
for _, rep := range representations {
representation, ok := rep.(map[string]interface{})
if !ok {
return &Resolved{
Err: fmt.Errorf("Got Error in Unmarshalling Input Argument"),
}
}
typename, ok := representation["__typename"].(string)
if !ok {
return &Resolved{
Err: fmt.Errorf("Unable to extract __typename from input"),
}
}
// Store all the typeNames into an Array to perfrom Validation at last.
typeNames = append(typeNames, typename)
keyFieldName, err := query.KeyField(typename)
if err != nil {
return &Resolved{
Err: err,
}
}
keyFieldValue, ok := representation[keyFieldName].(string)
if !ok {
return &Resolved{
Err: fmt.Errorf("Unable to Extract value for %s", keyFieldValue),
}
}
keyFieldValueList = append(keyFieldValueList, keyFieldValue)
}
// Since We have Restricted that All the typeNames for the inputs in the
// representation List should be same, we need to validate it and throw error
// if represenation of more than one type exists.
for _, typ := range typeNames {
if typ != typeNames[0] {
return &Resolved{
Err: fmt.Errorf("Expecting All the representations of the type %s, Got %s", typeNames[0], typ),
}
}
}
// Construct Filter Query to resolve the Type. Few things need to be understood.
// 1. We have restricted the representation to only one type there is only one filter query.
// 2. We are using filter Query to resolve the Fields so filter queries must not be turned off in the Schema.
qr, err := schema.ConstructFilterQueryFromKeyField(keyFieldValueList, typeNames[0], "_entities", query.Operation(), query.SelectionSet())
if err != nil {
return &Resolved{
Err: err,
}
}
return rf.queryResolverFor(qr).Resolve(ctx, qr)
})
})
for _, q := range s.Queries(schema.HTTPQuery) {
rf.WithQueryResolver(q, func(q schema.Query) QueryResolver {
return NewHTTPQueryResolver(&http.Client{
// TODO - This can be part of a config later.
Timeout: time.Minute,
}, StdQueryCompletion())
})
}
for _, q := range s.Queries(schema.DQLQuery) {
rf.WithQueryResolver(q, func(q schema.Query) QueryResolver {
// DQL queries don't need any QueryRewriter
return NewQueryResolver(nil, fns.Ex, StdQueryCompletion())
})
}
for _, m := range s.Mutations(schema.AddMutation) {
rf.WithMutationResolver(m, func(m schema.Mutation) MutationResolver {
return NewDgraphResolver(fns.Arw(), fns.Ex, StdMutationCompletion(m.Name()))
})
}
for _, m := range s.Mutations(schema.UpdateMutation) {
rf.WithMutationResolver(m, func(m schema.Mutation) MutationResolver {
return NewDgraphResolver(fns.Urw(), fns.Ex, StdMutationCompletion(m.Name()))
})
}
for _, m := range s.Mutations(schema.DeleteMutation) {
rf.WithMutationResolver(m, func(m schema.Mutation) MutationResolver {
return NewDgraphResolver(fns.Drw, fns.Ex, deleteCompletion())
})
}
for _, m := range s.Mutations(schema.HTTPMutation) {
rf.WithMutationResolver(m, func(m schema.Mutation) MutationResolver {
return NewHTTPMutationResolver(&http.Client{
// TODO - This can be part of a config later.
Timeout: time.Minute,
}, StdQueryCompletion())
})
}
return rf
}
func (rf *resolverFactory) WithQueryMiddlewareConfig(
config map[string]QueryMiddlewares) ResolverFactory {
if len(config) != 0 {
rf.queryMiddlewareConfig = config
}
return rf
}
func (rf *resolverFactory) WithMutationMiddlewareConfig(
config map[string]MutationMiddlewares) ResolverFactory {
if len(config) != 0 {
rf.mutationMiddlewareConfig = config
}
return rf
}
// NewResolverFactory returns a ResolverFactory that resolves requests via
// query/mutation rewriting and execution through Dgraph. If the factory gets asked
// to resolve a query/mutation it doesn't know how to rewrite, it uses
// the queryError/mutationError to build an error result.
func NewResolverFactory(
queryError QueryResolverFunc, mutationError MutationResolverFunc) ResolverFactory {
return &resolverFactory{
queryResolvers: make(map[string]func(schema.Query) QueryResolver),
mutationResolvers: make(map[string]func(schema.Mutation) MutationResolver),
queryMiddlewareConfig: make(map[string]QueryMiddlewares),
mutationMiddlewareConfig: make(map[string]MutationMiddlewares),
queryError: queryError,
mutationError: mutationError,
}
}
// StdQueryCompletion is the completion steps that get run for queries
func StdQueryCompletion() CompletionFunc {
return noopCompletion
}
// StdMutationCompletion is the completion steps that get run for add and update mutations
func StdMutationCompletion(name string) CompletionFunc {
return noopCompletion
}
// StdDeleteCompletion is the completion steps that get run for delete mutations
func StdDeleteCompletion(name string) CompletionFunc {
return deleteCompletion()
}
func (rf *resolverFactory) queryResolverFor(query schema.Query) QueryResolver {
rf.RLock()
defer rf.RUnlock()
mws := rf.queryMiddlewareConfig[query.Name()]
if resolver, ok := rf.queryResolvers[query.Name()]; ok {
return mws.Then(resolver(query))
}
return rf.queryError
}
func (rf *resolverFactory) mutationResolverFor(mutation schema.Mutation) MutationResolver {
rf.RLock()
defer rf.RUnlock()
mws := rf.mutationMiddlewareConfig[mutation.Name()]
if resolver, ok := rf.mutationResolvers[mutation.Name()]; ok {
return mws.Then(resolver(mutation))
}
return rf.mutationError
}
// New creates a new RequestResolver.
func New(s schema.Schema, resolverFactory ResolverFactory) *RequestResolver {
return &RequestResolver{
schema: s,
resolvers: resolverFactory,
}
}
// Resolve processes r.GqlReq and returns a GraphQL response.
// r.GqlReq should be set with a request before Resolve is called
// and a schema and backend Dgraph should have been added.
// Resolve records any errors in the response's error field.
func (r *RequestResolver) Resolve(ctx context.Context, gqlReq *schema.Request) *schema.Response {
span := otrace.FromContext(ctx)
stop := x.SpanTimer(span, methodResolve)
defer stop()
if r == nil {
glog.Errorf("Call to Resolve with nil RequestResolver")
return schema.ErrorResponse(errors.New(errInternal))
}
if r.schema == nil {
glog.Errorf("Call to Resolve with no schema")
return schema.ErrorResponse(errors.New(errInternal))
}
startTime := time.Now()
resp := &schema.Response{
Extensions: &schema.Extensions{
Tracing: &schema.Trace{
Version: 1,
StartTime: startTime.Format(time.RFC3339Nano),
},
},
}
defer func() {
endTime := time.Now()
resp.Extensions.Tracing.EndTime = endTime.Format(time.RFC3339Nano)
resp.Extensions.Tracing.Duration = endTime.Sub(startTime).Nanoseconds()
}()
ctx = context.WithValue(ctx, resolveStartTime, startTime)
op, err := r.schema.Operation(gqlReq)
if err != nil {
return schema.ErrorResponse(err)
}
if glog.V(3) {
// don't log the introspection queries they are sent too frequently
// by GraphQL dev tools
if !op.IsQuery() ||
(op.IsQuery() && !strings.HasPrefix(op.Queries()[0].Name(), "__")) {
b, err := json.Marshal(gqlReq.Variables)
if err != nil {
glog.Infof("Failed to marshal variables for logging : %s", err)
}
glog.Infof("Resolving GQL request: \n%s\nWith Variables: \n%s\n",
gqlReq.Query, string(b))
}
}
// resolveQueries will resolve user's queries.
resolveQueries := func() {
// Queries run in parallel and are independent of each other: e.g.
// an error in one query, doesn't affect the others.
var wg sync.WaitGroup
allResolved := make([]*Resolved, len(op.Queries()))
for i, q := range op.Queries() {
wg.Add(1)
go func(q schema.Query, storeAt int) {
defer wg.Done()
defer api.PanicHandler(
func(err error) {
allResolved[storeAt] = &Resolved{
Data: nil,
Field: q,
Err: err,
}
})
allResolved[storeAt] = r.resolvers.queryResolverFor(q).Resolve(ctx, q)
}(q, i)
}
wg.Wait()
// The GraphQL data response needs to be written in the same order as the
// queries in the request.
for _, res := range allResolved {
// Errors and data in the same response is valid. Both WithError and
// AddData handle nil cases.
addResult(resp, res)
}
}
// A single request can contain either queries or mutations - not both.
// GraphQL validation on the request would have caught that error case
// before we get here. At this point, we know it's valid, it's passed
// GraphQL validation and any additional validation we've added. So here,
// we can just execute it.
switch {
case op.IsQuery():
if op.CacheControl() != "" {
resp.Header = make(map[string][]string)
resp.Header.Set(schema.CacheControlHeader, op.CacheControl())
resp.Header.Set("Vary", "Accept-Encoding")
}
resolveQueries()
case op.IsMutation():
// A mutation operation can contain any number of mutation fields. Those should be executed
// serially.
// (spec https://graphql.github.io/graphql-spec/June2018/#sec-Normal-and-Serial-Execution)
//
// The spec is ambiguous about what to do in the case of errors during that serial execution
// - apparently deliberately so; see this comment from Lee Byron:
// https://github.com/graphql/graphql-spec/issues/277#issuecomment-385588590
// and clarification
// https://github.com/graphql/graphql-spec/pull/438
//
// A reasonable interpretation of that is to stop a list of mutations after the first error -
// which seems like the natural semantics and is what we enforce here.
allSuccessful := true
for _, m := range op.Mutations() {
if !allSuccessful {
resp.WithError(x.GqlErrorf(
"Mutation %s was not executed because of a previous error.",
m.ResponseName()).
WithLocations(m.Location()))
continue
}
var res *Resolved
res, allSuccessful = r.resolvers.mutationResolverFor(m).Resolve(ctx, m)
addResult(resp, res)
}
case op.IsSubscription():
resolveQueries()
}
return resp
}
// ValidateSubscription will check the given subscription query is valid or not.
func (r *RequestResolver) ValidateSubscription(req *schema.Request) error {
if r.schema == nil {
glog.Errorf("Call to ValidateSubscription with no schema")
return errors.New(errInternal)
}
op, err := r.schema.Operation(req)
if err != nil {
return err
}
for _, q := range op.Queries() {
for _, field := range q.SelectionSet() {
if err := validateCustomFieldsRecursively(field); err != nil {
return err
}
}
}
return nil
}
// validateCustomFieldsRecursively will return err if the given field is custom or any of its
// children is type of a custom field.
func validateCustomFieldsRecursively(field schema.Field) error {
if has, _ := field.HasCustomDirective(); has {
return x.GqlErrorf("Custom field `%s` is not supported in graphql subscription",
field.Name()).WithLocations(field.Location())
}
for _, f := range field.SelectionSet() {
err := validateCustomFieldsRecursively(f)
if err != nil {
return err
}
}
return nil
}
func addResult(resp *schema.Response, res *Resolved) {
// Errors should report the "path" into the result where the error was found.
//
// The definition of a path in a GraphQL error is here:
// https://graphql.github.io/graphql-spec/June2018/#sec-Errors
// For a query like (assuming field f is of a list type and g is a scalar type):
// - q { f { g } }
// a path to the 2nd item in the f list would look like:
// - [ "q", "f", 2, "g" ]
path := make([]interface{}, 0, maxPathLength(res.Field))
var b []byte
var gqlErr x.GqlErrorList
if res.Data != nil {
b, gqlErr = completeObject(path, []schema.Field{res.Field},
res.Data.(map[string]interface{}))
}
resp.WithError(res.Err)
resp.WithError(gqlErr)
resp.AddData(b)
resp.MergeExtensions(res.Extensions)
}
// noopCompletion just passes back it's result and err arguments
func noopCompletion(ctx context.Context, resolved *Resolved) {}
// Once a result has been returned from Dgraph, that result needs to be worked
// through for two main reasons:
//
// 1) (null insertion)
// Where an edge was requested in a query, but isn't in the store, Dgraph just
// won't return an edge for that in the results. But GraphQL wants those as
// "null" in the result. And then we need to inspect those nulls via pt (2)
//
// 2) (error propagation)
// The schema is a contract with consumers. So if there's an `f: T!` in the
// schema, that says: "this API never returns a null f". If f turned out null
// in the results, then returning null would break the contract. GraphQL specifies
// a set of rules about how to propagate and record those errors.
//
// The basic intuition is that if we asked for something that's nullable and we
// got back a null/error, then that's fine, just set it to null. But if we asked
// for something non-nullable and got a null/error, then the object we are building
// is in an error state, and we should propagate that up to it's parent, and so
// on, until we reach a nullable field, or the top level.
//
// The completeXYZ() functions below essentially covers the value completion alg from
// https://graphql.github.io/graphql-spec/June2018/#sec-Value-Completion.
// see also: error propagation
// https://graphql.github.io/graphql-spec/June2018/#sec-Errors-and-Non-Nullability
// and the spec requirements for response
// https://graphql.github.io/graphql-spec/June2018/#sec-Response.
//
// There's three basic types to consider here: GraphQL object types (equals json
// objects in the result), list types (equals lists of objects or scalars), and
// values (either scalar values, lists or objects).
//
// So the algorithm is a three way mutual recursion between those types.
//
// That works like this... if part of the json result from Dgraph
// looked like:
//
// {
// "name": "A name"
// "friends": [
// { "name": "Friend 1"},
// { "name": "Friend 2", "friends": [...] }
// ]
// }
//
// Then, schematically, the recursion tree would look like:
//
// completeObject ( {
// "name": completeValue("A name")
// "friends": completeValue( completeList([
// completeValue (completeObject ({ "name": completeValue ("Friend 1")} )),
// completeValue (completeObject ({
// "name": completeValue("Friend 2"),
// "friends": completeValue ( completeList([ completeObject(..), ..]) } )
//
// completeDgraphResult starts the recursion with field as the top level GraphQL
// query and dgResult as the matching full Dgraph result. Always returns a valid
// JSON []byte of the form
// { "query-name": null }
// if there's no result, or
// { "query-name": ... }
// if there is a result.
//
// Returned errors are generally lists of errors resulting from the value completion
// algorithm that may emit multiple errors
func completeDgraphResult(
ctx context.Context,
field schema.Field,
dgResult []byte,
e error) *Resolved {
span := trace.FromContext(ctx)
stop := x.SpanTimer(span, "completeDgraphResult")
defer stop()
// We need an initial case in the alg because Dgraph always returns a list
// result no matter what.
//
// If the query was for a non-list type, that needs to be corrected:
//
// { "q":[{ ... }] } ---> { "q":{ ... } }
//
// Also, if the query found nothing at all, that needs correcting too:
//
// { } ---> { "q": null }
nullResponse := func(err error) *Resolved {
return &Resolved{
Data: nil,
Field: field,
Err: err,
}
}
dgraphError := func() *Resolved {
glog.Errorf("Could not process Dgraph result : \n%s", string(dgResult))
return nullResponse(
x.GqlErrorf("Couldn't process the result from Dgraph. " +
"This probably indicates a bug in Dgraph. Please let us know by filing an issue.").
WithLocations(field.Location()))
}
if len(dgResult) == 0 {
return nullResponse(e)
}
errs := schema.AsGQLErrors(e)
// Dgraph should only return {} or a JSON object. Also,
// GQL type checking should ensure query results are only object types
// https://graphql.github.io/graphql-spec/June2018/#sec-Query
// So we are only building object results.
var valToComplete map[string]interface{}
d := json.NewDecoder(bytes.NewBuffer(dgResult))
d.UseNumber()
err := d.Decode(&valToComplete)
if err != nil {
glog.Errorf("%+v \n Dgraph result :\n%s\n",
errors.Wrap(err, "failed to unmarshal Dgraph query result"),
string(dgResult))
return nullResponse(
schema.GQLWrapLocationf(err, field.Location(), "couldn't unmarshal Dgraph result"))
}
alias := field.DgraphAlias()
switch val := valToComplete[alias].(type) {
case []interface{}:
if field.Type().ListType() == nil {
// Turn Dgraph list result to single object
// "q":[{ ... }] ---> "q":{ ... }
var internalVal interface{}
if len(val) > 0 {
var ok bool
if internalVal, ok = val[0].(map[string]interface{}); !ok {
// This really shouldn't happen. Dgraph only returns arrays
// of json objects.
return dgraphError()
}
}
if len(val) > 1 {
// This case may occur during handling of aggregate Queries. So, we don't throw an error
// and combine all items into one single item.
if strings.HasSuffix(field.Type().String(), "AggregateResult") {
for i := 1; i < len(val); i++ {
var internalValMap interface{}
var ok bool
if internalValMap, ok = val[i].(map[string]interface{}); !ok {
return dgraphError()
}
for key, val := range internalValMap.(map[string]interface{}) {
internalVal.(map[string]interface{})[key] = val
}
}
} else {
// If we get here, then we got a list result for a query that expected
// a single item. That probably indicates a schema error, or maybe
// a bug in GraphQL processing or some data corruption.
//
// We'll continue and just try the first item to return some data.
glog.Errorf("Got a list of length %v from Dgraph when expecting a "+
"one-item list.\n", len(val))
errs = append(errs,
x.GqlErrorf(
"Dgraph returned a list, but %s (type %s) was expecting just one item. "+
"The first item in the list was used to produce the result.",
field.Name(), field.Type().String()).WithLocations(field.Location()))
}
}
valToComplete[field.DgraphAlias()] = internalVal
}
case interface{}:
// no need to error in this case, this can be returned for custom HTTP query/mutation
default:
if val != nil {
return dgraphError()
}
// valToComplete[field.Name()] is nil, so resolving for the
// { } ---> "q": null
// case
}
// TODO: correctly handle DgraphAlias for custom field resolution, at present it uses f.Name(),
// it should be using f.DgraphAlias() to get values from valToComplete.
// It works ATM because there hasn't been a scenario where there are two fields with same
// name in implementing types of an interface with @custom on some field in those types.
err = resolveCustomFields(ctx, field.SelectionSet(), valToComplete[field.DgraphAlias()])
if err != nil {
errs = append(errs, schema.AsGQLErrors(err)...)
}
return &Resolved{
Data: valToComplete,
Field: field,
Err: errs,
}
}
func copyTemplate(input interface{}) (interface{}, error) {
b, err := json.Marshal(input)
if err != nil {
return nil, errors.Wrapf(err, "while marshaling map input: %+v", input)
}
var result interface{}
if err := json.Unmarshal(b, &result); err != nil {
return nil, errors.Wrapf(err, "while unmarshalling into map: %s", b)
}
return result, nil
}
func keyNotFoundError(f schema.Field, key string) *x.GqlError {
return x.GqlErrorf("Evaluation of custom field failed because key: %s "+
"could not be found in the JSON response returned by external request "+
"for field: %s within type: %s.", key, f.Name(),
f.GetObjectName()).WithLocations(f.Location())
}
func jsonMarshalError(err error, f schema.Field, input interface{}) *x.GqlError {
return x.GqlErrorf("Evaluation of custom field failed because json marshaling "+
"(of: %+v) returned an error: %s for field: %s within type: %s.", input, err,
f.Name(), f.GetObjectName()).WithLocations(f.Location())
}
func jsonUnmarshalError(err error, f schema.Field) *x.GqlError {
return x.GqlErrorf("Evaluation of custom field failed because json unmarshaling"+
" result of external request failed (with error: %s) for field: %s within "+
"type: %s.", err, f.Name(), f.GetObjectName()).WithLocations(
f.Location())
}
func externalRequestError(err error, f schema.Field) *x.GqlError {
return x.GqlErrorf("Evaluation of custom field failed because external request"+
" returned an error: %s for field: %s within type: %s.", err, f.Name(),
f.GetObjectName()).WithLocations(f.Location())
}
func internalServerError(err error, f schema.Field) error {
return schema.GQLWrapLocationf(err, f.Location(), "evaluation of custom field failed"+
" for field: %s within type: %s.", f.Name(), f.GetObjectName())
}
type graphqlResp struct {
Data map[string]interface{} `json:"data,omitempty"`
Errors x.GqlErrorList `json:"errors,omitempty"`
}
func resolveCustomField(ctx context.Context, f schema.Field, vals []interface{}, mu *sync.RWMutex,
errCh chan error) {
defer api.PanicHandler(func(err error) {
errCh <- internalServerError(err, f)
})
fconf, err := f.CustomHTTPConfig()
if err != nil {
errCh <- err
return
}
// Here we build the input for resolving the fields which is sent as the body for the request.
inputs := make([]interface{}, len(vals))
graphql := fconf.RemoteGqlQueryName != ""
// For GraphQL requests, we substitute arguments in the GraphQL query/mutation to make to
// the remote endpoint using the values of other fields obtained from Dgraph.
if graphql {
requiredArgs := fconf.RequiredArgs
for i := 0; i < len(inputs); i++ {
vars := make(map[string]interface{})
// vals[i] has all the values fetched for this type from Dgraph, lets copy over the
// values required to process the remote GraphQL for the field into a new map.
mu.RLock()
m := vals[i].(map[string]interface{})
for k, v := range m {
if _, ok := requiredArgs[k]; ok {
vars[k] = v
}
}
mu.RUnlock()
inputs[i] = vars
}
} else {
for i := 0; i < len(inputs); i++ {
if fconf.Template == nil {
continue
}
temp, err := copyTemplate(*fconf.Template)
if err != nil {
errCh <- err
return
}
mu.RLock()
schema.SubstituteVarsInBody(&temp, vals[i].(map[string]interface{}))
mu.RUnlock()
inputs[i] = temp
}
}
if fconf.Mode == schema.BATCH {
var requestInput interface{}
requestInput = inputs
if graphql {
body := make(map[string]interface{})
body["query"] = fconf.RemoteGqlQuery
body["variables"] = map[string]interface{}{fconf.GraphqlBatchModeArgument: requestInput}