-
Notifications
You must be signed in to change notification settings - Fork 1
/
validator.go
330 lines (290 loc) · 9.4 KB
/
validator.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
package graphql
import (
"github.com/sprucehealth/graphql/gqlerrors"
"github.com/sprucehealth/graphql/language/ast"
"github.com/sprucehealth/graphql/language/visitor"
)
type ValidationResult struct {
IsValid bool
Errors []gqlerrors.FormattedError
}
// ValidateDocument implements the "Validation" section of the spec.
//
// Validation runs synchronously, returning an array of encountered errors, or
// an empty array if no errors were encountered and the document is valid.
//
// A list of specific validation rules may be provided. If not provided, the
// default list of rules defined by the GraphQL specification will be used.
//
// Each validation rules is a function which returns a visitor
// (see the language/visitor API). Visitor methods are expected to return
// GraphQLErrors, or Arrays of GraphQLErrors when invalid.
func ValidateDocument(schema *Schema, astDoc *ast.Document, rules []ValidationRuleFn) (vr ValidationResult) {
if len(rules) == 0 {
rules = SpecifiedRules
}
vr.IsValid = false
if schema == nil {
vr.Errors = append(vr.Errors, gqlerrors.NewFormattedError("Must provide schema"))
return vr
}
if astDoc == nil {
vr.Errors = append(vr.Errors, gqlerrors.NewFormattedError("Must provide document"))
return vr
}
typeInfo := NewTypeInfo(&TypeInfoConfig{
Schema: schema,
})
vr.Errors = VisitUsingRules(schema, typeInfo, astDoc, rules)
vr.IsValid = len(vr.Errors) == 0
return vr
}
// VisitUsingRules This uses a specialized visitor which runs multiple visitors in parallel,
// while maintaining the visitor skip and break API.
//
// @internal
// Had to expose it to unit test experimental customizable validation feature,
// but not meant for public consumption
func VisitUsingRules(schema *Schema, typeInfo *TypeInfo, astDoc *ast.Document, rules []ValidationRuleFn) []gqlerrors.FormattedError {
context := NewValidationContext(schema, astDoc, typeInfo)
visitInstance := func(astNode ast.Node, instance *ValidationRuleInstance) {
err := visitor.Visit(astNode, &visitor.VisitorOptions{
Enter: func(p visitor.VisitFuncParams) (string, any) {
node, ok := p.Node.(ast.Node)
if !ok {
return visitor.ActionNoChange, nil
}
// Collect type information about the current position in the AST.
typeInfo.Enter(node)
action := visitor.ActionNoChange
var result any
if instance.Enter != nil {
action, result = instance.Enter(p)
}
// If the result is "false" (ie action === Action.Skip), we're not visiting any descendent nodes,
// but need to update typeInfo.
if action == visitor.ActionSkip {
typeInfo.Leave(node)
}
return action, result
},
Leave: func(p visitor.VisitFuncParams) (string, any) {
node, ok := p.Node.(ast.Node)
if !ok {
return visitor.ActionNoChange, nil
}
var action = visitor.ActionNoChange
var result any
if instance.Leave != nil {
action, result = instance.Leave(p)
}
typeInfo.Leave(node)
return action, result
},
})
// TODO: handle error
_ = err
}
for _, rule := range rules {
visitInstance(astDoc, rule(context))
}
return context.Errors()
}
type HasSelectionSet interface {
GetLoc() ast.Location
GetSelectionSet() *ast.SelectionSet
}
var _ HasSelectionSet = (*ast.OperationDefinition)(nil)
var _ HasSelectionSet = (*ast.FragmentDefinition)(nil)
type VariableUsage struct {
Node *ast.Variable
Type Input
}
type ValidationContext struct {
schema *Schema
astDoc *ast.Document
typeInfo *TypeInfo
fragments map[string]*ast.FragmentDefinition
variableUsages map[HasSelectionSet][]*VariableUsage
recursiveVariableUsages map[*ast.OperationDefinition][]*VariableUsage
recursivelyReferencedFragments map[*ast.OperationDefinition][]*ast.FragmentDefinition
fragmentSpreads map[HasSelectionSet][]*ast.FragmentSpread
errors []gqlerrors.FormattedError
}
func NewValidationContext(schema *Schema, astDoc *ast.Document, typeInfo *TypeInfo) *ValidationContext {
return &ValidationContext{
schema: schema,
astDoc: astDoc,
typeInfo: typeInfo,
variableUsages: make(map[HasSelectionSet][]*VariableUsage),
recursiveVariableUsages: make(map[*ast.OperationDefinition][]*VariableUsage),
recursivelyReferencedFragments: make(map[*ast.OperationDefinition][]*ast.FragmentDefinition),
fragmentSpreads: make(map[HasSelectionSet][]*ast.FragmentSpread),
}
}
func (ctx *ValidationContext) ReportError(err error) {
formattedErr := gqlerrors.FormatError(err)
ctx.errors = append(ctx.errors, formattedErr)
}
func (ctx *ValidationContext) Errors() []gqlerrors.FormattedError {
return ctx.errors
}
func (ctx *ValidationContext) Schema() *Schema {
return ctx.schema
}
func (ctx *ValidationContext) Document() *ast.Document {
return ctx.astDoc
}
func (ctx *ValidationContext) Fragment(name string) *ast.FragmentDefinition {
if ctx.fragments == nil {
if ctx.Document() == nil {
return nil
}
defs := ctx.Document().Definitions
fragments := make(map[string]*ast.FragmentDefinition)
for _, def := range defs {
if def, ok := def.(*ast.FragmentDefinition); ok {
defName := ""
if def.Name != nil {
defName = def.Name.Value
}
fragments[defName] = def
}
}
ctx.fragments = fragments
}
return ctx.fragments[name]
}
func (ctx *ValidationContext) FragmentSpreads(node HasSelectionSet) []*ast.FragmentSpread {
if spreads, ok := ctx.fragmentSpreads[node]; ok && spreads != nil {
return spreads
}
spreads := []*ast.FragmentSpread{}
setsToVisit := []*ast.SelectionSet{node.GetSelectionSet()}
for {
if len(setsToVisit) == 0 {
break
}
var set *ast.SelectionSet
// pop
set, setsToVisit = setsToVisit[len(setsToVisit)-1], setsToVisit[:len(setsToVisit)-1]
if set.Selections != nil {
for _, selection := range set.Selections {
switch selection := selection.(type) {
case *ast.FragmentSpread:
spreads = append(spreads, selection)
case *ast.Field:
if selection.SelectionSet != nil {
setsToVisit = append(setsToVisit, selection.SelectionSet)
}
case *ast.InlineFragment:
if selection.SelectionSet != nil {
setsToVisit = append(setsToVisit, selection.SelectionSet)
}
}
}
}
ctx.fragmentSpreads[node] = spreads
}
return spreads
}
func (ctx *ValidationContext) RecursivelyReferencedFragments(operation *ast.OperationDefinition) []*ast.FragmentDefinition {
if fragments, ok := ctx.recursivelyReferencedFragments[operation]; ok && fragments != nil {
return fragments
}
fragments := []*ast.FragmentDefinition{}
collectedNames := map[string]bool{}
nodesToVisit := []HasSelectionSet{operation}
for {
if len(nodesToVisit) == 0 {
break
}
var node HasSelectionSet
node, nodesToVisit = nodesToVisit[len(nodesToVisit)-1], nodesToVisit[:len(nodesToVisit)-1]
spreads := ctx.FragmentSpreads(node)
for _, spread := range spreads {
fragName := ""
if spread.Name != nil {
fragName = spread.Name.Value
}
if res, ok := collectedNames[fragName]; !ok || !res {
collectedNames[fragName] = true
fragment := ctx.Fragment(fragName)
if fragment != nil {
fragments = append(fragments, fragment)
nodesToVisit = append(nodesToVisit, fragment)
}
}
}
}
ctx.recursivelyReferencedFragments[operation] = fragments
return fragments
}
func (ctx *ValidationContext) VariableUsages(node HasSelectionSet) []*VariableUsage {
if usages, ok := ctx.variableUsages[node]; ok && usages != nil {
return usages
}
typeInfo := NewTypeInfo(&TypeInfoConfig{
Schema: ctx.schema,
})
var usages []*VariableUsage
err := visitor.Visit(node, &visitor.VisitorOptions{
Enter: func(p visitor.VisitFuncParams) (string, any) {
if node, ok := p.Node.(ast.Node); ok {
typeInfo.Enter(node)
switch node := node.(type) {
case *ast.VariableDefinition:
typeInfo.Leave(node)
return visitor.ActionSkip, nil
case *ast.Variable:
usages = append(usages, &VariableUsage{
Node: node,
Type: typeInfo.InputType(),
})
}
}
return visitor.ActionNoChange, nil
},
Leave: func(p visitor.VisitFuncParams) (string, any) {
if node, ok := p.Node.(ast.Node); ok {
typeInfo.Leave(node)
}
return visitor.ActionNoChange, nil
},
})
// TODO: handle error
_ = err
ctx.variableUsages[node] = usages
return usages
}
func (ctx *ValidationContext) RecursiveVariableUsages(operation *ast.OperationDefinition) []*VariableUsage {
if usages, ok := ctx.recursiveVariableUsages[operation]; ok && usages != nil {
return usages
}
usages := ctx.VariableUsages(operation)
fragments := ctx.RecursivelyReferencedFragments(operation)
for _, fragment := range fragments {
fragmentUsages := ctx.VariableUsages(fragment)
usages = append(usages, fragmentUsages...)
}
ctx.recursiveVariableUsages[operation] = usages
return usages
}
func (ctx *ValidationContext) Type() Output {
return ctx.typeInfo.Type()
}
func (ctx *ValidationContext) ParentType() Composite {
return ctx.typeInfo.ParentType()
}
func (ctx *ValidationContext) InputType() Input {
return ctx.typeInfo.InputType()
}
func (ctx *ValidationContext) FieldDef() *FieldDefinition {
return ctx.typeInfo.FieldDef()
}
func (ctx *ValidationContext) Directive() *Directive {
return ctx.typeInfo.Directive()
}
func (ctx *ValidationContext) Argument() *Argument {
return ctx.typeInfo.Argument()
}