-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathValidation.fs
More file actions
1562 lines (1467 loc) · 75.6 KB
/
Validation.fs
File metadata and controls
1562 lines (1467 loc) · 75.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// The MIT License (MIT)
// Copyright (c) 2016 Bazinga Technologies Inc
namespace FSharp.Data.GraphQL.Validation
open System.Collections.Generic
open FSharp.Data.GraphQL
open FSharp.Data.GraphQL.Ast
open FSharp.Data.GraphQL.Extensions
open FSharp.Data.GraphQL.Types
open FSharp.Data.GraphQL.Types.Patterns
open FSharp.Data.GraphQL.Types.Introspection
open FSharp.Data.GraphQL.Validation.ValidationResult
open FsToolkit.ErrorHandling
module Types =
let validateImplements (objdef : ObjectDef) (idef : InterfaceDef) =
let objectFields = objdef.Fields
let errors =
idef.Fields
|> Array.fold
(fun acc f ->
match Map.tryFind f.Name objectFields with
| None ->
$"'%s{f.Name}' field is defined by interface %s{idef.Name}, but not implemented in object %s{objdef.Name}"
:: acc
| Some objf when objf = f -> acc
| Some _ ->
$"'%s{objdef.Name}.%s{f.Name}' field signature does not match it's definition in interface %s{idef.Name}"
:: acc)
[]
match errors with
| [] -> Success
| err -> ValidationError err
let validateType typedef =
match typedef with
| Scalar _ -> Success
| Object objdef ->
let nonEmptyResult =
if objdef.Fields.Count > 0 then
Success
else
ValidationError [ objdef.Name + " must have at least one field defined" ]
let implementsResult =
objdef.Implements
|> ValidationResult.collect (validateImplements objdef)
nonEmptyResult @@ implementsResult
| InputObject indef ->
let nonEmptyResult =
if indef.Fields.Length > 0 then
Success
else
ValidationError [ indef.Name + " must have at least one field defined" ]
nonEmptyResult
| Union uniondef ->
let nonEmptyResult =
if uniondef.Options.Length > 0 then
Success
else
ValidationError [
uniondef.Name
+ " must have at least one type definition option"
]
nonEmptyResult
| Enum enumdef ->
let nonEmptyResult =
if enumdef.Options.Length > 0 then
Success
else
ValidationError [ enumdef.Name + " must have at least one enum value defined" ]
nonEmptyResult
| Interface idef ->
let nonEmptyResult =
if idef.Fields.Length > 0 then
Success
else
ValidationError [ idef.Name + " must have at least one field defined" ]
nonEmptyResult
| InputCustom _ -> Success
| _ -> failwithf "Unexpected value of typedef: %O" typedef
let validateTypeMap (namedTypes : TypeMap) : ValidationResult<string> =
namedTypes.ToSeq ()
|> Seq.fold (fun acc (_, namedDef) -> acc @@ validateType namedDef) Success
module Ast =
type MetaTypeFieldInfo = { Name : string; ArgumentNames : string[] }
let private metaTypeFields =
seq {
{ Name = "__type"; ArgumentNames = [| "name" |] }
{ Name = "__schema"; ArgumentNames = [||] }
{ Name = "__typename"; ArgumentNames = [||] }
}
|> Seq.map (fun x -> x.Name, x)
|> Map.ofSeq
let rec private tryGetSchemaTypeByRef (schemaTypes : Map<string, IntrospectionType>) (tref : IntrospectionTypeRef) =
match tref.Kind with
| TypeKind.NON_NULL
| TypeKind.LIST when tref.OfType.IsSome -> tryGetSchemaTypeByRef schemaTypes tref.OfType.Value
| _ -> tref.Name |> Option.bind schemaTypes.TryFind
type SchemaInfo = {
SchemaTypes : Map<string, IntrospectionType>
QueryType : IntrospectionType option
SubscriptionType : IntrospectionType option
MutationType : IntrospectionType option
Directives : IntrospectionDirective[]
} with
member x.TryGetTypeByRef (tref : IntrospectionTypeRef) = tryGetSchemaTypeByRef x.SchemaTypes tref
static member FromIntrospectionSchema (schema : IntrospectionSchema) =
let schemaTypes = schema.Types |> Seq.map (fun x -> x.Name, x) |> Map.ofSeq
{
SchemaTypes = schema.Types |> Seq.map (fun x -> x.Name, x) |> Map.ofSeq
QueryType = tryGetSchemaTypeByRef schemaTypes schema.QueryType
MutationType =
schema.MutationType
|> Option.bind (tryGetSchemaTypeByRef schemaTypes)
SubscriptionType =
schema.SubscriptionType
|> Option.bind (tryGetSchemaTypeByRef schemaTypes)
Directives = schema.Directives
}
member x.TryGetOperationType (ot : OperationType) =
match ot with
| Query -> x.QueryType
| Mutation -> x.MutationType
| Subscription -> x.SubscriptionType
member x.TryGetTypeByName (name : string) = x.SchemaTypes.TryFind (name)
member x.TryGetInputType (input : InputType) =
match input with
| NamedType name ->
x.TryGetTypeByName (name)
|> Option.bind (fun x ->
match x.Kind with
| TypeKind.INPUT_OBJECT
| TypeKind.SCALAR
| TypeKind.ENUM -> Some x
| _ -> None)
|> Option.map IntrospectionTypeRef.Named
| ListType inner ->
x.TryGetInputType (inner)
|> Option.map IntrospectionTypeRef.List
| NonNullType inner ->
x.TryGetInputType (inner)
|> Option.map IntrospectionTypeRef.NonNull
/// Contains information about the selection in a field or a fragment, with related GraphQL schema type information.
and SelectionInfo = {
/// Contains the information about the field inside the selection set of the parent type.
Field : Field
/// Contains the reference to tye field type in the schema.
FieldType : IntrospectionTypeRef voption
/// Contains the reference to the parent type of the current field in the schema.
ParentType : IntrospectionType
/// If the field is inside a fragment selection, gets the reference to the fragment type of the current field in the schema.
FragmentType : IntrospectionType voption
/// In case this field is part of a selection of a fragment spread, gets the name of the fragment spread.
FragmentSpreadName : string voption
/// Contains the selection info of this field, if it is an Object, Interface or Union type.
SelectionSet : SelectionInfo list
/// In case the schema definition fo this field has input values, gets information about the input values of the field in the schema.
InputValues : IntrospectionInputVal[]
/// Contains the path of the field in the document.
Path : FieldPath
} with
/// If the field has an alias, return its alias. Otherwise, returns its name.
member x.AliasOrName = x.Field.AliasOrName
/// If the field is inside a selection of a fragment definition, returns the fragment type containing the field.
/// Otherwise, return the parent type in the schema definition.
member x.FragmentOrParentType = x.FragmentType |> ValueOption.defaultValue x.ParentType
/// Contains information about an operation definition in the document, with related GraphQL schema type information.
type OperationDefinitionInfo = {
/// Returns the definition from the parsed document.
Definition : OperationDefinition
/// Returns the selection information about the operation, with related GraphQL schema type information.
SelectionSet : SelectionInfo list
} with
/// Returns the name of the operation definition, if it does have a name.
member x.Name = x.Definition.Name
/// Contains information about a fragment definition in the document, with related GraphQL schema type information.
type FragmentDefinitionInfo = {
/// Returns the definition from the parsed document.
Definition : FragmentDefinition
/// Returns the selection information about the fragment, with related GraphQL schema type information.
SelectionSet : SelectionInfo list
} with
/// Returns the name of the fragment definition, if it does have a name.
member x.Name = x.Definition.Name
/// Contains information about a definition in the document, with related GraphQL schema type information.
type DefinitionInfo =
| OperationDefinitionInfo of OperationDefinitionInfo
| FragmentDefinitionInfo of FragmentDefinitionInfo
/// Returns the definition from the parsed definition in the document.
member x.Definition =
match x with
| OperationDefinitionInfo x -> OperationDefinition x.Definition
| FragmentDefinitionInfo x -> FragmentDefinition x.Definition
/// Returns the name of the definition, if it does have a name.
member x.Name = x.Definition.Name
/// Returns the selection information about the definition, with related GraphQL schema type information.
member x.SelectionSet =
match x with
| OperationDefinitionInfo x -> x.SelectionSet
| FragmentDefinitionInfo x -> x.SelectionSet
/// Returns the directives from the parsed definition in the document.
member x.Directives =
match x with
| OperationDefinitionInfo x -> x.Definition.Directives
| FragmentDefinitionInfo x -> x.Definition.Directives
/// The validation context used to run validations against a parsed document.
/// It should have the schema type information, the original document and the definition information about the original document.
type ValidationContext = {
/// Gets information about all definitions in the original document, including related GraphQL schema type information for them.
Definitions : DefinitionInfo list
/// Gets information about the schema which the document is validated against.
Schema : SchemaInfo
/// Gets the document that is being validated.
Document : Document
} with
/// Gets the information about all the operations in the original document, including related GraphQL schema type information for them.
member x.OperationDefinitions =
x.Definitions
|> List.vchoose (function
| OperationDefinitionInfo x -> ValueSome x
| _ -> ValueNone)
/// Gets the information about all the fragments in the original document, including related GraphQL schema type information for them.
member x.FragmentDefinitions =
x.Definitions
|> List.vchoose (function
| FragmentDefinitionInfo x -> ValueSome x
| _ -> ValueNone)
/// Contains information about a fragment type and its related GraphQL schema type.
type FragmentTypeInfo =
| Inline of typeCondition : IntrospectionType
| Spread of name : string * directives : Directive list * typeCondition : IntrospectionType
/// Gets the schema type related to the type condition of this fragment.
member x.TypeCondition =
match x with
| Inline fragType -> fragType
| Spread (_, _, fragType) -> fragType
/// In case this fragment is a fragment spread, get its name.
member x.Name =
match x with
| Inline _ -> ValueNone
| Spread (name, _, _) -> ValueSome name
type SelectionInfoContext = {
Schema : SchemaInfo
FragmentDefinitions : FragmentDefinition list
ParentType : IntrospectionType
FragmentType : FragmentTypeInfo voption
Path : FieldPath
SelectionSet : Selection list
} with
member x.FragmentOrParentType =
x.FragmentType
|> ValueOption.map _.TypeCondition
|> ValueOption.defaultValue x.ParentType
let private tryFindInArrayOption (finder : 'T -> bool) =
ValueOption.ofOption
>> ValueOption.bind (Array.tryFind finder >> ValueOption.ofOption)
let private onAllSelections (ctx : ValidationContext) (onSelection : SelectionInfo -> ValidationResult<GQLProblemDetails>) =
let rec traverseSelections selection =
(onSelection selection)
@@ (selection.SelectionSet
|> ValidationResult.collect traverseSelections)
ctx.Definitions
|> ValidationResult.collect (fun def ->
def.SelectionSet
|> ValidationResult.collect traverseSelections)
let rec private getFragSelectionSetInfo
(visitedFragments : string list)
(fragmentTypeInfo : FragmentTypeInfo)
(fragmentSelectionSet : Selection list)
(parentCtx : SelectionInfoContext)
=
match fragmentTypeInfo with
| Inline fragType ->
let fragCtx = {
parentCtx with
ParentType = parentCtx.FragmentOrParentType
FragmentType = ValueSome (Inline fragType)
SelectionSet = fragmentSelectionSet
}
getSelectionSetInfo visitedFragments fragCtx
| Spread (fragName, _, _) when List.contains fragName visitedFragments -> []
| Spread (fragName, directives, fragType) ->
let fragCtx = {
parentCtx with
ParentType = parentCtx.FragmentOrParentType
FragmentType = ValueSome (Spread (fragName, directives, fragType))
SelectionSet = fragmentSelectionSet
}
getSelectionSetInfo (fragName :: visitedFragments) fragCtx
and private getSelectionSetInfo (visitedFragments : string list) (ctx : SelectionInfoContext) : SelectionInfo list =
// When building the selection info, we should not raise any error when a type referred by the document
// is not found in the schema. Not found types are validated in another validation, without the need of the
// selection info to do it. Info types are helpers to validate against their schema types when the match is found.
// Because of that, whenever a field or fragment type does not have a matching type in the schema, we skip the selection production.
ctx.SelectionSet
|> List.collect (function
| Field field ->
let introspectionField =
ctx.FragmentOrParentType.Fields
|> tryFindInArrayOption (fun f -> f.Name = field.Name)
let inputValues = introspectionField |> ValueOption.map (fun f -> f.Args)
let fieldTypeRef = introspectionField |> ValueOption.map (fun f -> f.Type)
let fieldPath = box field.AliasOrName :: ctx.Path
let fieldSelectionSet =
voption {
let! fieldTypeRef = fieldTypeRef
let! fieldType = ctx.Schema.TryGetTypeByRef fieldTypeRef
let fieldCtx = {
ctx with
ParentType = fieldType
FragmentType = ValueNone
Path = fieldPath
SelectionSet = field.SelectionSet
}
return getSelectionSetInfo visitedFragments fieldCtx
}
|> ValueOption.defaultValue []
{
Field = field
SelectionSet = fieldSelectionSet
FieldType = fieldTypeRef
ParentType = ctx.ParentType
FragmentType = ctx.FragmentType |> ValueOption.map _.TypeCondition
FragmentSpreadName = ctx.FragmentType |> ValueOption.bind _.Name
InputValues = inputValues |> ValueOption.defaultValue [||]
Path = fieldPath
}
|> List.singleton
| InlineFragment inlineFrag ->
voption {
let! typeCondition = inlineFrag.TypeCondition
let! fragType = ctx.Schema.TryGetTypeByName typeCondition
let fragType = Inline fragType
return getFragSelectionSetInfo visitedFragments fragType inlineFrag.SelectionSet ctx
}
|> ValueOption.defaultValue List.empty
| FragmentSpread fragSpread ->
voption {
let! fragDef =
ctx.FragmentDefinitions
|> List.tryFind (fun def -> def.Name.IsSome && def.Name.Value = fragSpread.Name)
let! typeCondition = fragDef.TypeCondition
let! fragType = ctx.Schema.TryGetTypeByName typeCondition
let fragType = Spread (fragSpread.Name, fragSpread.Directives, fragType)
return getFragSelectionSetInfo visitedFragments fragType fragDef.SelectionSet ctx
}
|> ValueOption.defaultValue List.empty)
let private getOperationDefinitions (ast : Document) =
ast.Definitions
|> List.vchoose (function
| OperationDefinition x -> ValueSome x
| _ -> ValueNone)
let private getFragmentDefinitions (ast : Document) =
ast.Definitions
|> List.vchoose (function
| FragmentDefinition x when x.Name.IsSome -> ValueSome x
| _ -> ValueNone)
/// Prepare a ValidationContext for the given Document and SchemaInfo to make validation operations easier.
let internal getValidationContext (schemaInfo : SchemaInfo) (ast : Document) =
let fragmentDefinitions = getFragmentDefinitions ast
let fragmentInfos =
fragmentDefinitions
|> List.vchoose (fun def -> voption {
let! typeCondition = def.TypeCondition
let! fragType = schemaInfo.TryGetTypeByName typeCondition
let fragCtx = {
Schema = schemaInfo
FragmentDefinitions = fragmentDefinitions
ParentType = fragType
FragmentType = ValueSome (Spread (def.Name.Value, def.Directives, fragType))
Path = [ def.Name.Value ]
SelectionSet = def.SelectionSet
}
return FragmentDefinitionInfo { Definition = def; SelectionSet = getSelectionSetInfo [] fragCtx }
})
let operationInfos =
getOperationDefinitions ast
|> List.vchoose (fun def -> voption {
let! parentType = schemaInfo.TryGetOperationType def.OperationType
let path = def.Name |> ValueOption.map box |> ValueOption.toList
let opCtx = {
Schema = schemaInfo
FragmentDefinitions = fragmentDefinitions
ParentType = parentType
FragmentType = ValueNone
Path = path
SelectionSet = def.SelectionSet
}
return OperationDefinitionInfo { Definition = def; SelectionSet = getSelectionSetInfo [] opCtx }
})
{
Definitions = fragmentInfos @ operationInfos
Schema = schemaInfo
Document = ast
}
let internal validateOperationNameUniqueness (ctx : ValidationContext) =
let names = ctx.Document.Definitions |> Seq.vchoose _.Name
names
|> Seq.map (fun name -> name, names |> Seq.filter (fun x -> x = name) |> Seq.length)
|> Seq.distinctBy fst
|> ValidationResult.collect (fun (name, count) ->
if count <= 1 then
Success
else
AstError.AsResult $"Operation '%s{name}' has %i{count} definitions. Each operation name must be unique.")
let internal validateLoneAnonymousOperation (ctx : ValidationContext) =
let operations = ctx.OperationDefinitions |> List.map _.Definition
let unamed = operations |> List.filter _.Name.IsNone
if unamed.Length = 0 then
Success
elif unamed.Length = 1 && operations.Length = 1 then
Success
else
AstError.AsResult
"An anonymous operation must be the only operation in a document. This document has at least one anonymous operation and more than one operation."
let internal validateSubscriptionSingleRootField (ctx : ValidationContext) =
let fragmentDefinitions = getFragmentDefinitions ctx.Document
let rec getFieldNames (selectionSet : Selection list) =
([], selectionSet)
||> List.fold (fun acc ->
function
| Field field -> field.AliasOrName :: acc
| InlineFragment frag -> List.append (getFieldNames frag.SelectionSet) acc
| FragmentSpread spread ->
fragmentDefinitions
|> List.tryFind (fun x -> x.Name.IsSome && x.Name.Value = spread.Name)
|> Option.unwrap acc (fun frag -> getFieldNames frag.SelectionSet))
ctx.Document.Definitions
|> ValidationResult.collect (function
| OperationDefinition def when def.OperationType = Subscription ->
let fieldNames = getFieldNames def.SelectionSet
if fieldNames.Length <= 1 then
Success
else
let fieldNamesAsString = System.String.Join (", ", fieldNames)
match def.Name with
| ValueSome operationName ->
AstError.AsResult
$"Subscription operations should have only one root field. Operation '%s{operationName}' has %i{fieldNames.Length} fields (%s{fieldNamesAsString})."
| ValueNone ->
AstError.AsResult
$"Subscription operations should have only one root field. Operation has %i{fieldNames.Length} fields (%s{fieldNamesAsString})."
| _ -> Success)
let internal validateSelectionFieldTypes (ctx : ValidationContext) =
onAllSelections ctx (fun selection ->
if metaTypeFields.ContainsKey (selection.Field.Name) then
Success
else
let exists =
selection.FragmentOrParentType.Fields
|> Option.map (Array.exists (fun f -> f.Name = selection.Field.Name))
|> Option.defaultValue false
if not exists then
AstError.AsResult (
$"Field '%s{selection.Field.Name}' is not defined in schema type '%s{selection.FragmentOrParentType.Name}'.",
selection.Path
)
else
Success)
let private typesAreApplicable (parentType : IntrospectionType, fragmentType : IntrospectionType) =
let parentPossibleTypes =
parentType.PossibleTypes
|> Option.defaultValue [||]
|> Seq.choose _.Name
|> Seq.append (Seq.singleton parentType.Name)
|> Set.ofSeq
let fragmentPossibleTypes =
fragmentType.PossibleTypes
|> Option.defaultValue [||]
|> Seq.choose _.Name
|> Seq.append (Seq.singleton fragmentType.Name)
|> Set.ofSeq
let applicableTypes = Set.intersect parentPossibleTypes fragmentPossibleTypes
applicableTypes.Count > 0
let rec private sameResponseShape (fieldA : SelectionInfo, fieldB : SelectionInfo) =
if fieldA.FieldType = fieldB.FieldType then
let fieldsForName = Dictionary<string, SelectionInfo list> ()
fieldA.SelectionSet
|> List.iter (fun selection -> Dictionary.addWith (List.append) selection.AliasOrName [ selection ] fieldsForName)
fieldB.SelectionSet
|> List.iter (fun selection -> Dictionary.addWith (List.append) selection.AliasOrName [ selection ] fieldsForName)
fieldsForName
|> ValidationResult.collect (fun (KeyValue (_, selectionSet)) ->
if selectionSet.Length < 2 then
Success
else
List.pairwise selectionSet
|> ValidationResult.collect sameResponseShape)
else
AstError.AsResult (
$"Field name or alias '%s{fieldA.AliasOrName}' appears two times, but they do not have the same return types in the scope of the parent type.",
fieldA.Path
)
let rec private fieldsInSetCanMerge (set : SelectionInfo list) =
let fieldsForName = set |> List.groupBy _.AliasOrName
fieldsForName
|> ValidationResult.collect (fun (aliasOrName, selectionSet) ->
if selectionSet.Length < 2 then
Success
else
List.pairwise selectionSet
|> ValidationResult.collect (fun (fieldA, fieldB) ->
let hasSameShape = sameResponseShape (fieldA, fieldB)
if
fieldA.FragmentOrParentType = fieldB.FragmentOrParentType
|| fieldA.FragmentOrParentType.Kind <> TypeKind.OBJECT
|| fieldB.FragmentOrParentType.Kind <> TypeKind.OBJECT
then
if fieldA.Field.Name <> fieldB.Field.Name then
hasSameShape
@@ AstError.AsResult (
$"Field name or alias '%s{aliasOrName}' is referring to fields '%s{fieldA.Field.Name}' and '%s{fieldB.Field.Name}', but they are different fields in the scope of the parent type.",
fieldA.Path
)
else if fieldA.Field.Arguments <> fieldB.Field.Arguments then
hasSameShape
@@ AstError.AsResult (
$"Field name or alias '%s{aliasOrName}' refers to field '%s{fieldA.Field.Name}' two times, but each reference has different argument sets.",
fieldA.Path
)
else
let mergedSet = fieldA.SelectionSet @ fieldB.SelectionSet
hasSameShape @@ (fieldsInSetCanMerge mergedSet)
else
hasSameShape))
let internal validateFieldSelectionMerging (ctx : ValidationContext) =
ctx.Definitions
|> ValidationResult.collect (fun def -> fieldsInSetCanMerge def.SelectionSet)
let rec private checkLeafFieldSelection (selection : SelectionInfo) =
let rec validateByKind (fieldType : IntrospectionTypeRef) (selectionSetLength : int) =
match fieldType.Kind with
| TypeKind.NON_NULL
| TypeKind.LIST when fieldType.OfType.IsSome -> validateByKind fieldType.OfType.Value selectionSetLength
| TypeKind.SCALAR
| TypeKind.ENUM when selectionSetLength > 0 ->
AstError.AsResult (
$"Field '%s{selection.Field.Name}' of '%s{selection.FragmentOrParentType.Name}' type is of type kind %s{fieldType.Kind.ToString ()}, and therefore should not contain inner fields in its selection.",
selection.Path
)
| TypeKind.INTERFACE
| TypeKind.UNION
| TypeKind.OBJECT when selectionSetLength = 0 ->
AstError.AsResult (
$"Field '%s{selection.Field.Name}' of '%s{selection.FragmentOrParentType.Name}' type is of type kind %s{fieldType.Kind.ToString ()}, and therefore should have inner fields in its selection.",
selection.Path
)
| _ -> Success
match selection.FieldType with
| ValueSome fieldType -> validateByKind fieldType selection.SelectionSet.Length
| ValueNone -> Success
let internal validateLeafFieldSelections (ctx : ValidationContext) = onAllSelections ctx checkLeafFieldSelection
let private checkFieldArgumentNames (schemaInfo : SchemaInfo) (selection : SelectionInfo) =
let argumentsValid =
selection.Field.Arguments
|> ValidationResult.collect (fun arg ->
let schemaArgumentNames =
metaTypeFields.TryFind (selection.Field.Name)
|> ValueOption.ofOption
|> ValueOption.map _.ArgumentNames
|> ValueOption.defaultWith (fun () -> selection.InputValues |> Array.map _.Name)
match schemaArgumentNames |> Array.tryFind (fun x -> x = arg.Name) with
| Some _ -> Success
| None ->
AstError.AsResult (
$"Field '%s{selection.Field.Name}' of type '%s{selection.FragmentOrParentType.Name}' does not have an input named '%s{arg.Name}' in its definition.",
selection.Path
))
let directivesValid =
selection.Field.Directives
|> ValidationResult.collect (fun directive ->
match
schemaInfo.Directives
|> Array.tryFind (fun d -> d.Name = directive.Name)
with
| Some directiveType ->
directive.Arguments
|> ValidationResult.collect (fun arg ->
match
directiveType.Args
|> Array.tryFind (fun argt -> argt.Name = arg.Name)
with
| Some _ -> Success
| _ ->
AstError.AsResult (
$"Directive '%s{directiveType.Name}' of field '%s{selection.Field.Name}' of type '%s{selection.FragmentOrParentType.Name}' does not have an argument named '%s{arg.Name}' in its definition.",
selection.Path
))
| None -> Success)
argumentsValid @@ directivesValid
let internal validateArgumentNames (ctx : ValidationContext) = onAllSelections ctx (checkFieldArgumentNames ctx.Schema)
let rec private validateArgumentUniquenessInSelection (selection : SelectionInfo) =
let validateArgs (fieldOrDirective : string) (path : FieldPath) (args : Argument list) =
args
|> List.countBy _.Name
|> ValidationResult.collect (fun (name, length) ->
if length > 1 then
AstError.AsResult (
$"There are %i{length} arguments with name '%s{name}' defined in %s{fieldOrDirective}. Field arguments must be unique.",
path
)
else
Success)
let argsValid =
validateArgs $"alias or field '%s{selection.AliasOrName}'" selection.Path selection.Field.Arguments
let directiveArgsValid =
selection.Field.Directives
|> ValidationResult.collect (fun directive -> validateArgs $"directive '%s{directive.Name}'" selection.Path directive.Arguments)
argsValid @@ directiveArgsValid
let internal validateArgumentUniqueness (ctx : ValidationContext) = onAllSelections ctx validateArgumentUniquenessInSelection
let private checkRequiredArguments (schemaInfo : SchemaInfo) (selection : SelectionInfo) =
let inputsValid =
selection.InputValues
|> ValidationResult.collect (fun argDef ->
match argDef.Type.Kind with
| TypeKind.NON_NULL when argDef.DefaultValue.IsNone ->
match
selection.Field.Arguments
|> List.tryFind (fun arg -> arg.Name = argDef.Name)
with
| Some arg when arg.Value <> NullValue -> Success
| _ ->
AstError.AsResult (
$"Argument '%s{argDef.Name}' of field '%s{selection.Field.Name}' of type '%s{selection.FragmentOrParentType.Name}' is required and does not have a default value.",
selection.Path
)
| _ -> Success)
let directivesValid =
selection.Field.Directives
|> ValidationResult.collect (fun directive ->
match
schemaInfo.Directives
|> Array.tryFind (fun d -> d.Name = directive.Name)
with
| Some directiveType ->
directiveType.Args
|> ValidationResult.collect (fun argDef ->
match argDef.Type.Kind with
| TypeKind.NON_NULL when argDef.DefaultValue.IsNone ->
match
directive.Arguments
|> List.tryFind (fun arg -> arg.Name = argDef.Name)
with
| Some arg when arg.Value <> NullValue -> Success
| _ ->
AstError.AsResult (
$"Argument '%s{argDef.Name}' of directive '%s{directiveType.Name}' of field '%s{selection.Field.Name}' of type '%s{selection.FragmentOrParentType.Name}' is required and does not have a default value.",
selection.Path
)
| _ -> Success)
| None -> Success)
inputsValid @@ directivesValid
let internal validateRequiredArguments (ctx : ValidationContext) = onAllSelections ctx (checkRequiredArguments ctx.Schema)
let internal validateFragmentNameUniqueness (ctx : ValidationContext) =
let counts = Dictionary<string, int> ()
ctx.FragmentDefinitions
|> List.iter (fun frag ->
frag.Definition.Name
|> ValueOption.iter (fun name -> Dictionary.addWith (+) name 1 counts))
counts
|> ValidationResult.collect (fun (KeyValue (name, length)) ->
if length > 1 then
AstError.AsResult
$"There are %i{length} fragments with name '%s{name}' in the document. Fragment definitions must have unique names."
else
Success)
let rec private checkFragmentTypeExistence
(fragmentDefinitions : FragmentDefinition list)
(schemaInfo : SchemaInfo)
(path : FieldPath)
(frag : FragmentDefinition)
=
let typeConditionsValid =
let fragType = voption {
let! typeCondition = frag.TypeCondition
return! schemaInfo.TryGetTypeByName typeCondition
}
match fragType with
| ValueSome _ -> Success
| ValueNone when frag.Name.IsSome ->
AstError.AsResult
$"Fragment '%s{frag.Name.Value}' has type condition '%s{frag.TypeCondition.Value}', but that type does not exist in the schema."
| ValueNone ->
AstError.AsResult (
$"Inline fragment has type condition '%s{frag.TypeCondition.Value}', but that type does not exist in the schema.",
path
)
typeConditionsValid
@@ (frag.SelectionSet
|> ValidationResult.collect (checkFragmentTypeExistenceInSelection fragmentDefinitions schemaInfo path))
and private checkFragmentTypeExistenceInSelection (fragmentDefinitions : FragmentDefinition list) (schemaInfo : SchemaInfo) (path : FieldPath) =
function
| Field field ->
let path = box field.AliasOrName :: path
field.SelectionSet
|> ValidationResult.collect (checkFragmentTypeExistenceInSelection fragmentDefinitions schemaInfo path)
| InlineFragment frag -> checkFragmentTypeExistence fragmentDefinitions schemaInfo path frag
| _ -> Success
let internal validateFragmentTypeExistence (ctx : ValidationContext) =
let fragmentDefinitions = getFragmentDefinitions ctx.Document
ctx.Document.Definitions
|> ValidationResult.collect (function
| FragmentDefinition frag ->
let path = frag.Name |> ValueOption.map box |> ValueOption.toList
checkFragmentTypeExistence fragmentDefinitions ctx.Schema path frag
| OperationDefinition odef ->
let path = odef.Name |> ValueOption.map box |> ValueOption.toList
odef.SelectionSet
|> ValidationResult.collect (checkFragmentTypeExistenceInSelection fragmentDefinitions ctx.Schema path))
let rec private checkFragmentOnCompositeType (selection : SelectionInfo) =
let fragmentTypeValid =
match selection.FragmentType with
| ValueSome fragType ->
match fragType.Kind with
| TypeKind.UNION
| TypeKind.OBJECT
| TypeKind.INTERFACE -> Success
| _ when selection.FragmentSpreadName.IsSome ->
AstError.AsResult (
$"Fragment '%s{selection.FragmentSpreadName.Value}' has type kind %s{fragType.Kind.ToString ()}, but fragments can only be defined in UNION, OBJECT or INTERFACE types.",
selection.Path
)
| _ ->
AstError.AsResult (
$"Inline fragment has type kind %s{fragType.Kind.ToString ()}, but fragments can only be defined in UNION, OBJECT or INTERFACE types.",
selection.Path
)
| ValueNone -> Success
fragmentTypeValid
@@ (selection.SelectionSet
|> ValidationResult.collect checkFragmentOnCompositeType)
let internal validateFragmentsOnCompositeTypes (ctx : ValidationContext) = onAllSelections ctx checkFragmentOnCompositeType
let internal validateFragmentsMustBeUsed (ctx : ValidationContext) =
let rec getSpreadNames (acc : Set<string>) =
function
| Field field ->
field.SelectionSet
|> Set.ofList
|> Set.collect (getSpreadNames acc)
| InlineFragment frag ->
frag.SelectionSet
|> Set.ofList
|> Set.collect (getSpreadNames acc)
| FragmentSpread spread -> acc.Add spread.Name
let fragmentSpreadNames =
Set.ofList ctx.Document.Definitions
|> Set.collect (fun def ->
Set.ofList def.SelectionSet
|> Set.collect (getSpreadNames Set.empty))
getFragmentDefinitions ctx.Document
|> ValidationResult.collect (fun def ->
if
def.Name.IsSome
&& Set.contains def.Name.Value fragmentSpreadNames
then
Success
else
AstError.AsResult
$"Fragment '%s{def.Name.Value}' is not used in any operation in the document. Fragments must be used in at least one operation.")
let rec private fragmentSpreadTargetDefinedInSelection (fragmentDefinitionNames : string list) (path : FieldPath) =
function
| Field field ->
let path = box field.AliasOrName :: path
field.SelectionSet
|> ValidationResult.collect (fragmentSpreadTargetDefinedInSelection fragmentDefinitionNames path)
| InlineFragment frag ->
frag.SelectionSet
|> ValidationResult.collect (fragmentSpreadTargetDefinedInSelection fragmentDefinitionNames path)
| FragmentSpread spread ->
if List.contains spread.Name fragmentDefinitionNames then
Success
else
AstError.AsResult ($"Fragment spread '%s{spread.Name}' refers to a non-existent fragment definition in the document.", path)
let internal validateFragmentSpreadTargetDefined (ctx : ValidationContext) =
let fragmentDefinitionNames = ctx.FragmentDefinitions |> List.vchoose _.Name
ctx.Document.Definitions
|> ValidationResult.collect (function
| FragmentDefinition frag ->
let path = frag.Name |> ValueOption.map box |> ValueOption.toList
frag.SelectionSet
|> ValidationResult.collect (fragmentSpreadTargetDefinedInSelection fragmentDefinitionNames path)
| OperationDefinition odef ->
let path = odef.Name |> ValueOption.map box |> ValueOption.toList
odef.SelectionSet
|> ValidationResult.collect (fragmentSpreadTargetDefinedInSelection fragmentDefinitionNames path))
let rec private checkFragmentMustNotHaveCycles
(fragmentDefinitions : FragmentDefinition list)
(visited : string list)
(fragName : string)
(fragSelectionSet : Selection list)
=
let visitCount =
visited
|> List.filter (fun x -> x = fragName)
|> List.length
if visitCount > 1 then
AstError.AsResult $"Fragment '%s{fragName}' is making a cyclic reference."
else
fragSelectionSet
|> ValidationResult.collect (checkFragmentsMustNotHaveCyclesInSelection fragmentDefinitions (fragName :: visited))
and private checkFragmentsMustNotHaveCyclesInSelection (fragmentDefinitions : FragmentDefinition list) (visited : string list) =
function
| Field field ->
field.SelectionSet
|> ValidationResult.collect (checkFragmentsMustNotHaveCyclesInSelection fragmentDefinitions visited)
| InlineFragment inlineFrag ->
inlineFrag.SelectionSet
|> ValidationResult.collect (checkFragmentsMustNotHaveCyclesInSelection fragmentDefinitions visited)
| FragmentSpread spread ->
match
fragmentDefinitions
|> List.tryFind (fun f -> f.Name.IsSome && f.Name.Value = spread.Name)
with
| Some frag -> checkFragmentMustNotHaveCycles fragmentDefinitions visited spread.Name frag.SelectionSet
| None -> Success
let internal validateFragmentsMustNotFormCycles (ctx : ValidationContext) =
let fragmentDefinitions =
ctx.FragmentDefinitions
|> List.map (fun frag -> frag.Definition)
let fragNamesAndSelections =
fragmentDefinitions
|> List.vchoose (fun frag -> frag.Name |> ValueOption.map (fun n -> n, frag.SelectionSet))
fragNamesAndSelections
|> ValidationResult.collect (fun (name, selectionSet) -> checkFragmentMustNotHaveCycles fragmentDefinitions [] name selectionSet)
let private checkFragmentSpreadIsPossibleInSelection (path : FieldPath, parentType : IntrospectionType, fragmentType : IntrospectionType) =
if not (typesAreApplicable (parentType, fragmentType)) then
AstError.AsResult (
$"Fragment type condition '%s{fragmentType.Name}' is not applicable to the parent type of the field '%s{parentType.Name}'.",
path
)
else
Success
let rec private getFragmentAndParentTypes (set : SelectionInfo list) =
([], set)
||> List.fold (fun acc selection ->
match selection.FragmentType with
| ValueSome fragType when fragType.Name <> selection.ParentType.Name -> (selection.Path, selection.ParentType, fragType) :: acc
| _ -> acc)
let internal validateFragmentSpreadIsPossible (ctx : ValidationContext) =
ctx.Definitions
|> ValidationResult.collect (fun def ->
def.SelectionSet
|> getFragmentAndParentTypes
|> ValidationResult.collect (checkFragmentSpreadIsPossibleInSelection))
let private checkInputValue (schemaInfo : SchemaInfo) (variables : VariableDefinition list option) (selection : SelectionInfo) =
let rec checkIsCoercible (tref : IntrospectionTypeRef) (argName : string) (value : InputValue) =
let canNotCoerce =
AstError.AsResult (
$"Argument field or value named '%s{argName}' can not be coerced. It does not match a valid literal representation for the type.",
selection.Path
)
match value with
| NullValue when tref.Kind = TypeKind.NON_NULL ->
AstError.AsResult (
$"Argument '%s{argName}' value can not be coerced. It's type is non-nullable but the argument has a null value.",
selection.Path
)
| NullValue -> Success
| _ when tref.Kind = TypeKind.NON_NULL -> checkIsCoercible tref.OfType.Value argName value
| IntValue _ ->
match tref.Name, tref.Kind with
| Some ("ID" | "Int" | "Float"), TypeKind.SCALAR -> Success
| _ -> canNotCoerce
| FloatValue _ ->
match tref.Name, tref.Kind with
| Some "Float", TypeKind.SCALAR -> Success
| _ -> canNotCoerce
| BooleanValue _ ->
match tref.Name, tref.Kind with
| Some "Boolean", TypeKind.SCALAR -> Success
| _ -> canNotCoerce
| StringValue _ ->
let invalidScalars = [| "Int"; "Float"; "Boolean" |]
match tref.Name, tref.Kind with
| (Some x, TypeKind.SCALAR) when not (Array.contains x invalidScalars) -> Success
| (Some x, TypeKind.INPUT_OBJECT) when x = FileType.Name -> Success
| _ -> canNotCoerce
| EnumValue _ ->
match tref.Kind with
| TypeKind.ENUM -> Success
| _ -> canNotCoerce
| ListValue values ->
match tref.Kind with
| TypeKind.LIST when tref.OfType.IsSome ->
values
|> ValidationResult.collect (checkIsCoercible tref.OfType.Value argName)
| _ -> canNotCoerce
| ObjectValue props ->
match tref.Kind with
| TypeKind.OBJECT
| TypeKind.INTERFACE
| TypeKind.UNION
| TypeKind.INPUT_OBJECT when tref.Name.IsSome ->
match schemaInfo.TryGetTypeByRef (tref) with
| Some itype ->
let fieldMap =
itype.InputFields
|> Option.defaultValue [||]
|> Array.fold (fun acc inputVal -> Map.add inputVal.Name inputVal.Type acc) Map.empty
let canCoerceFields =
fieldMap
|> ValidationResult.collect (fun kvp ->
if
kvp.Value.Kind = TypeKind.NON_NULL
&& not (props.ContainsKey (kvp.Key))
then
AstError.AsResult (
$"Can not coerce argument '%s{argName}'. Argument definition '%s{tref.Name.Value}' have a required field '%s{kvp.Key}', but that field does not exist in the literal value for the argument.",
selection.Path
)
else
Success)
let canCoerceProps =
props
|> ValidationResult.collect (fun kvp ->
match Map.tryFind kvp.Key fieldMap with
| Some fieldTypeRef -> checkIsCoercible fieldTypeRef kvp.Key kvp.Value
| None ->
AstError.AsResult (
$"Can not coerce argument '%s{argName}'. The field '%s{kvp.Key}' is not a valid field in the argument definition.",
selection.Path
))
canCoerceFields @@ canCoerceProps
| None -> canNotCoerce
| _ -> canNotCoerce
| VariableName varName ->
let variableDefinition =
variables
|> Option.defaultValue []
|> List.tryPick (fun v ->
if v.VariableName = varName then
Some (v, schemaInfo.TryGetInputType (v.Type))
else
None)
match variableDefinition with
| Some (vdef, Some vtype) when vdef.DefaultValue.IsSome -> checkIsCoercible vtype argName vdef.DefaultValue.Value
| Some (vdef, None) when vdef.DefaultValue.IsSome -> canNotCoerce
| _ -> Success
selection.Field.Arguments