-
Notifications
You must be signed in to change notification settings - Fork 242
/
index.ts
1461 lines (1317 loc) 路 51.9 KB
/
index.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 { deprecate } from 'util';
import { GraphQLService, Unsubscriber } from 'apollo-server-core';
import {
GraphQLExecutionResult,
Logger,
GraphQLRequestContextExecutionDidStart,
} from 'apollo-server-types';
import { InMemoryLRUCache } from 'apollo-server-caching';
import {
isObjectType,
isIntrospectionType,
GraphQLSchema,
VariableDefinitionNode,
DocumentNode,
print,
parse,
Source,
} from 'graphql';
import {
composeAndValidate,
compositionHasErrors,
ServiceDefinition,
} from '@apollo/federation';
import loglevel from 'loglevel';
import { buildOperationContext, OperationContext } from './operationContext';
import {
executeQueryPlan,
ServiceMap,
defaultFieldResolverWithAliasSupport,
} from './executeQueryPlan';
import { getServiceDefinitionsFromRemoteEndpoint } from './loadServicesFromRemoteEndpoint';
import {
GraphQLDataSource,
GraphQLDataSourceRequestKind,
} from './datasources/types';
import { RemoteGraphQLDataSource } from './datasources/RemoteGraphQLDataSource';
import { getVariableValues } from 'graphql/execution/values';
import fetcher from 'make-fetch-happen';
import { HttpRequestCache } from './cache';
import { fetch } from 'apollo-server-env';
import {
QueryPlanner,
QueryPlan,
prettyFormatQueryPlan,
toAPISchema,
} from '@apollo/query-planner';
import {
ServiceEndpointDefinition,
Experimental_DidFailCompositionCallback,
Experimental_DidResolveQueryPlanCallback,
Experimental_DidUpdateCompositionCallback,
Experimental_UpdateComposition,
CompositionInfo,
GatewayConfig,
StaticGatewayConfig,
RemoteGatewayConfig,
ManagedGatewayConfig,
isManuallyManagedConfig,
isLocalConfig,
isRemoteConfig,
isManagedConfig,
isDynamicConfig,
isStaticConfig,
CompositionMetadata,
isSupergraphSdlUpdate,
isServiceDefinitionUpdate,
ServiceDefinitionUpdate,
SupergraphSdlUpdate,
CompositionUpdate,
isManuallyManagedSupergraphSdlGatewayConfig,
ManuallyManagedSupergraphSdlGatewayConfig,
} from './config';
import { loadSupergraphSdlFromStorage } from './loadSupergraphSdlFromStorage';
import { buildComposedSchema } from '@apollo/query-planner';
import { SpanStatusCode } from '@opentelemetry/api';
import { OpenTelemetrySpanNames, tracer } from './utilities/opentelemetry';
import { CoreSchema } from '@apollo/core-schema';
import { featureSupport } from './core';
import { createHash } from 'apollo-graphql/lib/utilities/createHash';
type DataSourceMap = {
[serviceName: string]: { url?: string; dataSource: GraphQLDataSource };
};
// Local state to track whether particular UX-improving warning messages have
// already been emitted. This is particularly useful to prevent recurring
// warnings of the same type in, e.g. repeating timers, which don't provide
// additional value when they are repeated over and over during the life-time
// of a server.
type WarnedStates = {
remoteWithLocalConfig?: boolean;
};
export function getDefaultFetcher() {
const { name, version } = require('../package.json');
return fetcher.defaults({
cacheManager: new HttpRequestCache(),
// All headers should be lower-cased here, as `make-fetch-happen`
// treats differently cased headers as unique (unlike the `Headers` object).
// @see: https://git.io/JvRUa
headers: {
'apollographql-client-name': name,
'apollographql-client-version': version,
'user-agent': `${name}/${version}`,
'content-type': 'application/json',
},
retry: {
retries: 5,
// The default factor: expected attempts at 0, 1, 3, 7, 15, and 31 seconds elapsed
factor: 2,
// 1 second
minTimeout: 1000,
randomize: true,
},
});
}
export const HEALTH_CHECK_QUERY =
'query __ApolloServiceHealthCheck__ { __typename }';
export const SERVICE_DEFINITION_QUERY =
'query __ApolloGetServiceDefinition__ { _service { sdl } }';
type GatewayState =
| { phase: 'initialized' }
| { phase: 'failed to load' }
| { phase: 'loaded' }
| { phase: 'stopping'; stoppingDonePromise: Promise<void> }
| { phase: 'stopped' }
| {
phase: 'waiting to poll';
pollWaitTimer: NodeJS.Timer;
doneWaiting: () => void;
}
| { phase: 'polling'; pollingDonePromise: Promise<void> }
| { phase: 'updating schema' };
// We want to be compatible with `load()` as called by both AS2 and AS3, so we
// define its argument types ourselves instead of relying on imports.
// This is what AS3's ApolloConfig looks like; it's what we'll save internally.
interface ApolloConfigFromAS3 {
key?: string;
keyHash?: string;
graphRef?: string;
}
// This interface matches what we may receive from either version. We convert it
// to ApolloConfigFromAS3.
interface ApolloConfigFromAS2Or3 {
key?: string;
keyHash?: string;
graphRef?: string;
graphId?: string;
graphVariant?: string;
}
// This interface was the only way this data was provided prior to AS 2.18; it
// is being removed in AS 3, so we define our own version.
interface GraphQLServiceEngineConfig {
apiKeyHash: string;
graphId: string;
graphVariant?: string;
}
export class ApolloGateway implements GraphQLService {
public schema?: GraphQLSchema;
private serviceMap: DataSourceMap = Object.create(null);
private config: GatewayConfig;
private logger: Logger;
private queryPlanStore: InMemoryLRUCache<QueryPlan>;
private apolloConfig?: ApolloConfigFromAS3;
private onSchemaChangeListeners = new Set<(schema: GraphQLSchema) => void>();
private onSchemaLoadOrUpdateListeners = new Set<
(schemaContext: {
apiSchema: GraphQLSchema;
coreSupergraphSdl: string;
}) => void
>();
private serviceDefinitions: ServiceDefinition[] = [];
private compositionMetadata?: CompositionMetadata;
private serviceSdlCache = new Map<string, string>();
private warnedStates: WarnedStates = Object.create(null);
private queryPlanner?: QueryPlanner;
private supergraphSdl?: string;
private parsedSupergraphSdl?: DocumentNode;
private fetcher: typeof fetch;
private compositionId?: string;
private state: GatewayState;
// Observe query plan, service info, and operation info prior to execution.
// The information made available here will give insight into the resulting
// query plan and the inputs that generated it.
private experimental_didResolveQueryPlan?: Experimental_DidResolveQueryPlanCallback;
// Observe composition failures and the ServiceList that caused them. This
// enables reporting any issues that occur during composition. Implementors
// will be interested in addressing these immediately.
private experimental_didFailComposition?: Experimental_DidFailCompositionCallback;
// Used to communicated composition changes, and what definitions caused
// those updates
private experimental_didUpdateComposition?: Experimental_DidUpdateCompositionCallback;
// Used for overriding the default service list fetcher. This should return
// an array of ServiceDefinition. *This function must be awaited.*
private updateServiceDefinitions?: Experimental_UpdateComposition;
// how often service defs should be loaded/updated (in ms)
private experimental_pollInterval?: number;
// Configure the endpoint by which gateway will access its precomposed schema.
// * `string` means use that endpoint
// * `undefined` means the gateway is not using managed federation
private schemaConfigDeliveryEndpoint?: string;
// Functions to call during gateway cleanup (when stop() is called)
private toDispose: (() => Promise<void>)[] = [];
constructor(config?: GatewayConfig) {
this.config = {
// TODO: expose the query plan in a more flexible JSON format in the future
// and remove this config option in favor of `exposeQueryPlan`. Playground
// should cutover to use the new option when it's built.
__exposeQueryPlanExperimental: process.env.NODE_ENV !== 'production',
...config,
};
this.logger = this.initLogger();
this.queryPlanStore = this.initQueryPlanStore(
config?.experimental_approximateQueryPlanStoreMiB,
);
this.fetcher = config?.fetcher || getDefaultFetcher();
// set up experimental observability callbacks and config settings
this.experimental_didResolveQueryPlan =
config?.experimental_didResolveQueryPlan;
this.experimental_didFailComposition =
config?.experimental_didFailComposition;
this.experimental_didUpdateComposition =
config?.experimental_didUpdateComposition;
this.experimental_pollInterval = config?.experimental_pollInterval;
// 1. If config is set to a `string`, use it
// 2. If the env var is set, use that
// 3. If config is `undefined`, use the default uplink URL
if (isManagedConfig(this.config)) {
const envEndpoint = process.env.APOLLO_SCHEMA_CONFIG_DELIVERY_ENDPOINT;
this.schemaConfigDeliveryEndpoint =
this.config.schemaConfigDeliveryEndpoint ??
envEndpoint ??
'https://uplink.api.apollographql.com/';
}
if (isManuallyManagedConfig(this.config)) {
// Use the provided updater function if provided by the user, else default
if ('experimental_updateSupergraphSdl' in this.config) {
this.updateServiceDefinitions =
this.config.experimental_updateSupergraphSdl;
} else if ('experimental_updateServiceDefinitions' in this.config) {
this.updateServiceDefinitions =
this.config.experimental_updateServiceDefinitions;
} else if (isManuallyManagedSupergraphSdlGatewayConfig(this.config)) {
// TODO: do nothing maybe?
} else {
throw Error(
'Programming error: unexpected manual configuration provided',
);
}
} else {
this.updateServiceDefinitions = this.loadServiceDefinitions;
}
this.issueDeprecationWarningsIfApplicable();
if (isDynamicConfig(this.config)) {
this.issueDynamicWarningsIfApplicable();
}
this.state = { phase: 'initialized' };
}
private initLogger() {
// Setup logging facilities
if (this.config.logger) {
return this.config.logger;
}
// If the user didn't provide their own logger, we'll initialize one.
const loglevelLogger = loglevel.getLogger(`apollo-gateway`);
// And also support the `debug` option, if it's truthy.
if (this.config.debug === true) {
loglevelLogger.setLevel(loglevelLogger.levels.DEBUG);
} else {
loglevelLogger.setLevel(loglevelLogger.levels.WARN);
}
return loglevelLogger;
}
private initQueryPlanStore(approximateQueryPlanStoreMiB?: number) {
return new InMemoryLRUCache<QueryPlan>({
// Create ~about~ a 30MiB InMemoryLRUCache. This is less than precise
// since the technique to calculate the size of a DocumentNode is
// only using JSON.stringify on the DocumentNode (and thus doesn't account
// for unicode characters, etc.), but it should do a reasonable job at
// providing a caching document store for most operations.
maxSize: Math.pow(2, 20) * (approximateQueryPlanStoreMiB || 30),
sizeCalculator: approximateObjectSize,
});
}
private issueDynamicWarningsIfApplicable() {
// Warn against a pollInterval of < 10s in managed mode and reset it to 10s
if (
isManagedConfig(this.config) &&
this.config.experimental_pollInterval &&
this.config.experimental_pollInterval < 10000
) {
this.experimental_pollInterval = 10000;
this.logger.warn(
'Polling Apollo services at a frequency of less than once per 10 ' +
'seconds (10000) is disallowed. Instead, the minimum allowed ' +
'pollInterval of 10000 will be used. Please reconfigure your ' +
'experimental_pollInterval accordingly. If this is problematic for ' +
'your team, please contact support.',
);
}
// Warn against using the pollInterval and a serviceList simultaneously
// TODO(trevor:removeServiceList)
if (this.config.experimental_pollInterval && isRemoteConfig(this.config)) {
this.logger.warn(
'Polling running services is dangerous and not recommended in production. ' +
'Polling should only be used against a registry. ' +
'If you are polling running services, use with caution.',
);
}
if (
isManuallyManagedConfig(this.config) &&
'experimental_updateSupergraphSdl' in this.config &&
'experimental_updateServiceDefinitions' in this.config
) {
this.logger.warn(
'Gateway found two manual update configurations when only one should be ' +
'provided. Gateway will default to using the provided `experimental_updateSupergraphSdl` ' +
'function when both `experimental_updateSupergraphSdl` and experimental_updateServiceDefinitions` ' +
'are provided.',
);
}
}
private issueDeprecationWarningsIfApplicable() {
// TODO(trevor:removeServiceList)
if ('experimental_updateSupergraphSdl' in this.config) {
this.logger.warn(
'The `experimental_updateSupergraphSdl` option is deprecated and will be removed in a future version of `@apollo/gateway`. Please migrate to the function form of the `supergraphSdl` configuration option.',
);
}
// TODO(trevor:removeServiceList)
if ('experimental_updateServiceDefinitions' in this.config) {
this.logger.warn(
'The `experimental_updateServiceDefinitions` option is deprecated and will be removed in a future version of `@apollo/gateway`. Please migrate to the function form of the `supergraphSdl` configuration option.',
);
}
// TODO(trevor:removeServiceList)
if ('serviceList' in this.config) {
this.logger.warn(
'The `serviceList` option is deprecated and will be removed in a future version of `@apollo/gateway`. Please migrate to the function form of the `supergraphSdl` configuration option.',
);
}
// TODO(trevor:removeServiceList)
if ('localServiceList' in this.config) {
this.logger.warn(
'The `localServiceList` option is deprecated and will be removed in a future version of `@apollo/gateway`. Please migrate to the function form of the `supergraphSdl` configuration option.',
);
}
// TODO(trevor:removeServiceList)
if ('buildService' in this.config) {
this.logger.warn(
'The `buildService` option is deprecated and will be removed in a future version of `@apollo/gateway`. Please migrate to the function form of the `supergraphSdl` configuration option.',
);
}
}
public async load(options?: {
apollo?: ApolloConfigFromAS2Or3;
engine?: GraphQLServiceEngineConfig;
}) {
if (this.state.phase !== 'initialized') {
throw Error(
`ApolloGateway.load called in surprising state ${this.state.phase}`,
);
}
if (options?.apollo) {
const { key, keyHash, graphRef, graphId, graphVariant } = options.apollo;
this.apolloConfig = {
key,
keyHash,
graphRef:
graphRef ??
(graphId ? `${graphId}@${graphVariant ?? 'current'}` : undefined),
};
} else if (options?.engine) {
// Older version of apollo-server-core that isn't passing 'apollo' yet.
const { apiKeyHash, graphId, graphVariant } = options.engine;
this.apolloConfig = {
keyHash: apiKeyHash,
graphRef: graphId
? `${graphId}@${graphVariant ?? 'current'}`
: undefined,
};
}
// Before @apollo/gateway v0.23, ApolloGateway didn't expect stop() to be
// called after it started. The only thing that stop() did at that point was
// cancel the poll timer, and so to prevent that timer from keeping an
// otherwise-finished Node process alive, ApolloGateway unconditionally
// called unref() on that timeout. As part of making the ApolloGateway
// lifecycle more predictable and concrete (and to allow for a future where
// there are other reasons to make sure to explicitly stop your gateway),
// v0.23 tries to avoid calling unref().
//
// Apollo Server v2.20 and newer calls gateway.stop() from its stop()
// method, so as long as you're using v2.20, ApolloGateway won't keep
// running after you stop your server, and your Node process can shut down.
// To make this change a bit less backwards-incompatible, we detect if it
// looks like you're using an older version of Apollo Server; if so, we
// still call unref(). Specifically: Apollo Server has always passed an
// options object to load(), and before v2.18 it did not pass the `apollo`
// key on it. So if we detect that particular pattern, we assume we're with
// pre-v2.18 Apollo Server and we still call unref(). So this will be a
// behavior change only for:
// - non-Apollo-Server uses of ApolloGateway (where you can add your own
// call to gateway.stop())
// - Apollo Server v2.18 and v2.19 (where you can either do the small
// compatible upgrade or add your own call to gateway.stop())
// - if you don't call stop() on your ApolloServer (but in that case other
// things like usage reporting will also stop shutdown, so you should fix
// that)
const unrefTimer = !!options && !options.apollo;
this.maybeWarnOnConflictingConfig();
// Handles initial assignment of `this.schema`, `this.queryPlanner`
if (isStaticConfig(this.config)) {
this.loadStatic(this.config);
} else if (isManuallyManagedSupergraphSdlGatewayConfig(this.config)) {
await this.loadManuallyManaged(this.config);
} else {
await this.loadDynamic(unrefTimer);
}
const mode = isManagedConfig(this.config) ? 'managed' : 'unmanaged';
this.logger.info(
`Gateway successfully loaded schema.\n\t* Mode: ${mode}${
this.apolloConfig && this.apolloConfig.graphRef
? `\n\t* Service: ${this.apolloConfig.graphRef}`
: ''
}`,
);
return {
schema: this.schema!,
executor: this.executor,
};
}
// Synchronously load a statically configured schema, update class instance's
// schema and query planner.
private loadStatic(config: StaticGatewayConfig) {
let schema: GraphQLSchema;
let supergraphSdl: string;
try {
({ schema, supergraphSdl } = isLocalConfig(config)
? this.createSchemaFromServiceList(config.localServiceList)
: this.createSchemaFromSupergraphSdl(config.supergraphSdl));
// TODO(trevor): #580 redundant parse
this.parsedSupergraphSdl = parse(supergraphSdl);
this.supergraphSdl = supergraphSdl;
this.updateWithSchemaAndNotify(schema, supergraphSdl, true);
} catch (e) {
this.state = { phase: 'failed to load' };
throw e;
}
this.state = { phase: 'loaded' };
}
// Asynchronously load a dynamically configured schema. `this.updateSchema`
// is responsible for updating the class instance's schema and query planner.
private async loadDynamic(unrefTimer: boolean) {
try {
await this.updateSchema();
} catch (e) {
this.state = { phase: 'failed to load' };
throw e;
}
this.state = { phase: 'loaded' };
if (this.shouldBeginPolling()) {
this.pollServices(unrefTimer);
}
}
private getIdForSupergraphSdl(supergraphSdl: string) {
return createHash('sha256').update(supergraphSdl).digest('hex');
}
private async loadManuallyManaged(
config: ManuallyManagedSupergraphSdlGatewayConfig,
) {
try {
const result = await config.supergraphSdl({
update: this.externalSupergraphUpdateCallback.bind(this),
healthCheck: this.externalSubgraphHealthCheckCallback.bind(this),
});
if (!result?.supergraphSdl) {
throw new Error(
'User provided `supergraphSdl` function did not return an object containing a `supergraphSdl` property',
);
}
if (result?.cleanup) {
this.toDispose.push(result.cleanup);
}
this.externalSupergraphUpdateCallback(result.supergraphSdl);
} catch (e) {
this.logger.error(e.message ?? e);
this.state = { phase: 'failed to load' };
throw e;
}
this.state = { phase: 'loaded' };
}
private shouldBeginPolling() {
return isManagedConfig(this.config) || this.experimental_pollInterval;
}
private async updateSchema(): Promise<void> {
this.logger.debug('Checking for composition updates...');
if (!this.updateServiceDefinitions) {
throw new Error(
'Programming error: `updateSchema` was called unexpectedly.',
);
}
// This may throw, but an error here is caught and logged upstream
const result = await this.updateServiceDefinitions(this.config);
await this.maybePerformServiceHealthCheck(result);
if (isSupergraphSdlUpdate(result)) {
this.updateWithSupergraphSdl(result);
} else if (isServiceDefinitionUpdate(result)) {
this.updateByComposition(result);
} else {
throw new Error(
'Programming error: unexpected result type from `updateServiceDefinitions`',
);
}
}
private updateByComposition(result: ServiceDefinitionUpdate) {
if (
!result.serviceDefinitions ||
JSON.stringify(this.serviceDefinitions) ===
JSON.stringify(result.serviceDefinitions)
) {
this.logger.debug('No change in service definitions since last check.');
return;
}
const previousSchema = this.schema;
const previousServiceDefinitions = this.serviceDefinitions;
const previousCompositionMetadata = this.compositionMetadata;
if (previousSchema) {
this.logger.info('New service definitions were found.');
}
this.compositionMetadata = result.compositionMetadata;
this.serviceDefinitions = result.serviceDefinitions;
const { schema, supergraphSdl } = this.createSchemaFromServiceList(
result.serviceDefinitions,
);
if (!supergraphSdl) {
this.logger.error(
"A valid schema couldn't be composed. Falling back to previous schema.",
);
} else {
this.updateWithSchemaAndNotify(schema, supergraphSdl);
if (this.experimental_didUpdateComposition) {
this.experimental_didUpdateComposition(
{
serviceDefinitions: result.serviceDefinitions,
schema,
...(this.compositionMetadata && {
compositionMetadata: this.compositionMetadata,
}),
},
previousServiceDefinitions &&
previousSchema && {
serviceDefinitions: previousServiceDefinitions,
schema: previousSchema,
...(previousCompositionMetadata && {
compositionMetadata: previousCompositionMetadata,
}),
},
);
}
}
}
private externalSupergraphUpdateCallback(supergraphSdl: string) {
if (this.state.phase === "failed to load") {
throw new Error("Can't call `update` callback after gateway failed to load.");
} else if (this.state.phase === "updating schema") {
throw new Error("Can't call `update` callback while supergraph update is in progress.");
} else if (this.state.phase === "stopped") {
throw new Error("Can't call `update` callback after gateway has been stopped.");
}
this.state = { phase: "updating schema" };
this.updateWithSupergraphSdl({
supergraphSdl,
id: this.getIdForSupergraphSdl(supergraphSdl),
});
this.state = { phase: "loaded" };
}
private async externalSubgraphHealthCheckCallback(supergraphSdl: string) {
const parsedSupergraphSdl =
supergraphSdl === this.supergraphSdl
? this.parsedSupergraphSdl
: parse(supergraphSdl);
const serviceList = this.serviceListFromSupergraphSdl(parsedSupergraphSdl!);
// Here we need to construct new datasources based on the new schema info
// so we can check the health of the services we're _updating to_.
const serviceMap = serviceList.reduce((serviceMap, serviceDef) => {
serviceMap[serviceDef.name] = {
url: serviceDef.url,
dataSource: this.createDataSource(serviceDef),
};
return serviceMap;
}, Object.create(null) as DataSourceMap);
try {
await this.serviceHealthCheck(serviceMap);
} catch (e) {
throw new Error(
'The gateway subgraphs health check failed. Updating to the provided ' +
'`supergraphSdl` will likely result in future request failures to ' +
'subgraphs. The following error occurred during the health check:\n' +
e.message,
);
}
}
private updateWithSupergraphSdl({ supergraphSdl, id }: SupergraphSdlUpdate) {
// TODO(trevor): #580 redundant parse
// This may throw, so we'll calculate early (specifically before making any updates)
// In the case that it throws, the gateway will:
// * on initial load, throw the error
// * on update, log the error and don't update
const parsedSupergraphSdl = parse(supergraphSdl);
const previousSchema = this.schema;
const previousSupergraphSdl = this.parsedSupergraphSdl;
const previousCompositionId = this.compositionId;
if (previousSchema) {
this.logger.info('Updated Supergraph SDL was found.');
}
this.compositionId = id;
this.supergraphSdl = supergraphSdl;
this.parsedSupergraphSdl = parsedSupergraphSdl;
const { schema, supergraphSdl: generatedSupergraphSdl } =
this.createSchemaFromSupergraphSdl(supergraphSdl);
if (!generatedSupergraphSdl) {
this.logger.error(
"A valid schema couldn't be composed. Falling back to previous schema.",
);
} else {
this.updateWithSchemaAndNotify(schema, generatedSupergraphSdl);
if (this.experimental_didUpdateComposition) {
this.experimental_didUpdateComposition(
{
compositionId: id,
supergraphSdl,
schema,
},
previousCompositionId && previousSupergraphSdl && previousSchema
? {
compositionId: previousCompositionId,
supergraphSdl: print(previousSupergraphSdl),
schema: previousSchema,
}
: undefined,
);
}
}
}
// TODO: We should consolidate "schema derived data" state as we've done in Apollo Server to
// ensure we do not forget to update some of that state, and to avoid scenarios where
// concurrently executing code sees partially-updated state.
private updateWithSchemaAndNotify(
coreSchema: GraphQLSchema,
coreSupergraphSdl: string,
// Once we remove the deprecated onSchemaChange() method, we can remove this.
legacyDontNotifyOnSchemaChangeListeners: boolean = false,
): void {
if (this.queryPlanStore) this.queryPlanStore.flush();
this.schema = toAPISchema(coreSchema);
this.queryPlanner = new QueryPlanner(coreSchema);
// Notify onSchemaChange listeners of the updated schema
if (!legacyDontNotifyOnSchemaChangeListeners) {
this.onSchemaChangeListeners.forEach((listener) => {
try {
listener(this.schema!);
} catch (e) {
this.logger.error(
"An error was thrown from an 'onSchemaChange' listener. " +
'The schema will still update: ' +
((e && e.message) || e),
);
}
});
}
// Notify onSchemaLoadOrUpdate listeners of the updated schema
this.onSchemaLoadOrUpdateListeners.forEach((listener) => {
try {
listener({
apiSchema: this.schema!,
coreSupergraphSdl,
});
} catch (e) {
this.logger.error(
"An error was thrown from an 'onSchemaLoadOrUpdate' listener. " +
'The schema will still update: ' +
((e && e.message) || e),
);
}
});
}
private async maybePerformServiceHealthCheck(update: CompositionUpdate) {
// Run service health checks before we commit and update the new schema.
// This is the last chance to bail out of a schema update.
if (!this.config.serviceHealthCheck) return;
const serviceList = isSupergraphSdlUpdate(update)
? // TODO(trevor): #580 redundant parse
// Parsing could technically fail and throw here, but parseability has
// already been confirmed slightly earlier in the code path
this.serviceListFromSupergraphSdl(parse(update.supergraphSdl))
: // Existence of this is determined in advance with an early return otherwise
update.serviceDefinitions!;
// Here we need to construct new datasources based on the new schema info
// so we can check the health of the services we're _updating to_.
const serviceMap = serviceList.reduce((serviceMap, serviceDef) => {
serviceMap[serviceDef.name] = {
url: serviceDef.url,
dataSource: this.createDataSource(serviceDef),
};
return serviceMap;
}, Object.create(null) as DataSourceMap);
try {
await this.serviceHealthCheck(serviceMap);
} catch (e) {
throw new Error(
'The gateway did not update its schema due to failed service health checks. ' +
'The gateway will continue to operate with the previous schema and reattempt updates. ' +
'The following error occurred during the health check:\n' +
e.message,
);
}
}
/**
* This can be used without an argument in order to perform an ad-hoc health check
* of the downstream services like so:
*
* @example
* ```
* try {
* await gateway.serviceHealthCheck();
* } catch(e) {
* /* your error handling here *\/
* }
* ```
* @throws
* @param serviceMap {DataSourceMap}
*/
public serviceHealthCheck(serviceMap: DataSourceMap = this.serviceMap) {
return Promise.all(
Object.entries(serviceMap).map(([name, { dataSource }]) =>
dataSource
.process({
kind: GraphQLDataSourceRequestKind.HEALTH_CHECK,
request: { query: HEALTH_CHECK_QUERY },
context: {},
})
.then((response) => ({ name, response }))
.catch((e) => {
throw new Error(`[${name}]: ${e.message}`);
}),
),
);
}
private createSchemaFromServiceList(serviceList: ServiceDefinition[]) {
this.logger.debug(
`Composing schema from service list: \n${serviceList
.map(({ name, url }) => ` ${url || 'local'}: ${name}`)
.join('\n')}`,
);
const compositionResult = composeAndValidate(serviceList);
if (compositionHasErrors(compositionResult)) {
const { errors } = compositionResult;
if (this.experimental_didFailComposition) {
this.experimental_didFailComposition({
errors,
serviceList,
...(this.compositionMetadata && {
compositionMetadata: this.compositionMetadata,
}),
});
}
throw Error(
"A valid schema couldn't be composed. The following composition errors were found:\n" +
errors.map((e) => '\t' + e.message).join('\n'),
);
} else {
const { supergraphSdl } = compositionResult;
this.createServices(serviceList);
const schema = buildComposedSchema(parse(supergraphSdl));
this.logger.debug('Schema loaded and ready for execution');
// This is a workaround for automatic wrapping of all fields, which Apollo
// Server does in the case of implementing resolver wrapping for plugins.
// Here we wrap all fields with support for resolving aliases as part of the
// root value which happens because aliases are resolved by sub services and
// the shape of the root value already contains the aliased fields as
// responseNames
return {
schema: wrapSchemaWithAliasResolver(schema),
supergraphSdl,
};
}
}
private serviceListFromSupergraphSdl(
supergraphSdl: DocumentNode,
): Omit<ServiceDefinition, 'typeDefs'>[] {
const schema = buildComposedSchema(supergraphSdl);
return this.serviceListFromComposedSchema(schema);
}
private serviceListFromComposedSchema(schema: GraphQLSchema) {
const graphMap = schema.extensions?.federation?.graphs;
if (!graphMap) {
throw Error(`Couldn't find graph map in composed schema`);
}
return Array.from(graphMap.values());
}
private createSchemaFromSupergraphSdl(supergraphSdl: string) {
const core = CoreSchema.fromSource(
new Source(supergraphSdl, 'supergraphSdl'),
)
.check() // run basic core schema compliance checks
.check(featureSupport); // run supported feature check
// TODO(trevor): #580 redundant parse
this.parsedSupergraphSdl = core.document;
const schema = buildComposedSchema(this.parsedSupergraphSdl);
const serviceList = this.serviceListFromComposedSchema(schema);
this.createServices(serviceList);
return {
schema: wrapSchemaWithAliasResolver(schema),
supergraphSdl,
};
}
/**
* @deprecated Please use `onSchemaLoadOrUpdate` instead.
*/
public onSchemaChange(
callback: (schema: GraphQLSchema) => void,
): Unsubscriber {
this.onSchemaChangeListeners.add(callback);
return () => {
this.onSchemaChangeListeners.delete(callback);
};
}
public onSchemaLoadOrUpdate(
callback: (schemaContext: {
apiSchema: GraphQLSchema;
coreSupergraphSdl: string;
}) => void,
): Unsubscriber {
this.onSchemaLoadOrUpdateListeners.add(callback);
return () => {
this.onSchemaLoadOrUpdateListeners.delete(callback);
};
}
// TODO(trevor:removeServiceList): gateway shouldn't be responsible for polling
// in the future.
// This function waits an appropriate amount, updates composition, and calls itself
// again. Note that it is an async function whose Promise is not actually awaited;
// it should never throw itself other than due to a bug in its state machine.
private async pollServices(unrefTimer: boolean) {
switch (this.state.phase) {
case 'stopping':
case 'stopped':
case 'failed to load':
return;
case 'initialized':
throw Error('pollServices should not be called before load!');
case 'polling':
throw Error(
'pollServices should not be called while in the middle of polling!',
);
case 'waiting to poll':
throw Error(
'pollServices should not be called while already waiting to poll!',
);
case 'loaded':
// This is the normal case.
break;
case 'updating schema':
// This should never happen
throw Error(
"ApolloGateway.pollServices called from an unexpected state 'updating schema'",
);
default:
throw new UnreachableCaseError(this.state);
}
// Transition into 'waiting to poll' and set a timer. The timer resolves the
// Promise we're awaiting here; note that calling stop() also can resolve
// that Promise.
await new Promise<void>((doneWaiting) => {
this.state = {
phase: 'waiting to poll',
doneWaiting,
pollWaitTimer: setTimeout(() => {
// Note that we might be in 'stopped', in which case we just do
// nothing.
if (this.state.phase == 'waiting to poll') {
this.state.doneWaiting();
}
}, this.experimental_pollInterval || 10000),
};
if (unrefTimer) {
this.state.pollWaitTimer.unref();
}
});
// If we've been stopped, then we're done. The cast here is because TS
// doesn't understand that this.state can change during the await
// (https://github.com/microsoft/TypeScript/issues/9998).
if ((this.state as GatewayState).phase !== 'waiting to poll') {
return;
}
let pollingDone: () => void;
this.state = {
phase: 'polling',
pollingDonePromise: new Promise<void>((res) => {
pollingDone = res;
}),
};
try {
await this.updateSchema();