Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Query complexity #139

Merged
merged 14 commits into from
Sep 8, 2018
7 changes: 7 additions & 0 deletions @types/graphql-query-complexity/graphql.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Complexity } from "graphql-query-complexity";

declare module "graphql/type/definition" {
export interface GraphQLFieldConfig<TSource, TContext, TArgs = { [argName: string]: any }> {
complexity?: Complexity;
}
}
55 changes: 55 additions & 0 deletions @types/graphql-query-complexity/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
declare module "graphql-query-complexity" {
import { ValidationContext } from "graphql";
import QueryComplexity, {
QueryComplexityOptions,
} from "graphql-query-complexity/dist/QueryComplexity";

export type ComplexityResolver = (args: any, complexity: number) => number;

export type Complexity = number | ComplexityResolver;

export default function createQueryComplexityValidator(
options: QueryComplexityOptions,
): (context: ValidationContext) => QueryComplexity;
}

declare module "graphql-query-complexity/dist/QueryComplexity" {
import {
ValidationContext,
FragmentDefinitionNode,
OperationDefinitionNode,
FieldNode,
InlineFragmentNode,
GraphQLUnionType,
GraphQLObjectType,
GraphQLInterfaceType,
GraphQLError,
} from "graphql";

export interface QueryComplexityOptions {
maximumComplexity: number;
variables?: Object;
onComplete?: (complexity: number) => void;
createError?: (max: number, actual: number) => GraphQLError;
}

export default class QueryComplexity {
context: ValidationContext;
complexity: number;
options: QueryComplexityOptions;
fragments: {
[name: string]: FragmentDefinitionNode;
};
OperationDefinition: Object;
constructor(context: ValidationContext, options: QueryComplexityOptions);
onOperationDefinitionEnter(operation: OperationDefinitionNode): void;
onOperationDefinitionLeave(): GraphQLError | undefined;
nodeComplexity(
node: FieldNode | FragmentDefinitionNode | InlineFragmentNode | OperationDefinitionNode,
typeDef: GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType,
complexity?: number,
): number;
createError(): GraphQLError;
getDefaultComplexity(args: Object, childScore: number): number;
}
}
1 change: 1 addition & 0 deletions dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require("ts-node/register/transpile-only");
// require("./examples/redis-subscriptions/index.ts");
// require("./examples/resolvers-inheritance/index.ts");
// require("./examples/simple-subscriptions/index.ts");
// require("./examples/query-complexity/index.ts");
// require("./examples/simple-usage/index.ts");
// require("./examples/using-container/index.ts");
// require("./examples/using-scoped-container/index.ts");
Expand Down
71 changes: 71 additions & 0 deletions docs/complexity.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
---
title: Query Complexity
---
A single GraphQL query can potentially generate thousands of database operations. To keep track and limit of what each graphQl operation can do , `TypeGraphQL` provides you the option of integrating with Query Complexity tools like [graphql-query-complexity](https://github.com/ivome/graphql-query-complexity).
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • fix graphQl
  • ...can potentially generate huge workload for a server, like thousands of database operations.
  • maybe we should also mention DDoS and recursive queries, like user -> posts (1000) -> user -> posts (1000)



The cost analysis-based solution is very promising, since you can define a “cost” per field and then analyze the AST to estimate the total cost of the GraphQL query. Of course all the analysis is handled by `graphql-query-complexity` .

All you need to do is define your complexity cost for the fields (fields, mutattions, subscriptions) in`TypeGraphQL` and implement `graphql-query-complexity` in whatever graphQl server you have.

## How to use?
At first, you need to pass `complexity` as an option to the decorator on a field/query/mutation.

Example of complexity
```typescript

@ObjectType()
class MyObject {
@Field({ complexity: 2})
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

space - complexity: 2 })

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed

publicField: string;

@Field({ complexity: 3 })
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe show a field with args and show how to use complexityResolver?

complexField: string;
}
```

You can omit the `complexity` option if the complexity value is 1.

In next step, you need to integrate `graphql-query-complexity` with your graphql server.

```typescript
// Create GraphQL server
const server = new GraphQLServer({ schema });

// Configure server options
const serverOptions: Options = {
port: 4000,
endpoint: "/graphql",
playground: "/playground",
validationRules: req => [
queryComplexity({
// The maximum allowed query complexity, queries above this threshold will be rejected
maximumComplexity: 8,
// The query variables. This is needed because the variables are not available
// in the visitor of the graphql-js library
variables: req.query.variables,
// Optional callback function to retrieve the determined query complexity
// Will be invoked weather the query is rejected or not
// This can be used for logging or to implement rate limiting
onComplete: (complexity: number) => {
console.log("Query Complexity:", complexity);
},
}),
],
};

// Start the server
server.start(serverOptions, ({ port, playground }) => {
console.log(
`Server is running, GraphQL Playground available at http://localhost:${port}${playground}`,
);
});
```

And it's done! 😉 . You can pass complexity as option to any of `@field`, `@fieldResolver`, `@mutation` & `@subscription`. For the same property, if both the @fieldresolver as well as @field have complexity defined , then the complexity passed to the field resolver decorator takes precedence.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PascalCase for decorators names and always wrap in backticks

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move You can pass complexity as option to any... above this, place it below You can omit the complexity.


Have a look at the [graphql-query-complexity](https://github.com/ivome/graphql-query-complexity) docs to understand more about how query complexity is computed.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For more info about how query complexity is computed, please visit graphql-query-complexity docs.



## Example
You can see how this works together in the [simple query complexity example](https://github.com/19majkel94/type-graphql/tree/master/examples/query-complexity).
15 changes: 15 additions & 0 deletions examples/query-complexity/examples.gql
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@

query GetRecipesWithComplexityError {
recipes {
title
averageRating,
ratingsCount
}
}

query GetRecipesWithoutComplexityError {
recipes {
title
averageRating
}
}
Empty file.
52 changes: 52 additions & 0 deletions examples/query-complexity/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import "reflect-metadata";
import { GraphQLServer, Options } from "graphql-yoga";
import { buildSchema } from "../../src";
import queryComplexity from "graphql-query-complexity";
import { RecipeResolver } from "./recipe-resolver";

async function bootstrap() {
// build TypeGraphQL executable schema
const schema = await buildSchema({
resolvers: [RecipeResolver],
});

// Create GraphQL server
const server = new GraphQLServer({ schema });

// Configure server options
const serverOptions: Options = {
port: 4000,
endpoint: "/graphql",
playground: "/playground",
validationRules: req => [
/**
abhikmitra marked this conversation as resolved.
Show resolved Hide resolved
* This provides GraphQL query analysis to reject complex queries to your GraphQL server.
* This can be used to protect your GraphQL servers
* against resource exhaustion and DoS attacks.
* More documentation can be found (here)[https://github.com/ivome/graphql-query-complexity]
*/
queryComplexity({
// The maximum allowed query complexity, queries above this threshold will be rejected
maximumComplexity: 8,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here we can declare the maximum cost of the queries, it can be dynamically and depend on user privileges

// The query variables. This is needed because the variables are not available
// in the visitor of the graphql-js library
variables: req.query.variables,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we also have to pass the query variables to the queryComplexity validator

// Optional callback function to retrieve the determined query complexity
// Will be invoked weather the query is rejected or not
// This can be used for logging or to implement rate limiting
onComplete: (complexity: number) => {
console.log("Query Complexity:", complexity);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can also react on complexity calculation and do something (@abhikmitra I don't know why we show example with console.log btw 😆)

Copy link
Contributor Author

@abhikmitra abhikmitra Sep 2, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure what do you have in your mind other than console log ? I just followed the same format as what is followed in graphql-query-complexity repo

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think here you can subtract the amount from user's account points fund.

},
}),
],
};

// Start the server
server.start(serverOptions, ({ port, playground }) => {
console.log(
`Server is running, GraphQL Playground available at http://localhost:${port}${playground}`,
);
});
}

