-
Notifications
You must be signed in to change notification settings - Fork 257
/
Copy pathindex.ts
329 lines (292 loc) · 10.4 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import * as makeFetchHappen from 'make-fetch-happen';
import type { Logger } from '@apollo/utils.logger';
import type { Fetcher } from '@apollo/utils.fetcher';
import resolvable, { Resolvable } from '@josephg/resolvable';
import { SupergraphManager, SupergraphSdlHookOptions } from '../../config';
import {
SubgraphHealthCheckFunction,
SupergraphSdlUpdateFunction,
} from '../..';
import { getDefaultLogger } from '../../logger';
import { loadSupergraphSdlFromUplinks } from './loadSupergraphSdlFromStorage';
export type FailureToFetchSupergraphSdlFunctionParams = {
error: Error;
graphRef: string;
logger: Logger;
fetchCount: number;
};
export type FailureToFetchSupergraphSdlDuringInit = ({
error,
graphRef,
logger,
fetchCount,
}: FailureToFetchSupergraphSdlFunctionParams) => Promise<string>;
export type FailureToFetchSupergraphSdlAfterInit = ({
error,
graphRef,
logger,
fetchCount,
mostRecentSuccessfulFetchAt,
}:
| FailureToFetchSupergraphSdlFunctionParams & {
mostRecentSuccessfulFetchAt?: Date;
}) => Promise<string | null>;
type State =
| { phase: 'constructed' }
| { phase: 'initialized' }
| {
phase: 'polling';
pollingPromise?: Promise<void>;
nextFetchPromise?: Resolvable<void>;
}
| { phase: 'stopped' };
export class UplinkSupergraphManager implements SupergraphManager {
public static readonly DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
public static readonly MIN_POLL_INTERVAL_MS = 10_000;
public static readonly DEFAULT_UPLINK_ENDPOINTS = [
'https://uplink.api.apollographql.com/',
'https://aws.uplink.api.apollographql.com/',
];
public readonly uplinkEndpoints: string[] =
UplinkSupergraphManager.getUplinkEndpoints();
private apiKey: string;
private graphRef: string;
private fetcher: Fetcher = makeFetchHappen.defaults();
private maxRetries: number;
private requestTimeoutMs: number =
UplinkSupergraphManager.DEFAULT_REQUEST_TIMEOUT_MS;
private initialMaxRetries: number;
private pollIntervalMs: number = UplinkSupergraphManager.MIN_POLL_INTERVAL_MS;
private fallbackPollIntervalInMs?: number;
private logger: Logger;
private update?: SupergraphSdlUpdateFunction;
private shouldRunSubgraphHealthcheck: boolean = false;
private healthCheck?: SubgraphHealthCheckFunction;
private onFailureToFetchSupergraphSdlDuringInit?: FailureToFetchSupergraphSdlDuringInit;
private onFailureToFetchSupergraphSdlAfterInit?: FailureToFetchSupergraphSdlAfterInit;
private timerRef: NodeJS.Timeout | null = null;
private state: State;
private compositionId?: string;
private fetchCount: number = 0;
private mostRecentSuccessfulFetchAt?: Date;
constructor({
apiKey,
graphRef,
debug,
logger,
uplinkEndpoints,
fallbackPollIntervalInMs,
maxRetries,
initialMaxRetries,
fetcher,
shouldRunSubgraphHealthcheck,
onFailureToFetchSupergraphSdlDuringInit,
onFailureToFetchSupergraphSdlAfterInit,
}: {
apiKey: string;
graphRef: string;
debug?: boolean;
logger?: Logger;
uplinkEndpoints?: string[];
fallbackPollIntervalInMs?: number;
maxRetries?: number;
initialMaxRetries?: number;
fetcher?: Fetcher;
shouldRunSubgraphHealthcheck?: boolean;
onFailureToFetchSupergraphSdlDuringInit?: FailureToFetchSupergraphSdlDuringInit;
onFailureToFetchSupergraphSdlAfterInit?: FailureToFetchSupergraphSdlAfterInit;
}) {
this.apiKey = apiKey;
this.graphRef = graphRef;
this.logger = logger ?? getDefaultLogger(debug);
this.uplinkEndpoints = uplinkEndpoints ?? this.uplinkEndpoints;
// If the user didn't pass a `maxRetries`, default to trying each endpoint
// 3 times (minus 1 for the initial request) since we round-robin through
// each URL on failure
this.maxRetries = maxRetries ?? this.uplinkEndpoints.length * 3 - 1;
this.initialMaxRetries = initialMaxRetries ?? this.maxRetries;
this.pollIntervalMs = fallbackPollIntervalInMs ?? this.pollIntervalMs;
this.fallbackPollIntervalInMs = fallbackPollIntervalInMs;
if (this.pollIntervalMs < UplinkSupergraphManager.MIN_POLL_INTERVAL_MS) {
this.logger.warn(
'Polling Apollo services at a frequency of less than once per 10 seconds (10000) is disallowed. Instead, the minimum allowed pollInterval of 10000 will be used. Please reconfigure your `fallbackPollIntervalInMs` accordingly. If this is problematic for your team, please contact support.',
);
this.pollIntervalMs = UplinkSupergraphManager.MIN_POLL_INTERVAL_MS;
}
this.fetcher = fetcher ?? this.fetcher;
this.shouldRunSubgraphHealthcheck =
shouldRunSubgraphHealthcheck ?? this.shouldRunSubgraphHealthcheck;
this.onFailureToFetchSupergraphSdlDuringInit =
onFailureToFetchSupergraphSdlDuringInit;
this.onFailureToFetchSupergraphSdlAfterInit =
onFailureToFetchSupergraphSdlAfterInit;
if (!!process.env.APOLLO_OUT_OF_BAND_REPORTER_ENDPOINT) {
this.logger.warn('Out-of-band error reporting is no longer used by Apollo. You may remove the `APOLLO_OUT_OF_BAND_REPORTER_ENDPOINT` environment variable at your convenience.');
}
this.state = { phase: 'constructed' };
}
public async initialize({ update, healthCheck }: SupergraphSdlHookOptions) {
this.update = update;
if (this.shouldRunSubgraphHealthcheck) {
this.healthCheck = healthCheck;
}
let initialSupergraphSdl: string | null = null;
try {
initialSupergraphSdl = await this.updateSupergraphSdl(
this.initialMaxRetries,
);
if (!initialSupergraphSdl) {
throw new Error(
'Invalid supergraph schema supplied during initialization.',
);
}
} catch (e) {
this.logUpdateFailure(e);
throw e;
}
this.state = { phase: 'initialized' };
// Start polling after we resolve the first supergraph
this.beginPolling();
return {
supergraphSdl: initialSupergraphSdl,
cleanup: async () => {
if (this.state.phase === 'polling') {
await this.state.pollingPromise;
}
this.state = { phase: 'stopped' };
if (this.timerRef) {
clearTimeout(this.timerRef);
this.timerRef = null;
}
},
};
}
public async nextFetch(): Promise<void | null> {
if (this.state.phase !== 'polling') {
return;
}
return this.state.nextFetchPromise;
}
/**
* Configuration priority order:
* 1. APOLLO_SCHEMA_CONFIG_DELIVERY_ENDPOINT environment variable
* 2. default (GCP and AWS)
*/
public static getUplinkEndpoints(): string[] {
const envEndpoints =
process.env.APOLLO_SCHEMA_CONFIG_DELIVERY_ENDPOINT?.split(',');
return envEndpoints ?? UplinkSupergraphManager.DEFAULT_UPLINK_ENDPOINTS;
}
private async updateSupergraphSdl(
maxRetries: number,
): Promise<string | null> {
let supergraphSdl;
try {
const result = await loadSupergraphSdlFromUplinks({
graphRef: this.graphRef,
apiKey: this.apiKey,
endpoints: this.uplinkEndpoints,
fetcher: this.fetcher,
compositionId: this.compositionId ?? null,
maxRetries,
requestTimeoutMs: this.requestTimeoutMs,
roundRobinSeed: this.fetchCount++,
logger: this.logger,
});
this.mostRecentSuccessfulFetchAt = new Date();
this.logger.debug(
`Received Uplink response. Has updated SDL? ${!!result?.supergraphSdl}`,
);
if (!result) {
return null;
}
this.compositionId = result.id;
supergraphSdl = result.supergraphSdl;
if (result?.minDelaySeconds) {
this.pollIntervalMs = result.minDelaySeconds * 1000;
// We only want to take the max of the two _if_ a fallback interval is
// configured. If we take the max above unconditionally, then a gateway
// with an unconfigured fallback interval will only ever lengthen its
// poll interval rather than adapt to changes coming from Uplink.
if (this.fallbackPollIntervalInMs) {
this.pollIntervalMs = Math.max(
this.pollIntervalMs,
this.fallbackPollIntervalInMs,
);
}
}
} catch (e) {
this.logger.debug(
`Error fetching supergraphSdl from Uplink during phase '${this.state.phase}'`,
);
if (
this.state.phase === 'constructed' &&
this.onFailureToFetchSupergraphSdlDuringInit
) {
supergraphSdl = await this.onFailureToFetchSupergraphSdlDuringInit({
error: e,
graphRef: this.graphRef,
logger: this.logger,
fetchCount: this.fetchCount,
});
} else if (
this.state.phase === 'polling' &&
this.onFailureToFetchSupergraphSdlAfterInit
) {
supergraphSdl = await this.onFailureToFetchSupergraphSdlAfterInit({
error: e,
graphRef: this.graphRef,
logger: this.logger,
fetchCount: this.fetchCount,
mostRecentSuccessfulFetchAt: this.mostRecentSuccessfulFetchAt,
});
// This is really an error, but we'll let the caller decide what to do with it
if (!supergraphSdl) {
return null;
}
} else {
throw e;
}
}
// the healthCheck fn is only assigned if it's enabled in the config
await this.healthCheck?.(supergraphSdl);
return supergraphSdl;
}
private beginPolling() {
this.state = { phase: 'polling' };
this.poll();
}
private poll() {
if (this.state.phase !== 'polling') {
this.logger.debug(`Stopped polling Uplink [phase: ${this.state.phase}]`);
return;
}
this.state.nextFetchPromise = resolvable();
this.logger.debug(
`Will poll Uplink after ${this.pollIntervalMs}ms [phase: ${this.state.phase}]`,
);
this.timerRef = setTimeout(async () => {
if (this.state.phase === 'polling') {
const pollingPromise = resolvable();
this.state.pollingPromise = pollingPromise;
try {
const supergraphSdl = await this.updateSupergraphSdl(this.maxRetries);
if (supergraphSdl) {
this.update?.(supergraphSdl);
}
} catch (e) {
this.logUpdateFailure(e);
}
pollingPromise.resolve();
this.state.nextFetchPromise?.resolve();
}
this.poll();
}, this.pollIntervalMs);
}
private logUpdateFailure(e: any) {
this.logger.error(
'UplinkSupergraphManager failed to update supergraph with the following error: ' +
(e.message ?? e),
);
}
}