/
requestPipeline.ts
648 lines (570 loc) 路 21.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
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
import {
GraphQLSchema,
GraphQLFieldResolver,
specifiedRules,
DocumentNode,
getOperationAST,
ExecutionArgs,
GraphQLError,
GraphQLFormattedError,
validate as graphqlValidate,
parse as graphqlParse,
execute as graphqlExecute,
Kind,
ParseOptions,
} from 'graphql';
import type { DataSource } from 'apollo-datasource';
import type { PersistedQueryOptions } from './graphqlOptions';
import {
symbolExecutionDispatcherWillResolveField,
enablePluginsForSchemaResolvers,
symbolUserFieldResolver,
} from './utils/schemaInstrumentation';
import {
ApolloError,
fromGraphQLError,
SyntaxError,
ValidationError,
PersistedQueryNotSupportedError,
PersistedQueryNotFoundError,
formatApolloErrors,
UserInputError,
} from 'apollo-server-errors';
import type {
GraphQLRequest,
GraphQLResponse,
GraphQLRequestContext,
GraphQLExecutor,
GraphQLExecutionResult,
ValidationRule,
} from 'apollo-server-types';
import type {
ApolloServerPlugin,
GraphQLRequestListener,
GraphQLRequestContextDidResolveSource,
GraphQLRequestContextExecutionDidStart,
GraphQLRequestContextResponseForOperation,
GraphQLRequestContextDidResolveOperation,
GraphQLRequestContextParsingDidStart,
GraphQLRequestContextValidationDidStart,
GraphQLRequestContextWillSendResponse,
GraphQLRequestContextDidEncounterErrors,
GraphQLRequestExecutionListener,
} from 'apollo-server-plugin-base';
import { Dispatcher } from './utils/dispatcher';
import { KeyValueCache, PrefixingKeyValueCache } from 'apollo-server-caching';
export { GraphQLRequest, GraphQLResponse, GraphQLRequestContext };
import createSHA from './utils/createSHA';
import { HttpQueryError } from './runHttpQuery';
import type { DocumentStore } from './types';
import { Headers } from 'apollo-server-env';
export const APQ_CACHE_PREFIX = 'apq:';
function computeQueryHash(query: string) {
return createSHA('sha256').update(query).digest('hex');
}
export interface GraphQLRequestPipelineConfig<TContext> {
schema: GraphQLSchema;
rootValue?: ((document: DocumentNode) => any) | any;
validationRules?: ValidationRule[];
executor?: GraphQLExecutor;
fieldResolver?: GraphQLFieldResolver<any, TContext>;
dataSources?: () => DataSources<TContext>;
persistedQueries?: PersistedQueryOptions;
formatError?: (error: GraphQLError) => GraphQLFormattedError;
formatResponse?: (
response: GraphQLResponse,
requestContext: GraphQLRequestContext<TContext>,
) => GraphQLResponse | null;
plugins?: ApolloServerPlugin[];
documentStore?: DocumentStore | null;
parseOptions?: ParseOptions;
}
export type DataSources<TContext> = {
[name: string]: DataSource<TContext>;
};
type Mutable<T> = { -readonly [P in keyof T]: T[P] };
function isBadUserInputGraphQLError(error: GraphQLError): Boolean {
return (
error.nodes?.length === 1 &&
error.nodes[0].kind === Kind.VARIABLE_DEFINITION &&
(error.message.startsWith(
`Variable "$${error.nodes[0].variable.name.value}" got invalid value `,
) ||
error.message.startsWith(
`Variable "$${error.nodes[0].variable.name.value}" of required type `,
) ||
error.message.startsWith(
`Variable "$${error.nodes[0].variable.name.value}" of non-null type `,
))
);
}
export async function processGraphQLRequest<TContext>(
config: GraphQLRequestPipelineConfig<TContext>,
requestContext: Mutable<GraphQLRequestContext<TContext>>,
): Promise<GraphQLResponse> {
// For legacy reasons, this exported method may exist without a `logger` on
// the context. We'll need to make sure we account for that, even though
// all of our own machinery will certainly set it now.
const logger = requestContext.logger || console;
// If request context's `metrics` already exists, preserve it, but _ensure_ it
// exists there and shorthand it for use throughout this function.
const metrics = (requestContext.metrics =
requestContext.metrics || Object.create(null));
const dispatcher = await initializeRequestListenerDispatcher();
await initializeDataSources();
const request = requestContext.request;
let { query, extensions } = request;
let queryHash: string;
let persistedQueryCache: KeyValueCache | undefined;
metrics.persistedQueryHit = false;
metrics.persistedQueryRegister = false;
if (extensions?.persistedQuery) {
// It looks like we've received a persisted query. Check if we
// support them.
if (!config.persistedQueries || !config.persistedQueries.cache) {
return await sendErrorResponse(new PersistedQueryNotSupportedError());
} else if (extensions.persistedQuery.version !== 1) {
return await sendErrorResponse(
new GraphQLError('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;
// This is a bit hacky, but if `config` came from direct use of the old
// apollo-server 1.0-style middleware (graphqlExpress etc, not via the
// ApolloServer class), it won't have been converted to
// PrefixingKeyValueCache yet.
if (!(persistedQueryCache instanceof PrefixingKeyValueCache)) {
persistedQueryCache = new PrefixingKeyValueCache(
persistedQueryCache,
APQ_CACHE_PREFIX,
);
}
queryHash = extensions.persistedQuery.sha256Hash;
if (query === undefined) {
query = await persistedQueryCache.get(queryHash);
if (query) {
metrics.persistedQueryHit = true;
} else {
return await sendErrorResponse(new PersistedQueryNotFoundError());
}
} else {
const computedQueryHash = computeQueryHash(query);
// The provided hash must exactly match the SHA-256 hash of
// the query string. This prevents hash hijacking, where a
// new and potentially malicious query is associated with
// an existing hash.
if (queryHash !== computedQueryHash) {
return await sendErrorResponse(
new GraphQLError('provided sha does not match query'),
);
}
// We won't write to the persisted query cache until later.
// Deferring 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).
metrics.persistedQueryRegister = true;
}
} else if (query) {
// TODO: 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 {
return await sendErrorResponse(
new GraphQLError(
'GraphQL operations must contain a non-empty `query` or a `persistedQuery` extension.',
),
);
}
requestContext.queryHash = queryHash;
requestContext.source = query;
// Let the plugins know that we now have a STRING of what we hope will
// parse and validate into a document we can execute on. Unless we have
// retrieved this from our APQ cache, there's no guarantee that it is
// syntactically correct, so this string should not be trusted as a valid
// document until after it's parsed and validated.
await dispatcher.invokeHook(
'didResolveSource',
requestContext as GraphQLRequestContextDidResolveSource<TContext>,
);
// If we're configured with a document store (by default, we are), we'll
// utilize the operation's hash to lookup the AST from the previously
// parsed-and-validated operation. Failure to retrieve anything from the
// cache just means we're committed to doing the parsing and validation.
if (config.documentStore) {
try {
requestContext.document = await config.documentStore.get(queryHash);
} catch (err) {
logger.warn(
'An error occurred while attempting to read from the documentStore. ' +
(err as Error)?.message || err,
);
}
}
// If we still don't have a document, we'll need to parse and validate it.
// With success, we'll attempt to save it into the store for future use.
if (!requestContext.document) {
const parsingDidEnd = await dispatcher.invokeDidStartHook(
'parsingDidStart',
requestContext as GraphQLRequestContextParsingDidStart<TContext>,
);
try {
requestContext.document = parse(query, config.parseOptions);
await parsingDidEnd();
} catch (syntaxError) {
await parsingDidEnd(syntaxError as Error);
// XXX: This cast is pretty sketchy, as other error types can be thrown
// by parsingDidEnd!
return await sendErrorResponse(syntaxError as GraphQLError, SyntaxError);
}
const validationDidEnd = await dispatcher.invokeDidStartHook(
'validationDidStart',
requestContext as GraphQLRequestContextValidationDidStart<TContext>,
);
const validationErrors = validate(requestContext.document);
if (validationErrors.length === 0) {
await validationDidEnd();
} else {
await validationDidEnd(validationErrors);
return await sendErrorResponse(validationErrors, ValidationError);
}
if (config.documentStore) {
// The underlying cache store behind the `documentStore` returns a
// `Promise` which is resolved (or rejected), eventually, based on the
// success or failure (respectively) of the cache save attempt. While
// it's certainly possible to `await` this `Promise`, we don't care about
// whether or not it's successful at this point. We'll instead proceed
// to serve the rest of the request and just hope that this works out.
// If it doesn't work, the next request will have another opportunity to
// try again. Errors will surface as warnings, as appropriate.
//
// While it shouldn't normally be necessary to wrap this `Promise` in a
// `Promise.resolve` invocation, it seems that the underlying cache store
// is returning a non-native `Promise` (e.g. Bluebird, etc.).
Promise.resolve(
config.documentStore.set(queryHash, requestContext.document),
).catch((err) =>
logger.warn(
'Could not store validated document. ' + err?.message || err,
),
);
}
}
// TODO: 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(
requestContext.document,
request.operationName,
);
requestContext.operation = operation || undefined;
// We'll set `operationName` to `null` for anonymous operations.
requestContext.operationName = operation?.name?.value || null;
try {
await dispatcher.invokeHook(
'didResolveOperation',
requestContext as GraphQLRequestContextDidResolveOperation<TContext>,
);
} catch (err) {
// XXX: This cast is pretty sketchy, as other error types can be thrown
// by didResolveOperation!
return await sendErrorResponse(err as GraphQLError);
}
// 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 (metrics.persistedQueryRegister && persistedQueryCache) {
// While it shouldn't normally be necessary to wrap this `Promise` in a
// `Promise.resolve` invocation, it seems that the underlying cache store
// is returning a non-native `Promise` (e.g. Bluebird, etc.).
Promise.resolve(
persistedQueryCache.set(
queryHash,
query,
config.persistedQueries &&
typeof config.persistedQueries.ttl !== 'undefined'
? {
ttl: config.persistedQueries.ttl,
}
: Object.create(null),
),
).catch(logger.warn);
}
let response: GraphQLResponse | null =
await dispatcher.invokeHooksUntilNonNull(
'responseForOperation',
requestContext as GraphQLRequestContextResponseForOperation<TContext>,
);
if (response == null) {
// This execution dispatcher code is duplicated in `pluginTestHarness`
// right now.
const executionListeners: GraphQLRequestExecutionListener<TContext>[] = [];
(
await dispatcher.invokeHook(
'executionDidStart',
requestContext as GraphQLRequestContextExecutionDidStart<TContext>,
)
).forEach((executionListener) => {
if (executionListener) {
executionListeners.push(executionListener);
}
});
executionListeners.reverse();
const executionDispatcher = new Dispatcher(executionListeners);
if (executionDispatcher.hasHook('willResolveField')) {
// Create a callback that will trigger the execution dispatcher's
// `willResolveField` hook. We will attach this to the context on a
// symbol so it can be invoked by our `wrapField` method during execution.
const invokeWillResolveField: GraphQLRequestExecutionListener<TContext>['willResolveField'] =
(...args) =>
executionDispatcher.invokeSyncDidStartHook(
'willResolveField',
...args,
);
Object.defineProperty(
requestContext.context,
symbolExecutionDispatcherWillResolveField,
{ value: invokeWillResolveField },
);
// If the user has provided a custom field resolver, we will attach
// it to the context so we can still invoke it after we've wrapped the
// fields with `wrapField` within `enablePluginsForSchemaResolvers` of
// the `schemaInstrumentation` module.
if (config.fieldResolver) {
Object.defineProperty(requestContext.context, symbolUserFieldResolver, {
value: config.fieldResolver,
});
}
// If the schema is already enabled, this is a no-op. Otherwise, the
// schema will be augmented so it is able to invoke willResolveField. Note
// that if we never see a plugin with willResolveField then we will never
// need to instrument the schema, which might be a small performance gain.
// (For example, this can happen if you pass `fieldLevelInstrumentation:
// () => false` to the usage reporting plugin and disable the cache
// control plugin. We can consider changing the cache control plugin to
// have a "static cache control only" mode that doesn't use
// willResolveField too if this proves to be helpful in practice.)
enablePluginsForSchemaResolvers(config.schema);
}
try {
const result = await execute(
requestContext as GraphQLRequestContextExecutionDidStart<TContext>,
);
// The first thing that execution does is coerce the request's variables
// to the types declared in the operation, which can lead to errors if
// they are of the wrong type. It also makes sure that all non-null
// variables are required and get non-null values. If any of these things
// lead to errors, we change them into UserInputError so that their code
// doesn't end up being INTERNAL_SERVER_ERROR, since these are client
// errors.
//
// This is hacky! Hopefully graphql-js will give us a way to separate
// variable resolution from execution later; see
// https://github.com/graphql/graphql-js/issues/3169
const resultErrors = result.errors?.map((e) => {
if (isBadUserInputGraphQLError(e)) {
return fromGraphQLError(e, {
errorClass: UserInputError,
});
}
return e;
});
if (resultErrors) {
await didEncounterErrors(resultErrors);
}
response = {
...result,
errors: resultErrors ? formatErrors(resultErrors) : undefined,
};
await executionDispatcher.invokeHook('executionDidEnd');
} catch (executionError) {
await executionDispatcher.invokeHook(
'executionDidEnd',
executionError as Error,
);
// XXX: This cast is pretty sketchy, as other error types can be thrown
// in the try block!
return await sendErrorResponse(executionError as GraphQLError);
}
}
if (config.formatResponse) {
const formattedResponse: GraphQLResponse | null = config.formatResponse(
response,
requestContext,
);
if (formattedResponse != null) {
response = formattedResponse;
}
}
return sendResponse(response);
function parse(query: string, parseOptions?: ParseOptions): DocumentNode {
return graphqlParse(query, parseOptions);
}
function validate(document: DocumentNode): ReadonlyArray<GraphQLError> {
let rules = specifiedRules;
if (config.validationRules) {
rules = rules.concat(config.validationRules);
}
return graphqlValidate(config.schema, document, rules);
}
async function execute(
requestContext: GraphQLRequestContextExecutionDidStart<TContext>,
): Promise<GraphQLExecutionResult> {
const { request, document } = requestContext;
const executionArgs: ExecutionArgs = {
schema: config.schema,
document,
rootValue:
typeof config.rootValue === 'function'
? config.rootValue(document)
: config.rootValue,
contextValue: requestContext.context,
variableValues: request.variables,
operationName: request.operationName,
fieldResolver: config.fieldResolver,
};
if (config.executor) {
// XXX Nothing guarantees that the only errors thrown or returned
// in result.errors are GraphQLErrors, even though other code
// (eg usage reporting) assumes that.
return await config.executor(requestContext);
} else {
return await graphqlExecute(executionArgs);
}
}
async function sendResponse(
response: GraphQLResponse,
): Promise<GraphQLResponse> {
requestContext.response = {
...requestContext.response,
errors: response.errors,
data: response.data,
extensions: response.extensions,
};
if (response.http) {
if (!requestContext.response.http) {
requestContext.response.http = {
headers: new Headers(),
};
}
if (response.http.status) {
requestContext.response.http.status = response.http.status;
}
for (const [name, value] of response.http.headers) {
requestContext.response.http.headers.set(name, value);
}
}
await dispatcher.invokeHook(
'willSendResponse',
requestContext as GraphQLRequestContextWillSendResponse<TContext>,
);
return requestContext.response;
}
// Note that we ensure that all calls to didEncounterErrors are followed by
// calls to willSendResponse. (The usage reporting plugin depends on this.)
async function didEncounterErrors(errors: ReadonlyArray<GraphQLError>) {
requestContext.errors = errors;
return await dispatcher.invokeHook(
'didEncounterErrors',
requestContext as GraphQLRequestContextDidEncounterErrors<TContext>,
);
}
async 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];
await didEncounterErrors(errors);
const response: GraphQLResponse = {
errors: formatErrors(
errors.map((err) =>
err instanceof ApolloError && !errorClass
? err
: fromGraphQLError(
err,
errorClass && {
errorClass,
},
),
),
),
};
// Persisted query errors (especially "not found") need to be uncached,
// because hopefully we're about to fill in the APQ cache and the same
// request will succeed next time. We also want a 200 response to avoid any
// error handling that may mask the contents of an error response.
if (
errors.every(
(err) =>
err instanceof PersistedQueryNotSupportedError ||
err instanceof PersistedQueryNotFoundError,
)
) {
response.http = {
status: 200,
headers: new Headers({
'Cache-Control': 'private, no-cache, must-revalidate',
}),
};
} else if (errors.length === 1 && errors[0] instanceof HttpQueryError) {
response.http = {
status: errors[0].statusCode,
headers: new Headers(errors[0].headers),
};
}
return sendResponse(response);
}
function formatErrors(
errors: ReadonlyArray<GraphQLError>,
): ReadonlyArray<GraphQLFormattedError> {
return formatApolloErrors(errors, {
formatter: config.formatError,
debug: requestContext.debug,
});
}
async function initializeRequestListenerDispatcher(): Promise<
Dispatcher<GraphQLRequestListener<TContext>>
> {
const requestListeners: GraphQLRequestListener<TContext>[] = [];
if (config.plugins) {
for (const plugin of config.plugins) {
if (!plugin.requestDidStart) continue;
const listener = await plugin.requestDidStart(requestContext);
if (listener) {
requestListeners.push(listener);
}
}
}
return new Dispatcher(requestListeners);
}
async function initializeDataSources() {
if (config.dataSources) {
const context = requestContext.context;
const dataSources = config.dataSources();
const initializers: any[] = [];
for (const dataSource of Object.values(dataSources)) {
if (dataSource.initialize) {
initializers.push(
dataSource.initialize({
context,
cache: requestContext.cache,
}),
);
}
}
await Promise.all(initializers);
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;
}
}
}