index.js
5.43 KB
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
'use strict';
var through = require('through2');
var debug = require('debug')('retry-request');
var DEFAULTS = {
objectMode: false,
retries: 2,
noResponseRetries: 2,
currentRetryAttempt: 0,
shouldRetryFn: function (response) {
var 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]
];
var statusCode = response.statusCode;
debug(`Response status: ${statusCode}`);
var range;
while ((range = retryRanges.shift())) {
if (statusCode >= range[0] && statusCode <= range[1]) {
// Not a successful status or redirect.
return true;
}
}
}
};
function retryRequest(requestOpts, opts, callback) {
var streamMode = typeof arguments[arguments.length - 1] !== 'function';
if (typeof opts === 'function') {
callback = opts;
}
opts = opts || DEFAULTS;
if (typeof opts.objectMode === 'undefined') {
opts.objectMode = DEFAULTS.objectMode;
}
if (typeof opts.request === 'undefined') {
try {
opts.request = require('request');
} catch (e) {
throw new Error('A request library must be provided to retry-request.');
}
}
if (typeof opts.retries !== 'number') {
opts.retries = DEFAULTS.retries;
}
if (typeof opts.currentRetryAttempt !== 'number') {
opts.currentRetryAttempt = DEFAULTS.currentRetryAttempt;
}
if (typeof opts.noResponseRetries !== 'number') {
opts.noResponseRetries = DEFAULTS.noResponseRetries;
}
if (typeof opts.shouldRetryFn !== 'function') {
opts.shouldRetryFn = DEFAULTS.shouldRetryFn;
}
var currentRetryAttempt = opts.currentRetryAttempt;
var numNoResponseAttempts = 0;
var streamResponseHandled = false;
var retryStream;
var requestStream;
var delayStream;
var activeRequest;
var retryRequest = {
abort: function () {
if (activeRequest && activeRequest.abort) {
activeRequest.abort();
}
}
};
if (streamMode) {
retryStream = through({ objectMode: opts.objectMode });
retryStream.abort = resetStreams;
}
if (currentRetryAttempt > 0) {
retryAfterDelay(currentRetryAttempt);
} else {
makeRequest();
}
if (streamMode) {
return retryStream;
} else {
return retryRequest;
}
function resetStreams() {
delayStream = null;
if (requestStream) {
requestStream.abort && requestStream.abort();
requestStream.cancel && requestStream.cancel();
if (requestStream.destroy) {
requestStream.destroy();
} else if (requestStream.end) {
requestStream.end();
}
}
}
function makeRequest() {
currentRetryAttempt++;
debug(`Current retry attempt: ${currentRetryAttempt}`);
if (streamMode) {
streamResponseHandled = false;
delayStream = through({ objectMode: opts.objectMode });
requestStream = opts.request(requestOpts);
setImmediate(function () {
retryStream.emit('request');
});
requestStream
// gRPC via google-cloud-node can emit an `error` as well as a `response`
// Whichever it emits, we run with-- we can't run with both. That's what
// is up with the `streamResponseHandled` tracking.
.on('error', function (err) {
if (streamResponseHandled) {
return;
}
streamResponseHandled = true;
onResponse(err);
})
.on('response', function (resp, body) {
if (streamResponseHandled) {
return;
}
streamResponseHandled = true;
onResponse(null, resp, body);
})
.on('complete', retryStream.emit.bind(retryStream, 'complete'));
requestStream.pipe(delayStream);
} else {
activeRequest = opts.request(requestOpts, onResponse);
}
}
function retryAfterDelay(currentRetryAttempt) {
if (streamMode) {
resetStreams();
}
var nextRetryDelay = getNextRetryDelay(currentRetryAttempt);
debug(`Next retry delay: ${nextRetryDelay}`);
setTimeout(makeRequest, nextRetryDelay);
}
function onResponse(err, response, body) {
// An error such as DNS resolution.
if (err) {
numNoResponseAttempts++;
if (numNoResponseAttempts <= opts.noResponseRetries) {
retryAfterDelay(numNoResponseAttempts);
} else {
if (streamMode) {
retryStream.emit('error', err);
retryStream.end();
} else {
callback(err, response, body);
}
}
return;
}
// Send the response to see if we should try again.
if (currentRetryAttempt <= opts.retries && opts.shouldRetryFn(response)) {
retryAfterDelay(currentRetryAttempt);
return;
}
// No more attempts need to be made, just continue on.
if (streamMode) {
retryStream.emit('response', response);
delayStream.pipe(retryStream);
requestStream.on('error', function (err) {
retryStream.destroy(err);
});
} else {
callback(err, response, body);
}
}
}
module.exports = retryRequest;
function getNextRetryDelay(retryNumber) {
return (Math.pow(2, retryNumber) * 1000) + Math.floor(Math.random() * 1000);
}
module.exports.getNextRetryDelay = getNextRetryDelay;