forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRequestThrottle.ts
59 lines (49 loc) · 1.96 KB
/
RequestThrottle.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
import CONST from '@src/CONST';
import Log from './Log';
import type {RequestError} from './Network/SequentialQueue';
import {generateRandomInt} from './NumberUtils';
class RequestThrottle {
private requestWaitTime = 0;
private requestRetryCount = 0;
private timeoutID?: NodeJS.Timeout;
private name: string;
constructor(name: string) {
this.name = name;
}
clear() {
this.requestWaitTime = 0;
this.requestRetryCount = 0;
if (this.timeoutID) {
Log.info(`[RequestThrottle - ${this.name}] clearing timeoutID: ${String(this.timeoutID)}`);
clearTimeout(this.timeoutID);
this.timeoutID = undefined;
}
Log.info(`[RequestThrottle - ${this.name}] cleared`);
}
getRequestWaitTime() {
if (this.requestWaitTime) {
this.requestWaitTime = Math.min(this.requestWaitTime * 2, CONST.NETWORK.MAX_RETRY_WAIT_TIME_MS);
} else {
this.requestWaitTime = generateRandomInt(CONST.NETWORK.MIN_RETRY_WAIT_TIME_MS, CONST.NETWORK.MAX_RANDOM_RETRY_WAIT_TIME_MS);
}
return this.requestWaitTime;
}
getLastRequestWaitTime() {
return this.requestWaitTime;
}
sleep(error: RequestError, command: string): Promise<void> {
this.requestRetryCount++;
return new Promise((resolve, reject) => {
if (this.requestRetryCount <= CONST.NETWORK.MAX_REQUEST_RETRIES) {
const currentRequestWaitTime = this.getRequestWaitTime();
Log.info(
`[RequestThrottle - ${this.name}] Retrying request after error: '${error.name}', '${error.message}', '${error.status}'. Command: ${command}. Retry count: ${this.requestRetryCount}. Wait time: ${currentRequestWaitTime}`,
);
this.timeoutID = setTimeout(resolve, currentRequestWaitTime);
} else {
reject();
}
});
}
}
export default RequestThrottle;