1 | import {
|
2 | makeExecutableSchema,
|
3 | addMockFunctionsToSchema,
|
4 | GraphQLParseOptions,
|
5 | } from 'graphql-tools';
|
6 | import { Server as NetServer } from 'net';
|
7 | import { Server as TlsServer } from 'tls';
|
8 | import { Server as HttpServer } from 'http';
|
9 | import { Http2Server, Http2SecureServer } from 'http2';
|
10 | import { Server as HttpsServer } from 'https';
|
11 | import loglevel from 'loglevel';
|
12 | import {
|
13 | execute,
|
14 | GraphQLSchema,
|
15 | subscribe,
|
16 | ExecutionResult,
|
17 | GraphQLError,
|
18 | GraphQLFieldResolver,
|
19 | ValidationContext,
|
20 | FieldDefinitionNode,
|
21 | DocumentNode,
|
22 | } from 'graphql';
|
23 | import resolvable, { Resolvable } from '@josephg/resolvable';
|
24 | import { GraphQLExtension } from 'graphql-extensions';
|
25 | import {
|
26 | InMemoryLRUCache,
|
27 | PrefixingKeyValueCache,
|
28 | } from 'apollo-server-caching';
|
29 | import {
|
30 | ApolloServerPlugin,
|
31 | GraphQLServiceContext,
|
32 | GraphQLServerListener,
|
33 | } from 'apollo-server-plugin-base';
|
34 | import runtimeSupportsUploads from './utils/runtimeSupportsUploads';
|
35 |
|
36 | import {
|
37 | SubscriptionServer,
|
38 | ExecutionParams,
|
39 | } from 'subscriptions-transport-ws';
|
40 |
|
41 | import WebSocket from 'ws';
|
42 |
|
43 | import { formatApolloErrors } from 'apollo-server-errors';
|
44 | import { GraphQLServerOptions, PersistedQueryOptions } from './graphqlOptions';
|
45 |
|
46 | import {
|
47 | Config,
|
48 | Context,
|
49 | ContextFunction,
|
50 | SubscriptionServerOptions,
|
51 | FileUploadOptions,
|
52 | PluginDefinition,
|
53 | GraphQLService,
|
54 | } from './types';
|
55 |
|
56 | import { gql } from './index';
|
57 |
|
58 | import {
|
59 | createPlaygroundOptions,
|
60 | PlaygroundRenderPageOptions,
|
61 | } from './playground';
|
62 |
|
63 | import { generateSchemaHash } from './utils/schemaHash';
|
64 | import { isDirectiveDefined } from './utils/isDirectiveDefined';
|
65 | import {
|
66 | processGraphQLRequest,
|
67 | GraphQLRequestContext,
|
68 | GraphQLRequest,
|
69 | APQ_CACHE_PREFIX,
|
70 | } from './requestPipeline';
|
71 |
|
72 | import { Headers } from 'apollo-server-env';
|
73 | import { buildServiceDefinition } from '@apollographql/apollo-tools';
|
74 | import { plugin as pluginTracing } from 'apollo-tracing';
|
75 | import { Logger, SchemaHash, ApolloConfig } from 'apollo-server-types';
|
76 | import {
|
77 | plugin as pluginCacheControl,
|
78 | CacheControlExtensionOptions,
|
79 | } from 'apollo-cache-control';
|
80 | import { cloneObject } from './runHttpQuery';
|
81 | import isNodeLike from './utils/isNodeLike';
|
82 | import { determineApolloConfig } from './determineApolloConfig';
|
83 | import {
|
84 | ApolloServerPluginSchemaReporting,
|
85 | ApolloServerPluginUsageReportingFromLegacyOptions,
|
86 | ApolloServerPluginSchemaReportingOptions,
|
87 | ApolloServerPluginInlineTrace,
|
88 | ApolloServerPluginInlineTraceOptions,
|
89 | ApolloServerPluginUsageReporting,
|
90 | } from './plugin';
|
91 | import { InternalPluginId, pluginIsInternal } from './plugin/internalPlugin';
|
92 |
|
93 | const NoIntrospection = (context: ValidationContext) => ({
|
94 | Field(node: FieldDefinitionNode) {
|
95 | if (node.name.value === '__schema' || node.name.value === '__type') {
|
96 | context.reportError(
|
97 | new GraphQLError(
|
98 | 'GraphQL introspection is not allowed by Apollo Server, but the query contained __schema or __type. To enable introspection, pass introspection: true to ApolloServer in production',
|
99 | [node],
|
100 | ),
|
101 | );
|
102 | }
|
103 | },
|
104 | });
|
105 |
|
106 | const forbidUploadsForTesting =
|
107 | process && process.env.NODE_ENV === 'test' && !runtimeSupportsUploads;
|
108 |
|
109 | function approximateObjectSize<T>(obj: T): number {
|
110 | return Buffer.byteLength(JSON.stringify(obj), 'utf8');
|
111 | }
|
112 |
|
113 | type SchemaDerivedData = {
|
114 | schema: GraphQLSchema;
|
115 | schemaHash: SchemaHash;
|
116 | extensions: Array<() => GraphQLExtension>;
|
117 |
|
118 |
|
119 |
|
120 | documentStore?: InMemoryLRUCache<DocumentNode>;
|
121 | };
|
122 |
|
123 | type ServerState =
|
124 | | { phase: 'initialized with schema'; schemaDerivedData: SchemaDerivedData }
|
125 | | { phase: 'initialized with gateway'; gateway: GraphQLService }
|
126 | | { phase: 'starting'; barrier: Resolvable<void> }
|
127 | | {
|
128 | phase: 'invoking serverWillStart';
|
129 | barrier: Resolvable<void>;
|
130 | schemaDerivedData: SchemaDerivedData;
|
131 | }
|
132 | | { phase: 'failed to start'; error: Error; loadedSchema: boolean }
|
133 | | {
|
134 | phase: 'started';
|
135 | schemaDerivedData: SchemaDerivedData;
|
136 | }
|
137 | | { phase: 'stopping'; barrier: Resolvable<void> }
|
138 | | { phase: 'stopped'; stopError: Error | null };
|
139 |
|
140 |
|
141 |
|
142 |
|
143 | class UnreachableCaseError extends Error {
|
144 | constructor(val: never) {
|
145 | super(`Unreachable case: ${val}`);
|
146 | }
|
147 | }
|
148 | export class ApolloServerBase {
|
149 | private logger: Logger;
|
150 | public subscriptionsPath?: string;
|
151 | public graphqlPath: string = '/graphql';
|
152 | public requestOptions: Partial<GraphQLServerOptions<any>> = Object.create(
|
153 | null,
|
154 | );
|
155 |
|
156 | private context?: Context | ContextFunction;
|
157 | private apolloConfig: ApolloConfig;
|
158 | protected plugins: ApolloServerPlugin[] = [];
|
159 |
|
160 | protected subscriptionServerOptions?: SubscriptionServerOptions;
|
161 | protected uploadsConfig?: FileUploadOptions;
|
162 |
|
163 |
|
164 | private subscriptionServer?: SubscriptionServer;
|
165 |
|
166 |
|
167 | protected playgroundOptions?: PlaygroundRenderPageOptions;
|
168 |
|
169 | private parseOptions: GraphQLParseOptions;
|
170 | private config: Config;
|
171 | private state: ServerState;
|
172 |
|
173 | protected schema?: GraphQLSchema;
|
174 | private toDispose = new Set<() => Promise<void>>();
|
175 | private toDisposeLast = new Set<() => Promise<void>>();
|
176 | private experimental_approximateDocumentStoreMiB: Config['experimental_approximateDocumentStoreMiB'];
|
177 |
|
178 |
|
179 | constructor(config: Config) {
|
180 | if (!config) throw new Error('ApolloServer requires options.');
|
181 | this.config = config;
|
182 | const {
|
183 | context,
|
184 | resolvers,
|
185 | schema,
|
186 | schemaDirectives,
|
187 | modules,
|
188 | typeDefs,
|
189 | parseOptions = {},
|
190 | introspection,
|
191 | mocks,
|
192 | mockEntireSchema,
|
193 | extensions,
|
194 | subscriptions,
|
195 | uploads,
|
196 | playground,
|
197 | plugins,
|
198 | gateway,
|
199 | cacheControl,
|
200 | experimental_approximateDocumentStoreMiB,
|
201 | stopOnTerminationSignals,
|
202 | apollo,
|
203 | engine,
|
204 | ...requestOptions
|
205 | } = config;
|
206 |
|
207 | if (engine !== undefined && apollo) {
|
208 | throw new Error(
|
209 | 'You cannot provide both `engine` and `apollo` to `new ApolloServer()`. ' +
|
210 | 'For details on how to migrate all of your options out of `engine`, see ' +
|
211 | 'https://go.apollo.dev/s/migration-engine-plugins',
|
212 | );
|
213 | }
|
214 |
|
215 |
|
216 | if (config.logger) {
|
217 | this.logger = config.logger;
|
218 | } else {
|
219 |
|
220 | const loglevelLogger = loglevel.getLogger('apollo-server');
|
221 |
|
222 |
|
223 |
|
224 |
|
225 |
|
226 |
|
227 | if (this.config.debug === true) {
|
228 | loglevelLogger.setLevel(loglevel.levels.DEBUG);
|
229 | } else {
|
230 | loglevelLogger.setLevel(loglevel.levels.INFO);
|
231 | }
|
232 |
|
233 | this.logger = loglevelLogger;
|
234 | }
|
235 |
|
236 | this.apolloConfig = determineApolloConfig(apollo, engine, this.logger);
|
237 |
|
238 | if (gateway && (modules || schema || typeDefs || resolvers)) {
|
239 | throw new Error(
|
240 | 'Cannot define both `gateway` and any of: `modules`, `schema`, `typeDefs`, or `resolvers`',
|
241 | );
|
242 | }
|
243 |
|
244 | this.parseOptions = parseOptions;
|
245 | this.context = context;
|
246 |
|
247 |
|
248 |
|
249 |
|
250 |
|
251 |
|
252 | const isDev = process.env.NODE_ENV !== 'production';
|
253 |
|
254 |
|
255 |
|
256 |
|
257 | if (
|
258 | (typeof introspection === 'boolean' && !introspection) ||
|
259 | (introspection === undefined && !isDev)
|
260 | ) {
|
261 | const noIntro = [NoIntrospection];
|
262 | requestOptions.validationRules = requestOptions.validationRules
|
263 | ? requestOptions.validationRules.concat(noIntro)
|
264 | : noIntro;
|
265 | }
|
266 |
|
267 | if (!requestOptions.cache) {
|
268 | requestOptions.cache = new InMemoryLRUCache();
|
269 | }
|
270 |
|
271 | if (requestOptions.persistedQueries !== false) {
|
272 | const { cache: apqCache = requestOptions.cache!, ...apqOtherOptions } =
|
273 | requestOptions.persistedQueries || Object.create(null);
|
274 |
|
275 | requestOptions.persistedQueries = {
|
276 | cache: new PrefixingKeyValueCache(apqCache, APQ_CACHE_PREFIX),
|
277 | ...apqOtherOptions,
|
278 | };
|
279 | } else {
|
280 |
|
281 | delete requestOptions.persistedQueries;
|
282 | }
|
283 |
|
284 | this.requestOptions = requestOptions as GraphQLServerOptions;
|
285 |
|
286 | if (uploads !== false && !forbidUploadsForTesting) {
|
287 | if (this.supportsUploads()) {
|
288 | if (!runtimeSupportsUploads) {
|
289 | printNodeFileUploadsMessage(this.logger);
|
290 | throw new Error(
|
291 | '`graphql-upload` is no longer supported on Node.js < v8.5.0. ' +
|
292 | 'See https://bit.ly/gql-upload-node-6.',
|
293 | );
|
294 | }
|
295 |
|
296 | if (uploads === true || typeof uploads === 'undefined') {
|
297 | this.uploadsConfig = {};
|
298 | } else {
|
299 | this.uploadsConfig = uploads;
|
300 | }
|
301 |
|
302 |
|
303 | } else if (uploads) {
|
304 | throw new Error(
|
305 | 'This implementation of ApolloServer does not support file uploads because the environment cannot accept multi-part forms',
|
306 | );
|
307 | }
|
308 | }
|
309 |
|
310 | if (gateway && subscriptions !== false) {
|
311 |
|
312 | throw new Error(
|
313 | [
|
314 | 'Subscriptions are not yet compatible with the gateway.',
|
315 | "Set `subscriptions: false` in Apollo Server's constructor to",
|
316 | 'explicitly disable subscriptions (which are on by default)',
|
317 | 'and allow for gateway functionality.',
|
318 | ].join(' '),
|
319 | );
|
320 | } else if (subscriptions !== false) {
|
321 | if (this.supportsSubscriptions()) {
|
322 | if (subscriptions === true || typeof subscriptions === 'undefined') {
|
323 | this.subscriptionServerOptions = {
|
324 | path: this.graphqlPath,
|
325 | };
|
326 | } else if (typeof subscriptions === 'string') {
|
327 | this.subscriptionServerOptions = { path: subscriptions };
|
328 | } else {
|
329 | this.subscriptionServerOptions = {
|
330 | path: this.graphqlPath,
|
331 | ...subscriptions,
|
332 | };
|
333 | }
|
334 |
|
335 | this.subscriptionsPath = this.subscriptionServerOptions.path;
|
336 |
|
337 |
|
338 |
|
339 | } else if (subscriptions) {
|
340 | throw new Error(
|
341 | 'This implementation of ApolloServer does not support GraphQL subscriptions.',
|
342 | );
|
343 | }
|
344 | }
|
345 |
|
346 | this.playgroundOptions = createPlaygroundOptions(playground);
|
347 |
|
348 |
|
349 |
|
350 | this.ensurePluginInstantiation(plugins);
|
351 |
|
352 |
|
353 |
|
354 |
|
355 |
|
356 | if (
|
357 | typeof stopOnTerminationSignals === 'boolean'
|
358 | ? stopOnTerminationSignals
|
359 | : typeof engine === 'object' &&
|
360 | typeof engine.handleSignals === 'boolean'
|
361 | ? engine.handleSignals
|
362 | : isNodeLike && process.env.NODE_ENV !== 'test'
|
363 | ) {
|
364 | const signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM'];
|
365 | let receivedSignal = false;
|
366 | signals.forEach((signal) => {
|
367 |
|
368 |
|
369 | const handler: NodeJS.SignalsListener = async () => {
|
370 | if (receivedSignal) {
|
371 |
|
372 |
|
373 | return;
|
374 | }
|
375 | receivedSignal = true;
|
376 | try {
|
377 | await this.stop();
|
378 | } catch (e) {
|
379 | this.logger.error(`stop() threw during ${signal} shutdown`);
|
380 | this.logger.error(e);
|
381 |
|
382 | process.exit(1);
|
383 | }
|
384 |
|
385 |
|
386 |
|
387 |
|
388 |
|
389 | process.kill(process.pid, signal);
|
390 | };
|
391 | process.on(signal, handler);
|
392 | this.toDisposeLast.add(async () => {
|
393 | process.removeListener(signal, handler);
|
394 | });
|
395 | });
|
396 | }
|
397 |
|
398 | if (gateway) {
|
399 |
|
400 |
|
401 |
|
402 |
|
403 |
|
404 |
|
405 | this.state = { phase: 'initialized with gateway', gateway };
|
406 |
|
407 |
|
408 |
|
409 |
|
410 |
|
411 |
|
412 |
|
413 | this.requestOptions.executor = gateway.executor;
|
414 | } else {
|
415 |
|
416 |
|
417 |
|
418 |
|
419 | this.state = {
|
420 | phase: 'initialized with schema',
|
421 | schemaDerivedData: this.generateSchemaDerivedData(
|
422 | this.constructSchema(),
|
423 | ),
|
424 | };
|
425 |
|
426 |
|
427 |
|
428 |
|
429 | this.schema = this.state.schemaDerivedData.schema;
|
430 | }
|
431 |
|
432 |
|
433 |
|
434 |
|
435 |
|
436 |
|
437 |
|
438 |
|
439 |
|
440 |
|
441 | if (this.serverlessFramework()) {
|
442 | this.ensureStarting();
|
443 | }
|
444 | }
|
445 |
|
446 |
|
447 |
|
448 | public setGraphQLPath(path: string) {
|
449 | this.graphqlPath = path;
|
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 | public async start(): Promise<void> {
|
492 | if (this.serverlessFramework()) {
|
493 | throw new Error(
|
494 | 'When using an ApolloServer subclass from a serverless framework ' +
|
495 | "package, you don't need to call start(); just call createHandler().",
|
496 | );
|
497 | }
|
498 |
|
499 | return await this._start();
|
500 | }
|
501 |
|
502 |
|
503 |
|
504 | protected async _start(): Promise<void> {
|
505 | const initialState = this.state;
|
506 | if (
|
507 | initialState.phase !== 'initialized with gateway' &&
|
508 | initialState.phase !== 'initialized with schema'
|
509 | ) {
|
510 | throw new Error(
|
511 | `called start() with surprising state ${initialState.phase}`,
|
512 | );
|
513 | }
|
514 | const barrier = resolvable();
|
515 | this.state = { phase: 'starting', barrier };
|
516 | let loadedSchema = false;
|
517 | try {
|
518 | const schemaDerivedData =
|
519 | initialState.phase === 'initialized with schema'
|
520 | ? initialState.schemaDerivedData
|
521 | : this.generateSchemaDerivedData(
|
522 | await this.startGatewayAndLoadSchema(initialState.gateway),
|
523 | );
|
524 | loadedSchema = true;
|
525 | this.state = {
|
526 | phase: 'invoking serverWillStart',
|
527 | barrier,
|
528 | schemaDerivedData,
|
529 | };
|
530 |
|
531 | const service: GraphQLServiceContext = {
|
532 | logger: this.logger,
|
533 | schema: schemaDerivedData.schema,
|
534 | schemaHash: schemaDerivedData.schemaHash,
|
535 | apollo: this.apolloConfig,
|
536 | serverlessFramework: this.serverlessFramework(),
|
537 | engine: {
|
538 | serviceID: this.apolloConfig.graphId,
|
539 | apiKeyHash: this.apolloConfig.keyHash,
|
540 | },
|
541 | };
|
542 |
|
543 |
|
544 |
|
545 |
|
546 |
|
547 |
|
548 |
|
549 |
|
550 |
|
551 | if (this.requestOptions.persistedQueries?.cache) {
|
552 | service.persistedQueries = {
|
553 | cache: this.requestOptions.persistedQueries.cache,
|
554 | };
|
555 | }
|
556 |
|
557 | const serverListeners = (
|
558 | await Promise.all(
|
559 | this.plugins.map(
|
560 | (plugin) =>
|
561 | plugin.serverWillStart && plugin.serverWillStart(service),
|
562 | ),
|
563 | )
|
564 | ).filter(
|
565 | (maybeServerListener): maybeServerListener is GraphQLServerListener =>
|
566 | typeof maybeServerListener === 'object' &&
|
567 | !!maybeServerListener.serverWillStop,
|
568 | );
|
569 | this.toDispose.add(async () => {
|
570 | await Promise.all(
|
571 | serverListeners.map(({ serverWillStop }) => serverWillStop?.()),
|
572 | );
|
573 | });
|
574 |
|
575 | this.state = { phase: 'started', schemaDerivedData };
|
576 | } catch (error) {
|
577 | this.state = { phase: 'failed to start', error, loadedSchema };
|
578 | throw error;
|
579 | } finally {
|
580 | barrier.resolve();
|
581 | }
|
582 | }
|
583 |
|
584 | |
585 |
|
586 |
|
587 |
|
588 |
|
589 |
|
590 |
|
591 |
|
592 | protected async willStart() {
|
593 | try {
|
594 | this._start();
|
595 | } catch (e) {
|
596 | if (
|
597 | this.state.phase === 'failed to start' &&
|
598 | this.state.error === e &&
|
599 | !this.state.loadedSchema
|
600 | ) {
|
601 |
|
602 |
|
603 |
|
604 | return;
|
605 | }
|
606 | throw e;
|
607 | }
|
608 | }
|
609 |
|
610 |
|
611 |
|
612 |
|
613 |
|
614 |
|
615 |
|
616 |
|
617 |
|
618 |
|
619 |
|
620 |
|
621 | private async ensureStarted(): Promise<SchemaDerivedData> {
|
622 | while (true) {
|
623 | switch (this.state.phase) {
|
624 | case 'initialized with gateway':
|
625 | case 'initialized with schema':
|
626 | try {
|
627 | await this._start();
|
628 | } catch {
|
629 |
|
630 |
|
631 | }
|
632 |
|
633 | break;
|
634 | case 'starting':
|
635 | case 'invoking serverWillStart':
|
636 | await this.state.barrier;
|
637 |
|
638 | break;
|
639 | case 'failed to start':
|
640 |
|
641 |
|
642 | this.logStartupError(this.state.error);
|
643 |
|
644 |
|
645 |
|
646 | throw new Error(
|
647 | 'This data graph is missing a valid configuration. More details may be available in the server logs.',
|
648 | );
|
649 | case 'started':
|
650 | return this.state.schemaDerivedData;
|
651 | case 'stopping':
|
652 | throw new Error(
|
653 | 'Cannot execute GraphQL operations while the server is stopping.',
|
654 | );
|
655 | case 'stopped':
|
656 | throw new Error(
|
657 | 'Cannot execute GraphQL operations after the server has stopped.',
|
658 | );
|
659 | default:
|
660 | throw new UnreachableCaseError(this.state);
|
661 | }
|
662 | }
|
663 | }
|
664 |
|
665 |
|
666 |
|
667 |
|
668 |
|
669 |
|
670 |
|
671 |
|
672 |
|
673 |
|
674 |
|
675 |
|
676 |
|
677 | protected ensureStarting() {
|
678 | if (
|
679 | this.state.phase === 'initialized with gateway' ||
|
680 | this.state.phase === 'initialized with schema'
|
681 | ) {
|
682 |
|
683 |
|
684 |
|
685 |
|
686 |
|
687 |
|
688 | this._start().catch((e) => this.logStartupError(e));
|
689 | }
|
690 | }
|
691 |
|
692 |
|
693 |
|
694 |
|
695 |
|
696 |
|
697 |
|
698 |
|
699 | private logStartupError(err: Error) {
|
700 | const prelude = this.serverlessFramework()
|
701 | ? 'An error occurred during Apollo Server startup.'
|
702 | : 'Apollo Server was started implicitly and an error occurred during startup. ' +
|
703 | '(Consider calling `await server.start()` immediately after ' +
|
704 | '`server = new ApolloServer()` so you can handle these errors directly before ' +
|
705 | 'starting your web server.)';
|
706 | this.logger.error(
|
707 | prelude +
|
708 | ' All GraphQL requests will now fail. The startup error ' +
|
709 | 'was: ' +
|
710 | ((err && err.message) || err),
|
711 | );
|
712 | }
|
713 |
|
714 | private async startGatewayAndLoadSchema(
|
715 | gateway: GraphQLService,
|
716 | ): Promise<GraphQLSchema> {
|
717 |
|
718 |
|
719 | const unsubscriber = gateway.onSchemaChange((schema) => {
|
720 |
|
721 | if (this.state.phase === 'started') {
|
722 | this.state.schemaDerivedData = this.generateSchemaDerivedData(schema);
|
723 | }
|
724 | });
|
725 | this.toDispose.add(async () => unsubscriber());
|
726 |
|
727 |
|
728 | const engineConfig =
|
729 | this.apolloConfig.keyHash && this.apolloConfig.graphId
|
730 | ? {
|
731 | apiKeyHash: this.apolloConfig.keyHash,
|
732 | graphId: this.apolloConfig.graphId,
|
733 | graphVariant: this.apolloConfig.graphVariant,
|
734 | }
|
735 | : undefined;
|
736 |
|
737 | const config = await gateway.load({
|
738 | apollo: this.apolloConfig,
|
739 | engine: engineConfig,
|
740 | });
|
741 | this.toDispose.add(async () => await gateway.stop?.());
|
742 | return config.schema;
|
743 | }
|
744 |
|
745 | private constructSchema(): GraphQLSchema {
|
746 | const {
|
747 | schema,
|
748 | modules,
|
749 | typeDefs,
|
750 | resolvers,
|
751 | schemaDirectives,
|
752 | parseOptions,
|
753 | } = this.config;
|
754 | if (schema) {
|
755 | return schema;
|
756 | }
|
757 |
|
758 | if (modules) {
|
759 | const { schema, errors } = buildServiceDefinition(modules);
|
760 | if (errors && errors.length > 0) {
|
761 | throw new Error(errors.map((error) => error.message).join('\n\n'));
|
762 | }
|
763 | return schema!;
|
764 | }
|
765 |
|
766 | if (!typeDefs) {
|
767 | throw Error(
|
768 | 'Apollo Server requires either an existing schema, modules or typeDefs',
|
769 | );
|
770 | }
|
771 |
|
772 | const augmentedTypeDefs = Array.isArray(typeDefs) ? typeDefs : [typeDefs];
|
773 |
|
774 |
|
775 |
|
776 |
|
777 | if (!isDirectiveDefined(augmentedTypeDefs, 'cacheControl')) {
|
778 | augmentedTypeDefs.push(
|
779 | gql`
|
780 | enum CacheControlScope {
|
781 | PUBLIC
|
782 | PRIVATE
|
783 | }
|
784 |
|
785 | directive @cacheControl(
|
786 | maxAge: Int
|
787 | scope: CacheControlScope
|
788 | ) on FIELD_DEFINITION | OBJECT | INTERFACE
|
789 | `,
|
790 | );
|
791 | }
|
792 |
|
793 | if (this.uploadsConfig) {
|
794 | const { GraphQLUpload } = require('@apollographql/graphql-upload-8-fork');
|
795 | if (Array.isArray(resolvers)) {
|
796 | if (resolvers.every((resolver) => !resolver.Upload)) {
|
797 | resolvers.push({ Upload: GraphQLUpload });
|
798 | }
|
799 | } else {
|
800 | if (resolvers && !resolvers.Upload) {
|
801 | resolvers.Upload = GraphQLUpload;
|
802 | }
|
803 | }
|
804 |
|
805 |
|
806 |
|
807 | augmentedTypeDefs.push(
|
808 | gql`
|
809 | scalar Upload
|
810 | `,
|
811 | );
|
812 | }
|
813 |
|
814 | return makeExecutableSchema({
|
815 | typeDefs: augmentedTypeDefs,
|
816 | schemaDirectives,
|
817 | resolvers,
|
818 | parseOptions,
|
819 | });
|
820 | }
|
821 |
|
822 | private generateSchemaDerivedData(schema: GraphQLSchema): SchemaDerivedData {
|
823 | const schemaHash = generateSchemaHash(schema!);
|
824 |
|
825 | const { mocks, mockEntireSchema, extensions: _extensions } = this.config;
|
826 |
|
827 | if (mocks || (typeof mockEntireSchema !== 'undefined' && mocks !== false)) {
|
828 | addMockFunctionsToSchema({
|
829 | schema,
|
830 | mocks:
|
831 | typeof mocks === 'boolean' || typeof mocks === 'undefined'
|
832 | ? {}
|
833 | : mocks,
|
834 | preserveResolvers:
|
835 | typeof mockEntireSchema === 'undefined' ? false : !mockEntireSchema,
|
836 | });
|
837 | }
|
838 |
|
839 | const extensions = [];
|
840 |
|
841 |
|
842 |
|
843 | extensions.push(...(_extensions || []));
|
844 |
|
845 |
|
846 | const documentStore = this.initializeDocumentStore();
|
847 |
|
848 | return {
|
849 | schema,
|
850 | schemaHash,
|
851 | extensions,
|
852 | documentStore,
|
853 | };
|
854 | }
|
855 |
|
856 | public async stop() {
|
857 |
|
858 | if (this.state.phase === 'stopped') {
|
859 | if (this.state.stopError) {
|
860 | throw this.state.stopError;
|
861 | }
|
862 | return;
|
863 | }
|
864 |
|
865 |
|
866 |
|
867 | if (this.state.phase === 'stopping') {
|
868 | await this.state.barrier;
|
869 |
|
870 |
|
871 |
|
872 | const state = this.state as ServerState;
|
873 | if (state.phase !== 'stopped') {
|
874 | throw Error(`Surprising post-stopping state ${state.phase}`);
|
875 | }
|
876 | if (state.stopError) {
|
877 | throw state.stopError;
|
878 | }
|
879 | return;
|
880 | }
|
881 |
|
882 |
|
883 | this.state = { phase: 'stopping', barrier: resolvable() };
|
884 | try {
|
885 |
|
886 |
|
887 |
|
888 |
|
889 | await Promise.all([...this.toDispose].map((dispose) => dispose()));
|
890 | if (this.subscriptionServer) this.subscriptionServer.close();
|
891 | await Promise.all([...this.toDisposeLast].map((dispose) => dispose()));
|
892 | } catch (stopError) {
|
893 | this.state = { phase: 'stopped', stopError };
|
894 | return;
|
895 | }
|
896 | this.state = { phase: 'stopped', stopError: null };
|
897 | }
|
898 |
|
899 | public installSubscriptionHandlers(
|
900 | server:
|
901 | | HttpServer
|
902 | | HttpsServer
|
903 | | Http2Server
|
904 | | Http2SecureServer
|
905 | | WebSocket.Server,
|
906 | ) {
|
907 | if (!this.subscriptionServerOptions) {
|
908 | if (this.config.gateway) {
|
909 | throw Error(
|
910 | 'Subscriptions are not supported when operating as a gateway',
|
911 | );
|
912 | }
|
913 | if (this.supportsSubscriptions()) {
|
914 | throw Error(
|
915 | 'Subscriptions are disabled, due to subscriptions set to false in the ApolloServer constructor',
|
916 | );
|
917 | } else {
|
918 | throw Error(
|
919 | 'Subscriptions are not supported, choose an integration, such as apollo-server-express that allows persistent connections',
|
920 | );
|
921 | }
|
922 | }
|
923 | const { SubscriptionServer } = require('subscriptions-transport-ws');
|
924 | const {
|
925 | onDisconnect,
|
926 | onConnect,
|
927 | keepAlive,
|
928 | path,
|
929 | } = this.subscriptionServerOptions;
|
930 |
|
931 | let schema: GraphQLSchema;
|
932 | switch (this.state.phase) {
|
933 | case 'initialized with schema':
|
934 | case 'invoking serverWillStart':
|
935 | case 'started':
|
936 | schema = this.state.schemaDerivedData.schema;
|
937 | break;
|
938 | case 'initialized with gateway':
|
939 |
|
940 | case 'starting':
|
941 |
|
942 |
|
943 | case 'failed to start':
|
944 |
|
945 |
|
946 | case 'stopping':
|
947 | case 'stopped':
|
948 |
|
949 | throw new Error(
|
950 | `Can't install subscription handlers when state is ${this.state.phase}`,
|
951 | );
|
952 | default:
|
953 | throw new UnreachableCaseError(this.state);
|
954 | }
|
955 |
|
956 | this.subscriptionServer = SubscriptionServer.create(
|
957 | {
|
958 | schema,
|
959 | execute,
|
960 | subscribe,
|
961 | onConnect: onConnect
|
962 | ? onConnect
|
963 | : (connectionParams: Object) => ({ ...connectionParams }),
|
964 | onDisconnect: onDisconnect,
|
965 | onOperation: async (
|
966 | message: { payload: any },
|
967 | connection: ExecutionParams,
|
968 | ) => {
|
969 | connection.formatResponse = (value: ExecutionResult) => ({
|
970 | ...value,
|
971 | errors:
|
972 | value.errors &&
|
973 | formatApolloErrors([...value.errors], {
|
974 | formatter: this.requestOptions.formatError,
|
975 | debug: this.requestOptions.debug,
|
976 | }),
|
977 | });
|
978 |
|
979 | connection.formatError = this.requestOptions.formatError;
|
980 |
|
981 | let context: Context = this.context ? this.context : { connection };
|
982 |
|
983 | try {
|
984 | context =
|
985 | typeof this.context === 'function'
|
986 | ? await this.context({ connection, payload: message.payload })
|
987 | : context;
|
988 | } catch (e) {
|
989 | throw formatApolloErrors([e], {
|
990 | formatter: this.requestOptions.formatError,
|
991 | debug: this.requestOptions.debug,
|
992 | })[0];
|
993 | }
|
994 |
|
995 | return { ...connection, context };
|
996 | },
|
997 | keepAlive,
|
998 | validationRules: this.requestOptions.validationRules,
|
999 | },
|
1000 | server instanceof NetServer || server instanceof TlsServer
|
1001 | ? {
|
1002 | server,
|
1003 | path,
|
1004 | }
|
1005 | : server,
|
1006 | );
|
1007 | }
|
1008 |
|
1009 | protected supportsSubscriptions(): boolean {
|
1010 | return false;
|
1011 | }
|
1012 |
|
1013 | protected supportsUploads(): boolean {
|
1014 | return false;
|
1015 | }
|
1016 |
|
1017 | protected serverlessFramework(): boolean {
|
1018 | return false;
|
1019 | }
|
1020 |
|
1021 | private ensurePluginInstantiation(plugins: PluginDefinition[] = []): void {
|
1022 | const pluginsToInit: PluginDefinition[] = [];
|
1023 |
|
1024 |
|
1025 |
|
1026 |
|
1027 |
|
1028 |
|
1029 |
|
1030 |
|
1031 |
|
1032 |
|
1033 |
|
1034 |
|
1035 | if (this.config.tracing) {
|
1036 | pluginsToInit.push(pluginTracing());
|
1037 | }
|
1038 |
|
1039 |
|
1040 | if (this.config.cacheControl !== false) {
|
1041 | let cacheControlOptions: CacheControlExtensionOptions = {};
|
1042 | if (
|
1043 | typeof this.config.cacheControl === 'boolean' &&
|
1044 | this.config.cacheControl === true
|
1045 | ) {
|
1046 |
|
1047 |
|
1048 |
|
1049 | cacheControlOptions = {
|
1050 | stripFormattedExtensions: false,
|
1051 | calculateHttpHeaders: false,
|
1052 | defaultMaxAge: 0,
|
1053 | };
|
1054 | } else {
|
1055 |
|
1056 |
|
1057 | cacheControlOptions = {
|
1058 | stripFormattedExtensions: true,
|
1059 | calculateHttpHeaders: true,
|
1060 | defaultMaxAge: 0,
|
1061 | ...this.config.cacheControl,
|
1062 | };
|
1063 | }
|
1064 |
|
1065 | pluginsToInit.push(pluginCacheControl(cacheControlOptions));
|
1066 | }
|
1067 |
|
1068 | pluginsToInit.push(...plugins);
|
1069 |
|
1070 | this.plugins = pluginsToInit.map((plugin) => {
|
1071 | if (typeof plugin === 'function') {
|
1072 | return plugin();
|
1073 | }
|
1074 | return plugin;
|
1075 | });
|
1076 |
|
1077 | const alreadyHavePluginWithInternalId = (id: InternalPluginId) =>
|
1078 | this.plugins.some(
|
1079 | (p) => pluginIsInternal(p) && p.__internal_plugin_id__() === id,
|
1080 | );
|
1081 |
|
1082 |
|
1083 | {
|
1084 | const alreadyHavePlugin = alreadyHavePluginWithInternalId(
|
1085 | 'UsageReporting',
|
1086 | );
|
1087 | const { engine } = this.config;
|
1088 | const disabledViaLegacyOption =
|
1089 | engine === false ||
|
1090 | (typeof engine === 'object' && engine.reportTiming === false);
|
1091 | if (alreadyHavePlugin) {
|
1092 | if (engine !== undefined) {
|
1093 | throw Error(
|
1094 | "You can't combine the legacy `new ApolloServer({engine})` option with directly " +
|
1095 | 'creating an ApolloServerPluginUsageReporting plugin. See ' +
|
1096 | 'https://go.apollo.dev/s/migration-engine-plugins',
|
1097 | );
|
1098 | }
|
1099 | } else if (this.apolloConfig.key && !disabledViaLegacyOption) {
|
1100 |
|
1101 |
|
1102 |
|
1103 | this.plugins.unshift(
|
1104 | typeof engine === 'object'
|
1105 | ? ApolloServerPluginUsageReportingFromLegacyOptions(engine)
|
1106 | : ApolloServerPluginUsageReporting(),
|
1107 | );
|
1108 | }
|
1109 | }
|
1110 |
|
1111 |
|
1112 | {
|
1113 | const alreadyHavePlugin = alreadyHavePluginWithInternalId(
|
1114 | 'SchemaReporting',
|
1115 | );
|
1116 | const enabledViaEnvVar = process.env.APOLLO_SCHEMA_REPORTING === 'true';
|
1117 | const { engine } = this.config;
|
1118 | const enabledViaLegacyOption =
|
1119 | typeof engine === 'object' &&
|
1120 | (engine.reportSchema || engine.experimental_schemaReporting);
|
1121 | if (alreadyHavePlugin || enabledViaEnvVar || enabledViaLegacyOption) {
|
1122 | if (this.config.gateway) {
|
1123 | throw new Error(
|
1124 | [
|
1125 | "Schema reporting is not yet compatible with the gateway. If you're",
|
1126 | 'interested in using schema reporting with the gateway, please',
|
1127 | 'contact Apollo support. To set up managed federation, see',
|
1128 | 'https://go.apollo.dev/s/managed-federation',
|
1129 | ].join(' '),
|
1130 | );
|
1131 | }
|
1132 | }
|
1133 | if (alreadyHavePlugin) {
|
1134 | if (engine !== undefined) {
|
1135 | throw Error(
|
1136 | "You can't combine the legacy `new ApolloServer({engine})` option with directly " +
|
1137 | 'creating an ApolloServerPluginSchemaReporting plugin. See ' +
|
1138 | 'https://go.apollo.dev/s/migration-engine-plugins',
|
1139 | );
|
1140 | }
|
1141 | } else if (!this.apolloConfig.key) {
|
1142 | if (enabledViaEnvVar) {
|
1143 | throw new Error(
|
1144 | "You've enabled schema reporting by setting the APOLLO_SCHEMA_REPORTING " +
|
1145 | 'environment variable to true, but you also need to provide your ' +
|
1146 | 'Apollo API key, via the APOLLO_KEY environment ' +
|
1147 | 'variable or via `new ApolloServer({apollo: {key})',
|
1148 | );
|
1149 | }
|
1150 | if (enabledViaLegacyOption) {
|
1151 | throw new Error(
|
1152 | "You've enabled schema reporting in the `engine` argument to `new ApolloServer()`, " +
|
1153 | 'but you also need to provide your Apollo API key, via the APOLLO_KEY environment ' +
|
1154 | 'variable or via `new ApolloServer({apollo: {key})',
|
1155 | );
|
1156 | }
|
1157 | } else if (enabledViaEnvVar || enabledViaLegacyOption) {
|
1158 | const options: ApolloServerPluginSchemaReportingOptions = {};
|
1159 | if (typeof engine === 'object') {
|
1160 | options.initialDelayMaxMs =
|
1161 | engine.schemaReportingInitialDelayMaxMs ??
|
1162 | engine.experimental_schemaReportingInitialDelayMaxMs;
|
1163 | options.overrideReportedSchema =
|
1164 | engine.overrideReportedSchema ??
|
1165 | engine.experimental_overrideReportedSchema;
|
1166 | options.endpointUrl = engine.schemaReportingUrl;
|
1167 | }
|
1168 | this.plugins.push(ApolloServerPluginSchemaReporting(options));
|
1169 | }
|
1170 | }
|
1171 |
|
1172 |
|
1173 | {
|
1174 | const alreadyHavePlugin = alreadyHavePluginWithInternalId('InlineTrace');
|
1175 | const { engine } = this.config;
|
1176 | if (alreadyHavePlugin) {
|
1177 | if (engine !== undefined) {
|
1178 | throw Error(
|
1179 | "You can't combine the legacy `new ApolloServer({engine})` option with directly " +
|
1180 | 'creating an ApolloServerPluginInlineTrace plugin. See ' +
|
1181 | 'https://go.apollo.dev/s/migration-engine-plugins',
|
1182 | );
|
1183 | }
|
1184 | } else if (this.config.engine !== false) {
|
1185 |
|
1186 |
|
1187 |
|
1188 |
|
1189 |
|
1190 | const options: ApolloServerPluginInlineTraceOptions = {
|
1191 | __onlyIfSchemaIsFederated: true,
|
1192 | };
|
1193 | if (typeof engine === 'object') {
|
1194 | options.rewriteError = engine.rewriteError;
|
1195 | }
|
1196 | this.plugins.push(ApolloServerPluginInlineTrace(options));
|
1197 | }
|
1198 | }
|
1199 | }
|
1200 |
|
1201 | private initializeDocumentStore(): InMemoryLRUCache<DocumentNode> {
|
1202 | return new InMemoryLRUCache<DocumentNode>({
|
1203 |
|
1204 |
|
1205 |
|
1206 |
|
1207 |
|
1208 | maxSize:
|
1209 | Math.pow(2, 20) * (this.experimental_approximateDocumentStoreMiB || 30),
|
1210 | sizeCalculator: approximateObjectSize,
|
1211 | });
|
1212 | }
|
1213 |
|
1214 |
|
1215 |
|
1216 |
|
1217 | protected async graphQLServerOptions(
|
1218 | integrationContextArgument?: Record<string, any>,
|
1219 | ): Promise<GraphQLServerOptions> {
|
1220 | const {
|
1221 | schema,
|
1222 | schemaHash,
|
1223 | documentStore,
|
1224 | extensions,
|
1225 | } = await this.ensureStarted();
|
1226 |
|
1227 | let context: Context = this.context ? this.context : {};
|
1228 |
|
1229 | try {
|
1230 | context =
|
1231 | typeof this.context === 'function'
|
1232 | ? await this.context(integrationContextArgument || {})
|
1233 | : context;
|
1234 | } catch (error) {
|
1235 |
|
1236 | context = () => {
|
1237 | throw error;
|
1238 | };
|
1239 | }
|
1240 |
|
1241 | return {
|
1242 | schema,
|
1243 | schemaHash,
|
1244 | logger: this.logger,
|
1245 | plugins: this.plugins,
|
1246 | documentStore,
|
1247 | extensions,
|
1248 | context,
|
1249 |
|
1250 |
|
1251 |
|
1252 | persistedQueries: this.requestOptions
|
1253 | .persistedQueries as PersistedQueryOptions,
|
1254 | fieldResolver: this.requestOptions.fieldResolver as GraphQLFieldResolver<
|
1255 | any,
|
1256 | any
|
1257 | >,
|
1258 | parseOptions: this.parseOptions,
|
1259 | ...this.requestOptions,
|
1260 | };
|
1261 | }
|
1262 |
|
1263 | public async executeOperation(request: GraphQLRequest) {
|
1264 | const options = await this.graphQLServerOptions();
|
1265 |
|
1266 | if (typeof options.context === 'function') {
|
1267 | options.context = (options.context as () => never)();
|
1268 | } else if (typeof options.context === 'object') {
|
1269 | // FIXME: We currently shallow clone the context for every request,
|
1270 | // but that's unlikely to be what people want.
|
1271 | // We allow passing in a function for `context` to ApolloServer,
|
1272 | // but this only runs once for a batched request (because this is resolved
|
1273 |
|
1274 |
|
1275 | options.context = cloneObject(options.context);
|
1276 | }
|
1277 |
|
1278 | const requestCtx: GraphQLRequestContext = {
|
1279 | logger: this.logger,
|
1280 | schema: options.schema,
|
1281 | schemaHash: options.schemaHash,
|
1282 | request,
|
1283 | context: options.context || Object.create(null),
|
1284 | cache: options.cache!,
|
1285 | metrics: {},
|
1286 | response: {
|
1287 | http: {
|
1288 | headers: new Headers(),
|
1289 | },
|
1290 | },
|
1291 | debug: options.debug,
|
1292 | };
|
1293 |
|
1294 | return processGraphQLRequest(options, requestCtx);
|
1295 | }
|
1296 | }
|
1297 |
|
1298 | function printNodeFileUploadsMessage(logger: Logger) {
|
1299 | logger.error(
|
1300 | [
|
1301 | '*****************************************************************',
|
1302 | '* *',
|
1303 | '* ERROR! Manual intervention is necessary for Node.js < v8.5.0! *',
|
1304 | '* *',
|
1305 | '*****************************************************************',
|
1306 | '',
|
1307 | 'The third-party `graphql-upload` package, which is used to implement',
|
1308 | 'file uploads in Apollo Server 2.x, no longer supports Node.js LTS',
|
1309 | 'versions prior to Node.js v8.5.0.',
|
1310 | '',
|
1311 | 'Deployments which NEED file upload capabilities should update to',
|
1312 | 'Node.js >= v8.5.0 to continue using uploads.',
|
1313 | '',
|
1314 | 'If this server DOES NOT NEED file uploads and wishes to continue',
|
1315 | 'using this version of Node.js, uploads can be disabled by adding:',
|
1316 | '',
|
1317 | ' uploads: false,',
|
1318 | '',
|
1319 | '...to the options for Apollo Server and re-deploying the server.',
|
1320 | '',
|
1321 | 'For more information, see https:
|
1322 | '',
|
1323 | ].join('\n'),
|
1324 | );
|
1325 | }
|
1326 |
|
\ | No newline at end of file |