-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexecute.js
79 lines (66 loc) · 1.77 KB
/
execute.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
'use strict';
const RETRYABLE = Symbol();
module.exports = async function execute(task, { attempts, backoff, condition, timeout }) {
let number = 1, result, control, operationHandle, attemptHandle, delayHandle;
function abort(reason, retryable = true) {
if (result) {
return;
}
const error = typeof reason === 'string'
? new Error(reason)
: reason;
error[RETRYABLE] = retryable;
control(error);
}
const attempt = {
get attempt() {
return number;
},
get number() {
return number;
},
cancel(reason = 'Attempt cancelled') {
abort(reason);
},
timeout(duration) {
clearTimeout(attemptHandle);
attemptHandle = setTimeout(function attemptTimeout() {
abort(`Attempt timed out after ${duration} ms`);
}, duration);
},
};
if (timeout) {
operationHandle = setTimeout(function operationTimeout() {
abort(`Operation timed out after ${timeout} ms`, false);
}, timeout);
}
for (;; number += 1) {
try {
result = await Promise.race([
new Promise((_, reject) => { control = reject }),
task(attempt),
]);
return result;
} catch (error) {
const retryable = error[RETRYABLE];
delete error[RETRYABLE];
if (number < attempts) {
const shouldRetry = retryable === undefined
? await condition(error)
: retryable;
if (shouldRetry) {
const delay = await backoff(number, error);
await new Promise(resolve => {
delayHandle = setTimeout(resolve, delay);
});
continue;
}
}
throw error;
} finally {
clearTimeout(delayHandle);
clearTimeout(attemptHandle);
clearTimeout(operationHandle);
}
}
};