/
ApolloServer.ts
1397 lines (1307 loc) 路 52.2 KB
/
ApolloServer.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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { GatewayExecutor } from '@apollo/server-gateway-interface';
import { isNodeLike } from '@apollo/utils.isnodelike';
import {
InMemoryLRUCache,
PrefixingKeyValueCache,
type KeyValueCache,
} from '@apollo/utils.keyvaluecache';
import type { Logger } from '@apollo/utils.logger';
import type { WithRequired } from '@apollo/utils.withrequired';
import { makeExecutableSchema } from '@graphql-tools/schema';
import resolvable, { type Resolvable } from '@josephg/resolvable';
import {
GraphQLError,
assertValidSchema,
print,
printSchema,
type DocumentNode,
type FormattedExecutionResult,
type GraphQLFieldResolver,
type GraphQLFormattedError,
type GraphQLSchema,
type ParseOptions,
type TypedQueryDocumentNode,
type ValidationContext,
type ValidationRule,
} from 'graphql';
import loglevel from 'loglevel';
import Negotiator from 'negotiator';
import { newCachePolicy } from './cachePolicy.js';
import { determineApolloConfig } from './determineApolloConfig.js';
import {
ensureError,
ensureGraphQLError,
normalizeAndFormatErrors,
} from './errorNormalize.js';
import {
ApolloServerErrorCode,
ApolloServerValidationErrorCode,
} from './errors/index.js';
import type { ApolloServerOptionsWithStaticSchema } from './externalTypes/constructor.js';
import type {
ExecuteOperationOptions,
VariableValues,
} from './externalTypes/graphql.js';
import type {
ApolloConfig,
ApolloServerOptions,
ApolloServerPlugin,
BaseContext,
ContextThunk,
DocumentStore,
GraphQLRequest,
GraphQLRequestContext,
GraphQLResponse,
GraphQLServerContext,
GraphQLServerListener,
HTTPGraphQLHead,
HTTPGraphQLRequest,
HTTPGraphQLResponse,
LandingPage,
PersistedQueryOptions,
} from './externalTypes/index.js';
import { runPotentiallyBatchedHttpQuery } from './httpBatching.js';
import type { GraphQLExperimentalIncrementalExecutionResults } from './incrementalDeliveryPolyfill.js';
import { pluginIsInternal, type InternalPluginId } from './internalPlugin.js';
import {
preventCsrf,
recommendedCsrfPreventionRequestHeaders,
} from './preventCsrf.js';
import { APQ_CACHE_PREFIX, processGraphQLRequest } from './requestPipeline.js';
import { newHTTPGraphQLHead, prettyJSONStringify } from './runHttpQuery.js';
import { HeaderMap } from './utils/HeaderMap.js';
import { UnreachableCaseError } from './utils/UnreachableCaseError.js';
import { computeCoreSchemaHash } from './utils/computeCoreSchemaHash.js';
import { isDefined } from './utils/isDefined.js';
import { SchemaManager } from './utils/schemaManager.js';
const NoIntrospection: ValidationRule = (context: ValidationContext) => ({
Field(node) {
if (node.name.value === '__schema' || node.name.value === '__type') {
context.reportError(
new GraphQLError(
'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',
{
nodes: [node],
extensions: {
validationErrorCode:
ApolloServerValidationErrorCode.INTROSPECTION_DISABLED,
},
},
),
);
}
},
});
export type SchemaDerivedData = {
schema: GraphQLSchema;
// A store that, when enabled (default), will store the parsed and validated
// versions of operations in-memory, allowing subsequent parses/validates
// on the same operation to be executed immediately.
documentStore: DocumentStore | null;
// Prefix for keys in the DocumentStore if a custom one is provided (to
// separate the cache for different schema versions). This is vital to
// security so we do it explicitly so that
// PrefixingKeyValueCache.cacheDangerouslyDoesNotNeedPrefixesForIsolation
// doesn't affect it.
documentStoreKeyPrefix: string;
};
type RunningServerState = {
schemaManager: SchemaManager;
landingPage: LandingPage | null;
};
type ServerState =
| {
phase: 'initialized';
schemaManager: SchemaManager;
}
| {
phase: 'starting';
barrier: Resolvable<void>;
schemaManager: SchemaManager;
// This is set to true if you called
// startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests
// instead of start. The main purpose is that assertStarted allows you to
// still be in the starting phase if this is set. (This is the serverless
// use case.)
startedInBackground: boolean;
}
| {
phase: 'failed to start';
error: Error;
}
| ({
phase: 'started';
drainServers: (() => Promise<void>) | null;
toDispose: (() => Promise<void>)[];
toDisposeLast: (() => Promise<void>)[];
} & RunningServerState)
| ({
phase: 'draining';
barrier: Resolvable<void>;
} & RunningServerState)
| {
phase: 'stopping';
barrier: Resolvable<void>;
}
| {
phase: 'stopped';
stopError: Error | null;
};
export interface ApolloServerInternals<TContext extends BaseContext> {
state: ServerState;
gatewayExecutor: GatewayExecutor | null;
dangerouslyDisableValidation?: boolean;
formatError?: (
formattedError: GraphQLFormattedError,
error: unknown,
) => GraphQLFormattedError;
includeStacktraceInErrorResponses: boolean;
persistedQueries?: WithRequired<PersistedQueryOptions, 'cache'>;
nodeEnv: string;
allowBatchedHttpRequests: boolean;
apolloConfig: ApolloConfig;
plugins: ApolloServerPlugin<TContext>[];
parseOptions: ParseOptions;
// `undefined` means we figure out what to do during _start (because
// the default depends on whether or not we used the background version
// of start).
stopOnTerminationSignals: boolean | undefined;
csrfPreventionRequestHeaders: string[] | null;
rootValue?: ((parsedQuery: DocumentNode) => unknown) | unknown;
validationRules: Array<ValidationRule>;
fieldResolver?: GraphQLFieldResolver<any, TContext>;
// TODO(AS5): remove OR warn + ignore with this option set, ignore option and
// flip default behavior.
status400ForVariableCoercionErrors?: boolean;
__testing_incrementalExecutionResults?: GraphQLExperimentalIncrementalExecutionResults;
stringifyResult: (
value: FormattedExecutionResult,
) => string | Promise<string>;
}
function defaultLogger(): Logger {
const loglevelLogger = loglevel.getLogger('apollo-server');
loglevelLogger.setLevel(loglevel.levels.INFO);
return loglevelLogger;
}
// We really want to prevent this from being legal:
//
// const s: ApolloServer<{}> =
// new ApolloServer<{importantContextField: boolean}>({ ... });
// s.executeOperation({query}, {contextValue: {}});
//
// ie, if you declare an ApolloServer whose context values must be of a certain
// type, you can't assign it to a variable whose context values are less
// constrained and then pass in a context value missing important fields.
//
// We also want this to be illegal:
//
// const sBase = new ApolloServer<{}>({ ... });
// const s: ApolloServer<{importantContextField: boolean}> = sBase;
// s.addPlugin({async requestDidStart({contextValue: {importantContextField}}) { ... }})
// sBase.executeOperation({query}, {contextValue: {}});
//
// so you shouldn't be able to assign an ApolloServer to a variable whose
// context values are more constrained, either. So we want to declare that
// ApolloServer is *invariant* in TContext, which we do with `in out` (a
// TypeScript 4.7 feature).
export class ApolloServer<in out TContext extends BaseContext = BaseContext> {
private internals: ApolloServerInternals<TContext>;
public readonly cache: KeyValueCache<string>;
public readonly logger: Logger;
constructor(config: ApolloServerOptions<TContext>) {
const nodeEnv = config.nodeEnv ?? process.env.NODE_ENV ?? '';
this.logger = config.logger ?? defaultLogger();
const apolloConfig = determineApolloConfig(config.apollo, this.logger);
const isDev = nodeEnv !== 'production';
if (
config.cache &&
config.cache !== 'bounded' &&
PrefixingKeyValueCache.prefixesAreUnnecessaryForIsolation(config.cache)
) {
throw new Error(
'You cannot pass a cache returned from ' +
'`PrefixingKeyValueCache.cacheDangerouslyDoesNotNeedPrefixesForIsolation`' +
'to `new ApolloServer({ cache })`, because Apollo Server may use it for ' +
'multiple features whose cache keys must be distinct from each other.',
);
}
const state: ServerState = config.gateway
? // ApolloServer has been initialized but we have not yet tried to load the
// schema from the gateway. That will wait until `start()` or
// `startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests()`
// is called. (These may be called by other helpers; for example,
// `standaloneServer` calls `start` for you inside its `listen` method,
// and a serverless framework integration would call
// startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests
// for you.)
{
phase: 'initialized',
schemaManager: new SchemaManager({
gateway: config.gateway,
apolloConfig,
schemaDerivedDataProvider: (schema) =>
ApolloServer.generateSchemaDerivedData(
schema,
config.documentStore,
),
logger: this.logger,
}),
}
: // We construct the schema synchronously so that we can fail fast if the
// schema can't be constructed. (This used to be more important because we
// used to have a 'schema' field that was publicly accessible immediately
// after construction, though that field never actually worked with
// gateways.)
{
phase: 'initialized',
schemaManager: new SchemaManager({
apiSchema: ApolloServer.constructSchema(config),
schemaDerivedDataProvider: (schema) =>
ApolloServer.generateSchemaDerivedData(
schema,
config.documentStore,
),
logger: this.logger,
}),
};
const introspectionEnabled = config.introspection ?? isDev;
// We continue to allow 'bounded' for backwards-compatibility with the AS3.9
// API.
this.cache =
config.cache === undefined || config.cache === 'bounded'
? new InMemoryLRUCache()
: config.cache;
// Note that we avoid calling methods on `this` before `this.internals` is assigned
// (thus a bunch of things being static methods above).
this.internals = {
formatError: config.formatError,
rootValue: config.rootValue,
validationRules: [
...(config.validationRules ?? []),
...(introspectionEnabled ? [] : [NoIntrospection]),
],
dangerouslyDisableValidation:
config.dangerouslyDisableValidation ?? false,
fieldResolver: config.fieldResolver,
includeStacktraceInErrorResponses:
config.includeStacktraceInErrorResponses ??
(nodeEnv !== 'production' && nodeEnv !== 'test'),
persistedQueries:
config.persistedQueries === false
? undefined
: {
...config.persistedQueries,
cache: new PrefixingKeyValueCache(
config.persistedQueries?.cache ?? this.cache,
APQ_CACHE_PREFIX,
),
},
nodeEnv,
allowBatchedHttpRequests: config.allowBatchedHttpRequests ?? false,
apolloConfig,
// Note that more plugins can be added before `start()` with `addPlugin()`
// (eg, plugins that want to take this ApolloServer as an argument), and
// `start()` will call `addDefaultPlugins` to add default plugins.
plugins: config.plugins ?? [],
parseOptions: config.parseOptions ?? {},
state,
stopOnTerminationSignals: config.stopOnTerminationSignals,
gatewayExecutor: null, // set by _start
csrfPreventionRequestHeaders:
config.csrfPrevention === true || config.csrfPrevention === undefined
? recommendedCsrfPreventionRequestHeaders
: config.csrfPrevention === false
? null
: config.csrfPrevention.requestHeaders ??
recommendedCsrfPreventionRequestHeaders,
status400ForVariableCoercionErrors:
config.status400ForVariableCoercionErrors ?? false,
__testing_incrementalExecutionResults:
config.__testing_incrementalExecutionResults,
stringifyResult: config.stringifyResult ?? prettyJSONStringify,
};
}
// Awaiting a call to `start` ensures that a schema has been loaded and that
// all plugin `serverWillStart` hooks have been called. If either of these
// processes throw, `start` will (async) throw as well.
//
// If you're using `standaloneServer`, you don't need to call `start` yourself
// (in fact, it will throw if you do so); its `listen` method takes care of
// that for you.
//
// If instead you're using an integration package for a non-serverless
// framework (like Express), you must await a call to `start` immediately
// after creating your `ApolloServer`, before attaching it to your web
// framework and starting to accept requests. `start` should only be called
// once; if it throws and you'd like to retry, just create another
// `ApolloServer`. (Calling `start` was optional in Apollo Server 2, but in
// Apollo Server 3+ the functions like `expressMiddleware` use `assertStarted`
// to throw if `start` hasn't successfully completed.)
//
// Serverless integrations like Lambda do not support calling `start()`,
// because their lifecycle doesn't allow you to wait before assigning a
// handler or allowing the handler to be called. So they call
// `startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests()`
// instead, and don't really differentiate between startup failures and
// request failures. This is hopefully appropriate for a "serverless"
// framework. Serverless startup failures result in returning a redacted error
// to the end user and logging the more detailed error.
public async start(): Promise<void> {
return await this._start(false);
}
public startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests(): void {
this._start(true).catch((e) => this.logStartupError(e));
}
private async _start(startedInBackground: boolean): Promise<void> {
if (this.internals.state.phase !== 'initialized') {
// If we wanted we could make this error detectable and change
// `standaloneServer` to change the message to say not to call start() at
// all.
throw new Error(
`You should only call 'start()' or ` +
`'startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests()' ` +
`once on your ApolloServer.`,
);
}
const schemaManager = this.internals.state.schemaManager;
const barrier = resolvable();
this.internals.state = {
phase: 'starting',
barrier,
schemaManager,
startedInBackground,
};
try {
// Now that you can't call addPlugin any more, add default plugins like
// usage reporting if they're not already added.
await this.addDefaultPlugins();
const toDispose: (() => Promise<void>)[] = [];
const executor = await schemaManager.start();
if (executor) {
this.internals.gatewayExecutor = executor;
}
toDispose.push(async () => {
await schemaManager.stop();
});
const schemaDerivedData = schemaManager.getSchemaDerivedData();
const service: GraphQLServerContext = {
logger: this.logger,
cache: this.cache,
schema: schemaDerivedData.schema,
apollo: this.internals.apolloConfig,
startedInBackground,
};
const taggedServerListeners = (
await Promise.all(
this.internals.plugins.map(async (plugin) => ({
serverListener:
plugin.serverWillStart && (await plugin.serverWillStart(service)),
installedImplicitly:
isImplicitlyInstallablePlugin(plugin) &&
plugin.__internal_installed_implicitly__,
})),
)
).filter(
(
maybeTaggedServerListener,
): maybeTaggedServerListener is {
serverListener: GraphQLServerListener;
installedImplicitly: boolean;
} => typeof maybeTaggedServerListener.serverListener === 'object',
);
taggedServerListeners.forEach(
({ serverListener: { schemaDidLoadOrUpdate } }) => {
if (schemaDidLoadOrUpdate) {
schemaManager.onSchemaLoadOrUpdate(schemaDidLoadOrUpdate);
}
},
);
const serverWillStops = taggedServerListeners
.map((l) => l.serverListener.serverWillStop)
.filter(isDefined);
if (serverWillStops.length) {
toDispose.push(async () => {
await Promise.all(
serverWillStops.map((serverWillStop) => serverWillStop()),
);
});
}
const drainServerCallbacks = taggedServerListeners
.map((l) => l.serverListener.drainServer)
.filter(isDefined);
const drainServers = drainServerCallbacks.length
? async () => {
await Promise.all(
drainServerCallbacks.map((drainServer) => drainServer()),
);
}
: null;
// Find the renderLandingPage callback, if one is provided. If the user
// installed ApolloServerPluginLandingPageDisabled then there may be none
// found. On the other hand, if the user installed a landingPage plugin,
// then both the implicit installation of
// ApolloServerPluginLandingPage*Default and the other plugin will be
// found; we skip the implicit plugin.
let taggedServerListenersWithRenderLandingPage =
taggedServerListeners.filter((l) => l.serverListener.renderLandingPage);
if (taggedServerListenersWithRenderLandingPage.length > 1) {
taggedServerListenersWithRenderLandingPage =
taggedServerListenersWithRenderLandingPage.filter(
(l) => !l.installedImplicitly,
);
}
let landingPage: LandingPage | null = null;
if (taggedServerListenersWithRenderLandingPage.length > 1) {
throw Error('Only one plugin can implement renderLandingPage.');
} else if (taggedServerListenersWithRenderLandingPage.length) {
landingPage =
await taggedServerListenersWithRenderLandingPage[0].serverListener
.renderLandingPage!();
}
const toDisposeLast = this.maybeRegisterTerminationSignalHandlers(
['SIGINT', 'SIGTERM'],
startedInBackground,
);
this.internals.state = {
phase: 'started',
schemaManager,
drainServers,
landingPage,
toDispose,
toDisposeLast,
};
} catch (maybeError: unknown) {
const error = ensureError(maybeError);
try {
await Promise.all(
this.internals.plugins.map(
async (plugin) => plugin.startupDidFail?.({ error }),
),
);
} catch (pluginError) {
this.logger.error(`startupDidFail hook threw: ${pluginError}`);
}
this.internals.state = {
phase: 'failed to start',
error,
};
throw error;
} finally {
barrier.resolve();
}
}
private maybeRegisterTerminationSignalHandlers(
signals: NodeJS.Signals[],
startedInBackground: boolean,
): (() => Promise<void>)[] {
const toDisposeLast: (() => Promise<void>)[] = [];
// We handle signals if it was explicitly requested
// (stopOnTerminationSignals === true), or if we're in Node, not in a test,
// not in a serverless framework (which we guess based on whether they
// called
// startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests),
// and it wasn't explicitly turned off. (We only actually register the
// signal handlers once we've successfully started up, because there's
// nothing to stop otherwise.)
if (
this.internals.stopOnTerminationSignals === false ||
(this.internals.stopOnTerminationSignals === undefined &&
!(
isNodeLike &&
this.internals.nodeEnv !== 'test' &&
!startedInBackground
))
) {
return toDisposeLast;
}
let receivedSignal = false;
const signalHandler: NodeJS.SignalsListener = async (signal) => {
if (receivedSignal) {
// If we receive another SIGINT or SIGTERM while we're waiting
// for the server to stop, just ignore it.
return;
}
receivedSignal = true;
try {
await this.stop();
} catch (e) {
this.logger.error(`stop() threw during ${signal} shutdown`);
this.logger.error(e);
// Can't rely on the signal handlers being removed.
process.exit(1);
}
// Note: this.stop will call the toDisposeLast handlers below, so at
// this point this handler will have been removed and we can re-kill
// ourself to die with the appropriate signal exit status. this.stop
// takes care to call toDisposeLast last, so the signal handler isn't
// removed until after the rest of shutdown happens.
process.kill(process.pid, signal);
};
signals.forEach((signal) => {
process.on(signal, signalHandler);
toDisposeLast.push(async () => {
process.removeListener(signal, signalHandler);
});
});
return toDisposeLast;
}
// This method is called at the beginning of each GraphQL request by
// `executeHTTPGraphQLRequest` and `executeOperation`. Most of its logic is
// only helpful if you started the server in the background (ie, for
// serverless frameworks): unless you're in a serverless framework, you should
// have called `await server.start()` before the server got to the point of
// running GraphQL requests (`assertStarted` calls in the framework
// integrations verify that) and so the only cases for non-serverless
// frameworks that this should hit are 'started', 'stopping', and 'stopped'.
// But if you started the server in the background (with
// startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests), this
// lets the server wait until fully started before serving operations.
private async _ensureStarted(): Promise<RunningServerState> {
while (true) {
switch (this.internals.state.phase) {
case 'initialized':
// This error probably won't happen: serverless framework integrations
// should call
// `startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests`
// for you, and other frameworks call `assertStarted` before setting
// things up enough to make calling this function possible.
throw new Error(
'You need to call `server.start()` before using your Apollo Server.',
);
case 'starting':
await this.internals.state.barrier;
// continue the while loop
break;
case 'failed to start':
// First we log the error that prevented startup (which means it will
// get logged once for every GraphQL operation).
this.logStartupError(this.internals.state.error);
// Now make the operation itself fail.
// We intentionally do not re-throw actual startup error as it may contain
// implementation details and this error will propagate to the client.
throw new Error(
'This data graph is missing a valid configuration. More details may be available in the server logs.',
);
case 'started':
case 'draining': // We continue to run operations while draining.
return this.internals.state;
case 'stopping':
case 'stopped':
this.logger.warn(
'A GraphQL operation was received during server shutdown. The ' +
'operation will fail. Consider draining the HTTP server on shutdown; ' +
'see https://go.apollo.dev/s/drain for details.',
);
throw new Error(
`Cannot execute GraphQL operations ${
this.internals.state.phase === 'stopping'
? 'while the server is stopping'
: 'after the server has stopped'
}.'`,
);
default:
throw new UnreachableCaseError(this.internals.state);
}
}
}
// Framework integrations should call this to ensure that you've properly
// started your server before you get anywhere close to actually listening for
// incoming requests.
//
// There's a special case that if you called
// `startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests` and
// it hasn't finished starting up yet, this works too. This is intended for
// cases like a serverless integration (say, Google Cloud Functions) that
// calls
// `startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests` for
// you and then immediately sets up an integration based on another middleware
// like `expressMiddleware` which calls this function. We'd like this to be
// OK, but we still want normal Express users to start their ApolloServer
// before setting up their HTTP server unless they know what they are doing
// well enough to call the function with the long name themselves.
public assertStarted(expressionForError: string) {
if (
this.internals.state.phase !== 'started' &&
this.internals.state.phase !== 'draining' &&
!(
this.internals.state.phase === 'starting' &&
this.internals.state.startedInBackground
)
) {
throw new Error(
'You must `await server.start()` before calling `' +
expressionForError +
'`',
);
}
}
// Given an error that occurred during Apollo Server startup, log it with a
// helpful message. This should happen when you call
// `startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests` (ie,
// in serverless frameworks); with other frameworks, you must `await
// server.start()` which will throw the startup error directly instead of
// logging. This gets called both immediately when the startup error happens,
// and on all subsequent requests.
private logStartupError(err: Error) {
this.logger.error(
'An error occurred during Apollo Server startup. All GraphQL requests ' +
'will now fail. The startup error was: ' +
(err?.message || err),
);
}
private static constructSchema<TContext extends BaseContext>(
config: ApolloServerOptionsWithStaticSchema<TContext>,
): GraphQLSchema {
if (config.schema) {
return config.schema;
}
const { typeDefs, resolvers } = config;
const augmentedTypeDefs = Array.isArray(typeDefs) ? typeDefs : [typeDefs];
// For convenience, we allow you to pass a few options that we pass through
// to a particular version of `@graphql-tools/schema`'s
// `makeExecutableSchema`. If you want to use more of this function's
// features or have more control over the version of the packages used, just
// call it yourself like `new ApolloServer({schema:
// makeExecutableSchema(...)})`.
return makeExecutableSchema({
typeDefs: augmentedTypeDefs,
resolvers,
});
}
private static generateSchemaDerivedData(
schema: GraphQLSchema,
// null means don't use a documentStore at all.
// missing/undefined means use the default (creating a new one each
// time).
// defined means wrap this one in a random prefix for each new schema.
providedDocumentStore: DocumentStore | null | undefined,
): SchemaDerivedData {
// Instead of waiting for the first operation execution against the schema
// to find out if it's a valid schema or not, check right now. In the
// non-gateway case, if this throws then the `new ApolloServer` call will
// throw. In the gateway case if this throws then it will log a message and
// just not update the schema (although oddly the message will claim that
// the schema is updating).
assertValidSchema(schema);
return {
schema,
// The DocumentStore is schema-derived because we put documents in it
// after checking that they pass GraphQL validation against the schema and
// use this to skip validation as well as parsing. So we can't reuse the
// same DocumentStore for different schemas because that might make us
// treat invalid operations as valid. If we're using the default
// DocumentStore, then we just create it from scratch each time we get a
// new schema. If we're using a user-provided DocumentStore, then we use
// the schema hash as a prefix.
documentStore:
providedDocumentStore === undefined
? new InMemoryLRUCache<DocumentNode>()
: providedDocumentStore,
documentStoreKeyPrefix: providedDocumentStore
? `${computeCoreSchemaHash(printSchema(schema))}:`
: '',
};
}
public async stop() {
switch (this.internals.state.phase) {
case 'initialized':
case 'starting':
case 'failed to start':
throw Error(
'apolloServer.stop() should only be called after `await apolloServer.start()` has succeeded',
);
// Calling stop more than once should have the same result as the first time.
case 'stopped':
if (this.internals.state.stopError) {
throw this.internals.state.stopError;
}
return;
// Two parallel calls to stop; just wait for the other one to finish and
// do whatever it did.
case 'stopping':
case 'draining': {
await this.internals.state.barrier;
// The cast here is because TS doesn't understand that this.state can
// change during the await
// (https://github.com/microsoft/TypeScript/issues/9998).
const state = this.internals.state as ServerState;
if (state.phase !== 'stopped') {
throw Error(`Surprising post-stopping state ${state.phase}`);
}
if (state.stopError) {
throw state.stopError;
}
return;
}
case 'started':
// This is handled by the rest of the function.
break;
default:
throw new UnreachableCaseError(this.internals.state);
}
const barrier = resolvable();
const {
schemaManager,
drainServers,
landingPage,
toDispose,
toDisposeLast,
} = this.internals.state;
// Commit to stopping and start draining servers.
this.internals.state = {
phase: 'draining',
barrier,
schemaManager,
landingPage,
};
try {
await drainServers?.();
// Servers are drained. Prevent further operations from starting and call
// stop handlers.
this.internals.state = { phase: 'stopping', barrier };
// We run shutdown handlers in two phases because we don't want to turn
// off our signal listeners (ie, allow signals to kill the process) until
// we've done the important parts of shutdown like running serverWillStop
// handlers. (We can make this more generic later if it's helpful.)
await Promise.all([...toDispose].map((dispose) => dispose()));
await Promise.all([...toDisposeLast].map((dispose) => dispose()));
} catch (stopError) {
this.internals.state = {
phase: 'stopped',
stopError: stopError as Error,
};
barrier.resolve();
throw stopError;
}
this.internals.state = { phase: 'stopped', stopError: null };
}
private async addDefaultPlugins() {
const { plugins, apolloConfig, nodeEnv } = this.internals;
const isDev = nodeEnv !== 'production';
const alreadyHavePluginWithInternalId = (id: InternalPluginId) =>
plugins.some(
(p) => pluginIsInternal(p) && p.__internal_plugin_id__ === id,
);
// Make sure we're not trying to explicitly enable and disable the same
// feature. (Be careful: we are not trying to stop people from installing
// the same plugin twice if they have a use case for it, like two usage
// reporting plugins for different variants.)
//
// Note that this check doesn't work for the landing page plugin, because
// users can write their own landing page plugins and we don't know if a
// given plugin is a landing page plugin until the server has started.
const pluginsByInternalID = new Map<
InternalPluginId,
{ sawDisabled: boolean; sawNonDisabled: boolean }
>();
for (const p of plugins) {
if (pluginIsInternal(p)) {
const id = p.__internal_plugin_id__;
if (!pluginsByInternalID.has(id)) {
pluginsByInternalID.set(id, {
sawDisabled: false,
sawNonDisabled: false,
});
}
const seen = pluginsByInternalID.get(id)!;
if (p.__is_disabled_plugin__) {
seen.sawDisabled = true;
} else {
seen.sawNonDisabled = true;
}
if (seen.sawDisabled && seen.sawNonDisabled) {
throw new Error(
`You have tried to install both ApolloServerPlugin${id} and ` +
`ApolloServerPlugin${id}Disabled in your server. Please choose ` +
`whether or not you want to disable the feature and install the ` +
`appropriate plugin for your use case.`,
);
}
}
}
// Special case: cache control is on unless you explicitly disable it.
{
if (!alreadyHavePluginWithInternalId('CacheControl')) {
const { ApolloServerPluginCacheControl } = await import(
'./plugin/cacheControl/index.js'
);
plugins.push(ApolloServerPluginCacheControl());
}
}
// Special case: usage reporting is on by default (and first!) if you
// configure an API key.
{
const alreadyHavePlugin =
alreadyHavePluginWithInternalId('UsageReporting');
if (!alreadyHavePlugin && apolloConfig.key) {
if (apolloConfig.graphRef) {
// Keep this plugin first so it wraps everything. (Unfortunately despite
// the fact that the person who wrote this line also was the original
// author of the comment above in #1105, they don't quite understand why this was important.)
const { ApolloServerPluginUsageReporting } = await import(
'./plugin/usageReporting/index.js'
);
plugins.unshift(
ApolloServerPluginUsageReporting({
__onlyIfSchemaIsNotSubgraph: true,
}),
);
} else {
this.logger.warn(
'You have specified an Apollo key but have not specified a graph ref; usage ' +
'reporting is disabled. To enable usage reporting, set the `APOLLO_GRAPH_REF` ' +
'environment variable to `your-graph-id@your-graph-variant`. To disable this ' +
'warning, install `ApolloServerPluginUsageReportingDisabled`.',
);
}
}
}
// Special case: schema reporting can be turned on via environment variable.
{
const alreadyHavePlugin =
alreadyHavePluginWithInternalId('SchemaReporting');
const enabledViaEnvVar = process.env.APOLLO_SCHEMA_REPORTING === 'true';
if (!alreadyHavePlugin && enabledViaEnvVar) {
if (apolloConfig.key) {
const { ApolloServerPluginSchemaReporting } = await import(
'./plugin/schemaReporting/index.js'
);
plugins.push(ApolloServerPluginSchemaReporting());
} else {
throw new Error(
"You've enabled schema reporting by setting the APOLLO_SCHEMA_REPORTING " +
'environment variable to true, but you also need to provide your ' +
'Apollo API key, via the APOLLO_KEY environment ' +
'variable or via `new ApolloServer({apollo: {key})',
);
}
}
}
// Special case: inline tracing is on by default for federated schemas.
{
const alreadyHavePlugin = alreadyHavePluginWithInternalId('InlineTrace');
if (!alreadyHavePlugin) {
// If we haven't explicitly disabled inline tracing via
// ApolloServerPluginInlineTraceDisabled or explicitly installed our own
// ApolloServerPluginInlineTrace, we set up inline tracing in "only if
// federated" mode. (This is slightly different than the
// pre-ApolloServerPluginInlineTrace where we would also avoid doing
// this if an API key was configured and log a warning.)
const { ApolloServerPluginInlineTrace } = await import(
'./plugin/inlineTrace/index.js'
);
plugins.push(
ApolloServerPluginInlineTrace({ __onlyIfSchemaIsSubgraph: true }),
);
}
}
// Special case: If we're not in production, show our default landing page.
//
// This works a bit differently from the other implicitly installed plugins,
// which rely entirely on the __internal_plugin_id__ to decide whether the
// plugin takes effect. That's because we want third-party plugins to be
// able to provide a landing page that overrides the default landing page,
// without them having to know about __internal_plugin_id__. So unless we
// actively disable the default landing page with
// ApolloServerPluginLandingPageDisabled, we install the default landing
// page, but with a special flag that _start() uses to ignore it if some
// other plugin defines a renderLandingPage callback. (We can't just look
// now to see if the plugin defines renderLandingPage because we haven't run
// serverWillStart yet.)
const alreadyHavePlugin = alreadyHavePluginWithInternalId(
'LandingPageDisabled',
);
if (!alreadyHavePlugin) {
const {
ApolloServerPluginLandingPageLocalDefault,
ApolloServerPluginLandingPageProductionDefault,
} = await import('./plugin/landingPage/default/index.js');
const plugin: ApolloServerPlugin<TContext> = isDev
? ApolloServerPluginLandingPageLocalDefault()
: ApolloServerPluginLandingPageProductionDefault();
if (!isImplicitlyInstallablePlugin(plugin)) {
throw Error(
'default landing page plugin should be implicitly installable?',
);
}
plugin.__internal_installed_implicitly__ = true;
plugins.push(plugin);
}
}
public addPlugin(plugin: ApolloServerPlugin<TContext>) {
if (this.internals.state.phase !== 'initialized') {
throw new Error("Can't add plugins after the server has started");