-
Notifications
You must be signed in to change notification settings - Fork 242
/
legacyNetworkRequests.test.ts
279 lines (240 loc) 路 8.25 KB
/
legacyNetworkRequests.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import nock from 'nock';
import { fetch } from 'apollo-server-env';
import { Logger } from 'apollo-server-types';
import { ApolloGateway, GCS_RETRY_COUNT, getDefaultFetcher } from '../..';
import {
mockServiceHealthCheckSuccess,
mockServiceHealthCheck,
mockStorageSecretSuccess,
mockStorageSecret,
mockCompositionConfigLinkSuccess,
mockCompositionConfigLink,
mockCompositionConfigsSuccess,
mockCompositionConfigs,
mockImplementingServicesSuccess,
mockImplementingServices,
mockRawPartialSchemaSuccess,
mockRawPartialSchema,
apiKeyHash,
graphId,
} from './legacyNockMocks';
export interface MockService {
gcsDefinitionPath: string;
partialSchemaPath: string;
url: string;
sdl: string;
}
const service: MockService = {
gcsDefinitionPath: 'service-definition.json',
partialSchemaPath: 'accounts-partial-schema.json',
url: 'http://localhost:4001',
sdl: `#graphql
extend type Query {
me: User
everyone: [User]
}
"This is my User"
type User @key(fields: "id") {
id: ID!
name: String
username: String
}
`,
};
const updatedService: MockService = {
gcsDefinitionPath: 'updated-service-definition.json',
partialSchemaPath: 'updated-accounts-partial-schema.json',
url: 'http://localhost:4002',
sdl: `#graphql
extend type Query {
me: User
everyone: [User]
}
"This is my updated User"
type User @key(fields: "id") {
id: ID!
name: String
username: String
}
`,
};
let fetcher: typeof fetch;
let logger: Logger;
let gateway: ApolloGateway | null = null;
beforeEach(() => {
if (!nock.isActive()) nock.activate();
fetcher = getDefaultFetcher().defaults({
retry: {
retries: GCS_RETRY_COUNT,
minTimeout: 0,
maxTimeout: 0,
},
});
const warn = jest.fn();
const debug = jest.fn();
const error = jest.fn();
const info = jest.fn();
logger = {
warn,
debug,
error,
info,
};
});
afterEach(async () => {
expect(nock.isDone()).toBeTruthy();
nock.cleanAll();
nock.restore();
if (gateway) {
await gateway.stop();
gateway = null;
}
});
it('Extracts service definitions from remote storage', async () => {
mockStorageSecretSuccess();
mockCompositionConfigLinkSuccess();
mockCompositionConfigsSuccess([service]);
mockImplementingServicesSuccess(service);
mockRawPartialSchemaSuccess(service);
gateway = new ApolloGateway({ logger, schemaConfigDeliveryEndpoint: null });
await gateway.load({
apollo: { keyHash: apiKeyHash, graphId, graphVariant: 'current' },
});
expect(gateway.schema!.getType('User')!.description).toBe('This is my User');
});
function failNTimes(n: number, fn: () => nock.Interceptor) {
for (let i = 0; i < n; i++) {
fn().reply(500);
}
}
it(`Retries GCS (up to ${GCS_RETRY_COUNT} times) on failure for each request and succeeds`, async () => {
failNTimes(GCS_RETRY_COUNT, mockStorageSecret);
mockStorageSecretSuccess();
failNTimes(GCS_RETRY_COUNT, mockCompositionConfigLink);
mockCompositionConfigLinkSuccess();
failNTimes(GCS_RETRY_COUNT, mockCompositionConfigs);
mockCompositionConfigsSuccess([service]);
failNTimes(GCS_RETRY_COUNT, () => mockImplementingServices(service));
mockImplementingServicesSuccess(service);
failNTimes(GCS_RETRY_COUNT, () => mockRawPartialSchema(service));
mockRawPartialSchemaSuccess(service);
gateway = new ApolloGateway({
fetcher,
logger,
schemaConfigDeliveryEndpoint: null,
});
await gateway.load({
apollo: { keyHash: apiKeyHash, graphId, graphVariant: 'current' },
});
expect(gateway.schema!.getType('User')!.description).toBe('This is my User');
});
describe('Managed mode', () => {
it('Performs health checks to downstream services on load', async () => {
mockStorageSecretSuccess();
mockCompositionConfigLinkSuccess();
mockCompositionConfigsSuccess([service]);
mockImplementingServicesSuccess(service);
mockRawPartialSchemaSuccess(service);
mockServiceHealthCheckSuccess(service);
gateway = new ApolloGateway({
serviceHealthCheck: true,
logger,
schemaConfigDeliveryEndpoint: null,
});
await gateway.load({
apollo: { keyHash: apiKeyHash, graphId, graphVariant: 'current' },
});
expect(gateway.schema!.getType('User')!.description).toBe(
'This is my User',
);
});
it('Rejects on initial load when health check fails', async () => {
mockStorageSecretSuccess();
mockCompositionConfigLinkSuccess();
mockCompositionConfigsSuccess([service]);
mockImplementingServicesSuccess(service);
mockRawPartialSchemaSuccess(service);
mockServiceHealthCheck(service).reply(500);
const gateway = new ApolloGateway({
serviceHealthCheck: true,
logger,
schemaConfigDeliveryEndpoint: null,
});
await expect(
gateway.load({
apollo: { keyHash: apiKeyHash, graphId, graphVariant: 'current' },
}),
).rejects.toThrowErrorMatchingInlineSnapshot(`
"The gateway did not update its schema due to failed service health checks. The gateway will continue to operate with the previous schema and reattempt updates. The following error occurred during the health check:
[accounts]: 500: Internal Server Error"
`);
});
it('Preserves original schema when health check fails', async () => {
mockStorageSecretSuccess();
mockCompositionConfigLinkSuccess();
mockCompositionConfigsSuccess([service]);
mockImplementingServicesSuccess(service);
mockRawPartialSchemaSuccess(service);
mockServiceHealthCheckSuccess(service);
// Update
mockStorageSecretSuccess();
mockCompositionConfigLinkSuccess();
mockCompositionConfigsSuccess([updatedService]);
mockImplementingServicesSuccess(updatedService);
mockRawPartialSchemaSuccess(updatedService);
mockServiceHealthCheck(updatedService).reply(500);
let resolve: () => void;
const schemaChangeBlocker = new Promise<void>((res) => (resolve = res));
gateway = new ApolloGateway({
serviceHealthCheck: true,
logger,
schemaConfigDeliveryEndpoint: null,
});
// @ts-ignore for testing purposes, a short pollInterval is ideal so we'll override here
gateway.experimental_pollInterval = 100;
// @ts-ignore for testing purposes, we'll call the original `updateSchema`
// function from our mock. The first call should mimic original behavior,
// but the second call needs to handle the PromiseRejection. Typically for tests
// like these we would leverage the `gateway.onSchemaChange` callback to drive
// the test, but in this case, that callback isn't triggered when the update
// fails (as expected) so we get creative with the second mock as seen below.
const original = gateway.updateSchema;
const mockUpdateSchema = jest
.fn()
.mockImplementationOnce(async () => {
await original.apply(gateway);
})
.mockImplementationOnce(async () => {
// mock the first poll and handle the error which would otherwise be caught
// and logged from within the `pollServices` class method
try {
await original.apply(gateway);
} catch (e) {
var err = e;
}
expect(err.message).toMatchInlineSnapshot(`
"The gateway did not update its schema due to failed service health checks. The gateway will continue to operate with the previous schema and reattempt updates. The following error occurred during the health check:
[accounts]: 500: Internal Server Error"
`);
// finally resolve the promise which drives this test
resolve();
});
// @ts-ignore for testing purposes, replace the `updateSchema`
// function on the gateway with our mock
gateway.updateSchema = mockUpdateSchema;
// load the gateway as usual
await gateway.load({
apollo: { keyHash: apiKeyHash, graphId, graphVariant: 'current' },
});
expect(gateway.schema!.getType('User')!.description).toBe(
'This is my User',
);
await schemaChangeBlocker;
// At this point, the mock update should have been called but the schema
// should not have updated to the new one.
expect(mockUpdateSchema.mock.calls.length).toBe(2);
expect(gateway.schema!.getType('User')!.description).toBe(
'This is my User',
);
});
});