Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@
"error"
]
},
"ignorePatterns": ["jest.*"]
"ignorePatterns": ["jest.*", "build/*"]
}
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,5 @@ dist

# TernJS port file
.tern-port

build/*
21 changes: 21 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [{
"type": "node",
"request": "launch",
"name": "Jest Tests",
"program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
"args": [
"-i", "--verbose", "--no-cache"
],
// "preLaunchTask": "build",
// "internalConsoleOptions": "openOnSessionStart",
// "outFiles": [
// "${workspaceRoot}/dist/**/*"
// ],
// "envFile": "${workspaceRoot}/.env"
}]
}
15 changes: 15 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,19 @@
"source.fixAll.eslint": true
},
"editor.formatOnSave": true,
"configurations": [{
"type": "node",
"request": "launch",
"name": "Jest Tests",
"program": "${workspaceRoot}\\node_modules\\jest\\bin\\jest.js",
"args": [
"-i"
],
// "preLaunchTask": "build",
"internalConsoleOptions": "openOnSessionStart",
"outFiles": [
"${workspaceRoot}/dist/**/*"
],
"envFile": "${workspaceRoot}/.env"
}]
}
15 changes: 7 additions & 8 deletions src/@types/buildTypeWeights.d.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
interface Fields {
[index: string]: number | ((args: ArgumentNode[]) => number);
export interface Fields {
[index: string]: FieldWeight;
}

interface Type {
export type WeightFunction = (args: ArgumentNode[]) => number;
export type FieldWeight = number | WeightFunction;
export interface Type {
readonly weight: number;
readonly fields: Fields;
}

interface TypeWeightObject {
export interface TypeWeightObject {
[index: string]: Type;
}

interface TypeWeightConfig {
export interface TypeWeightConfig {
mutation?: number;
query?: number;
object?: number;
Expand Down
12 changes: 6 additions & 6 deletions src/@types/rateLimit.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
interface RateLimiter {
export interface RateLimiter {
/**
* Checks if a request is allowed under the given conditions and withdraws the specified number of tokens
* @param uuid Unique identifier for the user associated with the request
Expand All @@ -13,17 +13,17 @@ interface RateLimiter {
) => Promise<RateLimiterResponse>;
}

interface RateLimiterResponse {
export interface RateLimiterResponse {
success: boolean;
tokens: number;
}

interface RedisBucket {
export interface RedisBucket {
tokens: number;
timestamp: number;
}

type RateLimiterSelection =
export type RateLimiterSelection =
| 'TOKEN_BUCKET'
| 'LEAKY_BUCKET'
| 'FIXED_WINDOW'
Expand All @@ -34,12 +34,12 @@ type RateLimiterSelection =
* @type {number} bucketSize - Size of the token bucket
* @type {number} refillRate - Rate at which tokens are added to the bucket in seconds
*/
interface TokenBucketOptions {
export interface TokenBucketOptions {
bucketSize: number;
refillRate: number;
}

// TODO: This will be a union type where we can specify Option types for other Rate Limiters
// Record<string, never> represents the empty object for alogorithms that don't require settings
// and might be able to be removed in the future.
type RateLimiterOptions = TokenBucketOptions | Record<string, never>;
export type RateLimiterOptions = TokenBucketOptions | Record<string, never>;
157 changes: 157 additions & 0 deletions src/analysis/ASTnodefunctions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
/* eslint-disable @typescript-eslint/no-use-before-define */
import {
DocumentNode,
FieldNode,
SelectionSetNode,
DefinitionNode,
Kind,
SelectionNode,
ArgumentNode,
} from 'graphql';
import { FieldWeight, TypeWeightObject } from '../@types/buildTypeWeights';

// TODO: handle variables and arguments
// ! this is not functional
const getArgObj = (args: ArgumentNode[]): { [index: string]: any } => {
const argObj: { [index: string]: any } = {};
for (let i = 0; i < args.length; i + 1) {
const node = args[i];
if (args[i].value.kind !== Kind.VARIABLE) {
if (args[i].value.kind === Kind.INT) {
// FIXME: this does not work
argObj[args[i].name.value] = args[i].value;
}
}
}
return argObj;
};
/**
* The AST node functions call each other following the nested structure below
* Each function handles a specific GraphQL AST node type
*
* AST nodes call each other in the following way
*
* Document Node
* |
* Definiton Node
* (operation and fragment definitons)
* / \
* |-----> Selection Set Node not done
* | /
* | Selection Node
* | (Field, Inline fragment and fragment spread)
* | | \ \
* |--Field Node not done not done
*
*/

export function fieldNode(
node: FieldNode,
typeWeights: TypeWeightObject,
variables: any | undefined,
parentName: string
): number {
let complexity = 0;
// console.log('fieldNode', node, parentName);
// check if the field name is in the type weight object.
if (node.name.value.toLocaleLowerCase() in typeWeights) {
// if it is, than the field is an object type, add itss type weight to the total
complexity += typeWeights[node.name.value].weight;
// call the function to handle selection set node with selectionSet property if it is not undefined
if (node.selectionSet) {
complexity += selectionSetNode(
node.selectionSet,
typeWeights,
variables,
node.name.value
);
}
} else {
// otherwise the field is a scalar or a list.
const fieldWeight: FieldWeight = typeWeights[parentName].fields[node.name.value];
if (typeof fieldWeight === 'number') {
// if the feild weight is a number, add the number to the total complexity
complexity += fieldWeight;
} else if (node.arguments) {
// otherwise the the feild weight is a list, invoke the function with variables
// TODO: calculate the complexity for lists with arguments and varibales
// ! this is not functional
// iterate through the arguments to build the object to
complexity += fieldWeight([...node.arguments]);
}
}
return complexity;
}

export function selectionNode(
node: SelectionNode,
typeWeights: TypeWeightObject,
variables: any | undefined,
parentName: string
): number {
let complexity = 0;
// console.log('selectionNode', node, parentName);
// check the kind property against the set of selection nodes that are possible
if (node.kind === Kind.FIELD) {
// call the function that handle field nodes
complexity += fieldNode(node, typeWeights, variables, parentName);
}
// TODO: add checks for Kind.FRAGMENT_SPREAD and Kind.INLINE_FRAGMENT here
return complexity;
}

export function selectionSetNode(
node: SelectionSetNode,
typeWeights: TypeWeightObject,
variables: any | undefined,
parentName: string
): number {
let complexity = 0;
// iterate shrough the 'selections' array on the seletion set node
for (let i = 0; i < node.selections.length; i += 1) {
// call the function to handle seletion nodes
// pass the current parent through because selection sets act only as intermediaries
complexity += selectionNode(node.selections[i], typeWeights, variables, parentName);
}
return complexity;
}

export function definitionNode(
node: DefinitionNode,
typeWeights: TypeWeightObject,
variables: any | undefined
): number {
let complexity = 0;
// check the kind property against the set of definiton nodes that are possible
if (node.kind === Kind.OPERATION_DEFINITION) {
// check if the operation is in the type weights object.
if (node.operation.toLocaleLowerCase() in typeWeights) {
// if it is, it is an object type, add it's type weight to the total
complexity += typeWeights[node.operation].weight;
// call the function to handle selection set node with selectionSet property if it is not undefined
if (node.selectionSet)
complexity += selectionSetNode(
node.selectionSet,
typeWeights,
variables,
node.operation
);
}
}
// TODO: add checks for Kind.FRAGMENT_DEFINITION here (there are other type definition nodes that i think we can ignore. see ast.d.ts in 'graphql')
return complexity;
}

export function documentNode(
node: DocumentNode,
typeWeights: TypeWeightObject,
variables: any | undefined
): number {
let complexity = 0;
// iterate through 'definitions' array on the document node
for (let i = 0; i < node.definitions.length; i += 1) {
// call the function to handle the various types of definition nodes
complexity += definitionNode(node.definitions[i], typeWeights, variables);
}
return complexity;
}
8 changes: 5 additions & 3 deletions src/analysis/buildTypeWeights.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
import { Maybe } from 'graphql/jsutils/Maybe';
import { ObjMap } from 'graphql/jsutils/ObjMap';
import { GraphQLSchema } from 'graphql/type/schema';
import { TypeWeightConfig, TypeWeightObject } from '../@types/buildTypeWeights';

export const KEYWORDS = ['first', 'last', 'limit'];

Expand Down Expand Up @@ -81,6 +82,7 @@ function parseQuery(
queryFields[field].args.forEach((arg: GraphQLArgument) => {
// If query has an argument matching one of the limiting keywords and resolves to a list then the weight of the query
// should be dependent on both the weight of the resolved type and the limiting argument.
// FIXME: Can nonnull wrap list types?
if (KEYWORDS.includes(arg.name) && isListType(resolveType)) {
// Get the type that comprises the list
const listType = resolveType.ofType;
Expand Down Expand Up @@ -125,7 +127,7 @@ function parseQuery(
}
});

// if the field is a scalar or an enum set weight accordingly
// if the field is a scalar or an enum set weight accordingly. It is not a list in this case
if (isScalarType(resolveType) || isEnumType(resolveType)) {
result.query.fields[field] = typeWeights.scalar || DEFAULT_SCALAR_WEIGHT;
}
Expand All @@ -152,7 +154,7 @@ function parseTypes(

// Handle Object, Interface, Enum and Union types
Object.keys(typeMap).forEach((type) => {
const typeName = type.toLowerCase();
const typeName: string = type.toLowerCase();

const currentType: GraphQLNamedType = typeMap[type];
// Get all types that aren't Query or Mutation or a built in type that starts with '__'
Expand Down Expand Up @@ -219,7 +221,7 @@ function buildTypeWeightsFromSchema(
...typeWeightsConfig,
};

// Confirm that any custom weights are positive
// Confirm that any custom weights are non-negative
Object.entries(typeWeights).forEach((value: [string, number]) => {
if (value[1] < 0) {
throw new Error(`Type weights cannot be negative. Received: ${value[0]}: ${value[1]} `);
Expand Down
27 changes: 12 additions & 15 deletions src/analysis/typeComplexityAnalysis.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,25 @@
import { DocumentNode } from 'graphql';
import { TypeWeightObject } from '../@types/buildTypeWeights';
import { documentNode } from './ASTnodefunctions';

/**
* This function should
* 1. validate the query using graphql methods
* 2. parse the query string using the graphql parse method
* 3. itreate through the query AST and
* - cross reference the type weight object to check type weight
* - total all the eweights of all types in the query
* 4. return the total as the query complexity
* Calculate the complexity for the query by recursivly traversing through the query AST,
* checking the query fields against the type weight object and totaling the weights of every field.
*
* TO DO: extend the functionality to work for mutations and subscriptions
* TO DO: extend the functionality to work for mutations and subscriptions and directives
*
* @param {string} queryString
* @param {TypeWeightObject} typeWeights
* @param {string} queryAST
* @param {any | undefined} varibales
* @param {string} complexityOption
* @param {TypeWeightObject} typeWeights
*/
// TODO add queryVaribables parameter
function getQueryTypeComplexity(
queryString: DocumentNode,
varibales: any | undefined,
queryAST: DocumentNode,
variables: any | undefined,
typeWeights: TypeWeightObject
): number {
throw Error('getQueryComplexity is not implemented.');
let complexity = 0;
complexity += documentNode(queryAST, typeWeights, variables);
return complexity;
}

export default getQueryTypeComplexity;
Loading