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

Commit 824efbd

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

1 file changed

Lines changed: 46 additions & 2 deletions

File tree

lib/_inspect.js

Lines changed: 46 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,43 @@ 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+
const socket = net.connect(port, host);
107+
let didRetry = false;
108+
function retry() {
109+
if (!didRetry && !didTimeOut) {
110+
didRetry = true;
111+
setTimeout(pingPort, retryDelay);
112+
}
113+
}
114+
115+
socket.on('error', (error) => {
116+
if (error.code === 'ECONNREFUSED') {
117+
resolve();
118+
} else {
119+
retry();
120+
}
121+
});
122+
socket.on('connect', () => {
123+
socket.destroy();
124+
retry();
125+
});
126+
}
127+
pingPort();
128+
});
129+
}
130+
93131
class NodeInspector {
94132
constructor(options, stdin, stdout) {
95133
this.options = options;
@@ -169,7 +207,14 @@ class NodeInspector {
169207

170208
run() {
171209
this.killChild();
172-
return this._runScript().then((child) => {
210+
const { host, port } = this.options;
211+
212+
const runOncePortIsFree = () => {
213+
return portIsFree(host, port)
214+
.then(() => this._runScript());
215+
};
216+
217+
return runOncePortIsFree().then((child) => {
173218
this.child = child;
174219

175220
let connectionAttempts = 0;
@@ -194,7 +239,6 @@ class NodeInspector {
194239
});
195240
};
196241

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

0 commit comments

Comments
 (0)