-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathindex.ts
355 lines (316 loc) · 10.5 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import axios, {
AxiosError,
AxiosInstance,
AxiosRequestConfig,
AxiosResponse,
} from 'axios';
/**
* Configuration for the Axios `request` method.
*/
export interface RetryConfig {
/**
* The number of times to retry the request. Defaults to 3.
*/
retry?: number;
/**
* The number of retries already attempted.
*/
currentRetryAttempt?: number;
/**
* The amount of time to initially delay the retry. Defaults to 100.
*/
retryDelay?: number;
/**
* The instance of the axios object to which the interceptor is attached.
*/
instance?: AxiosInstance;
/**
* The HTTP Methods that will be automatically retried.
* Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE']
*/
httpMethodsToRetry?: string[];
/**
* The HTTP response status codes that will automatically be retried.
* Defaults to: [[100, 199], [429, 429], [500, 599]]
*/
statusCodesToRetry?: number[][];
/**
* Function to invoke when a retry attempt is made.
*/
onRetryAttempt?: (err: AxiosError) => void;
/**
* Function to invoke which determines if you should retry
*/
shouldRetry?: (err: AxiosError) => boolean;
/**
* When there is no response, the number of retries to attempt. Defaults to 2.
*/
noResponseRetries?: number;
/**
* Backoff Type; 'linear', 'static' or 'exponential'.
*/
backoffType?: 'linear' | 'static' | 'exponential';
/**
* Whether to check for 'Retry-After' header in response and use value as delay. Defaults to true.
*/
checkRetryAfter?: boolean;
/**
* Max permitted Retry-After value (in ms) - rejects if greater. Defaults to 5 mins.
*/
maxRetryAfter?: number;
/**
* Ceiling for calculated delay (in ms) - delay will not exceed this value.
*/
maxRetryDelay?: number;
}
export type RaxConfig = {
raxConfig: RetryConfig;
} & AxiosRequestConfig;
/**
* Attach the interceptor to the Axios instance.
* @param instance The optional Axios instance on which to attach the
* interceptor.
* @returns The id of the interceptor attached to the axios instance.
*/
export function attach(instance?: AxiosInstance) {
instance = instance || axios;
return instance.interceptors.response.use(onFulfilled, onError);
}
/**
* Eject the Axios interceptor that is providing retry capabilities.
* @param interceptorId The interceptorId provided in the config.
* @param instance The axios instance using this interceptor.
*/
export function detach(interceptorId: number, instance?: AxiosInstance) {
instance = instance || axios;
instance.interceptors.response.eject(interceptorId);
}
function onFulfilled(res: AxiosResponse) {
return res;
}
/**
* Some versions of axios are converting arrays into objects during retries.
* This will attempt to convert an object with the following structure into
* an array, where the keys correspond to the indices:
* {
* 0: {
* // some property
* },
* 1: {
* // another
* }
* }
* @param obj The object that (may) have integers that correspond to an index
* @returns An array with the pucked values
*/
function normalizeArray<T>(obj?: T[]): T[] | undefined {
const arr: T[] = [];
if (!obj) {
return undefined;
}
if (Array.isArray(obj)) {
return obj;
}
if (typeof obj === 'object') {
Object.keys(obj).forEach(key => {
if (typeof key === 'number') {
arr[key] = obj[key];
}
});
}
return arr;
}
/**
* Parse the Retry-After header.
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
* @param header Retry-After header value
* @returns Number of milliseconds, or undefined if invalid
*/
function parseRetryAfter(header: string): number | undefined {
// Header value may be string containing integer seconds
const value = Number(header);
if (!Number.isNaN(value)) {
return value * 1000;
}
// Or HTTP date time string
const dateTime = Date.parse(header);
if (!Number.isNaN(dateTime)) {
return dateTime - Date.now();
}
return undefined;
}
function onError(err: AxiosError) {
if (axios.isCancel(err)) {
return Promise.reject(err);
}
const config = getConfig(err) || {};
config.currentRetryAttempt = config.currentRetryAttempt || 0;
config.retry = typeof config.retry === 'number' ? config.retry : 3;
config.retryDelay =
typeof config.retryDelay === 'number' ? config.retryDelay : 100;
config.instance = config.instance || axios;
config.backoffType = config.backoffType || 'exponential';
config.httpMethodsToRetry = normalizeArray(config.httpMethodsToRetry) || [
'GET',
'HEAD',
'PUT',
'OPTIONS',
'DELETE',
];
config.noResponseRetries =
typeof config.noResponseRetries === 'number' ? config.noResponseRetries : 2;
config.checkRetryAfter =
typeof config.checkRetryAfter === 'boolean' ? config.checkRetryAfter : true;
config.maxRetryAfter =
typeof config.maxRetryAfter === 'number' ? config.maxRetryAfter : 60000 * 5;
// If this wasn't in the list of status codes where we want
// to automatically retry, return.
const retryRanges = [
// https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
// 1xx - Retry (Informational, request still processing)
// 2xx - Do not retry (Success)
// 3xx - Do not retry (Redirect)
// 4xx - Do not retry (Client errors)
// 429 - Retry ("Too Many Requests")
// 5xx - Retry (Server errors)
[100, 199],
[429, 429],
[500, 599],
];
config.statusCodesToRetry =
normalizeArray(config.statusCodesToRetry) || retryRanges;
// Put the config back into the err
err.config = err.config || {}; // allow for wider range of errors
(err.config as RaxConfig).raxConfig = {...config};
// Determine if we should retry the request
const shouldRetryFn = config.shouldRetry || shouldRetryRequest;
if (!shouldRetryFn(err)) {
return Promise.reject(err);
}
// Create a promise that invokes the retry after the backOffDelay
const onBackoffPromise = new Promise((resolve, reject) => {
let delay = 0;
// If enabled, check for 'Retry-After' header in response to use as delay
if (
config.checkRetryAfter &&
err.response &&
err.response.headers['retry-after']
) {
const retryAfter = parseRetryAfter(err.response.headers['retry-after']);
if (retryAfter && retryAfter > 0 && retryAfter <= config.maxRetryAfter!) {
delay = retryAfter;
} else {
return reject(err);
}
}
// Now it's certain that a retry is supposed to happen. Incremenent the
// counter, critical for linear and exp backoff delay calc. Note that
// `config.currentRetryAttempt` is local to this function whereas
// `(err.config as RaxConfig).raxConfig` is state that is tranferred across
// retries. That is, we want to mutate `(err.config as
// RaxConfig).raxConfig`. Another important note is about the definition of
// `currentRetryAttempt`: When we are here becasue the first and actual
// HTTP request attempt failed then `currentRetryAttempt` is still zero. We
// have found that a retry is indeed required. Since that is (will be)
// indeed the first retry it makes sense to now increase
// `currentRetryAttempt` by 1. So that it is in fact 1 for the first retry
// (as opposed to 0 or 2); an intuitive convention to use for the math
// below.
(err.config as RaxConfig).raxConfig!.currentRetryAttempt! += 1;
// store with shorter and more expressive variable name.
const retrycount = (err.config as RaxConfig).raxConfig!
.currentRetryAttempt!;
// Calculate delay according to chosen strategy
// Default to exponential backoff - formula: ((2^c - 1) / 2) * 1000
if (delay === 0) {
// was not set by Retry-After logic
if (config.backoffType === 'linear') {
// The delay between the first (actual) attempt and the first retry
// should be non-zero. Rely on the convention that `retrycount` is
// equal to 1 for the first retry when we are in here (was once 0,
// which was a bug -- see #122).
delay = retrycount * 1000;
} else if (config.backoffType === 'static') {
delay = config.retryDelay!;
} else {
delay = ((Math.pow(2, retrycount) - 1) / 2) * 1000;
}
if (typeof config.maxRetryDelay === 'number') {
delay = Math.min(delay, config.maxRetryDelay);
}
}
setTimeout(resolve, delay);
});
// Notify the user if they added an `onRetryAttempt` handler
const onRetryAttemptPromise = config.onRetryAttempt
? Promise.resolve(config.onRetryAttempt(err))
: Promise.resolve();
// Return the promise in which recalls axios to retry the request
return Promise.resolve()
.then(() => onBackoffPromise)
.then(() => onRetryAttemptPromise)
.then(() => config.instance!.request(err.config));
}
/**
* Determine based on config if we should retry the request.
* @param err The AxiosError passed to the interceptor.
*/
export function shouldRetryRequest(err: AxiosError) {
const config = (err.config as RaxConfig).raxConfig;
// If there's no config, or retries are disabled, return.
if (!config || config.retry === 0) {
return false;
}
// Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc)
if (
!err.response &&
(config.currentRetryAttempt || 0) >= config.noResponseRetries!
) {
return false;
}
// Only retry with configured HttpMethods.
if (
!err.config.method ||
config.httpMethodsToRetry!.indexOf(err.config.method.toUpperCase()) < 0
) {
return false;
}
// If this wasn't in the list of status codes where we want
// to automatically retry, return.
if (err.response && err.response.status) {
let isInRange = false;
for (const [min, max] of config.statusCodesToRetry!) {
const status = err.response.status;
if (status >= min && status <= max) {
isInRange = true;
break;
}
}
if (!isInRange) {
return false;
}
}
// If we are out of retry attempts, return
config.currentRetryAttempt = config.currentRetryAttempt || 0;
if (config.currentRetryAttempt >= config.retry!) {
return false;
}
return true;
}
/**
* Acquire the raxConfig object from an AxiosError if available.
* @param err The Axios error with a config object.
*/
export function getConfig(err: AxiosError) {
if (err && err.config) {
return (err.config as RaxConfig).raxConfig;
}
return;
}
// Include this so `config.raxConfig` works easily.
// See https://github.com/JustinBeckwith/retry-axios/issues/64.
declare module 'axios' {
export interface AxiosRequestConfig {
raxConfig?: RetryConfig;
}
}