@apollo/gateway 2.0.0-alpha.2 → 2.0.0-alpha.6

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 (130) hide show
  1. package/dist/config.d.ts +43 -15
  2. package/dist/config.d.ts.map +1 -1
  3. package/dist/config.js +28 -18
  4. package/dist/config.js.map +1 -1
  5. package/dist/datasources/LocalGraphQLDataSource.js.map +1 -1
  6. package/dist/datasources/RemoteGraphQLDataSource.d.ts.map +1 -1
  7. package/dist/datasources/RemoteGraphQLDataSource.js +4 -1
  8. package/dist/datasources/RemoteGraphQLDataSource.js.map +1 -1
  9. package/dist/executeQueryPlan.d.ts.map +1 -1
  10. package/dist/executeQueryPlan.js +2 -2
  11. package/dist/executeQueryPlan.js.map +1 -1
  12. package/dist/index.d.ts +37 -22
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +199 -283
  15. package/dist/index.js.map +1 -1
  16. package/dist/schema-helper/addResolversToSchema.d.ts +4 -0
  17. package/dist/schema-helper/addResolversToSchema.d.ts.map +1 -0
  18. package/dist/schema-helper/addResolversToSchema.js +62 -0
  19. package/dist/schema-helper/addResolversToSchema.js.map +1 -0
  20. package/dist/schema-helper/error.d.ts +6 -0
  21. package/dist/schema-helper/error.d.ts.map +1 -0
  22. package/dist/schema-helper/error.js +14 -0
  23. package/dist/schema-helper/error.js.map +1 -0
  24. package/dist/schema-helper/index.d.ts +4 -0
  25. package/dist/schema-helper/index.d.ts.map +1 -0
  26. package/dist/schema-helper/index.js +16 -0
  27. package/dist/schema-helper/index.js.map +1 -0
  28. package/dist/schema-helper/resolverMap.d.ts +16 -0
  29. package/dist/schema-helper/resolverMap.d.ts.map +1 -0
  30. package/dist/schema-helper/resolverMap.js +3 -0
  31. package/dist/schema-helper/resolverMap.js.map +1 -0
  32. package/dist/supergraphManagers/IntrospectAndCompose/index.d.ts +31 -0
  33. package/dist/supergraphManagers/IntrospectAndCompose/index.d.ts.map +1 -0
  34. package/dist/supergraphManagers/IntrospectAndCompose/index.js +112 -0
  35. package/dist/supergraphManagers/IntrospectAndCompose/index.js.map +1 -0
  36. package/dist/supergraphManagers/IntrospectAndCompose/loadServicesFromRemoteEndpoint.d.ts +12 -0
  37. package/dist/supergraphManagers/IntrospectAndCompose/loadServicesFromRemoteEndpoint.d.ts.map +1 -0
  38. package/dist/{loadServicesFromRemoteEndpoint.js → supergraphManagers/IntrospectAndCompose/loadServicesFromRemoteEndpoint.js} +6 -6
  39. package/dist/supergraphManagers/IntrospectAndCompose/loadServicesFromRemoteEndpoint.js.map +1 -0
  40. package/dist/supergraphManagers/LegacyFetcher/index.d.ts +33 -0
  41. package/dist/supergraphManagers/LegacyFetcher/index.d.ts.map +1 -0
  42. package/dist/supergraphManagers/LegacyFetcher/index.js +149 -0
  43. package/dist/supergraphManagers/LegacyFetcher/index.js.map +1 -0
  44. package/dist/supergraphManagers/LocalCompose/index.d.ts +19 -0
  45. package/dist/supergraphManagers/LocalCompose/index.d.ts.map +1 -0
  46. package/dist/supergraphManagers/LocalCompose/index.js +55 -0
  47. package/dist/supergraphManagers/LocalCompose/index.js.map +1 -0
  48. package/dist/supergraphManagers/UplinkFetcher/index.d.ts +33 -0
  49. package/dist/supergraphManagers/UplinkFetcher/index.d.ts.map +1 -0
  50. package/dist/supergraphManagers/UplinkFetcher/index.js +98 -0
  51. package/dist/supergraphManagers/UplinkFetcher/index.js.map +1 -0
  52. package/dist/supergraphManagers/UplinkFetcher/loadSupergraphSdlFromStorage.d.ts +25 -0
  53. package/dist/supergraphManagers/UplinkFetcher/loadSupergraphSdlFromStorage.d.ts.map +1 -0
  54. package/dist/{loadSupergraphSdlFromStorage.js → supergraphManagers/UplinkFetcher/loadSupergraphSdlFromStorage.js} +40 -15
  55. package/dist/supergraphManagers/UplinkFetcher/loadSupergraphSdlFromStorage.js.map +1 -0
  56. package/dist/supergraphManagers/UplinkFetcher/outOfBandReporter.d.ts +13 -0
  57. package/dist/supergraphManagers/UplinkFetcher/outOfBandReporter.d.ts.map +1 -0
  58. package/dist/supergraphManagers/UplinkFetcher/outOfBandReporter.js +85 -0
  59. package/dist/supergraphManagers/UplinkFetcher/outOfBandReporter.js.map +1 -0
  60. package/dist/supergraphManagers/index.d.ts +6 -0
  61. package/dist/supergraphManagers/index.d.ts.map +1 -0
  62. package/dist/supergraphManagers/index.js +14 -0
  63. package/dist/supergraphManagers/index.js.map +1 -0
  64. package/dist/utilities/createHash.d.ts +2 -0
  65. package/dist/utilities/createHash.d.ts.map +1 -0
  66. package/dist/utilities/createHash.js +15 -0
  67. package/dist/utilities/createHash.js.map +1 -0
  68. package/dist/utilities/isNodeLike.d.ts +3 -0
  69. package/dist/utilities/isNodeLike.d.ts.map +1 -0
  70. package/dist/utilities/isNodeLike.js +8 -0
  71. package/dist/utilities/isNodeLike.js.map +1 -0
  72. package/package.json +9 -7
  73. package/src/__mocks__/make-fetch-happen-fetcher.ts +3 -1
  74. package/src/__tests__/build-query-plan.feature +52 -0
  75. package/src/__tests__/executeQueryPlan.test.ts +599 -1
  76. package/src/__tests__/execution-utils.ts +3 -3
  77. package/src/__tests__/gateway/buildService.test.ts +3 -3
  78. package/src/__tests__/gateway/endToEnd.test.ts +1 -1
  79. package/src/__tests__/gateway/executor.test.ts +1 -1
  80. package/src/__tests__/gateway/lifecycle-hooks.test.ts +59 -125
  81. package/src/__tests__/gateway/opentelemetry.test.ts +8 -4
  82. package/src/__tests__/gateway/queryPlanCache.test.ts +25 -12
  83. package/src/__tests__/gateway/reporting.test.ts +42 -13
  84. package/src/__tests__/gateway/supergraphSdl.test.ts +397 -0
  85. package/src/__tests__/integration/aliases.test.ts +9 -4
  86. package/src/__tests__/integration/configuration.test.ts +146 -9
  87. package/src/__tests__/integration/logger.test.ts +1 -1
  88. package/src/__tests__/integration/networkRequests.test.ts +99 -147
  89. package/src/__tests__/integration/nockMocks.ts +30 -16
  90. package/src/__tests__/nockAssertions.ts +20 -0
  91. package/src/config.ts +149 -38
  92. package/src/datasources/LocalGraphQLDataSource.ts +1 -1
  93. package/src/datasources/RemoteGraphQLDataSource.ts +8 -2
  94. package/src/datasources/__tests__/LocalGraphQLDataSource.test.ts +1 -1
  95. package/src/datasources/__tests__/RemoteGraphQLDataSource.test.ts +4 -4
  96. package/src/executeQueryPlan.ts +14 -2
  97. package/src/index.ts +325 -452
  98. package/src/schema-helper/addResolversToSchema.ts +83 -0
  99. package/src/schema-helper/error.ts +11 -0
  100. package/src/schema-helper/index.ts +3 -0
  101. package/src/schema-helper/resolverMap.ts +23 -0
  102. package/src/supergraphManagers/IntrospectAndCompose/__tests__/IntrospectAndCompose.test.ts +370 -0
  103. package/src/{__tests__ → supergraphManagers/IntrospectAndCompose/__tests__}/loadServicesFromRemoteEndpoint.test.ts +5 -5
  104. package/src/supergraphManagers/IntrospectAndCompose/__tests__/tsconfig.json +8 -0
  105. package/src/supergraphManagers/IntrospectAndCompose/index.ts +160 -0
  106. package/src/{loadServicesFromRemoteEndpoint.ts → supergraphManagers/IntrospectAndCompose/loadServicesFromRemoteEndpoint.ts} +6 -6
  107. package/src/supergraphManagers/LegacyFetcher/index.ts +226 -0
  108. package/src/supergraphManagers/LocalCompose/index.ts +79 -0
  109. package/src/supergraphManagers/UplinkFetcher/__tests__/loadSupergraphSdlFromStorage.test.ts +397 -0
  110. package/src/supergraphManagers/UplinkFetcher/__tests__/tsconfig.json +8 -0
  111. package/src/supergraphManagers/UplinkFetcher/index.ts +130 -0
  112. package/src/{loadSupergraphSdlFromStorage.ts → supergraphManagers/UplinkFetcher/loadSupergraphSdlFromStorage.ts} +68 -17
  113. package/src/supergraphManagers/UplinkFetcher/outOfBandReporter.ts +126 -0
  114. package/src/supergraphManagers/index.ts +5 -0
  115. package/src/utilities/__tests__/cleanErrorOfInaccessibleElements.test.ts +12 -9
  116. package/src/utilities/createHash.ts +10 -0
  117. package/src/utilities/isNodeLike.ts +11 -0
  118. package/dist/loadServicesFromRemoteEndpoint.d.ts +0 -13
  119. package/dist/loadServicesFromRemoteEndpoint.d.ts.map +0 -1
  120. package/dist/loadServicesFromRemoteEndpoint.js.map +0 -1
  121. package/dist/loadSupergraphSdlFromStorage.d.ts +0 -13
  122. package/dist/loadSupergraphSdlFromStorage.d.ts.map +0 -1
  123. package/dist/loadSupergraphSdlFromStorage.js.map +0 -1
  124. package/dist/outOfBandReporter.d.ts +0 -15
  125. package/dist/outOfBandReporter.d.ts.map +0 -1
  126. package/dist/outOfBandReporter.js +0 -88
  127. package/dist/outOfBandReporter.js.map +0 -1
  128. package/src/__tests__/gateway/composedSdl.test.ts +0 -44
  129. package/src/__tests__/loadSupergraphSdlFromStorage.test.ts +0 -694
  130. package/src/outOfBandReporter.ts +0 -128
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ 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.UplinkFetcherError = 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");
@@ -22,7 +22,6 @@ const operationContext_1 = require("./operationContext");
22
22
  Object.defineProperty(exports, "buildOperationContext", { enumerable: true, get: function () { return operationContext_1.buildOperationContext; } });
