Skip to content
This repository was archived by the owner on Feb 1, 2022. It is now read-only.

Commit f6ccfc7

Browse files
author
Jan Krems
committed
fix: Only restart after port is free
1 parent b4d5ee2 commit f6ccfc7

File tree

1 file changed

+48
-2
lines changed

1 file changed

+48
-2
lines changed

lib/_inspect.js

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
'use strict';
2323
const { spawn } = require('child_process');
2424
const { EventEmitter } = require('events');
25+
const net = require('net');
2526
const util = require('util');
2627

2728
const runAsStandalone = typeof __dirname !== 'undefined';
@@ -90,6 +91,45 @@ function createAgentProxy(domain, client) {
9091
});
9192
}
9293

94+
function portIsFree(host, port, timeout = 2000) {
95+
const retryDelay = 150;
96+
let didTimeOut = false;
97+
98+
return new Promise((resolve, reject) => {
99+
setTimeout(() => {
100+
didTimeOut = true;
101+
reject(new Error(
102+
`Timeout (${timeout}) waiting for ${host}:${port} to be free`));
103+
}, timeout);
104+
105+
function pingPort() {
106+
if (didTimeOut) return;
107+
108+
const socket = net.connect(port, host);
109+
let didRetry = false;
110+
function retry() {
111+
if (!didRetry && !didTimeOut) {
112+
didRetry = true;
113+
setTimeout(pingPort, retryDelay);
114+
}
115+
}
116+
117+
socket.on('error', (error) => {
118+
if (error.code === 'ECONNREFUSED') {
119+
resolve();
120+
} else {
121+
retry();
122+
}
123+
});
124+
socket.on('connect', () => {
125+
socket.destroy();
126+
retry();
127+
});
128+
}
129+
pingPort();
130+
});
131+
}
132+
93133
class NodeInspector {
94134
constructor(options, stdin, stdout) {
95135
this.options = options;
@@ -169,7 +209,14 @@ class NodeInspector {
169209

170210
run() {
171211
this.killChild();
172-
return this._runScript().then((child) => {
212+
const { host, port } = this.options;
213+
214+
const runOncePortIsFree = () => {
215+
return portIsFree(host, port)
216+
.then(() => this._runScript());
217+
};
218+
219+
return runOncePortIsFree().then((child) => {
173220
this.child = child;
174221

175222
let connectionAttempts = 0;
@@ -194,7 +241,6 @@ class NodeInspector {
194241
});
195242
};
196243

197-
const { host, port } = this.options;
198244
this.print(`connecting to ${host}:${port} ..`, true);
199245
return attemptConnect();
200246
});

0 commit comments

Comments
 (0)