-
Notifications
You must be signed in to change notification settings - Fork 257
/
Copy pathindex.ts
1067 lines (969 loc) · 36.8 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,
GraphQLRequestContextExecutionDidStart,
} from 'apollo-server-types';
import { createHash } from '@apollo/utils.createhash';
import type { Logger } from '@apollo/utils.logger';
import { InMemoryLRUCache } from 'apollo-server-caching';
import {
isObjectType,
isIntrospectionType,
GraphQLSchema,
VariableDefinitionNode,
} from 'graphql';
import { buildOperationContext, OperationContext } from './operationContext';
import {
executeQueryPlan,
ServiceMap,
defaultFieldResolverWithAliasSupport,
} from './executeQueryPlan';
import {
GraphQLDataSource,
GraphQLDataSourceRequestKind,
} from './datasources/types';
import { RemoteGraphQLDataSource } from './datasources/RemoteGraphQLDataSource';
import { getVariableValues } from 'graphql/execution/values';
import {
QueryPlanner,
QueryPlan,
prettyFormatQueryPlan,
} from '@apollo/query-planner';
import {
ServiceEndpointDefinition,
Experimental_DidFailCompositionCallback,
Experimental_DidResolveQueryPlanCallback,
Experimental_DidUpdateSupergraphCallback,
Experimental_UpdateComposition,
CompositionInfo,
GatewayConfig,
isManuallyManagedConfig,
isLocalConfig,
isServiceListConfig,
isManagedConfig,
SupergraphSdlUpdate,
isManuallyManagedSupergraphSdlGatewayConfig,
isStaticSupergraphSdlConfig,
SupergraphManager,
} from './config';
import { SpanStatusCode } from '@opentelemetry/api';
import { OpenTelemetrySpanNames, tracer } from './utilities/opentelemetry';
import { addExtensions } from './schema-helper/addExtensions';
import {
IntrospectAndCompose,
UplinkSupergraphManager,
LegacyFetcher,
LocalCompose,
} from './supergraphManagers';
import {
buildSupergraphSchema,
operationFromDocument,
Schema,
ServiceDefinition,
} from '@apollo/federation-internals';
import { getDefaultLogger } from './logger';
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 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: '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;
// Same as a `schema` but as a `Schema` to avoid reconverting when we need it.
// TODO(sylvain): if we add caching in `Schema.toGraphQLJSSchema`, we could maybe only keep `apiSchema`
// and make `schema` a getter (though `schema` does rely on `wrapSchemaWithAliasResolver` so this should
// be accounted for and this may look ugly). Unsure if moving from a member to a getter could break anyone externally however
// (also unclear why we expose a mutable member public in the first place; don't everything break if the
// use manually assigns `schema`?).
private apiSchema?: Schema;
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 warnedStates: WarnedStates = Object.create(null);
private queryPlanner?: QueryPlanner;
private supergraphSdl?: string;
private supergraphSchema?: GraphQLSchema;
private compositionId?: string;
private state: GatewayState;
private _supergraphManager?: SupergraphManager;
// 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;
// Used to communicate supergraph updates
private experimental_didUpdateSupergraph?: Experimental_DidUpdateSupergraphCallback;
// how often service defs should be loaded/updated
private pollIntervalInMs?: number;
// 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.config.logger ?? getDefaultLogger(this.config.debug);
this.queryPlanStore = this.initQueryPlanStore(
config?.experimental_approximateQueryPlanStoreMiB,
);
// set up experimental observability callbacks and config settings
this.experimental_didResolveQueryPlan =
config?.experimental_didResolveQueryPlan;
this.experimental_didUpdateSupergraph =
config?.experimental_didUpdateSupergraph;
if (isManagedConfig(this.config)) {
this.pollIntervalInMs =
this.config.fallbackPollIntervalInMs ?? this.config.pollIntervalInMs;
} else if (isServiceListConfig(this.config)) {
this.pollIntervalInMs = this.config?.pollIntervalInMs;
}
this.issueConfigurationWarningsIfApplicable();
this.logger.debug('Gateway successfully initialized (but not yet loaded)');
this.state = { phase: 'initialized' };
}
public get supergraphManager(): SupergraphManager | undefined {
return this._supergraphManager;
}
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 issueConfigurationWarningsIfApplicable() {
// Warn against using the pollInterval and a serviceList simultaneously
// TODO(trevor:removeServiceList)
if (this.pollIntervalInMs && isServiceListConfig(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.',
);
}
if ('schemaConfigDeliveryEndpoint' in this.config) {
this.logger.warn(
'The `schemaConfigDeliveryEndpoint` option is deprecated and will be removed in a future version of `@apollo/gateway`. Please migrate to the equivalent (array form) `uplinkEndpoints` configuration option.',
);
}
if (isManagedConfig(this.config) && 'pollIntervalInMs' in this.config) {
this.logger.warn(
'The `pollIntervalInMs` option is deprecated and will be removed in a future version of `@apollo/gateway`. ' +
'Please migrate to the equivalent `fallbackPollIntervalInMs` configuration option. ' +
'The poll interval is now defined by Uplink, this option will only be used if it is greater than the value defined by Uplink or as a fallback.',
);
}
}
public async load(options?: {
apollo?: ApolloConfigFromAS2Or3;
engine?: GraphQLServiceEngineConfig;
}) {
this.logger.debug('Loading gateway...');
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,
};
}
this.maybeWarnOnConflictingConfig();
// Handles initial assignment of `this.schema`, `this.queryPlanner`
if (isStaticSupergraphSdlConfig(this.config)) {
const supergraphSdl = this.config.supergraphSdl;
await this.initializeSupergraphManager({
initialize: async () => {
return {
supergraphSdl,
};
},
});
} else if (isLocalConfig(this.config)) {
// TODO(trevor:removeServiceList)
await this.initializeSupergraphManager(
new LocalCompose({
localServiceList: this.config.localServiceList,
logger: this.logger,
}),
);
} else if (isManuallyManagedSupergraphSdlGatewayConfig(this.config)) {
const supergraphManager =
typeof this.config.supergraphSdl === 'object'
? this.config.supergraphSdl
: { initialize: this.config.supergraphSdl };
await this.initializeSupergraphManager(supergraphManager);
} else if (
'experimental_updateServiceDefinitions' in this.config ||
'experimental_updateSupergraphSdl' in this.config
) {
const updateServiceDefinitions =
'experimental_updateServiceDefinitions' in this.config
? this.config.experimental_updateServiceDefinitions
: this.config.experimental_updateSupergraphSdl;
await this.initializeSupergraphManager(
new LegacyFetcher({
logger: this.logger,
gatewayConfig: this.config,
updateServiceDefinitions,
pollIntervalInMs: this.pollIntervalInMs,
subgraphHealthCheck: this.config.serviceHealthCheck,
}),
);
} else if (isServiceListConfig(this.config)) {
// TODO(trevor:removeServiceList)
this.logger.warn(
'The `serviceList` option is deprecated and will be removed in a future version of `@apollo/gateway`. Please migrate to its replacement `IntrospectAndCompose`. More information on `IntrospectAndCompose` can be found in the documentation.',
);
await this.initializeSupergraphManager(
new IntrospectAndCompose({
subgraphs: this.config.serviceList,
pollIntervalInMs: this.pollIntervalInMs,
logger: this.logger,
subgraphHealthCheck: this.config.serviceHealthCheck,
introspectionHeaders: this.config.introspectionHeaders,
}),
);
} else {
// isManagedConfig(this.config)
const canUseManagedConfig =
this.apolloConfig?.graphRef && this.apolloConfig?.keyHash;
if (!canUseManagedConfig) {
throw new Error(
'When a manual configuration is not provided, gateway requires an Apollo ' +
'configuration. See https://www.apollographql.com/docs/apollo-server/federation/managed-federation/ ' +
'for more information. Manual configuration options include: ' +
'`serviceList`, `supergraphSdl`, and `experimental_updateServiceDefinitions`.',
);
}
const schemaDeliveryEndpoints: string[] | undefined = this.config
.schemaConfigDeliveryEndpoint
? [this.config.schemaConfigDeliveryEndpoint]
: undefined;
await this.initializeSupergraphManager(
new UplinkSupergraphManager({
graphRef: this.apolloConfig!.graphRef!,
apiKey: this.apolloConfig!.key!,
shouldRunSubgraphHealthcheck: this.config.serviceHealthCheck,
uplinkEndpoints:
this.config.uplinkEndpoints ?? schemaDeliveryEndpoints,
maxRetries: this.config.uplinkMaxRetries,
fetcher: this.config.fetcher,
logger: this.logger,
fallbackPollIntervalInMs: this.pollIntervalInMs,
}),
);
}
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}`
: ''
}`,
);
addExtensions(this.schema!);
return {
schema: this.schema!,
executor: this.executor,
};
}
private getIdForSupergraphSdl(supergraphSdl: string) {
return createHash('sha256').update(supergraphSdl).digest('hex');
}
private async initializeSupergraphManager<T extends SupergraphManager>(
supergraphManager: T,
) {
try {
const result = await supergraphManager.initialize({
update: this.externalSupergraphUpdateCallback.bind(this),
healthCheck: this.externalSubgraphHealthCheckCallback.bind(this),
getDataSource: this.externalGetDataSourceCallback.bind(this),
});
if (result?.cleanup) {
if (typeof result.cleanup === 'function') {
this.toDispose.push(result.cleanup);
} else {
this.logger.error(
'Provided `supergraphSdl` function returned an invalid `cleanup` property (must be a function)',
);
}
}
this.externalSupergraphUpdateCallback(result.supergraphSdl);
} catch (e) {
this.state = { phase: 'failed to load' };
await this.performCleanupAndLogErrors();
throw e;
}
this._supergraphManager = supergraphManager;
this.state = { phase: 'loaded' };
}
/**
* @throws Error
* when called from a state other than `loaded` or `intialized`
*
* @throws Error
* when the provided supergraphSdl is invalid
*/
private externalSupergraphUpdateCallback(supergraphSdl: string) {
switch (this.state.phase) {
case 'failed to load':
throw new Error(
"Can't call `update` callback after gateway failed to load.",
);
case 'updating schema':
throw new Error(
"Can't call `update` callback while supergraph update is in progress.",
);
case 'stopped':
throw new Error(
"Can't call `update` callback after gateway has been stopped.",
);
case 'stopping':
throw new Error(
"Can't call `update` callback while gateway is stopping.",
);
case 'loaded':
case 'initialized':
// typical case
break;
default:
throw new UnreachableCaseError(this.state);
}
this.state = { phase: 'updating schema' };
try {
this.updateWithSupergraphSdl({
supergraphSdl,
id: this.getIdForSupergraphSdl(supergraphSdl),
});
} finally {
// if update fails, we still want to go back to `loaded` state
this.state = { phase: 'loaded' };
}
}
/**
* @throws Error
* when any subgraph fails the health check
*/
private async externalSubgraphHealthCheckCallback(supergraphSdl: string) {
const serviceList = this.serviceListFromSupergraphSdl(supergraphSdl);
// 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 externalGetDataSourceCallback({
name,
url,
}: ServiceEndpointDefinition) {
return this.getOrCreateDataSource({ name, url });
}
private updateWithSupergraphSdl(result: SupergraphSdlUpdate) {
if (result.id === this.compositionId) {
this.logger.debug('No change in composition since last check.');
return;
}
// 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 { supergraphSchema, supergraphSdl } = this.createSchemaFromSupergraphSdl(
result.supergraphSdl,
);
const previousSchema = this.schema;
const previousSupergraphSdl = this.supergraphSdl;
const previousCompositionId = this.compositionId;
if (previousSchema) {
this.logger.info(`Updated Supergraph SDL was found [Composition ID ${this.compositionId} => ${result.id}]`);
}
this.compositionId = result.id;
this.supergraphSdl = supergraphSdl;
this.supergraphSchema = supergraphSchema.toGraphQLJSSchema();
if (!supergraphSdl) {
this.logger.error(
"A valid schema couldn't be composed. Falling back to previous schema.",
);
} else {
this.updateWithSchemaAndNotify(supergraphSchema, supergraphSdl);
if (this.experimental_didUpdateSupergraph) {
this.experimental_didUpdateSupergraph(
{
compositionId: result.id,
supergraphSdl,
schema: this.schema!,
},
previousCompositionId && previousSupergraphSdl && previousSchema
? {
compositionId: previousCompositionId,
supergraphSdl: 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: Schema,
coreSupergraphSdl: string,
// Once we remove the deprecated onSchemaChange() method, we can remove this.
legacyDontNotifyOnSchemaChangeListeners: boolean = false,
): void {
if (this.queryPlanStore) this.queryPlanStore.flush();
this.apiSchema = coreSchema.toAPISchema();
this.schema = addExtensions(
wrapSchemaWithAliasResolver(this.apiSchema.toGraphQLJSSchema()),
);
this.queryPlanner = new QueryPlanner(coreSchema, this.config.queryPlannerConfig);
// 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),
);
}
});
}
/**
* 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 serviceListFromSupergraphSdl(
supergraphSdl: string,
): Omit<ServiceDefinition, 'typeDefs'>[] {
return buildSupergraphSchema(supergraphSdl)[1];
}
private createSchemaFromSupergraphSdl(supergraphSdl: string) {
const [schema, serviceList] = buildSupergraphSchema(supergraphSdl);
this.createServices(serviceList);
return {
supergraphSchema: 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);
};
}
private getOrCreateDataSource(
serviceDef: ServiceEndpointDefinition,
): GraphQLDataSource {
// If the DataSource has already been created, early return
if (
this.serviceMap[serviceDef.name] &&
serviceDef.url === this.serviceMap[serviceDef.name].url
) {
return this.serviceMap[serviceDef.name].dataSource;
}
const dataSource = this.createDataSource(serviceDef);
// Cache the created DataSource
this.serviceMap[serviceDef.name] = { url: serviceDef.url, dataSource };
return dataSource;
}
private createDataSource(
serviceDef: ServiceEndpointDefinition,
): GraphQLDataSource {
if (!serviceDef.url && !isLocalConfig(this.config)) {
this.logger.error(
`Service definition for service ${serviceDef.name} is missing a url`,
);
}
return this.config.buildService
? this.config.buildService(serviceDef)
: new RemoteGraphQLDataSource({
url: serviceDef.url,
});
}
private createServices(services: ServiceEndpointDefinition[]) {
for (const serviceDef of services) {
this.getOrCreateDataSource(serviceDef);
}
}
private maybeWarnOnConflictingConfig() {
const canUseManagedConfig =
this.apolloConfig?.graphRef && this.apolloConfig?.keyHash;
// This might be a bit confusing just by reading, but `!isManagedConfig` just
// means it's any of the other types of config. If it's any other config _and_
// we have a studio config available (`canUseManagedConfig`) then we have a
// conflict.
if (
!isManagedConfig(this.config) &&
canUseManagedConfig &&
!this.warnedStates.remoteWithLocalConfig
) {
// Only display this warning once per start-up.
this.warnedStates.remoteWithLocalConfig = true;
// This error helps avoid common misconfiguration.
// We don't await this because a local configuration should assume
// remote is unavailable for one reason or another.
this.logger.warn(
'A local gateway configuration is overriding a managed federation ' +
'configuration. To use the managed ' +
'configuration, do not specify a service list or supergraphSdl locally.',
);
}
}
// XXX Nothing guarantees that the only errors thrown or returned in
// result.errors are GraphQLErrors, even though other code (eg
// ApolloServerPluginUsageReporting) assumes that. In fact, errors talking to backends
// are unlikely to show up as GraphQLErrors. Do we need to use
// formatApolloErrors or something?
public executor = async <TContext>(
requestContext: GraphQLRequestContextExecutionDidStart<TContext>,
): Promise<GraphQLExecutionResult> => {
const spanAttributes = requestContext.operationName
? { operationName: requestContext.operationName }
: {};
return tracer.startActiveSpan(
OpenTelemetrySpanNames.REQUEST,
{ attributes: spanAttributes },
async (span) => {
try {
const { request, document, queryHash } = requestContext;
const queryPlanStoreKey = queryHash + (request.operationName || '');
const operationContext = buildOperationContext({
schema: this.schema!,
operationDocument: document,
operationName: request.operationName,
});
// No need to build a query plan if we know the request is invalid beforehand
// In the future, this should be controlled by the requestPipeline
const validationErrors = this.validateIncomingRequest(
requestContext,
operationContext,
);
if (validationErrors.length > 0) {
span.setStatus({ code: SpanStatusCode.ERROR });
return { errors: validationErrors };
}
let queryPlan: QueryPlan | undefined;
if (this.queryPlanStore) {
queryPlan = await this.queryPlanStore.get(queryPlanStoreKey);
}
if (!queryPlan) {
queryPlan = tracer.startActiveSpan(
OpenTelemetrySpanNames.PLAN,
(span) => {
try {
const operation = operationFromDocument(
this.apiSchema!,
document,
request.operationName,
);
// TODO(#631): Can we be sure the query planner has been initialized here?
return this.queryPlanner!.buildQueryPlan(operation);
} catch (err) {
span.setStatus({ code: SpanStatusCode.ERROR });
throw err;
} finally {
span.end();
}
},
);
if (this.queryPlanStore) {
// The underlying cache store behind the `documentStore` returns a
// `Promise` which is resolved (or rejected), eventually, based on the
// success or failure (respectively) of the cache save attempt. While
// it's certainly possible to `await` this `Promise`, we don't care about
// whether or not it's successful at this point. We'll instead proceed
// to serve the rest of the request and just hope that this works out.
// If it doesn't work, the next request will have another opportunity to
// try again. Errors will surface as warnings, as appropriate.
//
// While it shouldn't normally be necessary to wrap this `Promise` in a
// `Promise.resolve` invocation, it seems that the underlying cache store
// is returning a non-native `Promise` (e.g. Bluebird, etc.).
Promise.resolve(
this.queryPlanStore.set(queryPlanStoreKey, queryPlan),
).catch((err) =>
this.logger.warn(
'Could not store queryPlan' + ((err && err.message) || err),
),
);
}
}
const serviceMap: ServiceMap = Object.entries(this.serviceMap).reduce(
(serviceDataSources, [serviceName, { dataSource }]) => {
serviceDataSources[serviceName] = dataSource;
return serviceDataSources;
},
Object.create(null) as ServiceMap,
);
if (this.experimental_didResolveQueryPlan) {
this.experimental_didResolveQueryPlan({
queryPlan,
serviceMap,
requestContext,
operationContext,
});
}
const response = await executeQueryPlan<TContext>(
queryPlan,
serviceMap,
requestContext,
operationContext,
this.supergraphSchema!,
);
const shouldShowQueryPlan =
this.config.__exposeQueryPlanExperimental &&
request.http &&
request.http.headers &&
request.http.headers.get('Apollo-Query-Plan-Experimental');
// We only want to serialize the query plan if we're going to use it, which is
// in two cases:
// 1) non-empty query plan and config.debug === true
// 2) non-empty query plan and shouldShowQueryPlan === true
const serializedQueryPlan =
queryPlan.node && (this.config.debug || shouldShowQueryPlan)
? // FIXME: I disabled printing the query plan because this lead to a
// circular dependency between the `@apollo/gateway` and
// `apollo-federation-integration-testsuite` packages.
// We should either solve that or switch Playground to
// the JSON serialization format.
prettyFormatQueryPlan(queryPlan)
: null;
if (this.config.debug && serializedQueryPlan) {
this.logger.debug(serializedQueryPlan);
}
if (shouldShowQueryPlan) {
// TODO: expose the query plan in a more flexible JSON format in the future
// and rename this to `queryPlan`. Playground should cutover to use the new
// option once we've built a way to print that representation.
// In the case that `serializedQueryPlan` is null (on introspection), we
// still want to respond to Playground with something truthy since it depends
// on this to decide that query plans are supported by this gateway.
response.extensions = {
__queryPlanExperimental: serializedQueryPlan || true,
};
}
if (response.errors) {
span.setStatus({ code: SpanStatusCode.ERROR });
}
return response;
} catch (err) {
span.setStatus({ code: SpanStatusCode.ERROR });
throw err;
} finally {
span.end();
}
},
);
};
private validateIncomingRequest<TContext>(
requestContext: GraphQLRequestContextExecutionDidStart<TContext>,
operationContext: OperationContext,
) {
return tracer.startActiveSpan(OpenTelemetrySpanNames.VALIDATE, (span) => {
try {
// casting out of `readonly`
const variableDefinitions = operationContext.operation
.variableDefinitions as VariableDefinitionNode[] | undefined;
if (!variableDefinitions) return [];
const { errors } = getVariableValues(
operationContext.schema,
variableDefinitions,
requestContext.request.variables || {},
);
if (errors) {
span.setStatus({ code: SpanStatusCode.ERROR });
}
return errors || [];
} catch (err) {
span.setStatus({ code: SpanStatusCode.ERROR });
throw err;
} finally {
span.end();
}
});
}
private async performCleanupAndLogErrors() {
if (this.toDispose.length === 0) return;
await Promise.all(
this.toDispose.map((p) =>
p().catch((e) => {
this.logger.error(
'Error occured while calling user provided `cleanup` function: ' +
(e.message ?? e),
);
}),
),
);
this.toDispose = [];
}
// Stops all processes involved with the gateway. Can be called multiple times
// safely. Once it (async) returns, all gateway background activity will be finished.
public async stop() {
switch (this.state.phase) {
case 'initialized':
case 'failed to load':
case 'stopped':
// Calls to stop() are idempotent.
return;
case 'stopping':
await this.state.stoppingDonePromise;
// 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 !== 'stopped') {
throw Error(
`Expected to be stopped when done stopping, but instead ${this.state.phase}`,
);
}
return;
case 'loaded':
const stoppingDonePromise = this.performCleanupAndLogErrors();
this.state = {
phase: 'stopping',
stoppingDonePromise,
};
await stoppingDonePromise;
this.state = { phase: 'stopped' };
return;
case 'updating schema': {
throw Error(
"`ApolloGateway.stop` shouldn't be called from inside a schema change listener",
);
}
default:
throw new UnreachableCaseError(this.state);
}
}
public __testing() {
return {
state: this.state,
compositionId: this.compositionId,
supergraphSdl: this.supergraphSdl,
};
}
}
ApolloGateway.prototype.onSchemaChange = deprecate(
ApolloGateway.prototype.onSchemaChange,
`'ApolloGateway.prototype.onSchemaChange' is deprecated. Use 'ApolloGateway.prototype.onSchemaLoadOrUpdate' instead.`,
);