@apollo/gateway 0.45.1 → 0.46.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/config.d.ts +42 -16
  3. package/dist/config.d.ts.map +1 -1
  4. package/dist/config.js +28 -18
  5. package/dist/config.js.map +1 -1
  6. package/dist/index.d.ts +35 -23
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +205 -308
  9. package/dist/index.js.map +1 -1
  10. package/dist/supergraphManagers/IntrospectAndCompose/index.d.ts +31 -0
  11. package/dist/supergraphManagers/IntrospectAndCompose/index.d.ts.map +1 -0
  12. package/dist/supergraphManagers/IntrospectAndCompose/index.js +112 -0
  13. package/dist/supergraphManagers/IntrospectAndCompose/index.js.map +1 -0
  14. package/dist/supergraphManagers/IntrospectAndCompose/loadServicesFromRemoteEndpoint.d.ts +12 -0
  15. package/dist/supergraphManagers/IntrospectAndCompose/loadServicesFromRemoteEndpoint.d.ts.map +1 -0
  16. package/dist/{loadServicesFromRemoteEndpoint.js → supergraphManagers/IntrospectAndCompose/loadServicesFromRemoteEndpoint.js} +6 -6
  17. package/dist/supergraphManagers/IntrospectAndCompose/loadServicesFromRemoteEndpoint.js.map +1 -0
  18. package/dist/supergraphManagers/LegacyFetcher/index.d.ts +33 -0
  19. package/dist/supergraphManagers/LegacyFetcher/index.d.ts.map +1 -0
  20. package/dist/supergraphManagers/LegacyFetcher/index.js +149 -0
  21. package/dist/supergraphManagers/LegacyFetcher/index.js.map +1 -0
  22. package/dist/supergraphManagers/LocalCompose/index.d.ts +19 -0
  23. package/dist/supergraphManagers/LocalCompose/index.d.ts.map +1 -0
  24. package/dist/supergraphManagers/LocalCompose/index.js +55 -0
  25. package/dist/supergraphManagers/LocalCompose/index.js.map +1 -0
  26. package/dist/supergraphManagers/UplinkFetcher/index.d.ts +32 -0
  27. package/dist/supergraphManagers/UplinkFetcher/index.d.ts.map +1 -0
  28. package/dist/supergraphManagers/UplinkFetcher/index.js +96 -0
  29. package/dist/supergraphManagers/UplinkFetcher/index.js.map +1 -0
  30. package/dist/{loadSupergraphSdlFromStorage.d.ts → supergraphManagers/UplinkFetcher/loadSupergraphSdlFromStorage.d.ts} +1 -1
  31. package/dist/supergraphManagers/UplinkFetcher/loadSupergraphSdlFromStorage.d.ts.map +1 -0
  32. package/dist/{loadSupergraphSdlFromStorage.js → supergraphManagers/UplinkFetcher/loadSupergraphSdlFromStorage.js} +1 -1
  33. package/dist/supergraphManagers/UplinkFetcher/loadSupergraphSdlFromStorage.js.map +1 -0
  34. package/dist/{outOfBandReporter.d.ts → supergraphManagers/UplinkFetcher/outOfBandReporter.d.ts} +0 -0
  35. package/dist/supergraphManagers/UplinkFetcher/outOfBandReporter.d.ts.map +1 -0
  36. package/dist/{outOfBandReporter.js → supergraphManagers/UplinkFetcher/outOfBandReporter.js} +2 -2
  37. package/dist/supergraphManagers/UplinkFetcher/outOfBandReporter.js.map +1 -0
  38. package/dist/supergraphManagers/index.d.ts +5 -0
  39. package/dist/supergraphManagers/index.d.ts.map +1 -0
  40. package/dist/supergraphManagers/index.js +12 -0
  41. package/dist/supergraphManagers/index.js.map +1 -0
  42. package/dist/utilities/createHash.d.ts +2 -0
  43. package/dist/utilities/createHash.d.ts.map +1 -0
  44. package/dist/utilities/createHash.js +15 -0
  45. package/dist/utilities/createHash.js.map +1 -0
  46. package/dist/utilities/isNodeLike.d.ts +3 -0
  47. package/dist/utilities/isNodeLike.d.ts.map +1 -0
  48. package/dist/utilities/isNodeLike.js +8 -0
  49. package/dist/utilities/isNodeLike.js.map +1 -0
  50. package/package.json +6 -4
  51. package/src/__tests__/execution-utils.ts +2 -2
  52. package/src/__tests__/gateway/buildService.test.ts +2 -2
  53. package/src/__tests__/gateway/lifecycle-hooks.test.ts +58 -99
  54. package/src/__tests__/gateway/opentelemetry.test.ts +8 -3
  55. package/src/__tests__/gateway/queryPlanCache.test.ts +25 -9
  56. package/src/__tests__/gateway/reporting.test.ts +4 -6
  57. package/src/__tests__/gateway/supergraphSdl.test.ts +390 -0
  58. package/src/__tests__/integration/aliases.test.ts +9 -3
  59. package/src/__tests__/integration/configuration.test.ts +109 -12
  60. package/src/__tests__/integration/logger.test.ts +1 -1
  61. package/src/__tests__/integration/networkRequests.test.ts +81 -118
  62. package/src/__tests__/integration/nockMocks.ts +15 -8
  63. package/src/config.ts +149 -40
  64. package/src/index.ts +314 -485
  65. package/src/supergraphManagers/IntrospectAndCompose/__tests__/IntrospectAndCompose.test.ts +370 -0
  66. package/src/{__tests__ → supergraphManagers/IntrospectAndCompose/__tests__}/loadServicesFromRemoteEndpoint.test.ts +5 -5
  67. package/src/supergraphManagers/IntrospectAndCompose/__tests__/tsconfig.json +8 -0
  68. package/src/supergraphManagers/IntrospectAndCompose/index.ts +163 -0
  69. package/src/{loadServicesFromRemoteEndpoint.ts → supergraphManagers/IntrospectAndCompose/loadServicesFromRemoteEndpoint.ts} +6 -6
  70. package/src/supergraphManagers/LegacyFetcher/index.ts +229 -0
  71. package/src/supergraphManagers/LocalCompose/index.ts +83 -0
  72. package/src/{__tests__ → supergraphManagers/UplinkFetcher/__tests__}/loadSupergraphSdlFromStorage.test.ts +4 -4
  73. package/src/supergraphManagers/UplinkFetcher/__tests__/tsconfig.json +8 -0
  74. package/src/supergraphManagers/UplinkFetcher/index.ts +128 -0
  75. package/src/{loadSupergraphSdlFromStorage.ts → supergraphManagers/UplinkFetcher/loadSupergraphSdlFromStorage.ts} +3 -3
  76. package/src/{outOfBandReporter.ts → supergraphManagers/UplinkFetcher/outOfBandReporter.ts} +2 -2
  77. package/src/supergraphManagers/index.ts +4 -0
  78. package/src/utilities/createHash.ts +10 -0
  79. package/src/utilities/isNodeLike.ts +11 -0
  80. package/dist/loadServicesFromRemoteEndpoint.d.ts +0 -13
  81. package/dist/loadServicesFromRemoteEndpoint.d.ts.map +0 -1
  82. package/dist/loadServicesFromRemoteEndpoint.js.map +0 -1
  83. package/dist/loadSupergraphSdlFromStorage.d.ts.map +0 -1
  84. package/dist/loadSupergraphSdlFromStorage.js.map +0 -1
  85. package/dist/outOfBandReporter.d.ts.map +0 -1
  86. package/dist/outOfBandReporter.js.map +0 -1
  87. package/src/__tests__/gateway/composedSdl.test.ts +0 -44
