-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
wrappers.go
2589 lines (2279 loc) · 73.3 KB
/
wrappers.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 schema
import (
"bytes"
"fmt"
"net/http"
"net/url"
"reflect"
"sort"
"strconv"
"strings"
"github.com/dgraph-io/gqlparser/v2/parser"
"github.com/dgraph-io/dgraph/x"
"github.com/dgraph-io/gqlparser/v2/ast"
"github.com/pkg/errors"
)
// Wrap the github.com/dgraph-io/gqlparser/ast defintions so that the bulk of the GraphQL
// algorithm and interface is dependent on behaviours we expect from a GraphQL schema
// and validation, but not dependent the exact structure in the gqlparser.
//
// This also auto hooks up some bookkeeping that's otherwise no fun. E.g. getting values for
// field arguments requires the variable map from the operation - so we'd need to carry vars
// through all the resolver functions. Much nicer if they are resolved by magic here.
// QueryType is currently supported queries
type QueryType string
// MutationType is currently supported mutations
type MutationType string
// FieldHTTPConfig contains the config needed to resolve a field using a remote HTTP endpoint
// which could a GraphQL or a REST endpoint.
type FieldHTTPConfig struct {
URL string
Method string
// would be nil if there is no body
Template *interface{}
Mode string
ForwardHeaders http.Header
// would be empty for non-GraphQL requests
RemoteGqlQueryName string
RemoteGqlQuery string
// args required by the HTTP/GraphQL request. These should be present in the parent type
// in the case of resolving a field or in the parent field in case of a query/mutation
RequiredArgs map[string]bool
// For the following request
// graphql: "query($sinput: [SchoolInput]) { schoolNames(schools: $sinput) }"
// the GraphqlBatchModeArgument would be sinput, we use it to know the GraphQL variable that
// we should send the data in.
GraphqlBatchModeArgument string
}
// Query/Mutation types and arg names
const (
GetQuery QueryType = "get"
FilterQuery QueryType = "query"
AggregateQuery QueryType = "aggregate"
SchemaQuery QueryType = "schema"
PasswordQuery QueryType = "checkPassword"
HTTPQuery QueryType = "http"
DQLQuery QueryType = "dql"
NotSupportedQuery QueryType = "notsupported"
AddMutation MutationType = "add"
UpdateMutation MutationType = "update"
DeleteMutation MutationType = "delete"
HTTPMutation MutationType = "http"
NotSupportedMutation MutationType = "notsupported"
IDType = "ID"
InputArgName = "input"
FilterArgName = "filter"
)
// Schema represents a valid GraphQL schema
type Schema interface {
Operation(r *Request) (Operation, error)
Queries(t QueryType) []string
Mutations(t MutationType) []string
}
// An Operation is a single valid GraphQL operation. It contains either
// Queries or Mutations, but not both. Subscriptions are not yet supported.
type Operation interface {
Queries() []Query
Mutations() []Mutation
Schema() Schema
IsQuery() bool
IsMutation() bool
IsSubscription() bool
CacheControl() string
}
// A Field is one field from an Operation.
type Field interface {
Name() string
Alias() string
// DgraphAlias is used as an alias in DQL while rewriting the GraphQL field
DgraphAlias() string
ResponseName() string
Arguments() map[string]interface{}
ArgValue(name string) interface{}
IsArgListType(name string) bool
IDArgValue() (*string, uint64, error)
XIDArg() string
SetArgTo(arg string, val interface{})
Skip() bool
Include() bool
Cascade() []string
HasCustomDirective() (bool, map[string]FieldDefinition)
HasLambdaDirective() bool
Type() Type
SelectionSet() []Field
Location() x.Location
DgraphPredicate() string
Operation() Operation
// AbstractType tells us whether this field represents a GraphQL Interface.
AbstractType() bool
IncludeInterfaceField(types []interface{}) bool
TypeName(dgraphTypes []interface{}) string
GetObjectName() string
IsAuthQuery() bool
CustomHTTPConfig() (FieldHTTPConfig, error)
EnumValues() []string
ConstructedFor() Type
ConstructedForDgraphPredicate() string
DgraphPredicateForAggregateField() string
IsAggregateField() bool
}
// A Mutation is a field (from the schema's Mutation type) from an Operation
type Mutation interface {
Field
MutationType() MutationType
MutatedType() Type
QueryField() Field
NumUidsField() Field
}
// A Query is a field (from the schema's Query type) from an Operation
type Query interface {
Field
QueryType() QueryType
DQLQuery() string
Rename(newName string)
AuthFor(typ Type, jwtVars map[string]interface{}) Query
}
// A Type is a GraphQL type like: Float, T, T! and [T!]!. If it's not a list, then
// ListType is nil. If it's an object type then Field gets field definitions by
// name from the definition of the type; IDField gets the ID field of the type.
type Type interface {
Field(name string) FieldDefinition
Fields() []FieldDefinition
IDField() FieldDefinition
XIDField() FieldDefinition
InterfaceImplHasAuthRules() bool
PasswordField() FieldDefinition
Name() string
DgraphName() string
DgraphPredicate(fld string) string
Nullable() bool
// true if this is a union type
IsUnion() bool
IsInterface() bool
// returns a list of member types for this union
UnionMembers([]interface{}) []Type
ListType() Type
Interfaces() []string
ImplementingTypes() []Type
EnsureNonNulls(map[string]interface{}, string) error
FieldOriginatedFrom(fieldName string) string
AuthRules() *TypeAuth
IsGeo() bool
IsInbuiltOrEnumType() bool
fmt.Stringer
}
// A FieldDefinition is a field as defined in some Type in the schema. As opposed
// to a Field, which is an instance of a query or mutation asking for a field
// (which in turn must have a FieldDefinition of the right type in the schema.)
type FieldDefinition interface {
Name() string
DgraphAlias() string
DgraphPredicate() string
Type() Type
ParentType() Type
IsID() bool
HasIDDirective() bool
Inverse() FieldDefinition
WithMemberType(string) FieldDefinition
// TODO - It might be possible to get rid of ForwardEdge and just use Inverse() always.
ForwardEdge() FieldDefinition
}
type astType struct {
typ *ast.Type
inSchema *schema
dgraphPredicate map[string]map[string]string
}
type schema struct {
schema *ast.Schema
// dgraphPredicate gives us the dgraph predicate corresponding to a typeName + fieldName.
// It is pre-computed so that runtime queries and mutations can look it
// up quickly.
// The key for the first map are the type names. The second map has a mapping of the
// fieldName => dgraphPredicate.
dgraphPredicate map[string]map[string]string
// Map of mutation field name to mutated type.
mutatedType map[string]*astType
// Map from typename to ast.Definition
typeNameAst map[string][]*ast.Definition
// map from field name to bool, indicating if a field name was repeated across different types
// implementing the same interface
repeatedFieldNames map[string]bool
// customDirectives stores the mapping of typeName -> fieldName -> @custom definition.
// It is read-only.
// The outer map will contain typeName key only if one of the fields on that type has @custom.
// The inner map will contain fieldName key only if that field has @custom.
// It is pre-computed so that runtime queries and mutations can look it up quickly, and not do
// something like field.Directives.ForName("custom"), which results in iterating over all the
// directives of the field.
customDirectives map[string]map[string]*ast.Directive
// lambdaDirectives stores the mapping of typeName->fieldName->true, if the field has @lambda.
// It is read-only.
lambdaDirectives map[string]map[string]bool
// Map from typename to auth rules
authRules map[string]*TypeAuth
}
type operation struct {
op *ast.OperationDefinition
vars map[string]interface{}
header http.Header
// interfaceImplFragFields stores a mapping from a field collected from a fragment inside an
// interface to its typeCondition. It is used during completion to find out if a field should
// be included in GraphQL response or not.
interfaceImplFragFields map[*ast.Field]string
// The fields below are used by schema introspection queries.
query string
doc *ast.QueryDocument
inSchema *schema
}
type field struct {
field *ast.Field
op *operation
sel ast.Selection
// arguments contains the computed values for arguments taking into account the values
// for the GraphQL variables supplied in the query.
arguments map[string]interface{}
}
type fieldDefinition struct {
fieldDef *ast.FieldDefinition
parentType Type
inSchema *schema
dgraphPredicate map[string]map[string]string
}
type mutation field
type query field
func (s *schema) Queries(t QueryType) []string {
if s.schema.Query == nil {
return nil
}
var result []string
for _, q := range s.schema.Query.Fields {
if queryType(q.Name, s.customDirectives["Query"][q.Name]) == t {
result = append(result, q.Name)
}
}
return result
}
func (s *schema) Mutations(t MutationType) []string {
if s.schema.Mutation == nil {
return nil
}
var result []string
for _, m := range s.schema.Mutation.Fields {
if mutationType(m.Name, s.customDirectives["Mutation"][m.Name]) == t {
result = append(result, m.Name)
}
}
return result
}
func (o *operation) IsQuery() bool {
return o.op.Operation == ast.Query
}
func (o *operation) IsMutation() bool {
return o.op.Operation == ast.Mutation
}
func (o *operation) IsSubscription() bool {
return o.op.Operation == ast.Subscription
}
func (o *operation) Schema() Schema {
return o.inSchema
}
func (o *operation) Queries() (qs []Query) {
if o.IsMutation() {
return
}
for _, s := range o.op.SelectionSet {
if f, ok := s.(*ast.Field); ok {
qs = append(qs, &query{field: f, op: o, sel: s})
}
}
return
}
func (o *operation) Mutations() (ms []Mutation) {
if !o.IsMutation() {
return
}
for _, s := range o.op.SelectionSet {
if f, ok := s.(*ast.Field); ok {
ms = append(ms, &mutation{field: f, op: o})
}
}
return
}
func (o *operation) CacheControl() string {
if o.op.Directives.ForName(cacheControlDirective) == nil {
return ""
}
return "public,max-age=" + o.op.Directives.ForName(cacheControlDirective).Arguments[0].Value.Raw
}
// parentInterface returns the name of an interface that a field belonging to a type definition
// typDef inherited from. If there is no such interface, then it returns an empty string.
//
// Given the following schema
// interface A {
// name: String
// }
//
// type B implements A {
// name: String
// age: Int
// }
//
// calling parentInterface on the fieldName name with type definition for B, would return A.
func parentInterface(sch *ast.Schema, typDef *ast.Definition, fieldName string) *ast.Definition {
if len(typDef.Interfaces) == 0 {
return nil
}
for _, iface := range typDef.Interfaces {
interfaceDef := sch.Types[iface]
for _, interfaceField := range interfaceDef.Fields {
if fieldName == interfaceField.Name {
return interfaceDef
}
}
}
return nil
}
func parentInterfaceForPwdField(sch *ast.Schema, typDef *ast.Definition,
fieldName string) *ast.Definition {
if len(typDef.Interfaces) == 0 {
return nil
}
for _, iface := range typDef.Interfaces {
interfaceDef := sch.Types[iface]
pwdField := getPasswordField(interfaceDef)
if pwdField != nil && fieldName == pwdField.Name {
return interfaceDef
}
}
return nil
}
func convertPasswordDirective(dir *ast.Directive) *ast.FieldDefinition {
if dir.Name != "secret" {
return nil
}
name := dir.Arguments.ForName("field").Value.Raw
pred := dir.Arguments.ForName("pred")
dirs := ast.DirectiveList{}
if pred != nil {
dirs = ast.DirectiveList{{
Name: "dgraph",
Arguments: ast.ArgumentList{{
Name: "pred",
Value: &ast.Value{
Raw: pred.Value.Raw,
Kind: ast.StringValue,
},
}},
Position: dir.Position,
}}
}
fd := &ast.FieldDefinition{
Name: name,
Type: &ast.Type{
NamedType: "String",
NonNull: true,
Position: dir.Position,
},
Directives: dirs,
Position: dir.Position,
}
return fd
}
func dgraphMapping(sch *ast.Schema) map[string]map[string]string {
const (
add = "Add"
update = "Update"
del = "Delete"
payload = "Payload"
)
dgraphPredicate := make(map[string]map[string]string)
for _, inputTyp := range sch.Types {
// We only want to consider input types (object and interface) defined by the user as part
// of the schema hence we ignore BuiltIn, query and mutation types and Geo types.
isInputTypeGeo := func(typName string) bool {
return typName == "Point" || typName == "PointList" || typName == "Polygon" || typName == "MultiPolygon"
}
if inputTyp.BuiltIn || isQueryOrMutationType(inputTyp) || inputTyp.Name == "Subscription" ||
(inputTyp.Kind != ast.Object && inputTyp.Kind != ast.Interface) || isInputTypeGeo(inputTyp.Name) {
continue
}
originalTyp := inputTyp
inputTypeName := inputTyp.Name
if strings.HasPrefix(inputTypeName, add) && strings.HasSuffix(inputTypeName, payload) {
continue
}
dgraphPredicate[originalTyp.Name] = make(map[string]string)
if (strings.HasPrefix(inputTypeName, update) || strings.HasPrefix(inputTypeName, del)) &&
strings.HasSuffix(inputTypeName, payload) {
// For UpdateTypePayload and DeleteTypePayload, inputTyp should be Type.
if strings.HasPrefix(inputTypeName, update) {
inputTypeName = strings.TrimSuffix(strings.TrimPrefix(inputTypeName, update),
payload)
} else if strings.HasPrefix(inputTypeName, del) {
inputTypeName = strings.TrimSuffix(strings.TrimPrefix(inputTypeName, del), payload)
}
inputTyp = sch.Types[inputTypeName]
}
// We add password field to the cached type information to be used while opening
// resolving and rewriting queries to be sent to dgraph. Otherwise, rewriter won't
// know what the password field in AddInputType/ TypePatch/ TypeRef is.
var fields ast.FieldList
fields = append(fields, inputTyp.Fields...)
for _, directive := range inputTyp.Directives {
fd := convertPasswordDirective(directive)
if fd == nil {
continue
}
fields = append(fields, fd)
}
for _, fld := range fields {
if isID(fld) {
// We don't need a mapping for the field, as we the dgraph predicate for them is
// fixed i.e. uid.
continue
}
typName := typeName(inputTyp)
parentInt := parentInterface(sch, inputTyp, fld.Name)
if parentInt != nil {
typName = typeName(parentInt)
}
// 1. For fields that have @dgraph(pred: xxxName) directive, field name would be
// xxxName.
// 2. For fields where the type (or underlying interface) has a @dgraph(type: xxxName)
// directive, field name would be xxxName.fldName.
//
// The cases below cover the cases where neither the type or field have @dgraph
// directive.
// 3. For types which don't inherit from an interface the keys, value would be.
// typName,fldName => typName.fldName
// 4. For types which inherit fields from an interface
// typName,fldName => interfaceName.fldName
// 5. For DeleteTypePayload type
// DeleteTypePayload,fldName => typName.fldName
fname := fieldName(fld, typName)
dgraphPredicate[originalTyp.Name][fld.Name] = fname
}
}
return dgraphPredicate
}
func mutatedTypeMapping(s *schema,
dgraphPredicate map[string]map[string]string) map[string]*astType {
if s.schema.Mutation == nil {
return nil
}
m := make(map[string]*astType, len(s.schema.Mutation.Fields))
for _, field := range s.schema.Mutation.Fields {
mutatedTypeName := ""
switch {
case strings.HasPrefix(field.Name, "add"):
mutatedTypeName = strings.TrimPrefix(field.Name, "add")
case strings.HasPrefix(field.Name, "update"):
mutatedTypeName = strings.TrimPrefix(field.Name, "update")
case strings.HasPrefix(field.Name, "delete"):
mutatedTypeName = strings.TrimPrefix(field.Name, "delete")
default:
}
// This is a convoluted way of getting the type for mutatedTypeName. We get the definition
// for AddTPayload and get the type from the first field. There is no direct way to get
// the type from the definition of an object. Interfaces can't have Add and if there is no non Id
// field then Update also will not be there, so we use Delete if there is no AddTPayload.
var def *ast.Definition
if def = s.schema.Types["Add"+mutatedTypeName+"Payload"]; def == nil {
def = s.schema.Types["Delete"+mutatedTypeName+"Payload"]
}
if def == nil {
continue
}
// Accessing 0th element should be safe to do as according to the spec an object must define
// one or more fields.
typ := def.Fields[0].Type
// This would contain mapping of mutation field name to the Type()
// for e.g. addPost => astType for Post
m[field.Name] = &astType{typ, s, dgraphPredicate}
}
return m
}
func typeMappings(s *ast.Schema) map[string][]*ast.Definition {
typeNameAst := make(map[string][]*ast.Definition)
for _, typ := range s.Types {
name := typeName(typ)
typeNameAst[name] = append(typeNameAst[name], typ)
}
return typeNameAst
}
func repeatedFieldMappings(s *ast.Schema, dgPreds map[string]map[string]string) map[string]bool {
repeatedFieldNames := make(map[string]bool)
for _, typ := range s.Types {
if !isAbstractKind(typ.Kind) {
continue
}
type fieldInfo struct {
dgPred string
repeated bool
}
repeatedFieldsInTypesWithCommonAncestor := make(map[string]*fieldInfo)
for _, typ := range s.PossibleTypes[typ.Name] {
typPreds := dgPreds[typ.Name]
for _, field := range typ.Fields {
// ignore this field if it was inherited from the common interface or is of ID type.
// We ignore ID type fields too, because they map only to uid in dgraph and can't
// map to two different predicates.
if field.Type.Name() == IDType {
continue
}
// if we find a field with same name from types implementing a common interface
// and its DgraphPredicate is different than what was previously encountered, then
// we mark it as repeated field, so that queries will rewrite it with correct alias.
// For fields, which these types have implemented from a common interface, their
// DgraphPredicate will be same, so they won't be marked as repeated.
dgPred := typPreds[field.Name]
if fInfo, ok := repeatedFieldsInTypesWithCommonAncestor[field.Name]; ok && fInfo.
dgPred != dgPred {
repeatedFieldsInTypesWithCommonAncestor[field.Name].repeated = true
} else {
repeatedFieldsInTypesWithCommonAncestor[field.Name] = &fieldInfo{dgPred: dgPred}
}
}
}
for fName, info := range repeatedFieldsInTypesWithCommonAncestor {
if info.repeated {
repeatedFieldNames[fName] = true
}
}
}
return repeatedFieldNames
}
// customAndLambdaMappings does following things:
// * If there is @custom on any field, it removes the directive from the list of directives on
// that field. Instead, it puts it in a map of typeName->fieldName->custom directive definition.
// This mapping is returned as the first return value, which is later used to determine if some
// field has custom directive or not, and accordingly construct the HTTP request for the field.
// * If there is @lambda on any field, it removes the directive from the list of directives on
// that field. Instead, it puts it in a map of typeName->fieldName->bool. This mapping is returned
// as the second return value, which is later used to determine if some field has lambda directive
// or not. An appropriate @custom directive is also constructed for the field with @lambda and
// put into the first mapping. Both of these mappings together are used to construct the HTTP
// request for @lambda field. Internally, @lambda is just @custom(http: {
// url: "<graphql_lambda_url: a-fixed-pre-defined-url>",
// method: POST,
// body: "<all-the-args-for-a-query-or-mutation>/<all-the-scalar-fields-from-parent-type-for-a
// -@lambda-on-field>"
// mode: BATCH (set only if @lambda was on a non query/mutation field)
// })
// So, by constructing an appropriate custom directive for @lambda fields,
// we just reuse logic from @custom.
func customAndLambdaMappings(s *ast.Schema) (map[string]map[string]*ast.Directive,
map[string]map[string]bool) {
customDirectives := make(map[string]map[string]*ast.Directive)
lambdaDirectives := make(map[string]map[string]bool)
for _, typ := range s.Types {
for _, field := range typ.Fields {
for i, dir := range field.Directives {
if dir.Name == customDirective || dir.Name == lambdaDirective {
// remove @custom/@lambda directive from s
lastIndex := len(field.Directives) - 1
field.Directives[i] = field.Directives[lastIndex]
field.Directives = field.Directives[:lastIndex]
// get the @custom mapping for this type
var customFieldMap map[string]*ast.Directive
if existingCustomFieldMap, ok := customDirectives[typ.Name]; ok {
customFieldMap = existingCustomFieldMap
} else {
customFieldMap = make(map[string]*ast.Directive)
}
if dir.Name == customDirective {
// if it was @custom, put the directive at the @custom mapping for the field
customFieldMap[field.Name] = dir
} else {
// for lambda, first update the lambda directives map
var lambdaFieldMap map[string]bool
if existingLambdaFieldMap, ok := lambdaDirectives[typ.Name]; ok {
lambdaFieldMap = existingLambdaFieldMap
} else {
lambdaFieldMap = make(map[string]bool)
}
lambdaFieldMap[field.Name] = true
lambdaDirectives[typ.Name] = lambdaFieldMap
// then, build a custom directive with correct semantics to be put
// into custom directives map at this field
customFieldMap[field.Name] = buildCustomDirectiveForLambda(typ, field,
dir, func(f *ast.FieldDefinition) bool {
// Need to skip the fields which have a @custom/@lambda from
// going in body template. The field itself may not have the
// directive anymore because the directive may have been removed by
// this function already. So, using these maps to find the same.
return lambdaFieldMap[f.Name] || customFieldMap[f.Name] != nil
})
}
// finally, update the custom directives map for this type
customDirectives[typ.Name] = customFieldMap
// break, as there can only be one @custom/@lambda
break
}
}
}
}
return customDirectives, lambdaDirectives
}
func hasCustomOrLambda(f *ast.FieldDefinition) bool {
for _, dir := range f.Directives {
if dir.Name == customDirective || dir.Name == lambdaDirective {
return true
}
}
return false
}
// buildCustomDirectiveForLambda returns custom directive for the given field to be used for @lambda
// The constructed @custom looks like this:
// @custom(http: {
// url: "<graphql_lambda_url: a-fixed-pre-defined-url>",
// method: POST,
// body: "<all-the-args-for-a-query-or-mutation>/<all-the-scalar-fields-from-parent-type-for-a
// -@lambda-on-field>"
// mode: BATCH (set only if @lambda was on a non query/mutation field)
// })
func buildCustomDirectiveForLambda(defn *ast.Definition, field *ast.FieldDefinition,
lambdaDir *ast.Directive, skipInBodyTemplate func(f *ast.FieldDefinition) bool) *ast.Directive {
comma := ""
var bodyTemplate strings.Builder
// this function appends a variable to the body template for @custom
appendToBodyTemplate := func(varName string) {
bodyTemplate.WriteString(comma)
bodyTemplate.WriteString(varName)
bodyTemplate.WriteString(": $")
bodyTemplate.WriteString(varName)
comma = ", "
}
// first let's construct the body template for the custom directive
bodyTemplate.WriteString("{")
if isQueryOrMutationType(defn) {
// for queries and mutations we need to put their arguments in the body template
for _, arg := range field.Arguments {
appendToBodyTemplate(arg.Name)
}
} else {
// For fields in other types, skip the ones in body template which have a @lambda or @custom
// or are not scalar. The skipInBodyTemplate function is also used to check these
// conditions, in case the field can't tell by itself.
for _, f := range defn.Fields {
if hasCustomOrLambda(f) || !isScalar(f.Type.Name()) || skipInBodyTemplate(f) {
continue
}
appendToBodyTemplate(f.Name)
}
}
bodyTemplate.WriteString("}")
// build the children for http argument
httpArgChildrens := []*ast.ChildValue{
getChildValue(httpUrl, x.Config.GraphqlLambdaUrl, ast.StringValue, lambdaDir.Position),
getChildValue(httpMethod, http.MethodPost, ast.EnumValue, lambdaDir.Position),
getChildValue(httpBody, bodyTemplate.String(), ast.StringValue, lambdaDir.Position),
}
if !isQueryOrMutationType(defn) {
httpArgChildrens = append(httpArgChildrens,
getChildValue(mode, BATCH, ast.EnumValue, lambdaDir.Position))
}
// build the custom directive
return &ast.Directive{
Name: customDirective,
Arguments: []*ast.Argument{{
Name: httpArg,
Value: &ast.Value{
Kind: ast.ObjectValue,
Children: httpArgChildrens,
Position: lambdaDir.Position,
},
Position: lambdaDir.Position,
}},
Position: lambdaDir.Position,
}
}
func getChildValue(name, raw string, kind ast.ValueKind, position *ast.Position) *ast.ChildValue {
return &ast.ChildValue{
Name: name,
Value: &ast.Value{Raw: raw, Kind: kind, Position: position},
Position: position,
}
}
// AsSchema wraps a github.com/dgraph-io/gqlparser/ast.Schema.
func AsSchema(s *ast.Schema) (Schema, error) {
// Auth rules can't be effectively validated as part of the normal rules -
// because they need the fully generated schema to be checked against.
authRules, err := authRules(s)
if err != nil {
return nil, err
}
customDirs, lambdaDirs := customAndLambdaMappings(s)
dgraphPredicate := dgraphMapping(s)
sch := &schema{
schema: s,
dgraphPredicate: dgraphPredicate,
typeNameAst: typeMappings(s),
repeatedFieldNames: repeatedFieldMappings(s, dgraphPredicate),
customDirectives: customDirs,
lambdaDirectives: lambdaDirs,
authRules: authRules,
}
sch.mutatedType = mutatedTypeMapping(sch, dgraphPredicate)
return sch, nil
}
func responseName(f *ast.Field) string {
if f.Alias == "" {
return f.Name
}
return f.Alias
}
func (f *field) Name() string {
return f.field.Name
}
func (f *field) Alias() string {
return f.field.Alias
}
func (f *field) DgraphAlias() string {
// if this field is repeated, then it should be aliased using its dgraph predicate which will be
// unique across repeated fields
if f.op.inSchema.repeatedFieldNames[f.Name()] {
dgraphPredicate := f.DgraphPredicate()
// There won't be any dgraph predicate for fields in introspection queries, as they are not
// stored in dgraph. So we identify those fields using this condition, and just let the
// field name get returned for introspection query fields, because the raw data response is
// prepared for them using only the field name, so that is what should be used to pick them
// back up from that raw data response before completion is performed.
// Now, the reason to not combine this if check with the outer one is because this
// function is performance critical. If there are a million fields in the output,
// it would be called a million times. So, better to perform this check and allocate memory
// for the variable only when necessary to do so.
if dgraphPredicate != "" {
return dgraphPredicate
}
}
// if not repeated, alias it using its name
return f.Name()
}
func (f *field) ResponseName() string {
return responseName(f.field)
}
func (f *field) SetArgTo(arg string, val interface{}) {
if f.arguments == nil {
f.arguments = make(map[string]interface{})
}
f.arguments[arg] = val
// If the argument doesn't exist, add it to the list. It is used later on to get
// parameters. Value isn't required because it's fetched using the arguments map.
argument := f.field.Arguments.ForName(arg)
if argument == nil {
f.field.Arguments = append(f.field.Arguments, &ast.Argument{Name: arg})
}
}
func (f *field) IsAuthQuery() bool {
return f.field.Arguments.ForName("dgraph.uid") != nil
}
func (f *field) IsAggregateField() bool {
return strings.HasSuffix(f.DgraphAlias(), "Aggregate") &&
strings.HasSuffix(f.Type().Name(), "AggregateResult")
}
func (f *field) Arguments() map[string]interface{} {
if f.arguments == nil {
// Compute and cache the map first time this function is called for a field.
f.arguments = f.field.ArgumentMap(f.op.vars)
// use a deep-copy only if the request uses variables, as a variable could be shared by
// multiple queries in a single request and internally in our code we may overwrite field
// arguments which may result in the shared value being overwritten for all queries in a
// request.
if f.op.vars != nil {
f.arguments = x.DeepCopyJsonMap(f.arguments)
}
}
return f.arguments
}
func (f *field) ArgValue(name string) interface{} {
return f.Arguments()[name]
}
func (f *field) IsArgListType(name string) bool {
arg := f.field.Arguments.ForName(name)
if arg == nil {
return false
}
return arg.Value.ExpectedType.Elem != nil
}
func (f *field) Skip() bool {
dir := f.field.Directives.ForName("skip")
if dir == nil {
return false
}
return dir.ArgumentMap(f.op.vars)["if"].(bool)
}
func (f *field) Include() bool {
dir := f.field.Directives.ForName("include")
if dir == nil {
return true
}
return dir.ArgumentMap(f.op.vars)["if"].(bool)
}
func (f *field) Cascade() []string {
dir := f.field.Directives.ForName(cascadeDirective)
if dir == nil {
return nil
}
arg := dir.Arguments.ForName(cascadeArg)
if arg == nil || arg.Value == nil || len(arg.Value.Children) == 0 {
return []string{"__all__"}
}
fields := make([]string, 0, len(arg.Value.Children))
typ := f.Type()
idField := typ.IDField()
for _, child := range arg.Value.Children {
if idField != nil && idField.Name() == child.Value.Raw {
fields = append(fields, "uid")
} else {
fields = append(fields, typ.DgraphPredicate(child.Value.Raw))
}
}
return fields
}
func toRequiredFieldDefs(requiredFieldNames map[string]bool, sibling *field) map[string]FieldDefinition {
res := make(map[string]FieldDefinition, len(requiredFieldNames))
parentType := &astType{
typ: &ast.Type{NamedType: sibling.field.ObjectDefinition.Name},
inSchema: sibling.op.inSchema,
dgraphPredicate: sibling.op.inSchema.dgraphPredicate,
}
for rfName := range requiredFieldNames {
fieldDef := parentType.Field(rfName)
res[fieldDef.DgraphAlias()] = fieldDef
}
return res
}
func (f *field) HasCustomDirective() (bool, map[string]FieldDefinition) {
custom := f.op.inSchema.customDirectives[f.GetObjectName()][f.Name()]
if custom == nil {
return false, nil
}
var rf map[string]bool
httpArg := custom.Arguments.ForName("http")
bodyArg := httpArg.Value.Children.ForName("body")
graphqlArg := httpArg.Value.Children.ForName("graphql")
if bodyArg != nil {
bodyTemplate := bodyArg.Raw
_, rf, _ = parseBodyTemplate(bodyTemplate, graphqlArg == nil)
}
if rf == nil {
rf = make(map[string]bool)
}
rawURL := httpArg.Value.Children.ForName("url").Raw
// Error here should be nil as we should have parsed and validated the URL
// already.
u, _ := url.Parse(rawURL)
// Parse variables from the path and query params.
elems := strings.Split(u.Path, "/")
for _, elem := range elems {
if strings.HasPrefix(elem, "$") {
rf[elem[1:]] = true
}
}
for k := range u.Query() {
val := u.Query().Get(k)
if strings.HasPrefix(val, "$") {
rf[val[1:]] = true
}
}