|
| 1 | +import type { GraphQLResolveInfo } from 'graphql'; |
| 2 | +import get from 'lodash.get'; |
| 3 | +import ms from 'ms'; |
| 4 | +import { getNoOpCache, getWeakMapCache } from './batch-request-cache.js'; |
| 5 | +import { InMemoryStore } from './in-memory-store.js'; |
| 6 | +import type { |
| 7 | + FormatErrorInput, |
| 8 | + GraphQLRateLimitConfig, |
| 9 | + GraphQLRateLimitDirectiveArgs, |
| 10 | + Identity, |
| 11 | +} from './types.js'; |
| 12 | + |
| 13 | +// Default field options |
| 14 | +const DEFAULT_WINDOW = 60 * 1000; |
| 15 | +const DEFAULT_MAX = 5; |
| 16 | +const DEFAULT_FIELD_IDENTITY_ARGS: readonly string[] = []; |
| 17 | + |
| 18 | +/** |
| 19 | + * Returns a string key for the given field + args. With no identityArgs are provided, just the fieldName |
| 20 | + * will be used for the key. If an array of resolveArgs are provided, the values of those will be built |
| 21 | + * into the key. |
| 22 | + * |
| 23 | + * Example: |
| 24 | + * (fieldName = 'books', identityArgs: ['id', 'title'], resolveArgs: { id: 1, title: 'Foo', subTitle: 'Bar' }) |
| 25 | + * => books:1:Foo |
| 26 | + * |
| 27 | + * @param fieldName |
| 28 | + * @param identityArgs |
| 29 | + * @param resolveArgs |
| 30 | + */ |
| 31 | +const getFieldIdentity = ( |
| 32 | + fieldName: string, |
| 33 | + identityArgs: readonly string[], |
| 34 | + resolveArgs: unknown, |
| 35 | +): string => { |
| 36 | + const argsKey = identityArgs.map(arg => get(resolveArgs, arg)); |
| 37 | + return [fieldName, ...argsKey].join(':'); |
| 38 | +}; |
| 39 | + |
| 40 | +/** |
| 41 | + * This is the core rate limiting logic function, APIs (directive, sheild etc.) |
| 42 | + * can wrap this or it can be used directly in resolvers. |
| 43 | + * @param userConfig - global (usually app-wide) rate limiting config |
| 44 | + */ |
| 45 | +const getGraphQLRateLimiter = ( |
| 46 | + // Main config (e.g. the config passed to the createRateLimitDirective func) |
| 47 | + userConfig: GraphQLRateLimitConfig, |
| 48 | +): (( |
| 49 | + { |
| 50 | + args, |
| 51 | + context, |
| 52 | + info, |
| 53 | + }: { |
| 54 | + parent: any; |
| 55 | + args: Record<string, any>; |
| 56 | + context: any; |
| 57 | + info: GraphQLResolveInfo; |
| 58 | + }, |
| 59 | + { |
| 60 | + arrayLengthField, |
| 61 | + identityArgs, |
| 62 | + max, |
| 63 | + window, |
| 64 | + message, |
| 65 | + uncountRejected, |
| 66 | + }: GraphQLRateLimitDirectiveArgs, |
| 67 | +) => Promise<string | undefined>) => { |
| 68 | + // Default directive config |
| 69 | + const defaultConfig = { |
| 70 | + enableBatchRequestCache: false, |
| 71 | + formatError: ({ fieldName }: FormatErrorInput) => { |
| 72 | + return `You are trying to access '${fieldName}' too often`; |
| 73 | + }, |
| 74 | + // Required |
| 75 | + identifyContext: () => { |
| 76 | + throw new Error('You must implement a createRateLimitDirective.config.identifyContext'); |
| 77 | + }, |
| 78 | + store: new InMemoryStore(), |
| 79 | + }; |
| 80 | + |
| 81 | + const { enableBatchRequestCache, identifyContext, formatError, store } = { |
| 82 | + ...defaultConfig, |
| 83 | + ...userConfig, |
| 84 | + }; |
| 85 | + |
| 86 | + const batchRequestCache = enableBatchRequestCache ? getWeakMapCache() : getNoOpCache(); |
| 87 | + |
| 88 | + /** |
| 89 | + * Field level rate limiter function that returns the error message or undefined |
| 90 | + * @param args - pass the resolver args as an object |
| 91 | + * @param config - field level config |
| 92 | + */ |
| 93 | + const rateLimiter = async ( |
| 94 | + // Resolver args |
| 95 | + { |
| 96 | + args, |
| 97 | + context, |
| 98 | + info, |
| 99 | + }: { |
| 100 | + parent: any; |
| 101 | + args: Record<string, any>; |
| 102 | + context: any; |
| 103 | + info: GraphQLResolveInfo; |
| 104 | + }, |
| 105 | + // Field level config (e.g. the directive parameters) |
| 106 | + { |
| 107 | + arrayLengthField, |
| 108 | + identityArgs, |
| 109 | + max, |
| 110 | + window, |
| 111 | + message, |
| 112 | + readOnly, |
| 113 | + uncountRejected, |
| 114 | + }: GraphQLRateLimitDirectiveArgs, |
| 115 | + ): Promise<string | undefined> => { |
| 116 | + // Identify the user or client on the context |
| 117 | + const contextIdentity = identifyContext(context); |
| 118 | + // User defined window in ms that this field can be accessed for before the call is expired |
| 119 | + const windowMs = (window ? ms(window as ms.StringValue) : DEFAULT_WINDOW) as number; |
| 120 | + // String key for this field |
| 121 | + const fieldIdentity = getFieldIdentity( |
| 122 | + info.fieldName, |
| 123 | + identityArgs || DEFAULT_FIELD_IDENTITY_ARGS, |
| 124 | + args, |
| 125 | + ); |
| 126 | + |
| 127 | + // User configured maximum calls to this field |
| 128 | + const maxCalls = max || DEFAULT_MAX; |
| 129 | + // Call count could be determined by the lenght of the array value, but most commonly 1 |
| 130 | + const callCount = (arrayLengthField && get(args, [arrayLengthField, 'length'])) || 1; |
| 131 | + // Allinclusive 'identity' for this resolver call |
| 132 | + const identity: Identity = { contextIdentity, fieldIdentity }; |
| 133 | + // Timestamp of this call to be save for future ref |
| 134 | + const timestamp = Date.now(); |
| 135 | + // Create an array of callCount length, filled with the current timestamp |
| 136 | + const newTimestamps = [...new Array(callCount || 1)].map(() => timestamp); |
| 137 | + |
| 138 | + // We set these new timestamps in a temporary memory cache so we can enforce |
| 139 | + // ratelimits across queries batched in a single request. |
| 140 | + const batchedTimestamps = batchRequestCache.set({ |
| 141 | + context, |
| 142 | + fieldIdentity, |
| 143 | + newTimestamps, |
| 144 | + }); |
| 145 | + |
| 146 | + // Fetch timestamps from previous requests out of the store |
| 147 | + // and get all the timestamps that haven't expired |
| 148 | + const filteredAccessTimestamps = (await store.getForIdentity(identity)).filter(t => { |
| 149 | + return t + windowMs > Date.now(); |
| 150 | + }); |
| 151 | + |
| 152 | + // Flag indicating requests limit reached |
| 153 | + const limitReached = filteredAccessTimestamps.length + batchedTimestamps.length > maxCalls; |
| 154 | + |
| 155 | + // Confogure access timestamps to save according to uncountRejected setting |
| 156 | + const timestampsToStore: readonly any[] = [ |
| 157 | + ...filteredAccessTimestamps, |
| 158 | + ...(!uncountRejected || !limitReached ? batchedTimestamps : []), |
| 159 | + ]; |
| 160 | + |
| 161 | + // Save these access timestamps for future requests. |
| 162 | + if (!readOnly) { |
| 163 | + await store.setForIdentity(identity, timestampsToStore, windowMs); |
| 164 | + } |
| 165 | + |
| 166 | + // Field level custom message or a global formatting function |
| 167 | + const errorMessage = |
| 168 | + message || |
| 169 | + formatError({ |
| 170 | + contextIdentity, |
| 171 | + fieldIdentity, |
| 172 | + fieldName: info.fieldName, |
| 173 | + max: maxCalls, |
| 174 | + window: windowMs, |
| 175 | + }); |
| 176 | + |
| 177 | + // Returns an error message or undefined if no error |
| 178 | + return limitReached ? errorMessage : undefined; |
| 179 | + }; |
| 180 | + |
| 181 | + return rateLimiter; |
| 182 | +}; |
| 183 | + |
| 184 | +export { getGraphQLRateLimiter, getFieldIdentity }; |
0 commit comments