-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.js
56 lines (51 loc) · 1.4 KB
/
util.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
const net = require('net');
const MAX_RETRY = 120;
const WAIT_RETRY = 1000; // in milliseconds
/**
*
* @returns {Promise<number>}
*/
async function getFreePort() {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.listen(0, '127.0.0.1', () => {
const port = server.address().port;
server.close(() => {
resolve(port);
});
});
server.on('error', (err) => {
reject(err);
});
});
}
async function tryConnect(connFn) {
let retries = 0;
let aborted = true;
while (retries < MAX_RETRY) {
try {
await new Promise((resolve, reject) => {
connFn(function (err, req, res) {
if (res && res.closed) {
aborted = true;
retries = MAX_RETRY;
}
err ? reject(err) : resolve();
});
})
} catch (err) {
retries += 1;
if (retries < MAX_RETRY) {
console.log(`Retrying to connect for ${retries}-th time`);
await new Promise(res => setTimeout(res, WAIT_RETRY));
} else {
console.error(`Connection retry hang up: ${err}`);
throw err;
}
}
}
}
module.exports = {
getFreePort,
tryConnect
}