23
23
  const executeQueryPlan_1 = require("./executeQueryPlan");
24
24
  Object.defineProperty(exports, "executeQueryPlan", { enumerable: true, get: function () { return executeQueryPlan_1.executeQueryPlan; } });
25
- const loadServicesFromRemoteEndpoint_1 = require("./loadServicesFromRemoteEndpoint");
26
25
  const types_1 = require("./datasources/types");
27
26
  const RemoteGraphQLDataSource_1 = require("./datasources/RemoteGraphQLDataSource");
28
27
  const values_1 = require("graphql/execution/values");
@@ -30,11 +29,13 @@ const make_fetch_happen_1 = __importDefault(require("make-fetch-happen"));
30
29
  const cache_1 = require("./cache");
31
30
  const query_planner_1 = require("@apollo/query-planner");
32
31
  const config_1 = require("./config");
33
- const loadSupergraphSdlFromStorage_1 = require("./loadSupergraphSdlFromStorage");
34
32
  const api_1 = require("@opentelemetry/api");
35
33
  const opentelemetry_1 = require("./utilities/opentelemetry");
34
+ const createHash_1 = require("./utilities/createHash");
35
+ const supergraphManagers_1 = require("./supergraphManagers");
36
+ Object.defineProperty(exports, "IntrospectAndCompose", { enumerable: true, get: function () { return supergraphManagers_1.IntrospectAndCompose; } });
37
+ Object.defineProperty(exports, "LocalCompose", { enumerable: true, get: function () { return supergraphManagers_1.LocalCompose; } });
36
38
  const federation_internals_1 = require("@apollo/federation-internals");