package/dist/index.js CHANGED
@@ -13,17 +13,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
13
13
  return (mod && mod.__esModule) ? mod : { "default": mod };
14
14
  };
15
15
  Object.defineProperty(exports, "__esModule", { value: true });
16
- exports.buildOperationContext = exports.executeQueryPlan = exports.ApolloGateway = exports.SERVICE_DEFINITION_QUERY = exports.HEALTH_CHECK_QUERY = exports.getDefaultFetcher = void 0;
16
+ exports.LocalCompose = exports.IntrospectAndCompose = exports.buildOperationContext = exports.executeQueryPlan = exports.ApolloGateway = exports.SERVICE_DEFINITION_QUERY = exports.HEALTH_CHECK_QUERY = exports.getDefaultFetcher = void 0;
17
17
  const util_1 = require("util");
18
18
  const apollo_server_caching_1 = require("apollo-server-caching");
19
19
  const graphql_1 = require("graphql");
20
- const federation_1 = require("@apollo/federation");
21
20
  const loglevel_1 = __importDefault(require("loglevel"));
22
21
  const operationContext_1 = require("./operationContext");
23
22
  Object.defineProperty(exports, "buildOperationContext", { enumerable: true, get: function () { return operationContext_1.buildOperationContext; } });
24
23
  const executeQueryPlan_1 = require("./executeQueryPlan");
25
24
  Object.defineProperty(exports, "executeQueryPlan", { enumerable: true, get: function () { return executeQueryPlan_1.executeQueryPlan; } });
26
- const loadServicesFromRemoteEndpoint_1 = require("./loadServicesFromRemoteEndpoint");
27
25
  const types_1 = require("./datasources/types");
28
26
  const RemoteGraphQLDataSource_1 = require("./datasources/RemoteGraphQLDataSource");
29
27
  const values_1 = require("graphql/execution/values");
@@ -32,11 +30,14 @@ const cache_1 = require("./cache");
32
30
  const query_planner_1 = require("@apollo/query-planner");
33
31
  const config_1 = require("./config");
34
32
  const query_planner_2 = require("@apollo/query-planner");
35
- const loadSupergraphSdlFromStorage_1 = require("./loadSupergraphSdlFromStorage");
36
33
  const api_1 = require("@opentelemetry/api");
37
34
  const opentelemetry_1 = require("./utilities/opentelemetry");
38
35
  const core_schema_1 = require("@apollo/core-schema");
39
36
  const core_1 = require("./core");
