/
fetchWithRetries.js
127 lines (115 loc) · 3.87 KB
/
fetchWithRetries.js
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
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule fetchWithRetries
* @typechecks
* @flow
*/
'use strict';
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
var Promise = require('bluebird');
var sprintf = require('fbjs/lib/sprintf');
var fetch = require('../fetch');
var warning = require('fbjs/lib/warning');
type InitWitRetries = {
body?: mixed;
cache?: ?string;
credentials?: ?string;
fetchTimeout?: number;
headers?: mixed;
method?: ?string;
mode?: ?string;
retryDelays?: Array<number>;
};
var DEFAULT_FETCH_TIMEOUT = 15000;
var DEFAULT_RETRY_DELAYS = [1000, 3000];
/**
* Posts a request to the server with the given data as the payload.
* Automatic retries are done based on the values in `retryDelays`.
*/
function fetchWithRetries(
uri: string,
initWithRetries: InitWitRetries
): Promise {
var {fetchTimeout, retryDelays, ...init} = initWithRetries;
var nonNullFetchTimeout = fetchTimeout || DEFAULT_FETCH_TIMEOUT;
var nonNullRetryDelays = retryDelays || DEFAULT_RETRY_DELAYS;
var requestsAttempted = 0;
var requestStartTime = 0;
return new Promise((resolve, reject) => {
/**
* Sends a request to the server that will timeout after `fetchTimeout`.
* If the request fails or times out a new request might be scheduled.
*/
function sendTimedRequest(): void {
requestsAttempted++;
requestStartTime = Date.now();
var isRequestAlive = true;
var request = fetch(uri, init);
var requestTimeout = setTimeout(() => {
isRequestAlive = false;
if (shouldRetry(requestsAttempted)) {
warning(false, 'fetchWithRetries: HTTP timeout, retrying.');
retryRequest();
} else {
reject(new Error(sprintf(
'fetchWithRetries(): Failed to get response from server, ' +
'tried %s times.',
requestsAttempted
)));
}
}, nonNullFetchTimeout);
request.then(response => {
clearTimeout(requestTimeout);
if (isRequestAlive) {
// We got a response, we can clear the timeout.
if (response.status >= 200 && response.status < 300) {
// Got a response code that indicates success, resolve the promise.
resolve(response);
} else if (shouldRetry(requestsAttempted)) {
// Fetch was not successful, retrying.
// TODO(#7595849): Only retry on transient HTTP errors.
warning(false, 'fetchWithRetries: HTTP error, retrying.'),
retryRequest();
} else {
// Request was not successful, giving up.
reject(response);
}
}
}).catch(error => {
clearTimeout(requestTimeout);
if (shouldRetry(requestsAttempted)) {
retryRequest();
} else {
reject(error);
}
});
}
/**
* Schedules another run of sendTimedRequest based on how much time has
* passed between the time the last request was sent and now.
*/
function retryRequest(): void {
var retryDelay = nonNullRetryDelays[requestsAttempted - 1];
var retryStartTime = requestStartTime + retryDelay;
// Schedule retry for a configured duration after last request started.
setTimeout(sendTimedRequest, retryStartTime - Date.now());
}
/**
* Checks if another attempt should be done to send a request to the server.
*/
function shouldRetry(attempt: number): boolean {
return (
ExecutionEnvironment.canUseDOM &&
attempt <= nonNullRetryDelays.length
);
}
sendTimedRequest();
});
}
module.exports = fetchWithRetries;