37
- const composition_1 = require("@apollo/composition");
38
39
  function getDefaultFetcher() {
39
40
  const { name, version } = require('../package.json');
40
41
  return make_fetch_happen_1.default.defaults({
@@ -58,13 +59,12 @@ exports.HEALTH_CHECK_QUERY = 'query __ApolloServiceHealthCheck__ { __typename }'
58
59
  exports.SERVICE_DEFINITION_QUERY = 'query __ApolloGetServiceDefinition__ { _service { sdl } }';
59
60
  class ApolloGateway {
60
61
  constructor(config) {
61
- var _a, _b;
62
+ var _a;
62
63
  this.serviceMap = Object.create(null);
63
64
  this.onSchemaChangeListeners = new Set();
64
65
  this.onSchemaLoadOrUpdateListeners = new Set();
65
- this.serviceDefinitions = [];
66
- this.serviceSdlCache = new Map();
67
66
  this.warnedStates = Object.create(null);
67
+ this.toDispose = [];
68
68
  this.executor = async (requestContext) => {
69
69
  const spanAttributes = requestContext.operationName
70
70
  ? { operationName: requestContext.operationName }
@@ -157,35 +157,12 @@ class ApolloGateway {
157
157
  this.fetcher = (config === null || config === void 0 ? void 0 : config.fetcher) || getDefaultFetcher();
158
158
  this.experimental_didResolveQueryPlan =
159
159
  config === null || config === void 0 ? void 0 : config.experimental_didResolveQueryPlan;
160
- this.experimental_didFailComposition =
161
- config === null || config === void 0 ? void 0 : config.experimental_didFailComposition;
162
- this.experimental_didUpdateComposition =
163
- config === null || config === void 0 ? void 0 : config.experimental_didUpdateComposition;
164
- this.experimental_pollInterval = config === null || config === void 0 ? void 0 : config.experimental_pollInterval;
165
- if ((0, config_1.isManagedConfig)(this.config)) {
166
- const envEndpoint = process.env.APOLLO_SCHEMA_CONFIG_DELIVERY_ENDPOINT;
167
- this.schemaConfigDeliveryEndpoint =
168
- (_b = (_a = this.config.schemaConfigDeliveryEndpoint) !== null && _a !== void 0 ? _a : envEndpoint) !== null && _b !== void 0 ? _b : 'https://uplink.api.apollographql.com/';
169
- }
170
- if ((0, config_1.isManuallyManagedConfig)(this.config)) {
171
- if ('experimental_updateSupergraphSdl' in this.config) {
172
- this.updateServiceDefinitions =
173
- this.config.experimental_updateSupergraphSdl;
174
- }
175
- else if ('experimental_updateServiceDefinitions' in this.config) {
176
- this.updateServiceDefinitions =
177
- this.config.experimental_updateServiceDefinitions;
178
- }
179
- else {
180
- throw Error('Programming error: unexpected manual configuration provided');
181
- }
182
- }
183
- else {
184
- this.updateServiceDefinitions = this.loadServiceDefinitions;
185
- }
186
- if ((0, config_1.isDynamicConfig)(this.config)) {
187
- this.issueDynamicWarningsIfApplicable();
188
- }
160
+ this.experimental_didUpdateSupergraph =
161
+ config === null || config === void 0 ? void 0 : config.experimental_didUpdateSupergraph;
162
+ this.pollIntervalInMs =
163
+ (_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;
164
+ this.issueConfigurationWarningsIfApplicable();
165
+ this.logger.debug('Gateway successfully initialized (but not yet loaded)');
189
166
  this.state = { phase: 'initialized' };
190
167
  }
191
168
  initLogger() {
@@ -207,18 +184,18 @@ class ApolloGateway {
207
184
  sizeCalculator: approximateObjectSize,
208
185
  });
209
186
  }
210
- issueDynamicWarningsIfApplicable() {
187
+ issueConfigurationWarningsIfApplicable() {
211
188
  if ((0, config_1.isManagedConfig)(this.config) &&
212
- this.config.experimental_pollInterval &&
213
- this.config.experimental_pollInterval < 10000) {
214
- this.experimental_pollInterval = 10000;
189
+ this.pollIntervalInMs &&
190
+ this.pollIntervalInMs < 10000) {
191
+ this.pollIntervalInMs = 10000;
215
192
  this.logger.warn('Polling Apollo services at a frequency of less than once per 10 ' +
216
193
  'seconds (10000) is disallowed. Instead, the minimum allowed ' +
217
194
  'pollInterval of 10000 will be used. Please reconfigure your ' +
218
- 'experimental_pollInterval accordingly. If this is problematic for ' +
195
+ '`pollIntervalInMs` accordingly. If this is problematic for ' +
219
196
  'your team, please contact support.');
220
197
  }
221
- if (this.config.experimental_pollInterval && (0, config_1.isRemoteConfig)(this.config)) {
198
+ if (this.pollIntervalInMs && (0, config_1.isServiceListConfig)(this.config)) {
222
199
  this.logger.warn('Polling running services is dangerous and not recommended in production. ' +
223
200
  'Polling should only be used against a registry. ' +
224
201
  'If you are polling running services, use with caution.');
@@ -231,8 +208,16 @@ class ApolloGateway {
231
208
  'function when both `experimental_updateSupergraphSdl` and experimental_updateServiceDefinitions` ' +
232
209
  'are provided.');
233
210
  }
211
+ if ('schemaConfigDeliveryEndpoint' in this.config) {
212
+ 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.');
213
+ }
214
+ if ('experimental_pollInterval' in this.config) {
215
+ 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.');
216
+ }
234
217
  }
235
218
  async load(options) {
219
+ var _a, _b, _c, _d;
220
+ this.logger.debug('Loading gateway...');
236
221
  if (this.state.phase !== 'initialized') {
237
222
  throw Error(`ApolloGateway.load called in surprising state ${this.state.phase}`);
238
223
  }
@@ -253,11 +238,72 @@ class ApolloGateway {
253
238
  : undefined,
254
239
  };
255
240
  }
256
- const unrefTimer = !!options && !options.apollo;
257
241
  this.maybeWarnOnConflictingConfig();
258
- (0, config_1.isStaticConfig)(this.config)
259
- ? this.loadStatic(this.config)
260
- : await this.loadDynamic(unrefTimer);
242
+ if ((0, config_1.isStaticSupergraphSdlConfig)(this.config)) {
243
+ const supergraphSdl = this.config.supergraphSdl;
244
+ await this.initializeSupergraphManager({
245
+ initialize: async () => {
246
+ return {
247
+ supergraphSdl,
248
+ };
249
+ },
250
+ });
251
+ }
252
+ else if ((0, config_1.isLocalConfig)(this.config)) {
253
+ await this.initializeSupergraphManager(new supergraphManagers_1.LocalCompose({
254
+ localServiceList: this.config.localServiceList,
255
+ logger: this.logger,
256
+ }));
257
+ }
258
+ else if ((0, config_1.isManuallyManagedSupergraphSdlGatewayConfig)(this.config)) {
259
+ const supergraphManager = typeof this.config.supergraphSdl === 'object'
260
+ ? this.config.supergraphSdl
261
+ : { initialize: this.config.supergraphSdl };
262
+ await this.initializeSupergraphManager(supergraphManager);
263
+ }
264
+ else if ('experimental_updateServiceDefinitions' in this.config ||
265
+ 'experimental_updateSupergraphSdl' in this.config) {
266
+ const updateServiceDefinitions = 'experimental_updateServiceDefinitions' in this.config
267
+ ? this.config.experimental_updateServiceDefinitions
268
+ : this.config.experimental_updateSupergraphSdl;
269
+ await this.initializeSupergraphManager(new supergraphManagers_1.LegacyFetcher({
270
+ logger: this.logger,
271
+ gatewayConfig: this.config,
272
+ updateServiceDefinitions,
273
+ pollIntervalInMs: this.pollIntervalInMs,
274
+ subgraphHealthCheck: this.config.serviceHealthCheck,
275
+ }));
276
+ }
277
+ else if ((0, config_1.isServiceListConfig)(this.config)) {
278
+ 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.');
279
+ await this.initializeSupergraphManager(new supergraphManagers_1.IntrospectAndCompose({
280
+ subgraphs: this.config.serviceList,
281
+ pollIntervalInMs: this.pollIntervalInMs,
282
+ logger: this.logger,
283
+ subgraphHealthCheck: this.config.serviceHealthCheck,
284
+ introspectionHeaders: this.config.introspectionHeaders,
285
+ }));
286
+ }
287
+ else {
288
+ const canUseManagedConfig = ((_a = this.apolloConfig) === null || _a === void 0 ? void 0 : _a.graphRef) && ((_b = this.apolloConfig) === null || _b === void 0 ? void 0 : _b.keyHash);
289
+ if (!canUseManagedConfig) {
290
+ throw new Error('When a manual configuration is not provided, gateway requires an Apollo ' +
291
+ 'configuration. See https://www.apollographql.com/docs/apollo-server/federation/managed-federation/ ' +
292
+ 'for more information. Manual configuration options include: ' +
293
+ '`serviceList`, `supergraphSdl`, and `experimental_updateServiceDefinitions`.');
294
+ }
295
+ const uplinkEndpoints = this.getUplinkEndpoints(this.config);
296
+ await this.initializeSupergraphManager(new supergraphManagers_1.UplinkFetcher({
297
+ graphRef: this.apolloConfig.graphRef,
298
+ apiKey: this.apolloConfig.key,
299
+ uplinkEndpoints,
300
+ maxRetries: (_c = this.config.uplinkMaxRetries) !== null && _c !== void 0 ? _c : uplinkEndpoints.length * 3 - 1,
301
+ subgraphHealthCheck: this.config.serviceHealthCheck,
302
+ fetcher: this.fetcher,
303
+ logger: this.logger,
304
+ pollIntervalInMs: (_d = this.pollIntervalInMs) !== null && _d !== void 0 ? _d : 10000,
305
+ }));
306
+ }
261
307
  const mode = (0, config_1.isManagedConfig)(this.config) ? 'managed' : 'unmanaged';
262
308
  this.logger.info(`Gateway successfully loaded schema.\n\t* Mode: ${mode}${this.apolloConfig && this.apolloConfig.graphRef
263
309
  ? `\n\t* Service: ${this.apolloConfig.graphRef}`
@@ -267,92 +313,97 @@ class ApolloGateway {
267
313
  executor: this.executor,
268
314
  };
269
315
  }
270
- loadStatic(config) {
271
- let schema;
272
- let supergraphSdl;
273
- try {
274
- ({ schema, supergraphSdl } = (0, config_1.isLocalConfig)(config)
275
- ? this.createSchemaFromServiceList(config.localServiceList)
276
- : this.createSchemaFromSupergraphSdl(config.supergraphSdl));
277
- this.supergraphSdl = supergraphSdl;
278
- this.updateWithSchemaAndNotify(schema, supergraphSdl, true);
279
- }
280
- catch (e) {
281
- this.state = { phase: 'failed to load' };
282
- throw e;
283
- }
284
- this.state = { phase: 'loaded' };
316
+ getUplinkEndpoints(config) {
317
+ var _a, _b, _c, _d;
318
+ const rawEndpointsString = process.env.APOLLO_SCHEMA_CONFIG_DELIVERY_ENDPOINT;
319
+ const envEndpoints = (_a = rawEndpointsString === null || rawEndpointsString === void 0 ? void 0 : rawEndpointsString.split(',')) !== null && _a !== void 0 ? _a : null;
320
+ return ((_d = (_c = (_b = config.uplinkEndpoints) !== null && _b !== void 0 ? _b : (config.schemaConfigDeliveryEndpoint
321
+ ? [config.schemaConfigDeliveryEndpoint]
322
+ : null)) !== null && _c !== void 0 ? _c : envEndpoints) !== null && _d !== void 0 ? _d : [
323
+ 'https://uplink.api.apollographql.com/',
324
+ 'https://aws.uplink.api.apollographql.com/',
325
+ ]);
285
326
  }
286
- async loadDynamic(unrefTimer) {
327
+ getIdForSupergraphSdl(supergraphSdl) {
328
+ return (0, createHash_1.createHash)('sha256').update(supergraphSdl).digest('hex');
329
+ }
330
+ async initializeSupergraphManager(supergraphManager) {
287
331
  try {
288
- await this.updateSchema();
332
+ const result = await supergraphManager.initialize({
333
+ update: this.externalSupergraphUpdateCallback.bind(this),
334
+ healthCheck: this.externalSubgraphHealthCheckCallback.bind(this),
335
+ getDataSource: this.externalGetDataSourceCallback.bind(this),
336
+ });
337
+ if (!(result === null || result === void 0 ? void 0 : result.supergraphSdl)) {
338
+ throw new Error('Provided `supergraphSdl` function did not return an object containing a `supergraphSdl` property');
339
+ }
340
+ if (result === null || result === void 0 ? void 0 : result.cleanup) {
341
+ if (typeof result.cleanup === 'function') {
342
+ this.toDispose.push(result.cleanup);
343
+ }
344
+ else {
345
+ this.logger.error('Provided `supergraphSdl` function returned an invalid `cleanup` property (must be a function)');
346
+ }
347
+ }
348
+ this.externalSupergraphUpdateCallback(result.supergraphSdl);
289
349
  }
290
350
  catch (e) {
291
351
  this.state = { phase: 'failed to load' };
352
+ await this.performCleanupAndLogErrors();
292
353
  throw e;
293
354
  }
294
355
  this.state = { phase: 'loaded' };
295
- if (this.shouldBeginPolling()) {
296
- this.pollServices(unrefTimer);
297
- }
298
- }
299
- shouldBeginPolling() {
300
- return (0, config_1.isManagedConfig)(this.config) || this.experimental_pollInterval;
301
356
  }
302
- async updateSchema() {
303
- this.logger.debug('Checking for composition updates...');
304
- const result = await this.updateServiceDefinitions(this.config);
305
- if ((0, config_1.isSupergraphSdlUpdate)(result)) {
306
- await this.updateWithSupergraphSdl(result);
357
+ externalSupergraphUpdateCallback(supergraphSdl) {
358
+ switch (this.state.phase) {
359
+ case 'failed to load':
360
+ throw new Error("Can't call `update` callback after gateway failed to load.");
361
+ case 'updating schema':
362
+ throw new Error("Can't call `update` callback while supergraph update is in progress.");
363
+ case 'stopped':
364
+ throw new Error("Can't call `update` callback after gateway has been stopped.");
365
+ case 'stopping':
366
+ throw new Error("Can't call `update` callback while gateway is stopping.");
367
+ case 'loaded':
368
+ case 'initialized':
369
+ break;
370
+ default:
371
+ throw new UnreachableCaseError(this.state);
307
372
  }
308
- else if ((0, config_1.isServiceDefinitionUpdate)(result)) {
309
- await this.updateByComposition(result);
373
+ this.state = { phase: 'updating schema' };
374
+ try {
375
+ this.updateWithSupergraphSdl({
376
+ supergraphSdl,
377
+ id: this.getIdForSupergraphSdl(supergraphSdl),
378
+ });
310
379
  }
311
- else {
312
- throw new Error('Programming error: unexpected result type from `updateServiceDefinitions`');
380
+ finally {
381
+ this.state = { phase: 'loaded' };
313
382
  }
314
383
  }
315
- async updateByComposition(result) {
316
- if (!result.serviceDefinitions ||
317
- JSON.stringify(this.serviceDefinitions) ===
318
- JSON.stringify(result.serviceDefinitions)) {
319
- this.logger.debug('No change in service definitions since last check.');
320
- return;
321
- }
322
- const previousSchema = this.schema;
323
- const previousServiceDefinitions = this.serviceDefinitions;
324
- const previousCompositionMetadata = this.compositionMetadata;
325
- if (previousSchema) {
326
- this.logger.info('New service definitions were found.');
327
- }
328
- await this.maybePerformServiceHealthCheck(result);
329
- this.compositionMetadata = result.compositionMetadata;
330
- this.serviceDefinitions = result.serviceDefinitions;
331
- const { schema, supergraphSdl } = this.createSchemaFromServiceList(result.serviceDefinitions);
332
- if (!supergraphSdl) {
333
- this.logger.error("A valid schema couldn't be composed. Falling back to previous schema.");
384
+ async externalSubgraphHealthCheckCallback(supergraphSdl) {
385
+ const serviceList = this.serviceListFromSupergraphSdl(supergraphSdl);
386
+ const serviceMap = serviceList.reduce((serviceMap, serviceDef) => {
387
+ serviceMap[serviceDef.name] = {
388
+ url: serviceDef.url,
389
+ dataSource: this.createDataSource(serviceDef),
390
+ };
391
+ return serviceMap;
392
+ }, Object.create(null));
393
+ try {
394
+ await this.serviceHealthCheck(serviceMap);
334
395
  }
335
- else {
336
- this.updateWithSchemaAndNotify(schema, supergraphSdl);
337
- if (this.experimental_didUpdateComposition) {
338
- this.experimental_didUpdateComposition({
339
- serviceDefinitions: result.serviceDefinitions,
340
- schema: schema.toGraphQLJSSchema(),
341
- ...(this.compositionMetadata && {
342
- compositionMetadata: this.compositionMetadata,
343
- }),
344
- }, previousServiceDefinitions &&
345
- previousSchema && {
346
- serviceDefinitions: previousServiceDefinitions,
347
- schema: previousSchema,
348
- ...(previousCompositionMetadata && {
349
- compositionMetadata: previousCompositionMetadata,
350
- }),
351
- });
352
- }
396
+ catch (e) {
397
+ throw new Error('The gateway subgraphs health check failed. Updating to the provided ' +
398
+ '`supergraphSdl` will likely result in future request failures to ' +
399
+ 'subgraphs. The following error occurred during the health check:\n' +
400
+ e.message);
353
401
  }
354
402
  }
355
- async updateWithSupergraphSdl(result) {
403
+ externalGetDataSourceCallback({ name, url, }) {
404
+ return this.getOrCreateDataSource({ name, url });
405
+ }
406
+ updateWithSupergraphSdl(result) {
356
407
  if (result.id === this.compositionId) {
357
408
  this.logger.debug('No change in composition since last check.');
358
409
  return;
@@ -364,18 +415,17 @@ class ApolloGateway {
364
415
  if (previousSchema) {
365
416
  this.logger.info('Updated Supergraph SDL was found.');
366
417
  }
367
- await this.maybePerformServiceHealthCheck(result);
368
418
  this.compositionId = result.id;
369
- this.supergraphSdl = result.supergraphSdl;
419
+ this.supergraphSdl = supergraphSdl;
370
420
  if (!supergraphSdl) {
371
421
  this.logger.error("A valid schema couldn't be composed. Falling back to previous schema.");
372
422
  }
373
423
  else {
374
424
  this.updateWithSchemaAndNotify(schema, supergraphSdl);
375
- if (this.experimental_didUpdateComposition) {
376
- this.experimental_didUpdateComposition({
425
+ if (this.experimental_didUpdateSupergraph) {
426
+ this.experimental_didUpdateSupergraph({
377
427
  compositionId: result.id,
378
- supergraphSdl: result.supergraphSdl,
428
+ supergraphSdl,
379
429
  schema: schema.toGraphQLJSSchema(),
380
430
  }, previousCompositionId && previousSupergraphSdl && previousSchema
381
431
  ? {
@@ -419,31 +469,6 @@ class ApolloGateway {
419
469
  }
420
470
  });
421
471
  }
422
- async maybePerformServiceHealthCheck(update) {
423
- if (this.config.serviceHealthCheck) {
424
- const serviceList = (0, config_1.isSupergraphSdlUpdate)(update)
425
- ?
426
- this.serviceListFromSupergraphSdl(update.supergraphSdl)
427
- :
428
- update.serviceDefinitions;
429
- const serviceMap = serviceList.reduce((serviceMap, serviceDef) => {
430
- serviceMap[serviceDef.name] = {
431
- url: serviceDef.url,
432
- dataSource: this.createDataSource(serviceDef),
433
- };
434
- return serviceMap;
435
- }, Object.create(null));
436
- try {
437
- await this.serviceHealthCheck(serviceMap);
438
- }
439
- catch (e) {
440
- throw new Error('The gateway did not update its schema due to failed service health checks. ' +
441
- 'The gateway will continue to operate with the previous schema and reattempt updates. ' +
442
- 'The following error occurred during the health check:\n' +
443
- e.message);
444
- }
445
- }
446
- }
447
472
  serviceHealthCheck(serviceMap = this.serviceMap) {
448
473
  return Promise.all(Object.entries(serviceMap).map(([name, { dataSource }]) => dataSource
449
474
  .process({
@@ -456,34 +481,6 @@ class ApolloGateway {
456
481
  throw new Error(`[${name}]: ${e.message}`);
457
482
  })));
458
483
  }
459
- createSchemaFromServiceList(serviceList) {
460
- this.logger.debug(`Composing schema from service list: \n${serviceList
461
- .map(({ name, url }) => ` ${url || 'local'}: ${name}`)
462
- .join('\n')}`);
463
- const compositionResult = (0, composition_1.composeServices)(serviceList);
464
- const errors = compositionResult.errors;
465
- if (errors) {
466
- if (this.experimental_didFailComposition) {
467
- this.experimental_didFailComposition({
468
- errors,
469
- serviceList,
470
- ...(this.compositionMetadata && {
471
- compositionMetadata: this.compositionMetadata,
472
- }),
473
- });
474
- }
475
- throw Error("A valid schema couldn't be composed. The following composition errors were found:\n" +
476
- errors.map((e) => '\t' + e.message).join('\n'));
477
- }
478
- else {
479
- this.createServices(serviceList);
480
- this.logger.debug('Schema loaded and ready for execution');
481
- return {
482
- schema: compositionResult.schema,
483
- supergraphSdl: compositionResult.supergraphSdl,
484
- };
485
- }
486
- }
487
484
  serviceListFromSupergraphSdl(supergraphSdl) {
488
485
  return (0, federation_internals_1.buildSupergraphSchema)(supergraphSdl)[1];
489
486
  }
@@ -507,63 +504,11 @@ class ApolloGateway {
507
504
  this.onSchemaLoadOrUpdateListeners.delete(callback);
508
505
  };
509
506
  }
510
- async pollServices(unrefTimer) {
511
- switch (this.state.phase) {
512
- case 'stopping':
513
- case 'stopped':
514
- case 'failed to load':
515
- return;
516
- case 'initialized':
517
- throw Error('pollServices should not be called before load!');
518
- case 'polling':
519
- throw Error('pollServices should not be called while in the middle of polling!');
520
- case 'waiting to poll':
521
- throw Error('pollServices should not be called while already waiting to poll!');
522
- case 'loaded':
523
- break;
524
- default:
525
- throw new UnreachableCaseError(this.state);
526
- }
527
- await new Promise((doneWaiting) => {
528
- this.state = {
529
- phase: 'waiting to poll',
530
- doneWaiting,
531
- pollWaitTimer: setTimeout(() => {
532
- if (this.state.phase == 'waiting to poll') {
533
- this.state.doneWaiting();
534
- }
535
- }, this.experimental_pollInterval || 10000),
536
- };
537
- if (unrefTimer) {
538
- this.state.pollWaitTimer.unref();
539
- }
540
- });
541
- if (this.state.phase !== 'waiting to poll') {
542
- return;
543
- }
544
- let pollingDone;
545
- this.state = {
546
- phase: 'polling',
547
- pollingDonePromise: new Promise((res) => {
548
- pollingDone = res;
549
- }),
550
- };
551
- try {
552
- await this.updateSchema();
553
- }
554
- catch (err) {
555
- this.logger.error((err && err.message) || err);
556
- }
557
- if (this.state.phase === 'polling') {
558
- this.state = { phase: 'loaded' };
559
- setImmediate(() => this.pollServices(unrefTimer));
560
- }
561
- pollingDone();
562
- }
563
- createAndCacheDataSource(serviceDef) {
507
+ getOrCreateDataSource(serviceDef) {
564
508
  if (this.serviceMap[serviceDef.name] &&
565
- serviceDef.url === this.serviceMap[serviceDef.name].url)
509
+ serviceDef.url === this.serviceMap[serviceDef.name].url) {
566
510
  return this.serviceMap[serviceDef.name].dataSource;
511
+ }
567
512
  const dataSource = this.createDataSource(serviceDef);
568
513
  this.serviceMap[serviceDef.name] = { url: serviceDef.url, dataSource };
569
514
  return dataSource;
@@ -580,44 +525,8 @@ class ApolloGateway {
580
525
  }
581
526
  createServices(services) {
582
527
  for (const serviceDef of services) {
583
- this.createAndCacheDataSource(serviceDef);
584
- }
585
- }
586
- async loadServiceDefinitions(config) {
587
- var _a, _b, _c;
588
- if ((0, config_1.isRemoteConfig)(config)) {
589
- const serviceList = config.serviceList.map((serviceDefinition) => ({
590
- ...serviceDefinition,
591
- dataSource: this.createAndCacheDataSource(serviceDefinition),
592
- }));
593
- return (0, loadServicesFromRemoteEndpoint_1.getServiceDefinitionsFromRemoteEndpoint)({
594
- serviceList,
595
- async getServiceIntrospectionHeaders(service) {
596
- return typeof config.introspectionHeaders === 'function'
597
- ? await config.introspectionHeaders(service)
598
- : config.introspectionHeaders;
599
- },
600
- serviceSdlCache: this.serviceSdlCache,
601
- });
528
+ this.getOrCreateDataSource(serviceDef);
602
529
  }
603
- const canUseManagedConfig = ((_a = this.apolloConfig) === null || _a === void 0 ? void 0 : _a.graphRef) && ((_b = this.apolloConfig) === null || _b === void 0 ? void 0 : _b.keyHash);
604
- if (!canUseManagedConfig) {
605
- throw new Error('When a manual configuration is not provided, gateway requires an Apollo ' +
606
- 'configuration. See https://www.apollographql.com/docs/apollo-server/federation/managed-federation/ ' +
607
- 'for more information. Manual configuration options include: ' +
608
- '`serviceList`, `supergraphSdl`, and `experimental_updateServiceDefinitions`.');
609
- }
610
- const result = await (0, loadSupergraphSdlFromStorage_1.loadSupergraphSdlFromStorage)({
611
- graphRef: this.apolloConfig.graphRef,
612
- apiKey: this.apolloConfig.key,
613
- endpoint: this.schemaConfigDeliveryEndpoint,
614
- fetcher: this.fetcher,
615
- compositionId: (_c = this.compositionId) !== null && _c !== void 0 ? _c : null,
616
- });
617
- return (result !== null && result !== void 0 ? result : {
618
- id: this.compositionId,
619
- supergraphSdl: this.supergraphSdl,
620
- });
621
530
  }
622
531
  maybeWarnOnConflictingConfig() {
623
532
  var _a, _b;
@@ -653,6 +562,16 @@ class ApolloGateway {
653
562
  }
654
563
  });
655
564
  }
565
+ async performCleanupAndLogErrors() {
566
+ if (this.toDispose.length === 0)
567
+ return;
568
+ await Promise.all(this.toDispose.map((p) => p().catch((e) => {
569
+ var _a;
570
+ this.logger.error('Error occured while calling user provided `cleanup` function: ' +
571
+ ((_a = e.message) !== null && _a !== void 0 ? _a : e));
572
+ })));
573
+ this.toDispose = [];
574
+ }
656
575
  async stop() {
657
576
  switch (this.state.phase) {
658
577
  case 'initialized':
@@ -667,33 +586,28 @@ class ApolloGateway {
667
586
  }
668
587
  return;
669
588
  case 'loaded':
670
- this.state = { phase: 'stopped' };
671
- return;
672
- case 'waiting to poll': {
673
- const doneWaiting = this.state.doneWaiting;
674
- clearTimeout(this.state.pollWaitTimer);
675
- this.state = { phase: 'stopped' };
676
- doneWaiting();
677
- return;
678
- }
679
- case 'polling': {
680
- const pollingDonePromise = this.state.pollingDonePromise;
681
- let stoppingDone;
589
+ const stoppingDonePromise = this.performCleanupAndLogErrors();
682
590
  this.state = {
683
591
  phase: 'stopping',
684
- stoppingDonePromise: new Promise((res) => {
685
- stoppingDone = res;
686
- }),
592
+ stoppingDonePromise,
687
593
  };
688
- await pollingDonePromise;
594
+ await stoppingDonePromise;
689
595
  this.state = { phase: 'stopped' };
690
- stoppingDone();
691
596
  return;
597
+ case 'updating schema': {
598
+ throw Error("`ApolloGateway.stop` shouldn't be called from inside a schema change listener");
692
599
  }
693
600
  default:
694
601
  throw new UnreachableCaseError(this.state);
695
602
  }
696
603
  }
604
+ __testing() {
605
+ return {
606
+ state: this.state,
607
+ compositionId: this.compositionId,
608
+ supergraphSdl: this.supergraphSdl,
609
+ };
610
+ }
697
611
  }
698
612
  exports.ApolloGateway = ApolloGateway;
699
613
  ApolloGateway.prototype.onSchemaChange = (0, util_1.deprecate)(ApolloGateway.prototype.onSchemaChange, `'ApolloGateway.prototype.onSchemaChange' is deprecated. Use 'ApolloGateway.prototype.onSchemaLoadOrUpdate' instead.`);
@@ -720,4 +634,6 @@ class UnreachableCaseError extends Error {
720
634
  }
721
635
  }
722
636
  __exportStar(require("./datasources"), exports);
637
+ var supergraphManagers_2 = require("./supergraphManagers");
638
+ Object.defineProperty(exports, "UplinkFetcherError", { enumerable: true, get: function () { return supergraphManagers_2.UplinkFetcherError; } });
723
639
  //# sourceMappingURL=index.js.map