bootstrap();
22 changes: 22 additions & 0 deletions examples/query-complexity/recipe-resolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Resolver, Query, FieldResolver, Arg, Root, Int, ResolverInterface } from "../../src";

import { Recipe } from "./recipe-type";
import { createRecipeSamples } from "./recipe-samples";

@Resolver(of => Recipe)
export class RecipeResolver implements ResolverInterface<Recipe> {
private readonly items: Recipe[] = createRecipeSamples();

@Query(returns => [Recipe], { description: "Get all the recipes from around the world " })
async recipes(): Promise<Recipe[]> {
return await this.items;
}
/* Complexity in field resolver overrides complexity of equivalent field type*/
@FieldResolver({ complexity: 10 })
ratingsCount(
@Root() recipe: Recipe,
@Arg("minRate", type => Int, { nullable: true }) minRate: number = 0.0,
): number {
return recipe.ratings.filter(rating => rating >= minRate).length;
}
}
26 changes: 26 additions & 0 deletions examples/query-complexity/recipe-samples.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { plainToClass } from "class-transformer";

import { Recipe } from "./recipe-type";

export function createRecipeSamples() {
return plainToClass(Recipe, [
{
description: "Desc 1",
title: "Recipe 1",
ratings: [0, 3, 1],
creationDate: new Date("2018-04-11"),
},
{
description: "Desc 2",
title: "Recipe 2",
ratings: [4, 2, 3, 1],
creationDate: new Date("2018-04-15"),
},
{
description: "Desc 3",
title: "Recipe 3",
ratings: [5, 4],
creationDate: new Date(),
},
]);
}
49 changes: 49 additions & 0 deletions examples/query-complexity/recipe-type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Field, ObjectType, Int, Float } from "../../src";

@ObjectType({ description: "Object representing cooking recipe" })
export class Recipe {
/*
By default, every field gets a complexity of 1.
Which can be customized by passing the complexity parameter
*/
@Field({ complexity: 6 })
title: string;

@Field(type => String, { nullable: true, deprecationReason: "Use `description` field instead" })
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove also all this not needed fields - keep focus only on complexity feature, the Recipe is just the background.

get specification(): string | undefined {
return this.description;
}

@Field({ complexity: 5, nullable: true, description: "The recipe" })
description?: string;

@Field(type => [Int])
ratings: number[];

@Field()
creationDate: Date;

@Field(type => Int, { complexity: 5 })
ratingsCount: number;

@Field(type => Float, {
nullable: true,
/*
By default, every field gets a complexity of 1.
You can also pass a calculation function in the complexity option
to determine a custom complexity.
This function will provide the complexity of
the child nodes as well as the field input arguments.
That way you can make a more realistic estimation of individual field complexity values:
*/
complexity: (args, childComplexity) => childComplexity + 1,
})
get averageRating(): number | null {
const ratingsCount = this.ratings.length;
if (ratingsCount === 0) {
return null;
}
const ratingsSum = this.ratings.reduce((a, b) => a + b, 0);
return ratingsSum / ratingsCount;
}
}
2 changes: 1 addition & 1 deletion examples/simple-usage/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import "reflect-metadata";
import { GraphQLServer, Options } from "graphql-yoga";
import { buildSchema } from "../../src";

import queryComplexity from "graphql-query-complexity";
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one is not needed.

import { RecipeResolver } from "./recipe-resolver";

async function bootstrap() {
Expand Down
Loading