@apollo/gateway 2.0.0-alpha.0 → 2.0.0-alpha.4

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 (154) hide show
  1. package/README.md +1 -1
  2. package/dist/__generated__/graphqlTypes.d.ts +13 -11
  3. package/dist/__generated__/graphqlTypes.d.ts.map +1 -1
  4. package/dist/__generated__/graphqlTypes.js.map +1 -1
  5. package/dist/config.d.ts +45 -24
  6. package/dist/config.d.ts.map +1 -1
  7. package/dist/config.js +30 -31
  8. package/dist/config.js.map +1 -1
  9. package/dist/datasources/LocalGraphQLDataSource.js.map +1 -1
  10. package/dist/datasources/RemoteGraphQLDataSource.d.ts.map +1 -1
  11. package/dist/datasources/RemoteGraphQLDataSource.js +4 -1
  12. package/dist/datasources/RemoteGraphQLDataSource.js.map +1 -1
  13. package/dist/datasources/types.d.ts +1 -1
  14. package/dist/datasources/types.d.ts.map +1 -1
  15. package/dist/executeQueryPlan.d.ts.map +1 -1
  16. package/dist/executeQueryPlan.js +6 -6
  17. package/dist/executeQueryPlan.js.map +1 -1
  18. package/dist/index.d.ts +36 -23
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +197 -297
  21. package/dist/index.js.map +1 -1
  22. package/dist/operationContext.js +0 -1
  23. package/dist/operationContext.js.map +1 -1
  24. package/dist/schema-helper/addResolversToSchema.d.ts +4 -0
  25. package/dist/schema-helper/addResolversToSchema.d.ts.map +1 -0
  26. package/dist/schema-helper/addResolversToSchema.js +62 -0
  27. package/dist/schema-helper/addResolversToSchema.js.map +1 -0
  28. package/dist/schema-helper/error.d.ts +6 -0
  29. package/dist/schema-helper/error.d.ts.map +1 -0
  30. package/dist/schema-helper/error.js +14 -0
  31. package/dist/schema-helper/error.js.map +1 -0
  32. package/dist/schema-helper/index.d.ts +4 -0
  33. package/dist/schema-helper/index.d.ts.map +1 -0
  34. package/dist/schema-helper/index.js +16 -0
  35. package/dist/schema-helper/index.js.map +1 -0
  36. package/dist/schema-helper/resolverMap.d.ts +16 -0
  37. package/dist/schema-helper/resolverMap.d.ts.map +1 -0
  38. package/dist/schema-helper/resolverMap.js +3 -0
  39. package/dist/schema-helper/resolverMap.js.map +1 -0
  40. package/dist/supergraphManagers/IntrospectAndCompose/index.d.ts +31 -0
  41. package/dist/supergraphManagers/IntrospectAndCompose/index.d.ts.map +1 -0
  42. package/dist/supergraphManagers/IntrospectAndCompose/index.js +112 -0
  43. package/dist/supergraphManagers/IntrospectAndCompose/index.js.map +1 -0
  44. package/dist/supergraphManagers/IntrospectAndCompose/loadServicesFromRemoteEndpoint.d.ts +12 -0
  45. package/dist/supergraphManagers/IntrospectAndCompose/loadServicesFromRemoteEndpoint.d.ts.map +1 -0
  46. package/dist/{loadServicesFromRemoteEndpoint.js → supergraphManagers/IntrospectAndCompose/loadServicesFromRemoteEndpoint.js} +6 -6
  47. package/dist/supergraphManagers/IntrospectAndCompose/loadServicesFromRemoteEndpoint.js.map +1 -0
  48. package/dist/supergraphManagers/LegacyFetcher/index.d.ts +33 -0
  49. package/dist/supergraphManagers/LegacyFetcher/index.d.ts.map +1 -0
  50. package/dist/supergraphManagers/LegacyFetcher/index.js +149 -0
  51. package/dist/supergraphManagers/LegacyFetcher/index.js.map +1 -0
  52. package/dist/supergraphManagers/LocalCompose/index.d.ts +19 -0
  53. package/dist/supergraphManagers/LocalCompose/index.d.ts.map +1 -0
  54. package/dist/supergraphManagers/LocalCompose/index.js +55 -0
  55. package/dist/supergraphManagers/LocalCompose/index.js.map +1 -0
  56. package/dist/supergraphManagers/UplinkFetcher/index.d.ts +32 -0
  57. package/dist/supergraphManagers/UplinkFetcher/index.d.ts.map +1 -0
  58. package/dist/supergraphManagers/UplinkFetcher/index.js +96 -0
  59. package/dist/supergraphManagers/UplinkFetcher/index.js.map +1 -0
  60. package/dist/supergraphManagers/UplinkFetcher/loadSupergraphSdlFromStorage.d.ts +21 -0
  61. package/dist/supergraphManagers/UplinkFetcher/loadSupergraphSdlFromStorage.d.ts.map +1 -0
  62. package/dist/{loadSupergraphSdlFromStorage.js → supergraphManagers/UplinkFetcher/loadSupergraphSdlFromStorage.js} +41 -10
  63. package/dist/supergraphManagers/UplinkFetcher/loadSupergraphSdlFromStorage.js.map +1 -0
  64. package/dist/supergraphManagers/UplinkFetcher/outOfBandReporter.d.ts +13 -0
  65. package/dist/supergraphManagers/UplinkFetcher/outOfBandReporter.d.ts.map +1 -0
  66. package/dist/supergraphManagers/UplinkFetcher/outOfBandReporter.js +85 -0
  67. package/dist/supergraphManagers/UplinkFetcher/outOfBandReporter.js.map +1 -0
  68. package/dist/supergraphManagers/index.d.ts +5 -0
  69. package/dist/supergraphManagers/index.d.ts.map +1 -0
  70. package/dist/supergraphManagers/index.js +12 -0
  71. package/dist/supergraphManagers/index.js.map +1 -0
  72. package/dist/utilities/array.js +1 -1
  73. package/dist/utilities/array.js.map +1 -1
  74. package/dist/utilities/createHash.d.ts +2 -0
  75. package/dist/utilities/createHash.d.ts.map +1 -0
  76. package/dist/utilities/createHash.js +15 -0
  77. package/dist/utilities/createHash.js.map +1 -0
  78. package/dist/utilities/isNodeLike.d.ts +3 -0
  79. package/dist/utilities/isNodeLike.d.ts.map +1 -0
  80. package/dist/utilities/isNodeLike.js +8 -0
  81. package/dist/utilities/isNodeLike.js.map +1 -0
  82. package/package.json +9 -9
  83. package/src/__generated__/graphqlTypes.ts +13 -11
  84. package/src/__mocks__/make-fetch-happen-fetcher.ts +3 -1
  85. package/src/__tests__/buildQueryPlan.test.ts +1 -1
  86. package/src/__tests__/executeQueryPlan.test.ts +1171 -77
  87. package/src/__tests__/execution-utils.ts +5 -7
  88. package/src/__tests__/gateway/buildService.test.ts +3 -3
  89. package/src/__tests__/gateway/endToEnd.test.ts +1 -1
  90. package/src/__tests__/gateway/executor.test.ts +3 -1
  91. package/src/__tests__/gateway/lifecycle-hooks.test.ts +59 -121
  92. package/src/__tests__/gateway/opentelemetry.test.ts +8 -3
  93. package/src/__tests__/gateway/queryPlanCache.test.ts +25 -9
  94. package/src/__tests__/gateway/reporting.test.ts +42 -13
  95. package/src/__tests__/gateway/supergraphSdl.test.ts +397 -0
  96. package/src/__tests__/integration/aliases.test.ts +9 -3
  97. package/src/__tests__/integration/configuration.test.ts +140 -21
  98. package/src/__tests__/integration/logger.test.ts +2 -2
  99. package/src/__tests__/integration/networkRequests.test.ts +126 -149
  100. package/src/__tests__/integration/nockMocks.ts +57 -16
  101. package/src/__tests__/nockAssertions.ts +20 -0
  102. package/src/config.ts +153 -77
  103. package/src/core/__tests__/core.test.ts +6 -6
  104. package/src/datasources/LocalGraphQLDataSource.ts +1 -1
  105. package/src/datasources/RemoteGraphQLDataSource.ts +8 -2
  106. package/src/datasources/__tests__/LocalGraphQLDataSource.test.ts +1 -1
  107. package/src/datasources/__tests__/RemoteGraphQLDataSource.test.ts +4 -4
  108. package/src/datasources/types.ts +1 -1
  109. package/src/executeQueryPlan.ts +18 -9
  110. package/src/index.ts +323 -481
  111. package/src/make-fetch-happen.d.ts +1 -1
  112. package/src/operationContext.ts +2 -2
  113. package/src/schema-helper/addResolversToSchema.ts +83 -0
  114. package/src/schema-helper/error.ts +11 -0
  115. package/src/schema-helper/index.ts +3 -0
  116. package/src/schema-helper/resolverMap.ts +23 -0
  117. package/src/supergraphManagers/IntrospectAndCompose/__tests__/IntrospectAndCompose.test.ts +370 -0
  118. package/src/{__tests__ → supergraphManagers/IntrospectAndCompose/__tests__}/loadServicesFromRemoteEndpoint.test.ts +7 -7
  119. package/src/supergraphManagers/IntrospectAndCompose/__tests__/tsconfig.json +8 -0
  120. package/src/supergraphManagers/IntrospectAndCompose/index.ts +160 -0
  121. package/src/{loadServicesFromRemoteEndpoint.ts → supergraphManagers/IntrospectAndCompose/loadServicesFromRemoteEndpoint.ts} +7 -7
  122. package/src/supergraphManagers/LegacyFetcher/index.ts +226 -0
  123. package/src/supergraphManagers/LocalCompose/index.ts +79 -0
  124. package/src/supergraphManagers/UplinkFetcher/__tests__/loadSupergraphSdlFromStorage.test.ts +343 -0
  125. package/src/supergraphManagers/UplinkFetcher/__tests__/tsconfig.json +8 -0
  126. package/src/supergraphManagers/UplinkFetcher/index.ts +128 -0
  127. package/src/{loadSupergraphSdlFromStorage.ts → supergraphManagers/UplinkFetcher/loadSupergraphSdlFromStorage.ts} +63 -14
  128. package/src/supergraphManagers/UplinkFetcher/outOfBandReporter.ts +126 -0
  129. package/src/supergraphManagers/index.ts +4 -0
  130. package/src/utilities/__tests__/cleanErrorOfInaccessibleElements.test.ts +13 -10
  131. package/src/utilities/array.ts +1 -1
  132. package/src/utilities/createHash.ts +10 -0
  133. package/src/utilities/isNodeLike.ts +11 -0
  134. package/CHANGELOG.md +0 -452
  135. package/dist/legacyLoadServicesFromStorage.d.ts +0 -20
  136. package/dist/legacyLoadServicesFromStorage.d.ts.map +0 -1
  137. package/dist/legacyLoadServicesFromStorage.js +0 -62
  138. package/dist/legacyLoadServicesFromStorage.js.map +0 -1
  139. package/dist/loadServicesFromRemoteEndpoint.d.ts +0 -13
  140. package/dist/loadServicesFromRemoteEndpoint.d.ts.map +0 -1
  141. package/dist/loadServicesFromRemoteEndpoint.js.map +0 -1
  142. package/dist/loadSupergraphSdlFromStorage.d.ts +0 -12
  143. package/dist/loadSupergraphSdlFromStorage.d.ts.map +0 -1
  144. package/dist/loadSupergraphSdlFromStorage.js.map +0 -1
  145. package/dist/outOfBandReporter.d.ts +0 -15
  146. package/dist/outOfBandReporter.d.ts.map +0 -1
  147. package/dist/outOfBandReporter.js +0 -88
  148. package/dist/outOfBandReporter.js.map +0 -1
  149. package/src/__tests__/gateway/composedSdl.test.ts +0 -44
  150. package/src/__tests__/integration/legacyNetworkRequests.test.ts +0 -279
  151. package/src/__tests__/integration/legacyNockMocks.ts +0 -113
  152. package/src/__tests__/loadSupergraphSdlFromStorage.test.ts +0 -664
  153. package/src/legacyLoadServicesFromStorage.ts +0 -170
  154. package/src/outOfBandReporter.ts +0 -128