37
+ const createHash_1 = require("./utilities/createHash");
38
+ const supergraphManagers_1 = require("./supergraphManagers");
39
+ Object.defineProperty(exports, "IntrospectAndCompose", { enumerable: true, get: function () { return supergraphManagers_1.IntrospectAndCompose; } });
40
+ Object.defineProperty(exports, "LocalCompose", { enumerable: true, get: function () { return supergraphManagers_1.LocalCompose; } });
40
41
  function getDefaultFetcher() {
41
42
  const { name, version } = require('../package.json');
42
43
  return make_fetch_happen_1.default.defaults({
@@ -60,14 +61,12 @@ exports.HEALTH_CHECK_QUERY = 'query __ApolloServiceHealthCheck__ { __typename }'
60
61
  exports.SERVICE_DEFINITION_QUERY = 'query __ApolloGetServiceDefinition__ { _service { sdl } }';
61
62
  class ApolloGateway {
62
63
  constructor(config) {
63
- var _a, _b, _c, _d, _e;
64
+ var _a;
64
65
  this.serviceMap = Object.create(null);
65
66
  this.onSchemaChangeListeners = new Set();
66
67
  this.onSchemaLoadOrUpdateListeners = new Set();
67
- this.serviceDefinitions = [];
68
- this.serviceSdlCache = new Map();
69
68
  this.warnedStates = Object.create(null);
70
- this.errorReportingEndpoint = (_a = process.env.APOLLO_OUT_OF_BAND_REPORTER_ENDPOINT) !== null && _a !== void 0 ? _a : undefined;
69
+ this.toDispose = [];
71
70
  this.executor = async (requestContext) => {
72
71
  const spanAttributes = requestContext.operationName
73
72
  ? { operationName: requestContext.operationName }
@@ -161,44 +160,12 @@ class ApolloGateway {
161
160
  this.fetcher = (config === null || config === void 0 ? void 0 : config.fetcher) || getDefaultFetcher();
162
161
  this.experimental_didResolveQueryPlan =
163
162
  config === null || config === void 0 ? void 0 : config.experimental_didResolveQueryPlan;
164
- this.experimental_didFailComposition =
165
- config === null || config === void 0 ? void 0 : config.experimental_didFailComposition;
166
- this.experimental_didUpdateComposition =
167
- config === null || config === void 0 ? void 0 : config.experimental_didUpdateComposition;
168
- this.experimental_pollInterval = config === null || config === void 0 ? void 0 : config.experimental_pollInterval;
169
- if ((0, config_1.isManagedConfig)(this.config)) {
170
- const rawEndpointsString = process.env.APOLLO_SCHEMA_CONFIG_DELIVERY_ENDPOINT;
171
- const envEndpoints = (_b = rawEndpointsString === null || rawEndpointsString === void 0 ? void 0 : rawEndpointsString.split(",")) !== null && _b !== void 0 ? _b : null;
172
- if (this.config.schemaConfigDeliveryEndpoint && !this.config.uplinkEndpoints) {
173
- this.uplinkEndpoints = [this.config.schemaConfigDeliveryEndpoint];
174
- }
175
- else {
176
- this.uplinkEndpoints = (_d = (_c = this.config.uplinkEndpoints) !== null && _c !== void 0 ? _c : envEndpoints) !== null && _d !== void 0 ? _d : [
177
- 'https://uplink.api.apollographql.com/',
178
- 'https://aws.uplink.api.apollographql.com/'
179
- ];
180
- }
181
- this.uplinkMaxRetries = (_e = this.config.uplinkMaxRetries) !== null && _e !== void 0 ? _e : this.uplinkEndpoints.length * 3;
182
- }
183
- if ((0, config_1.isManuallyManagedConfig)(this.config)) {
184
- if ('experimental_updateSupergraphSdl' in this.config) {
185
- this.updateServiceDefinitions =
186
- this.config.experimental_updateSupergraphSdl;
187
- }
188
- else if ('experimental_updateServiceDefinitions' in this.config) {
189
- this.updateServiceDefinitions =
190
- this.config.experimental_updateServiceDefinitions;
191
- }
192
- else {
193
- throw Error('Programming error: unexpected manual configuration provided');
194
- }
195
- }
196
- else {
197
- this.updateServiceDefinitions = this.loadServiceDefinitions;
198
- }
199
- if ((0, config_1.isDynamicConfig)(this.config)) {
200
- this.issueDynamicWarningsIfApplicable();
201
- }
163
+ this.experimental_didUpdateSupergraph =
164
+ config === null || config === void 0 ? void 0 : config.experimental_didUpdateSupergraph;
165
+ this.pollIntervalInMs =
166
+ (_a = config === null || config === void 0 ? void 0 : config.pollIntervalInMs) !== null && _a !== void 0 ? _a : config === null || config === void 0 ? void 0 : config.experimental_pollInterval;
167
+ this.issueConfigurationWarningsIfApplicable();
168
+ this.logger.debug('Gateway successfully initialized (but not yet loaded)');
202
169
  this.state = { phase: 'initialized' };
203
170
  }
204
171
  initLogger() {
@@ -220,18 +187,18 @@ class ApolloGateway {
220
187
  sizeCalculator: approximateObjectSize,
221
188
  });
222
189
  }
223
- issueDynamicWarningsIfApplicable() {
190
+ issueConfigurationWarningsIfApplicable() {
224
191
  if ((0, config_1.isManagedConfig)(this.config) &&
225
- this.config.experimental_pollInterval &&
226
- this.config.experimental_pollInterval < 10000) {
227
- this.experimental_pollInterval = 10000;
192
+ this.pollIntervalInMs &&
193
+ this.pollIntervalInMs < 10000) {
194
+ this.pollIntervalInMs = 10000;
228
195
  this.logger.warn('Polling Apollo services at a frequency of less than once per 10 ' +
229
196
  'seconds (10000) is disallowed. Instead, the minimum allowed ' +
230
197
  'pollInterval of 10000 will be used. Please reconfigure your ' +
231
- 'experimental_pollInterval accordingly. If this is problematic for ' +
198
+ '`pollIntervalInMs` accordingly. If this is problematic for ' +
232
199
  'your team, please contact support.');
233
200
  }
234
- if (this.config.experimental_pollInterval && (0, config_1.isRemoteConfig)(this.config)) {
201
+ if (this.pollIntervalInMs && (0, config_1.isServiceListConfig)(this.config)) {
235
202
  this.logger.warn('Polling running services is dangerous and not recommended in production. ' +
236
203
  'Polling should only be used against a registry. ' +
237
204
  'If you are polling running services, use with caution.');
@@ -244,8 +211,16 @@ class ApolloGateway {
244
211
  'function when both `experimental_updateSupergraphSdl` and experimental_updateServiceDefinitions` ' +
245
212
  'are provided.');
246
213
  }
214
+ if ('schemaConfigDeliveryEndpoint' in this.config) {
215
+ 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.');
216
+ }
217
+ if ('experimental_pollInterval' in this.config) {
218
+ this.logger.warn('The `experimental_pollInterval` option is deprecated and will be removed in a future version of `@apollo/gateway`. Please migrate to the equivalent `pollIntervalInMs` configuration option.');
219
+ }
247
220
  }
248
221
  async load(options) {
222
+ var _a, _b, _c, _d;
223
+ this.logger.debug('Loading gateway...');
249
224
  if (this.state.phase !== 'initialized') {
250
225
  throw Error(`ApolloGateway.load called in surprising state ${this.state.phase}`);
251
226
  }
@@ -266,11 +241,71 @@ class ApolloGateway {
266
241
  : undefined,
267
242
  };
268
243
  }
269
- const unrefTimer = !!options && !options.apollo;
270
244
  this.maybeWarnOnConflictingConfig();
271
- (0, config_1.isStaticConfig)(this.config)
272
- ? this.loadStatic(this.config)
273
- : await this.loadDynamic(unrefTimer);
245
+ if ((0, config_1.isStaticSupergraphSdlConfig)(this.config)) {
246
+ const supergraphSdl = this.config.supergraphSdl;
247
+ await this.initializeSupergraphManager({
248
+ initialize: async () => {
249
+ return {
250
+ supergraphSdl,
251
+ };
252
+ },
253
+ });
254
+ }
255
+ else if ((0, config_1.isLocalConfig)(this.config)) {
256
+ await this.initializeSupergraphManager(new supergraphManagers_1.LocalCompose({
257
+ localServiceList: this.config.localServiceList,
258
+ logger: this.logger,
259
+ }));
260
+ }
261
+ else if ((0, config_1.isManuallyManagedSupergraphSdlGatewayConfig)(this.config)) {
262
+ const supergraphManager = typeof this.config.supergraphSdl === 'object'
263
+ ? this.config.supergraphSdl
264
+ : { initialize: this.config.supergraphSdl };
265
+ await this.initializeSupergraphManager(supergraphManager);
266
+ }
267
+ else if ('experimental_updateServiceDefinitions' in this.config || 'experimental_updateSupergraphSdl' in this.config) {
268
+ const updateServiceDefinitions = 'experimental_updateServiceDefinitions' in this.config
269
+ ? this.config.experimental_updateServiceDefinitions
270
+ : this.config.experimental_updateSupergraphSdl;
271
+ await this.initializeSupergraphManager(new supergraphManagers_1.LegacyFetcher({
272
+ logger: this.logger,
273
+ gatewayConfig: this.config,
274
+ updateServiceDefinitions,
275
+ pollIntervalInMs: this.pollIntervalInMs,
276
+ subgraphHealthCheck: this.config.serviceHealthCheck,
277
+ }));
278
+ }
279
+ else if ((0, config_1.isServiceListConfig)(this.config)) {
280
+ 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.');
281
+ await this.initializeSupergraphManager(new supergraphManagers_1.IntrospectAndCompose({
282
+ subgraphs: this.config.serviceList,
283
+ pollIntervalInMs: this.pollIntervalInMs,
284
+ logger: this.logger,
285
+ subgraphHealthCheck: this.config.serviceHealthCheck,
286
+ introspectionHeaders: this.config.introspectionHeaders,
287
+ }));
288
+ }
289
+ else {
290
+ const canUseManagedConfig = ((_a = this.apolloConfig) === null || _a === void 0 ? void 0 : _a.graphRef) && ((_b = this.apolloConfig) === null || _b === void 0 ? void 0 : _b.keyHash);
291
+ if (!canUseManagedConfig) {
292
+ throw new Error('When a manual configuration is not provided, gateway requires an Apollo ' +
293
+ 'configuration. See https://www.apollographql.com/docs/apollo-server/federation/managed-federation/ ' +
294
+ 'for more information. Manual configuration options include: ' +
295
+ '`serviceList`, `supergraphSdl`, and `experimental_updateServiceDefinitions`.');
296
+ }
297
+ const uplinkEndpoints = this.getUplinkEndpoints(this.config);
298
+ await this.initializeSupergraphManager(new supergraphManagers_1.UplinkFetcher({
299
+ graphRef: this.apolloConfig.graphRef,
300
+ apiKey: this.apolloConfig.key,
301
+ uplinkEndpoints,
302
+ maxRetries: (_c = this.config.uplinkMaxRetries) !== null && _c !== void 0 ? _c : uplinkEndpoints.length * 3,
303
+ subgraphHealthCheck: this.config.serviceHealthCheck,
304
+ fetcher: this.fetcher,
305
+ logger: this.logger,
306
+ pollIntervalInMs: (_d = this.pollIntervalInMs) !== null && _d !== void 0 ? _d : 10000,
307
+ }));
308
+ }
274
309
  const mode = (0, config_1.isManagedConfig)(this.config) ? 'managed' : 'unmanaged';
275
310
  this.logger.info(`Gateway successfully loaded schema.\n\t* Mode: ${mode}${this.apolloConfig && this.apolloConfig.graphRef
276
311
  ? `\n\t* Service: ${this.apolloConfig.graphRef}`
@@ -280,118 +315,120 @@ class ApolloGateway {
280
315
  executor: this.executor,
281
316
  };
282
317
  }
283
- loadStatic(config) {
284
- let schema;
285
- let supergraphSdl;
286
- try {
287
- ({ schema, supergraphSdl } = (0, config_1.isLocalConfig)(config)
288
- ? this.createSchemaFromServiceList(config.localServiceList)
289
- : this.createSchemaFromSupergraphSdl(config.supergraphSdl));
290
- this.parsedSupergraphSdl = (0, graphql_1.parse)(supergraphSdl);
291
- this.supergraphSdl = supergraphSdl;
292
- this.updateWithSchemaAndNotify(schema, supergraphSdl, true);
293
- }
294
- catch (e) {
295
- this.state = { phase: 'failed to load' };
296
- throw e;
297
- }
298
- this.state = { phase: 'loaded' };
318
+ getUplinkEndpoints(config) {
319
+ var _a, _b, _c, _d;
320
+ const rawEndpointsString = process.env.APOLLO_SCHEMA_CONFIG_DELIVERY_ENDPOINT;
321
+ const envEndpoints = (_a = rawEndpointsString === null || rawEndpointsString === void 0 ? void 0 : rawEndpointsString.split(',')) !== null && _a !== void 0 ? _a : null;
322
+ return (_d = (_c = (_b = config.uplinkEndpoints) !== null && _b !== void 0 ? _b : (config.schemaConfigDeliveryEndpoint
323
+ ? [config.schemaConfigDeliveryEndpoint]
324
+ : null)) !== null && _c !== void 0 ? _c : envEndpoints) !== null && _d !== void 0 ? _d : [
325
+ 'https://uplink.api.apollographql.com/',
326
+ 'https://aws.uplink.api.apollographql.com/',
327
+ ];
328
+ }
329
+ getIdForSupergraphSdl(supergraphSdl) {
330
+ return (0, createHash_1.createHash)('sha256').update(supergraphSdl).digest('hex');
299
331
  }
300
- async loadDynamic(unrefTimer) {
332
+ async initializeSupergraphManager(supergraphManager) {
301
333
  try {
302
- await this.updateSchema();
334
+ const result = await supergraphManager.initialize({
335
+ update: this.externalSupergraphUpdateCallback.bind(this),
336
+ healthCheck: this.externalSubgraphHealthCheckCallback.bind(this),
337
+ getDataSource: this.externalGetDataSourceCallback.bind(this),
338
+ });
339
+ if (!(result === null || result === void 0 ? void 0 : result.supergraphSdl)) {
340
+ throw new Error('Provided `supergraphSdl` function did not return an object containing a `supergraphSdl` property');
341
+ }
342
+ if (result === null || result === void 0 ? void 0 : result.cleanup) {
343
+ if (typeof result.cleanup === 'function') {
344
+ this.toDispose.push(result.cleanup);
345
+ }
346
+ else {
347
+ this.logger.error('Provided `supergraphSdl` function returned an invalid `cleanup` property (must be a function)');
348
+ }
349
+ }
350
+ this.externalSupergraphUpdateCallback(result.supergraphSdl);
303
351
  }
304
352
  catch (e) {
305
353
  this.state = { phase: 'failed to load' };
354
+ await this.performCleanupAndLogErrors();
306
355
  throw e;
307
356
  }
308
357
  this.state = { phase: 'loaded' };
309
- if (this.shouldBeginPolling()) {
310
- this.pollServices(unrefTimer);
311
- }
312
- }
313
- shouldBeginPolling() {
314
- return (0, config_1.isManagedConfig)(this.config) || this.experimental_pollInterval;
315
358
  }
316
- async updateSchema() {
317
- this.logger.debug('Checking for composition updates...');
318
- const result = await this.updateServiceDefinitions(this.config);
319
- if ((0, config_1.isSupergraphSdlUpdate)(result)) {
320
- await this.updateWithSupergraphSdl(result);
359
+ externalSupergraphUpdateCallback(supergraphSdl) {
360
+ switch (this.state.phase) {
361
+ case 'failed to load':
362
+ throw new Error("Can't call `update` callback after gateway failed to load.");
363
+ case 'updating schema':
364
+ throw new Error("Can't call `update` callback while supergraph update is in progress.");
365
+ case 'stopped':
366
+ throw new Error("Can't call `update` callback after gateway has been stopped.");
367
+ case 'stopping':
368
+ throw new Error("Can't call `update` callback while gateway is stopping.");
369
+ case 'loaded':
370
+ case 'initialized':
371
+ break;
372
+ default:
373
+ throw new UnreachableCaseError(this.state);
321
374
  }
322
- else if ((0, config_1.isServiceDefinitionUpdate)(result)) {
323
- await this.updateByComposition(result);
375
+ this.state = { phase: 'updating schema' };
376
+ try {
377
+ this.updateWithSupergraphSdl({
378
+ supergraphSdl,
379
+ id: this.getIdForSupergraphSdl(supergraphSdl),
380
+ });
324
381
  }
325
- else {
326
- throw new Error('Programming error: unexpected result type from `updateServiceDefinitions`');
382
+ finally {
383
+ this.state = { phase: 'loaded' };
327
384
  }
328
385
  }
329
- async updateByComposition(result) {
330
- if (!result.serviceDefinitions ||
331
- JSON.stringify(this.serviceDefinitions) ===
332
- JSON.stringify(result.serviceDefinitions)) {
333
- this.logger.debug('No change in service definitions since last check.');
334
- return;
335
- }
336
- const previousSchema = this.schema;
337
- const previousServiceDefinitions = this.serviceDefinitions;
338
- const previousCompositionMetadata = this.compositionMetadata;
339
- if (previousSchema) {
340
- this.logger.info('New service definitions were found.');
341
- }
342
- await this.maybePerformServiceHealthCheck(result);
343
- this.compositionMetadata = result.compositionMetadata;
344
- this.serviceDefinitions = result.serviceDefinitions;
345
- const { schema, supergraphSdl } = this.createSchemaFromServiceList(result.serviceDefinitions);
346
- if (!supergraphSdl) {
347
- this.logger.error("A valid schema couldn't be composed. Falling back to previous schema.");
386
+ async externalSubgraphHealthCheckCallback(supergraphSdl) {
387
+ const parsedSupergraphSdl = supergraphSdl === this.supergraphSdl
388
+ ? this.parsedSupergraphSdl
389
+ : (0, graphql_1.parse)(supergraphSdl);
390
+ const serviceList = this.serviceListFromSupergraphSdl(parsedSupergraphSdl);
391
+ const serviceMap = serviceList.reduce((serviceMap, serviceDef) => {
392
+ serviceMap[serviceDef.name] = {
393
+ url: serviceDef.url,
394
+ dataSource: this.createDataSource(serviceDef),
395
+ };
396
+ return serviceMap;
397
+ }, Object.create(null));
398
+ try {
399
+ await this.serviceHealthCheck(serviceMap);
348
400
  }
349
- else {
350
- this.updateWithSchemaAndNotify(schema, supergraphSdl);
351
- if (this.experimental_didUpdateComposition) {
352
- this.experimental_didUpdateComposition({
353
- serviceDefinitions: result.serviceDefinitions,
354
- schema,
355
- ...(this.compositionMetadata && {
356
- compositionMetadata: this.compositionMetadata,
357
- }),
358
- }, previousServiceDefinitions &&
359
- previousSchema && {
360
- serviceDefinitions: previousServiceDefinitions,
361
- schema: previousSchema,
362
- ...(previousCompositionMetadata && {
363
- compositionMetadata: previousCompositionMetadata,
364
- }),
365
- });
366
- }
401
+ catch (e) {
402
+ throw new Error('The gateway subgraphs health check failed. Updating to the provided ' +
403
+ '`supergraphSdl` will likely result in future request failures to ' +
404
+ 'subgraphs. The following error occurred during the health check:\n' +
405
+ e.message);
367
406
  }
368
407
  }
369
- async updateWithSupergraphSdl(result) {
370
- if (result.id === this.compositionId) {
371
- this.logger.debug('No change in composition since last check.');
372
- return;
373
- }
374
- const parsedSupergraphSdl = (0, graphql_1.parse)(result.supergraphSdl);
408
+ externalGetDataSourceCallback({ name, url, }) {
409
+ return this.getOrCreateDataSource({ name, url });
410
+ }
411
+ updateWithSupergraphSdl({ supergraphSdl, id }) {
412
+ const parsedSupergraphSdl = (0, graphql_1.parse)(supergraphSdl);
375
413
  const previousSchema = this.schema;
376
414
  const previousSupergraphSdl = this.parsedSupergraphSdl;
377
415
  const previousCompositionId = this.compositionId;
378
416
  if (previousSchema) {
379
417
  this.logger.info('Updated Supergraph SDL was found.');
380
418
  }
381
- await this.maybePerformServiceHealthCheck(result);
382
- this.compositionId = result.id;
383
- this.supergraphSdl = result.supergraphSdl;
419
+ this.compositionId = id;
420
+ this.supergraphSdl = supergraphSdl;
384
421
  this.parsedSupergraphSdl = parsedSupergraphSdl;
385
- const { schema, supergraphSdl } = this.createSchemaFromSupergraphSdl(result.supergraphSdl);
386
- if (!supergraphSdl) {
422
+ const { schema, supergraphSdl: generatedSupergraphSdl } = this.createSchemaFromSupergraphSdl(supergraphSdl);
423
+ if (!generatedSupergraphSdl) {
387
424
  this.logger.error("A valid schema couldn't be composed. Falling back to previous schema.");
388
425
  }
389
426
  else {
390
- this.updateWithSchemaAndNotify(schema, supergraphSdl);
391
- if (this.experimental_didUpdateComposition) {
392
- this.experimental_didUpdateComposition({
393
- compositionId: result.id,
394
- supergraphSdl: result.supergraphSdl,
427
+ this.updateWithSchemaAndNotify(schema, generatedSupergraphSdl);
428
+ if (this.experimental_didUpdateSupergraph) {
429
+ this.experimental_didUpdateSupergraph({
430
+ compositionId: id,
431
+ supergraphSdl,
395
432
  schema,
396
433
  }, previousCompositionId && previousSupergraphSdl && previousSchema
397
434
  ? {
@@ -434,31 +471,6 @@ class ApolloGateway {
434
471
  }
435
472
  });
436
473
  }
437
- async maybePerformServiceHealthCheck(update) {
438
- if (this.config.serviceHealthCheck) {
439
- const serviceList = (0, config_1.isSupergraphSdlUpdate)(update)
440
- ?
441
- this.serviceListFromSupergraphSdl((0, graphql_1.parse)(update.supergraphSdl))
442
- :
443
- update.serviceDefinitions;
444
- const serviceMap = serviceList.reduce((serviceMap, serviceDef) => {
445
- serviceMap[serviceDef.name] = {
446
- url: serviceDef.url,
447
- dataSource: this.createDataSource(serviceDef),
448
- };
449
- return serviceMap;
450
- }, Object.create(null));
451
- try {
452
- await this.serviceHealthCheck(serviceMap);
453
- }
454
- catch (e) {
455
- throw new Error('The gateway did not update its schema due to failed service health checks. ' +
456
- 'The gateway will continue to operate with the previous schema and reattempt updates. ' +
457
- 'The following error occurred during the health check:\n' +
458
- e.message);
459
- }
460
- }
461
- }
462
474
  serviceHealthCheck(serviceMap = this.serviceMap) {
463
475
  return Promise.all(Object.entries(serviceMap).map(([name, { dataSource }]) => dataSource
464
476
  .process({
@@ -471,36 +483,6 @@ class ApolloGateway {
471
483
  throw new Error(`[${name}]: ${e.message}`);
472
484
  })));
473
485
  }
474
- createSchemaFromServiceList(serviceList) {
475
- this.logger.debug(`Composing schema from service list: \n${serviceList
476
- .map(({ name, url }) => ` ${url || 'local'}: ${name}`)
477
- .join('\n')}`);
478
- const compositionResult = (0, federation_1.composeAndValidate)(serviceList);
479
- if ((0, federation_1.compositionHasErrors)(compositionResult)) {
480
- const { errors } = compositionResult;
481
- if (this.experimental_didFailComposition) {
482
- this.experimental_didFailComposition({
483
- errors,
484
- serviceList,
485
- ...(this.compositionMetadata && {
486
- compositionMetadata: this.compositionMetadata,
487
- }),
488
- });
489
- }
490
- throw Error("A valid schema couldn't be composed. The following composition errors were found:\n" +
491
- errors.map((e) => '\t' + e.message).join('\n'));
492
- }
493
- else {
494
- const { supergraphSdl } = compositionResult;
495
- this.createServices(serviceList);
496
- const schema = (0, query_planner_2.buildComposedSchema)((0, graphql_1.parse)(supergraphSdl));
497
- this.logger.debug('Schema loaded and ready for execution');
498
- return {
499
- schema: wrapSchemaWithAliasResolver(schema),
500
- supergraphSdl,
501
- };
502
- }
503
- }
504
486
  serviceListFromSupergraphSdl(supergraphSdl) {
505
487
  const schema = (0, query_planner_2.buildComposedSchema)(supergraphSdl);
506
488
  return this.serviceListFromComposedSchema(schema);
@@ -538,63 +520,11 @@ class ApolloGateway {
538
520
  this.onSchemaLoadOrUpdateListeners.delete(callback);
539
521
  };
540
522
  }
541
- async pollServices(unrefTimer) {
542
- switch (this.state.phase) {
543
- case 'stopping':
544
- case 'stopped':
545
- case 'failed to load':
546
- return;
547
- case 'initialized':
548
- throw Error('pollServices should not be called before load!');
549
- case 'polling':
550
- throw Error('pollServices should not be called while in the middle of polling!');
551
- case 'waiting to poll':
552
- throw Error('pollServices should not be called while already waiting to poll!');
553
- case 'loaded':
554
- break;
555
- default:
556
- throw new UnreachableCaseError(this.state);
557
- }
558
- await new Promise((doneWaiting) => {
559
- this.state = {
560
- phase: 'waiting to poll',
561
- doneWaiting,
562
- pollWaitTimer: setTimeout(() => {
563
- if (this.state.phase == 'waiting to poll') {
564
- this.state.doneWaiting();
565
- }
566
- }, this.experimental_pollInterval || 10000),
567
- };
568
- if (unrefTimer) {
569
- this.state.pollWaitTimer.unref();
570
- }
571
- });
572
- if (this.state.phase !== 'waiting to poll') {
573
- return;
574
- }
575
- let pollingDone;
576
- this.state = {
577
- phase: 'polling',
578
- pollingDonePromise: new Promise((res) => {
579
- pollingDone = res;
580
- }),
581
- };
582
- try {
583
- await this.updateSchema();
584
- }
585
- catch (err) {
586
- this.logger.error((err && err.message) || err);
587
- }
588
- if (this.state.phase === 'polling') {
589
- this.state = { phase: 'loaded' };
590
- setImmediate(() => this.pollServices(unrefTimer));
591
- }
592
- pollingDone();
593
- }
594
- createAndCacheDataSource(serviceDef) {
523
+ getOrCreateDataSource(serviceDef) {
595
524
  if (this.serviceMap[serviceDef.name] &&
596
- serviceDef.url === this.serviceMap[serviceDef.name].url)
525
+ serviceDef.url === this.serviceMap[serviceDef.name].url) {
597
526
  return this.serviceMap[serviceDef.name].dataSource;
527
+ }
598
528
  const dataSource = this.createDataSource(serviceDef);
599
529
  this.serviceMap[serviceDef.name] = { url: serviceDef.url, dataSource };
600
530
  return dataSource;
@@ -611,47 +541,9 @@ class ApolloGateway {
611
541
  }
612
542
  createServices(services) {
613
543
  for (const serviceDef of services) {
614
- this.createAndCacheDataSource(serviceDef);
544
+ this.getOrCreateDataSource(serviceDef);
615
545
  }
616
546
  }
617
- async loadServiceDefinitions(config) {
618
- var _a, _b, _c;
619
- if ((0, config_1.isRemoteConfig)(config)) {
620
- const serviceList = config.serviceList.map((serviceDefinition) => ({
621
- ...serviceDefinition,
622
- dataSource: this.createAndCacheDataSource(serviceDefinition),
623
- }));
624
- return (0, loadServicesFromRemoteEndpoint_1.getServiceDefinitionsFromRemoteEndpoint)({
625
- serviceList,
626
- async getServiceIntrospectionHeaders(service) {
627
- return typeof config.introspectionHeaders === 'function'
628
- ? await config.introspectionHeaders(service)
629
- : config.introspectionHeaders;
630
- },
631
- serviceSdlCache: this.serviceSdlCache,
632
- });
633
- }
634
- const canUseManagedConfig = ((_a = this.apolloConfig) === null || _a === void 0 ? void 0 : _a.graphRef) && ((_b = this.apolloConfig) === null || _b === void 0 ? void 0 : _b.keyHash);
635
- if (!canUseManagedConfig) {
636
- throw new Error('When a manual configuration is not provided, gateway requires an Apollo ' +
637
- 'configuration. See https://www.apollographql.com/docs/apollo-server/federation/managed-federation/ ' +
638
- 'for more information. Manual configuration options include: ' +
639
- '`serviceList`, `supergraphSdl`, and `experimental_updateServiceDefinitions`.');
640
- }
641
- const result = await (0, loadSupergraphSdlFromStorage_1.loadSupergraphSdlFromUplinks)({
642
- graphRef: this.apolloConfig.graphRef,
643
- apiKey: this.apolloConfig.key,
644
- endpoints: this.uplinkEndpoints,
645
- errorReportingEndpoint: this.errorReportingEndpoint,
646
- fetcher: this.fetcher,
647
- compositionId: (_c = this.compositionId) !== null && _c !== void 0 ? _c : null,
648
- maxRetries: this.uplinkMaxRetries,
649
- });
650
- return (result !== null && result !== void 0 ? result : {
651
- id: this.compositionId,
652
- supergraphSdl: this.supergraphSdl,
653
- });
654
- }
655
547
  maybeWarnOnConflictingConfig() {
656
548
  var _a, _b;
657
549
  const canUseManagedConfig = ((_a = this.apolloConfig) === null || _a === void 0 ? void 0 : _a.graphRef) && ((_b = this.apolloConfig) === null || _b === void 0 ? void 0 : _b.keyHash);
@@ -686,6 +578,16 @@ class ApolloGateway {
686
578
  }
687
579
  });
688
580
  }
581
+ async performCleanupAndLogErrors() {
582
+ if (this.toDispose.length === 0)
583
+ return;
584
+ await Promise.all(this.toDispose.map((p) => p().catch((e) => {
585
+ var _a;
586
+ this.logger.error('Error occured while calling user provided `cleanup` function: ' +
587
+ ((_a = e.message) !== null && _a !== void 0 ? _a : e));
588
+ })));
589
+ this.toDispose = [];
590
+ }
689
591
  async stop() {
690
592
  switch (this.state.phase) {
691
593
  case 'initialized':
@@ -700,33 +602,28 @@ class ApolloGateway {
700
602
  }
701
603
  return;
702
604
  case 'loaded':
703
- this.state = { phase: 'stopped' };
704
- return;
705
- case 'waiting to poll': {
706
- const doneWaiting = this.state.doneWaiting;
707
- clearTimeout(this.state.pollWaitTimer);
708
- this.state = { phase: 'stopped' };
709
- doneWaiting();
710
- return;
711
- }
712
- case 'polling': {
713
- const pollingDonePromise = this.state.pollingDonePromise;
714
- let stoppingDone;
605
+ const stoppingDonePromise = this.performCleanupAndLogErrors();
715
606
  this.state = {
716
607
  phase: 'stopping',
717
- stoppingDonePromise: new Promise((res) => {
718
- stoppingDone = res;
719
- }),
608
+ stoppingDonePromise,
720
609
  };
721
- await pollingDonePromise;
610
+ await stoppingDonePromise;
722
611
  this.state = { phase: 'stopped' };
723
- stoppingDone();
724
612
  return;
613
+ case 'updating schema': {
614
+ throw Error('`ApolloGateway.stop` shouldn\'t be called from inside a schema change listener');
725
615
  }
726
616
  default:
727
617
  throw new UnreachableCaseError(this.state);
728
618
  }
729
619
  }
620
+ __testing() {
621
+ return {
622
+ state: this.state,
623
+ compositionId: this.compositionId,
624
+ supergraphSdl: this.supergraphSdl,
625
+ };
626
+ }
730
627
  }
731
628
  exports.ApolloGateway = ApolloGateway;
732
629
  ApolloGateway.prototype.onSchemaChange = (0, util_1.deprecate)(ApolloGateway.prototype.onSchemaChange, `'ApolloGateway.prototype.onSchemaChange' is deprecated. Use 'ApolloGateway.prototype.onSchemaLoadOrUpdate' instead.`);