forked from slicknode/graphql-query-complexity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueryComplexity.ts
505 lines (459 loc) · 15.4 KB
/
QueryComplexity.ts
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
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-use-before-define */
/**
* Created by Ivo Meißner on 28.07.17.
*/
import {
getArgumentValues,
getDirectiveValues,
getVariableValues,
} from 'graphql/execution/values.js';
import {
ValidationContext,
FragmentDefinitionNode,
OperationDefinitionNode,
FieldNode,
FragmentSpreadNode,
InlineFragmentNode,
GraphQLField,
isCompositeType,
GraphQLCompositeType,
GraphQLFieldMap,
GraphQLSchema,
DocumentNode,
TypeInfo,
visit,
visitWithTypeInfo,
GraphQLDirective,
isAbstractType,
GraphQLNamedType,
GraphQLUnionType,
GraphQLObjectType,
GraphQLInterfaceType,
Kind,
getNamedType,
GraphQLError,
} from 'graphql';
export type ComplexityEstimatorArgs = {
type: GraphQLCompositeType;
field: GraphQLField<any, any>;
node: FieldNode;
args: { [key: string]: any };
childComplexity: number;
context?: Record<string, any>;
};
export type ComplexityEstimator = (
options: ComplexityEstimatorArgs
) => number | void;
// Complexity can be anything that is supported by the configured estimators
export type Complexity = any;
// Map of complexities for possible types (of Union, Interface types)
type ComplexityMap = {
[typeName: string]: number;
};
export interface QueryComplexityOptions {
// The maximum allowed query complexity, queries above this threshold will be rejected
maximumComplexity: number;
// The query variables. This is needed because the variables are not available
// in the visitor of the graphql-js library
variables?: Record<string, any>;
// specify operation name only when pass multi-operation documents
operationName?: string;
// Optional callback function to retrieve the determined query complexity
// Will be invoked whether the query is rejected or not
// This can be used for logging or to implement rate limiting
onComplete?: (complexity: number) => void;
// Optional function to create a custom error
createError?: (max: number, actual: number) => GraphQLError;
// An array of complexity estimators to use for estimating the complexity
estimators: Array<ComplexityEstimator>;
// Pass request context to the estimators via estimationContext
context?: Record<string, any>;
}
function queryComplexityMessage(max: number, actual: number): string {
return (
`The query exceeds the maximum complexity of ${max}. ` +
`Actual complexity is ${actual}`
);
}
export function getComplexity(options: {
estimators: ComplexityEstimator[];
schema: GraphQLSchema;
query: DocumentNode;
variables?: Record<string, any>;
operationName?: string;
context?: Record<string, any>;
}): number {
const typeInfo = new TypeInfo(options.schema);
const errors: GraphQLError[] = [];
const context = new ValidationContext(
options.schema,
options.query,
typeInfo,
(error) => errors.push(error)
);
const visitor = new QueryComplexity(context, {
// Maximum complexity does not matter since we're only interested in the calculated complexity.
maximumComplexity: Infinity,
estimators: options.estimators,
variables: options.variables,
operationName: options.operationName,
context: options.context,
});
visit(options.query, visitWithTypeInfo(typeInfo, visitor));
// Throw first error if any
if (errors.length) {
throw errors.pop();
}
return visitor.complexity;
}
export default class QueryComplexity {
context: ValidationContext;
complexity: number;
options: QueryComplexityOptions;
OperationDefinition: Record<string, any>;
estimators: Array<ComplexityEstimator>;
includeDirectiveDef: GraphQLDirective;
skipDirectiveDef: GraphQLDirective;
variableValues: Record<string, any>;
requestContext?: Record<string, any>;
constructor(context: ValidationContext, options: QueryComplexityOptions) {
if (
!(
typeof options.maximumComplexity === 'number' &&
options.maximumComplexity > 0
)
) {
throw new Error('Maximum query complexity must be a positive number');
}
this.context = context;
this.complexity = 0;
this.options = options;
this.includeDirectiveDef = this.context.getSchema().getDirective('include');
this.skipDirectiveDef = this.context.getSchema().getDirective('skip');
this.estimators = options.estimators;
this.variableValues = {};
this.requestContext = options.context;
this.OperationDefinition = {
enter: this.onOperationDefinitionEnter,
leave: this.onOperationDefinitionLeave,
};
}
onOperationDefinitionEnter(operation: OperationDefinitionNode): void {
if (
typeof this.options.operationName === 'string' &&
this.options.operationName !== operation.name.value
) {
return;
}
// Get variable values from variables that are passed from options, merged
// with default values defined in the operation
const { coerced, errors } = getVariableValues(
this.context.getSchema(),
// We have to create a new array here because input argument is not readonly in graphql ~14.6.0
operation.variableDefinitions ? [...operation.variableDefinitions] : [],
this.options.variables ?? {}
);
if (errors && errors.length) {
// We have input validation errors, report errors and abort
errors.forEach((error) => this.context.reportError(error));
return;
}
this.variableValues = coerced;
switch (operation.operation) {
case 'query':
this.complexity += this.nodeComplexity(
operation,
this.context.getSchema().getQueryType()
);
break;
case 'mutation':
this.complexity += this.nodeComplexity(
operation,
this.context.getSchema().getMutationType()
);
break;
case 'subscription':
this.complexity += this.nodeComplexity(
operation,
this.context.getSchema().getSubscriptionType()
);
break;
default:
throw new Error(
`Query complexity could not be calculated for operation of type ${operation.operation}`
);
}
}
onOperationDefinitionLeave(
operation: OperationDefinitionNode
): GraphQLError | void {
if (
typeof this.options.operationName === 'string' &&
this.options.operationName !== operation.name.value
) {
return;
}
if (this.options.onComplete) {
this.options.onComplete(this.complexity);
}
if (this.complexity > this.options.maximumComplexity) {
return this.context.reportError(this.createError());
}
}
nodeComplexity(
node:
| FieldNode
| FragmentDefinitionNode
| InlineFragmentNode
| OperationDefinitionNode,
typeDef:
| GraphQLObjectType
| GraphQLInterfaceType
| GraphQLUnionType
| undefined
): number {
if (node.selectionSet && typeDef) {
let fields: GraphQLFieldMap<any, any> = {};
if (
typeDef instanceof GraphQLObjectType ||
typeDef instanceof GraphQLInterfaceType
) {
fields = typeDef.getFields();
}
// Determine all possible types of the current node
let possibleTypeNames: string[];
if (isAbstractType(typeDef)) {
possibleTypeNames = this.context
.getSchema()
.getPossibleTypes(typeDef)
.map((t) => t.name);
} else {
possibleTypeNames = [typeDef.name];
}
// Collect complexities for all possible types individually
const selectionSetComplexities: ComplexityMap =
node.selectionSet.selections.reduce(
(
complexities: ComplexityMap,
childNode: FieldNode | FragmentSpreadNode | InlineFragmentNode
): ComplexityMap => {
// let nodeComplexity = 0;
let innerComplexities = complexities;
let includeNode = true;
let skipNode = false;
for (const directive of childNode.directives ?? []) {
const directiveName = directive.name.value;
switch (directiveName) {
case 'include': {
const values = getDirectiveValues(
this.includeDirectiveDef,
childNode,
this.variableValues || {}
);
if (typeof values.if === 'boolean') {
includeNode = values.if;
}
break;
}
case 'skip': {
const values = getDirectiveValues(
this.skipDirectiveDef,
childNode,
this.variableValues || {}
);
if (typeof values.if === 'boolean') {
skipNode = values.if;
}
break;
}
}
}
if (!includeNode || skipNode) {
return complexities;
}
switch (childNode.kind) {
case Kind.FIELD: {
const field = fields[childNode.name.value];
// Invalid field, should be caught by other validation rules
if (!field) {
break;
}
const fieldType = getNamedType(field.type);
// Get arguments
let args: { [key: string]: any };
try {
args = getArgumentValues(
field,
childNode,
this.variableValues || {}
);
} catch (e) {
this.context.reportError(e);
return complexities;
}
// Check if we have child complexity
let childComplexity = 0;
if (isCompositeType(fieldType)) {
childComplexity = this.nodeComplexity(childNode, fieldType);
}
// Run estimators one after another and return first valid complexity
// score
const estimatorArgs: ComplexityEstimatorArgs = {
childComplexity,
args,
field,
node: childNode,
type: typeDef,
context: this.requestContext,
};
const validScore = this.estimators.find((estimator) => {
const tmpComplexity = estimator(estimatorArgs);
if (
typeof tmpComplexity === 'number' &&
!isNaN(tmpComplexity)
) {
innerComplexities = addComplexities(
tmpComplexity,
complexities,
possibleTypeNames
);
return true;
}
return false;
});
if (!validScore) {
this.context.reportError(
new GraphQLError(
`No complexity could be calculated for field ${typeDef.name}.${field.name}. ` +
'At least one complexity estimator has to return a complexity score.'
)
);
return complexities;
}
break;
}
case Kind.FRAGMENT_SPREAD: {
const fragment = this.context.getFragment(childNode.name.value);
// Unknown fragment, should be caught by other validation rules
if (!fragment) {
break;
}
const fragmentType = this.context
.getSchema()
.getType(fragment.typeCondition.name.value);
// Invalid fragment type, ignore. Should be caught by other validation rules
if (!isCompositeType(fragmentType)) {
break;
}
const nodeComplexity = this.nodeComplexity(
fragment,
fragmentType
);
if (isAbstractType(fragmentType)) {
// Add fragment complexity for all possible types
innerComplexities = addComplexities(
nodeComplexity,
complexities,
this.context
.getSchema()
.getPossibleTypes(fragmentType)
.map((t) => t.name)
);
} else {
// Add complexity for object type
innerComplexities = addComplexities(
nodeComplexity,
complexities,
[fragmentType.name]
);
}
break;
}
case Kind.INLINE_FRAGMENT: {
let inlineFragmentType: GraphQLNamedType = typeDef;
if (childNode.typeCondition && childNode.typeCondition.name) {
inlineFragmentType = this.context
.getSchema()
.getType(childNode.typeCondition.name.value);
if (!isCompositeType(inlineFragmentType)) {
break;
}
}
const nodeComplexity = this.nodeComplexity(
childNode,
inlineFragmentType
);
if (isAbstractType(inlineFragmentType)) {
// Add fragment complexity for all possible types
innerComplexities = addComplexities(
nodeComplexity,
complexities,
this.context
.getSchema()
.getPossibleTypes(inlineFragmentType)
.map((t) => t.name)
);
} else {
// Add complexity for object type
innerComplexities = addComplexities(
nodeComplexity,
complexities,
[inlineFragmentType.name]
);
}
break;
}
default: {
innerComplexities = addComplexities(
this.nodeComplexity(childNode, typeDef),
complexities,
possibleTypeNames
);
break;
}
}
return innerComplexities;
},
{}
);
// Only return max complexity of all possible types
if (!selectionSetComplexities) {
return NaN;
}
return Math.max(...Object.values(selectionSetComplexities), 0);
}
return 0;
}
createError(): GraphQLError {
if (typeof this.options.createError === 'function') {
return this.options.createError(
this.options.maximumComplexity,
this.complexity
);
}
return new GraphQLError(
queryComplexityMessage(this.options.maximumComplexity, this.complexity)
);
}
}
/**
* Adds a complexity to the complexity map for all possible types
* @param complexity
* @param complexityMap
* @param possibleTypes
*/
function addComplexities(
complexity: number,
complexityMap: ComplexityMap,
possibleTypes: string[]
): ComplexityMap {
for (const type of possibleTypes) {
if (Object.prototype.hasOwnProperty.call(complexityMap, type)) {
complexityMap[type] += complexity;
} else {
complexityMap[type] = complexity;
}
}
return complexityMap;
}