-
Notifications
You must be signed in to change notification settings - Fork 2k
/
requestPipeline.ts
426 lines (362 loc) 路 11.9 KB
/
requestPipeline.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
import {
GraphQLSchema,
GraphQLFieldResolver,
specifiedRules,
DocumentNode,
getOperationAST,
ExecutionArgs,
ExecutionResult,
GraphQLError,
} from 'graphql';
import * as graphql from 'graphql';
import {
GraphQLExtension,
GraphQLExtensionStack,
enableGraphQLExtensions,
} from 'graphql-extensions';
import { DataSource } from 'apollo-datasource';
import { PersistedQueryOptions } from '.';
import {
CacheControlExtension,
CacheControlExtensionOptions,
} from 'apollo-cache-control';
import { TracingExtension } from 'apollo-tracing';
import {
ApolloError,
fromGraphQLError,
SyntaxError,
ValidationError,
PersistedQueryNotSupportedError,
PersistedQueryNotFoundError,
} from 'apollo-server-errors';
import { createHash } from 'crypto';
import {
GraphQLRequest,
GraphQLResponse,
GraphQLRequestContext,
InvalidGraphQLRequestError,
ValidationRule,
} from '../dist/requestPipelineAPI';
import {
ApolloServerPlugin,
GraphQLRequestListener,
WithRequired,
} from 'apollo-server-plugin-base';
import { Dispatcher } from './utils/dispatcher';
import { KeyValueCache } from 'apollo-server-caching';
export {
GraphQLRequest,
GraphQLResponse,
GraphQLRequestContext,
InvalidGraphQLRequestError,
};
function computeQueryHash(query: string) {
return createHash('sha256')
.update(query)
.digest('hex');
}
export interface GraphQLRequestPipelineConfig<TContext> {
schema: GraphQLSchema;
rootValue?: ((document: DocumentNode) => any) | any;
validationRules?: ValidationRule[];
fieldResolver?: GraphQLFieldResolver<any, TContext>;
dataSources?: () => DataSources<TContext>;
extensions?: Array<() => GraphQLExtension>;
tracing?: boolean;
persistedQueries?: PersistedQueryOptions;
cacheControl?: CacheControlExtensionOptions;
formatError?: Function;
formatResponse?: Function;
plugins?: ApolloServerPlugin[];
}
export type DataSources<TContext> = {
[name: string]: DataSource<TContext>;
};
type Mutable<T> = { -readonly [P in keyof T]: T[P] };
export async function processGraphQLRequest<TContext>(
config: GraphQLRequestPipelineConfig<TContext>,
requestContext: Mutable<GraphQLRequestContext<TContext>>,
): Promise<GraphQLResponse> {
let cacheControlExtension: CacheControlExtension | undefined;
const extensionStack = initializeExtensionStack();
(requestContext.context as any)._extensionStack = extensionStack;
const dispatcher = initializeRequestListenerDispatcher();
initializeDataSources();
const request = requestContext.request;
let { query, extensions } = request;
let queryHash: string;
let persistedQueryCache: KeyValueCache | undefined;
let persistedQueryHit = false;
let persistedQueryRegister = false;
if (extensions && extensions.persistedQuery) {
// It looks like we've received a persisted query. Check if we
// support them.
if (!config.persistedQueries || !config.persistedQueries.cache) {
throw new PersistedQueryNotSupportedError();
} else if (extensions.persistedQuery.version !== 1) {
throw new InvalidGraphQLRequestError(
'Unsupported persisted query version',
);
}
// We'll store a reference to the persisted query cache so we can actually
// do the write at a later point in the request pipeline processing.
persistedQueryCache = config.persistedQueries.cache;
queryHash = extensions.persistedQuery.sha256Hash;
if (query === undefined) {
query = await persistedQueryCache.get(`apq:${queryHash}`);
if (query) {
persistedQueryHit = true;
} else {
throw new PersistedQueryNotFoundError();
}
} else {
const computedQueryHash = computeQueryHash(query);
if (queryHash !== computedQueryHash) {
throw new InvalidGraphQLRequestError(
'provided sha does not match query',
);
}
// We won't write to the persisted query cache until later.
// Defering the writing gives plugins the ability to "win" from use of
// the cache, but also have their say in whether or not the cache is
// written to (by interrupting the request with an error).
persistedQueryRegister = true;
}
} else if (query) {
// FIXME: We'll compute the APQ query hash to use as our cache key for
// now, but this should be replaced with the new operation ID algorithm.
queryHash = computeQueryHash(query);
} else {
throw new InvalidGraphQLRequestError('Must provide query string.');
}
requestContext.queryHash = queryHash;
const requestDidEnd = extensionStack.requestDidStart({
request: request.http!,
queryString: request.query,
operationName: request.operationName,
variables: request.variables,
extensions: request.extensions,
persistedQueryHit,
persistedQueryRegister,
context: requestContext.context,
requestContext,
});
const parsingDidEnd = await dispatcher.invokeDidStartHook(
'parsingDidStart',
requestContext,
);
try {
let document: DocumentNode;
try {
document = parse(query);
parsingDidEnd();
} catch (syntaxError) {
parsingDidEnd(syntaxError);
return sendErrorResponse(syntaxError, SyntaxError);
}
requestContext.document = document;
const validationDidEnd = await dispatcher.invokeDidStartHook(
'validationDidStart',
requestContext as WithRequired<typeof requestContext, 'document'>,
);
const validationErrors = validate(document);
if (validationErrors.length === 0) {
validationDidEnd();
} else {
validationDidEnd(validationErrors);
return sendErrorResponse(validationErrors, ValidationError);
}
// FIXME: If we want to guarantee an operation has been set when invoking
// `willExecuteOperation` and executionDidStart`, we need to throw an
// error here and not leave this to `buildExecutionContext` in
// `graphql-js`.
const operation = getOperationAST(document, request.operationName);
requestContext.operation = operation || undefined;
// We'll set `operationName` to `null` for anonymous operations.
requestContext.operationName =
(operation && operation.name && operation.name.value) || null;
await dispatcher.invokeHookAsync(
'didResolveOperation',
requestContext as WithRequired<
typeof requestContext,
'document' | 'operation' | 'operationName'
>,
);
// Now that we've gone through the pre-execution phases of the request
// pipeline, and given plugins appropriate ability to object (by throwing
// an error) and not actually write, we'll write to the cache if it was
// determined earlier in the request pipeline that we should do so.
if (persistedQueryRegister && persistedQueryCache) {
Promise.resolve(persistedQueryCache.set(`apq:${queryHash}`, query)).catch(
console.warn,
);
}
const executionDidEnd = await dispatcher.invokeDidStartHook(
'executionDidStart',
requestContext as WithRequired<
typeof requestContext,
'document' | 'operation' | 'operationName'
>,
);
let response: GraphQLResponse;
try {
response = (await execute(
document,
request.operationName,
request.variables,
)) as GraphQLResponse;
executionDidEnd();
} catch (executionError) {
executionDidEnd(executionError);
return sendErrorResponse(executionError);
}
const formattedExtensions = extensionStack.format();
if (Object.keys(formattedExtensions).length > 0) {
response.extensions = formattedExtensions;
}
if (config.formatResponse) {
response = config.formatResponse(response, {
context: requestContext.context,
});
}
return sendResponse(response);
} finally {
requestDidEnd();
}
function parse(query: string): DocumentNode {
const parsingDidEnd = extensionStack.parsingDidStart({
queryString: query,
});
try {
return graphql.parse(query);
} finally {
parsingDidEnd();
}
}
function validate(document: DocumentNode): ReadonlyArray<GraphQLError> {
let rules = specifiedRules;
if (config.validationRules) {
rules = rules.concat(config.validationRules);
}
const validationDidEnd = extensionStack.validationDidStart();
try {
return graphql.validate(config.schema, document, rules);
} finally {
validationDidEnd();
}
}
async function execute(
document: DocumentNode,
operationName: GraphQLRequest['operationName'],
variables: GraphQLRequest['variables'],
): Promise<ExecutionResult> {
const executionArgs: ExecutionArgs = {
schema: config.schema,
document,
rootValue:
typeof config.rootValue === 'function'
? config.rootValue(document)
: config.rootValue,
contextValue: requestContext.context,
variableValues: variables,
operationName,
fieldResolver: config.fieldResolver,
};
const executionDidEnd = extensionStack.executionDidStart({
executionArgs,
});
try {
return graphql.execute(executionArgs);
} finally {
executionDidEnd();
}
}
async function sendResponse(
response: GraphQLResponse,
): Promise<GraphQLResponse> {
// We override errors, data, and extensions with the passed in response,
// but keep other properties (like http)
requestContext.response = extensionStack.willSendResponse({
graphqlResponse: {
...requestContext.response,
errors: response.errors,
data: response.data,
extensions: response.extensions,
},
context: requestContext.context,
}).graphqlResponse;
await dispatcher.invokeHookAsync(
'willSendResponse',
requestContext as WithRequired<typeof requestContext, 'response'>,
);
return requestContext.response!;
}
function sendErrorResponse(
errorOrErrors: ReadonlyArray<GraphQLError> | GraphQLError,
errorClass?: typeof ApolloError,
) {
// If a single error is passed, it should still be encapsulated in an array.
const errors = Array.isArray(errorOrErrors)
? errorOrErrors
: [errorOrErrors];
return sendResponse({
errors: errors.map(err =>
fromGraphQLError(
err,
errorClass && {
errorClass,
},
),
),
});
}
function initializeRequestListenerDispatcher(): Dispatcher<
GraphQLRequestListener
> {
const requestListeners: GraphQLRequestListener<TContext>[] = [];
if (config.plugins) {
for (const plugin of config.plugins) {
if (!plugin.requestDidStart) continue;
const listener = plugin.requestDidStart(requestContext);
if (listener) {
requestListeners.push(listener);
}
}
}
return new Dispatcher(requestListeners);
}
function initializeExtensionStack(): GraphQLExtensionStack<TContext> {
enableGraphQLExtensions(config.schema);
// If custom extension factories were provided, create per-request extension
// objects.
const extensions = config.extensions ? config.extensions.map(f => f()) : [];
if (config.tracing) {
extensions.push(new TracingExtension());
}
if (config.cacheControl) {
cacheControlExtension = new CacheControlExtension(config.cacheControl);
extensions.push(cacheControlExtension);
}
return new GraphQLExtensionStack(extensions);
}
function initializeDataSources() {
if (config.dataSources) {
const context = requestContext.context;
const dataSources = config.dataSources();
for (const dataSource of Object.values(dataSources)) {
if (dataSource.initialize) {
dataSource.initialize({
context,
cache: requestContext.cache,
});
}
}
if ('dataSources' in context) {
throw new Error(
'Please use the dataSources config option instead of putting dataSources on the context yourself.',
);
}
(context as any).dataSources = dataSources;
}
}
}