@@ -36,7 +36,7 @@ declare module 'make-fetch-happen' {
36
36
  }
37
37
 
38
38
  export interface CacheManager {
39
- delete(req: Request): Promise<Boolean>;
39
+ delete(req: Request): Promise<boolean>;
40
40
  put(req: Request, res: Response): Promise<Response>;
41
41
  match(req: Request): Promise<Response | undefined>;
42
42
  }
@@ -20,7 +20,7 @@ interface BuildOperationContextOptions {
20
20
  schema: GraphQLSchema;
21
21
  operationDocument: DocumentNode;
22
22
  operationName?: string;
23
- };
23
+ }
24
24
 
25
25
  export function buildOperationContext({
26
26
  schema,
@@ -28,7 +28,7 @@ export function buildOperationContext({
28
28
  operationName,
29
29
  }: BuildOperationContextOptions): OperationContext {
30
30
  let operation: OperationDefinitionNode | undefined;
31
- let operationCount: number = 0;
31
+ let operationCount = 0;
32
32
  const fragments: {
33
33
  [fragmentName: string]: FragmentDefinitionNode;
34
34
  } = Object.create(null);
@@ -0,0 +1,83 @@
1
+ import {
2
+ GraphQLSchema,
3
+ isObjectType,
4
+ GraphQLEnumType,
5
+ isAbstractType,
6
+ isScalarType,
7
+ isEnumType,
8
+ GraphQLEnumValueConfig,
9
+ } from 'graphql';
10
+
11
+ import { GraphQLResolverMap } from './resolverMap';
12
+
13
+ export function addResolversToSchema(
14
+ schema: GraphQLSchema,
15
+ resolvers: GraphQLResolverMap<any>
16
+ ) {
17
+ for (const [typeName, fieldConfigs] of Object.entries(resolvers)) {
18
+ const type = schema.getType(typeName);
19
+
20
+ if (isAbstractType(type)) {
21
+ for (const [fieldName, fieldConfig] of Object.entries(fieldConfigs)) {
22
+ if (fieldName.startsWith("__")) {
23
+ (type as any)[fieldName.substring(2)] = fieldConfig;
24
+ }
25
+ }
26
+ }
27
+
28
+ if (isScalarType(type)) {
29
+ for (const fn in fieldConfigs) {
30
+ (type as any)[fn] = (fieldConfigs as any)[fn];
31
+ }
32
+ }
33
+
34
+ if (isEnumType(type)) {
35
+ const values = type.getValues();
36
+ const newValues: { [key: string]: GraphQLEnumValueConfig } = {};
37
+ values.forEach(value => {
38
+ let newValue = (fieldConfigs as any)[value.name];
39
+ if (newValue === undefined) {
40
+ newValue = value.name;
41
+ }
42
+
43
+ newValues[value.name] = {
44
+ value: newValue,
45
+ deprecationReason: value.deprecationReason,
46
+ description: value.description,
47
+ astNode: value.astNode,
48
+ extensions: undefined
49
+ };
50
+ });
51
+
52
+ // In place updating hack to get around pulling in the full
53
+ // schema walking and immutable updating machinery from graphql-tools
54
+ Object.assign(
55
+ type,
56
+ new GraphQLEnumType({
57
+ ...type.toConfig(),
58
+ values: newValues
59
+ })
60
+ );
61
+ }
62
+
63
+ if (!isObjectType(type)) continue;
64
+
65
+ const fieldMap = type.getFields();
66
+
67
+ for (const [fieldName, fieldConfig] of Object.entries(fieldConfigs)) {
68
+ if (fieldName.startsWith("__")) {
69
+ (type as any)[fieldName.substring(2)] = fieldConfig;
70
+ continue;
71
+ }
72
+
73
+ const field = fieldMap[fieldName];
74
+ if (!field) continue;
75
+
76
+ if (typeof fieldConfig === "function") {
77
+ field.resolve = fieldConfig;
78
+ } else {
79
+ field.resolve = fieldConfig.resolve;
80
+ }
81
+ }
82
+ }
83
+ }
@@ -0,0 +1,11 @@
1
+ import { GraphQLError } from "graphql";
2
+
3
+ export class GraphQLSchemaValidationError extends Error {
4
+ constructor(public errors: ReadonlyArray<GraphQLError>) {
5
+ super();
6
+
7
+ this.name = this.constructor.name;
8
+ Error.captureStackTrace(this, this.constructor);
9
+ this.message = errors.map(error => error.message).join("\n\n");
10
+ }
11
+ }
@@ -0,0 +1,3 @@
1
+ export * from './resolverMap';
2
+ export * from './addResolversToSchema';
3
+ export * from './error';
@@ -0,0 +1,23 @@
1
+ import { GraphQLFieldResolver, GraphQLScalarType, DocumentNode } from 'graphql';
2
+
3
+ export interface GraphQLSchemaModule {
4
+ typeDefs: DocumentNode;
5
+ resolvers?: GraphQLResolverMap<any>;
6
+ }
7
+
8
+ // eslint-disable-next-line @typescript-eslint/ban-types
9
+ export interface GraphQLResolverMap<TContext = {}> {
10
+ [typeName: string]:
11
+ | {
12
+ [fieldName: string]:
13
+ | GraphQLFieldResolver<any, TContext>
14
+ | {
15
+ requires?: string;
16
+ resolve: GraphQLFieldResolver<any, TContext>;
17
+ };
18
+ }
19
+ | GraphQLScalarType
20
+ | {
21
+ [enumValue: string]: string | number;
22
+ };
23
+ }
@@ -0,0 +1,370 @@
1
+ import nock from 'nock';
2
+ import {
3
+ fixtures,
4
+ fixturesWithUpdate,
5
+ } from 'apollo-federation-integration-testsuite';
6
+ import { nockBeforeEach, nockAfterEach } from '../../../__tests__/nockAssertions';
7
+ import { RemoteGraphQLDataSource, ServiceEndpointDefinition } from '../../..';
8
+ import { IntrospectAndCompose } from '..';
9
+ import { mockAllServicesSdlQuerySuccess } from '../../../__tests__/integration/nockMocks';
10
+ import { getTestingSupergraphSdl, wait } from '../../../__tests__/execution-utils';
11
+ import resolvable from '@josephg/resolvable';
12
+ import { Logger } from 'apollo-server-types';
13
+
14
+ describe('IntrospectAndCompose', () => {
15
+ beforeEach(nockBeforeEach);
16
+ afterEach(nockAfterEach);
17
+
18
+ it('constructs', () => {
19
+ expect(
20
+ () =>
21
+ new IntrospectAndCompose({
22
+ subgraphs: fixtures,
23
+ }),
24
+ ).not.toThrow();
25
+ });
26
+
27
+ it('has an `initialize` property which is callable (simulating the gateway calling it)', async () => {
28
+ mockAllServicesSdlQuerySuccess();
29
+ const instance = new IntrospectAndCompose({ subgraphs: fixtures });
30
+ await expect(
31
+ instance.initialize({
32
+ update() {},
33
+ async healthCheck() {},
34
+ getDataSource({ url }) {
35
+ return new RemoteGraphQLDataSource({ url });
36
+ },
37
+ }),
38
+ ).resolves.toBeTruthy();
39
+ });
40
+
41
+ it('uses `GraphQLDataSource`s provided by the `buildService` function', async () => {
42
+ mockAllServicesSdlQuerySuccess();
43
+
44
+ const processSpies: jest.SpyInstance[] = [];
45
+ function getDataSourceSpy(definition: ServiceEndpointDefinition) {
46
+ const datasource = new RemoteGraphQLDataSource({
47
+ url: definition.url,
48
+ });
49
+ const processSpy = jest.spyOn(datasource, 'process');
50
+ processSpies.push(processSpy);
51
+ return datasource;
52
+ }
53
+
54
+ const instance = new IntrospectAndCompose({
55
+ subgraphs: fixtures,
56
+ });
57
+
58
+ await instance.initialize({
59
+ update() {},
60
+ async healthCheck() {},
61
+ getDataSource: getDataSourceSpy,
62
+ });
63
+
64
+ expect(processSpies.length).toBe(fixtures.length);
65
+ for (const processSpy of processSpies) {
66
+ expect(processSpy).toHaveBeenCalledTimes(1);
67
+ }
68
+ });
69
+
70
+ it('polls services when a `pollInterval` is set and stops when `cleanup` is called', async () => {
71
+ // This is mocked 4 times to include the initial load (followed by 3 polls)
72
+ // We need to alternate schemas, else the update will be ignored
73
+ mockAllServicesSdlQuerySuccess();
74
+ mockAllServicesSdlQuerySuccess(fixturesWithUpdate);
75
+ mockAllServicesSdlQuerySuccess();
76
+ mockAllServicesSdlQuerySuccess(fixturesWithUpdate);
77
+
78
+ const p1 = resolvable();
79
+ const p2 = resolvable();
80
+ const p3 = resolvable();
81
+
82
+ // `update` (below) is called each time we poll (and there's an update to
83
+ // the supergraph), so this is a reasonable hook into "when" the poll
84
+ // happens and drives this test cleanly with `Promise`s.
85
+ const updateSpy = jest
86
+ .fn()
87
+ .mockImplementationOnce(() => p1.resolve())
88
+ .mockImplementationOnce(() => p2.resolve())
89
+ .mockImplementationOnce(() => p3.resolve());
90
+
91
+ const instance = new IntrospectAndCompose({
92
+ subgraphs: fixtures,
93
+ pollIntervalInMs: 10,
94
+ });
95
+
96
+ const { cleanup } = await instance.initialize({
97
+ update(supergraphSdl) {
98
+ updateSpy(supergraphSdl);
99
+ },
100
+ async healthCheck() {},
101
+ getDataSource({ url }) {
102
+ return new RemoteGraphQLDataSource({ url });
103
+ },
104
+ });
105
+
106
+ await Promise.all([p1, p2, p3]);
107
+
108
+ expect(updateSpy).toHaveBeenCalledTimes(3);
109
+
110
+ // stop polling
111
+ await cleanup!();
112
+
113
+ expect(updateSpy).toHaveBeenCalledTimes(3);
114
+
115
+ // ensure we cancelled the timer
116
+ // @ts-ignore
117
+ expect(instance.timerRef).toBe(null);
118
+ });
119
+
120
+ // TODO: useFakeTimers (though I'm struggling to get this to work as expected)
121
+ it("doesn't call `update` when there's no change to the supergraph", async () => {
122
+ const fetcher =
123
+ jest.requireActual<typeof import('apollo-server-env')>(
124
+ 'apollo-server-env',
125
+ ).fetch;
126
+
127
+ // mock for initial load and a few polls against an unchanging schema
128
+ mockAllServicesSdlQuerySuccess();
129
+ mockAllServicesSdlQuerySuccess();
130
+ mockAllServicesSdlQuerySuccess();
131
+ mockAllServicesSdlQuerySuccess();
132
+
133
+ const instance = new IntrospectAndCompose({
134
+ subgraphs: fixtures,
135
+ pollIntervalInMs: 100,
136
+ });
137
+
138
+ const updateSpy = jest.fn();
139
+ const { cleanup } = await instance.initialize({
140
+ update(supergraphSdl) {
141
+ updateSpy(supergraphSdl);
142
+ },
143
+ async healthCheck() {},
144
+ getDataSource({ url }) {
145
+ return new RemoteGraphQLDataSource({
146
+ url,
147
+ fetcher,
148
+ });
149
+ },
150
+ });
151
+
152
+ // let the instance poll through all the active mocks
153
+ // wouldn't need to do this if I could get fakeTimers working as expected
154
+ while (nock.activeMocks().length > 0) {
155
+ await wait(0);
156
+ }
157
+
158
+ await cleanup!();
159
+
160
+ expect(updateSpy).not.toHaveBeenCalled();
161
+ });
162
+
163
+ it('issues subgraph health checks when enabled (and polling)', async () => {
164
+ mockAllServicesSdlQuerySuccess();
165
+ mockAllServicesSdlQuerySuccess(fixturesWithUpdate);
166
+
167
+ const healthCheckPromiseOnLoad = resolvable();
168
+ const healthCheckPromiseOnUpdate = resolvable();
169
+
170
+ const healthCheckSpy = jest
171
+ .fn()
172
+ .mockImplementationOnce(() => healthCheckPromiseOnLoad.resolve())
173
+ .mockImplementationOnce(() => healthCheckPromiseOnUpdate.resolve());
174
+
175
+ const instance = new IntrospectAndCompose({
176
+ subgraphs: fixtures,
177
+ pollIntervalInMs: 10,
178
+ subgraphHealthCheck: true,
179
+ });
180
+
181
+ const { cleanup } = await instance.initialize({
182
+ update() {},
183
+ async healthCheck(supergraphSdl) {
184
+ healthCheckSpy(supergraphSdl);
185
+ },
186
+ getDataSource({ url }) {
187
+ return new RemoteGraphQLDataSource({ url });
188
+ },
189
+ });
190
+
191
+ await Promise.all([
192
+ healthCheckPromiseOnLoad,
193
+ healthCheckPromiseOnUpdate,
194
+ ]);
195
+
196
+ expect(healthCheckSpy).toHaveBeenNthCalledWith(
197
+ 1,
198
+ getTestingSupergraphSdl(fixtures),
199
+ );
200
+ expect(healthCheckSpy).toHaveBeenNthCalledWith(
201
+ 2,
202
+ getTestingSupergraphSdl(fixturesWithUpdate),
203
+ );
204
+
205
+ // stop polling
206
+ await cleanup!();
207
+ });
208
+
209
+ describe('errors', () => {
210
+ it('logs an error when `update` function throws', async () => {
211
+ const errorLoggedPromise = resolvable();
212
+
213
+ const errorSpy = jest.fn(() => {
214
+ errorLoggedPromise.resolve();
215
+ });
216
+ const logger: Logger = {
217
+ error: errorSpy,
218
+ debug() {},
219
+ info() {},
220
+ warn() {},
221
+ };
222
+
223
+ // mock successful initial load
224
+ mockAllServicesSdlQuerySuccess();
225
+
226
+ // mock first update
227
+ mockAllServicesSdlQuerySuccess(fixturesWithUpdate);
228
+
229
+ const instance = new IntrospectAndCompose({
230
+ subgraphs: fixtures,
231
+ pollIntervalInMs: 1000,
232
+ logger,
233
+ });
234
+
235
+ const thrownErrorMessage = 'invalid supergraph';
236
+ // simulate gateway throwing an error when `update` is called
237
+ const updateSpy = jest.fn().mockImplementationOnce(() => {
238
+ throw new Error(thrownErrorMessage);
239
+ });
240
+
241
+ const { cleanup } = await instance.initialize({
242
+ update: updateSpy,
243
+ async healthCheck() {},
244
+ getDataSource({ url }) {
245
+ return new RemoteGraphQLDataSource({ url });
246
+ },
247
+ });
248
+
249
+ await errorLoggedPromise;
250
+ // stop polling
251
+ await cleanup!();
252
+
253
+ expect(updateSpy).toHaveBeenCalledTimes(1);
254
+ expect(logger.error).toHaveBeenCalledTimes(1);
255
+ expect(logger.error).toHaveBeenCalledWith(
256
+ `IntrospectAndCompose failed to update supergraph with the following error: ${thrownErrorMessage}`,
257
+ );
258
+ });
259
+
260
+ it('fails to load when `healthCheck` function throws on startup', async () => {
261
+ mockAllServicesSdlQuerySuccess();
262
+
263
+ const expectedErrorMsg = 'error reaching subgraph';
264
+ const errorLoggedPromise = resolvable();
265
+ const errorSpy = jest.fn(() => {
266
+ errorLoggedPromise.resolve();
267
+ });
268
+ const logger: Logger = {
269
+ error: errorSpy,
270
+ debug() {},
271
+ info() {},
272
+ warn() {},
273
+ };
274
+
275
+ const updateSpy = jest.fn();
276
+
277
+ const instance = new IntrospectAndCompose({
278
+ subgraphs: fixtures,
279
+ pollIntervalInMs: 10,
280
+ subgraphHealthCheck: true,
281
+ logger,
282
+ });
283
+
284
+ await expect(
285
+ instance.initialize({
286
+ update() {
287
+ updateSpy();
288
+ },
289
+ async healthCheck() {
290
+ throw new Error(expectedErrorMsg);
291
+ },
292
+ getDataSource({ url }) {
293
+ return new RemoteGraphQLDataSource({ url });
294
+ },
295
+ }),
296
+ ).rejects.toThrowErrorMatchingInlineSnapshot(`"error reaching subgraph"`);
297
+
298
+ await errorLoggedPromise;
299
+
300
+ expect(errorSpy).toHaveBeenCalledWith(
301
+ `IntrospectAndCompose failed to update supergraph with the following error: ${expectedErrorMsg}`,
302
+ );
303
+ expect(updateSpy).not.toHaveBeenCalled();
304
+ });
305
+
306
+ it('does not attempt to update when `healthCheck` function throws', async () => {
307
+ mockAllServicesSdlQuerySuccess();
308
+ mockAllServicesSdlQuerySuccess(fixturesWithUpdate);
309
+
310
+ const expectedErrorMsg = 'error reaching subgraph';
311
+ const errorLoggedPromise = resolvable();
312
+ const errorSpy = jest.fn(() => {
313
+ errorLoggedPromise.resolve();
314
+ });
315
+ const logger: Logger = {
316
+ error: errorSpy,
317
+ debug() {},
318
+ info() {},
319
+ warn() {},
320
+ };
321
+
322
+ const healthCheckPromiseOnLoad = resolvable();
323
+ const healthCheckPromiseOnUpdate = resolvable();
324
+ const healthCheckSpyWhichEventuallyThrows = jest
325
+ .fn()
326
+ .mockImplementationOnce(() => healthCheckPromiseOnLoad.resolve())
327
+ .mockImplementationOnce(() => {
328
+ healthCheckPromiseOnUpdate.resolve();
329
+ throw new Error(expectedErrorMsg);
330
+ });
331
+
332
+ const updateSpy = jest.fn();
333
+
334
+ const instance = new IntrospectAndCompose({
335
+ subgraphs: fixtures,
336
+ pollIntervalInMs: 10,
337
+ subgraphHealthCheck: true,
338
+ logger,
339
+ });
340
+
341
+ const { cleanup } = await instance.initialize({
342
+ update() {
343
+ updateSpy();
344
+ },
345
+ async healthCheck(supergraphSdl) {
346
+ healthCheckSpyWhichEventuallyThrows(supergraphSdl);
347
+ },
348
+ getDataSource({ url }) {
349
+ return new RemoteGraphQLDataSource({ url });
350
+ },
351
+ });
352
+
353
+ await Promise.all([
354
+ healthCheckPromiseOnLoad,
355
+ healthCheckPromiseOnUpdate,
356
+ errorLoggedPromise,
357
+ ]);
358
+
359
+ expect(errorSpy).toHaveBeenCalledWith(
360
+ `IntrospectAndCompose failed to update supergraph with the following error: ${expectedErrorMsg}`,
361
+ );
362
+ expect(healthCheckSpyWhichEventuallyThrows).toHaveBeenCalledTimes(2);
363
+ // update isn't called on load so this shouldn't be called even once
364
+ expect(updateSpy).not.toHaveBeenCalled();
365
+
366
+ // stop polling
367
+ await cleanup!();
368
+ });
369
+ });
370
+ });
@@ -1,13 +1,13 @@
1
- import { getServiceDefinitionsFromRemoteEndpoint } from '../loadServicesFromRemoteEndpoint';
2
- import { RemoteGraphQLDataSource } from '../datasources';
1
+ import { loadServicesFromRemoteEndpoint } from '../loadServicesFromRemoteEndpoint';
2
+ import { RemoteGraphQLDataSource } from '../../../datasources';
3
3
 
4
- describe('getServiceDefinitionsFromRemoteEndpoint', () => {
4
+ describe('loadServicesFromRemoteEndpoint', () => {
5
5
  it('errors when no URL was specified', async () => {
6
6
  const serviceSdlCache = new Map<string, string>();
7
7
  const dataSource = new RemoteGraphQLDataSource({ url: '' });
8
8
  const serviceList = [{ name: 'test', dataSource }];
9
9
  await expect(
10
- getServiceDefinitionsFromRemoteEndpoint({
10
+ loadServicesFromRemoteEndpoint({
11
11
  serviceList,
12
12
  serviceSdlCache,
13
13
  getServiceIntrospectionHeaders: async () => ({})
@@ -19,7 +19,7 @@ describe('getServiceDefinitionsFromRemoteEndpoint', () => {
19
19
 
20
20
  it('throws when the downstream service returns errors', async () => {
21
21
  const serviceSdlCache = new Map<string, string>();
22
- const host = 'http://host-which-better-not-resolve';
22
+ const host = 'http://host-which-better-not-resolve.invalid';
23
23
  const url = host + '/graphql';
24
24
 
25
25
  const dataSource = new RemoteGraphQLDataSource({ url });
@@ -28,13 +28,13 @@ describe('getServiceDefinitionsFromRemoteEndpoint', () => {
28
28
  // of `EAI_AGAIN` or `ENOTFOUND`. This `toThrowError` uses a Regex
29
29
  // to match either case.
30
30
  await expect(
31
- getServiceDefinitionsFromRemoteEndpoint({
31
+ loadServicesFromRemoteEndpoint({
32
32
  serviceList,
33
33
  serviceSdlCache,
34
34
  getServiceIntrospectionHeaders: async () => ({}),
35
35
  }),
36
36
  ).rejects.toThrowError(
37
- /^Couldn't load service definitions for "test" at http:\/\/host-which-better-not-resolve\/graphql: request to http:\/\/host-which-better-not-resolve\/graphql failed, reason: getaddrinfo (ENOTFOUND|EAI_AGAIN)/,
37
+ /^Couldn't load service definitions for "test" at http:\/\/host-which-better-not-resolve.invalid\/graphql: request to http:\/\/host-which-better-not-resolve.invalid\/graphql failed, reason: getaddrinfo (ENOTFOUND|EAI_AGAIN)/,
38
38
  );
39
39
  });
40
40
  });
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../../../tsconfig.test",
3
+ "include": ["**/*"],
4
+ "references": [
5
+ { "path": "../../../../" },
6
+ { "path": "../../../../../federation-integration-testsuite-js" },
7
+ ]
8
+ }