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

Commit

Permalink
fix: Only restart after port is free
Browse files Browse the repository at this point in the history
  • Loading branch information
Jan Krems committed Mar 15, 2017
1 parent b4d5ee2 commit 824efbd
Showing 1 changed file with 46 additions and 2 deletions.
48 changes: 46 additions & 2 deletions lib/_inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
'use strict';
const { spawn } = require('child_process');
const { EventEmitter } = require('events');
const net = require('net');
const util = require('util');

const runAsStandalone = typeof __dirname !== 'undefined';
Expand Down Expand Up @@ -90,6 +91,43 @@ function createAgentProxy(domain, client) {
});
}

function portIsFree(host, port, timeout = 2000) {
const retryDelay = 150;
let didTimeOut = false;

return new Promise((resolve, reject) => {
setTimeout(() => {
didTimeOut = true;
reject(new Error(
`Timeout (${timeout}) waiting for ${host}:${port} to be free`));
}, timeout);

function pingPort() {
const socket = net.connect(port, host);
let didRetry = false;
function retry() {
if (!didRetry && !didTimeOut) {
didRetry = true;
setTimeout(pingPort, retryDelay);
}
}

socket.on('error', (error) => {
if (error.code === 'ECONNREFUSED') {
resolve();
} else {
retry();
}
});
socket.on('connect', () => {
socket.destroy();
retry();
});
}
pingPort();
});
}

class NodeInspector {
constructor(options, stdin, stdout) {
this.options = options;
Expand Down Expand Up @@ -169,7 +207,14 @@ class NodeInspector {

run() {
this.killChild();
return this._runScript().then((child) => {
const { host, port } = this.options;

const runOncePortIsFree = () => {
return portIsFree(host, port)
.then(() => this._runScript());
};

return runOncePortIsFree().then((child) => {
this.child = child;

let connectionAttempts = 0;
Expand All @@ -194,7 +239,6 @@ class NodeInspector {
});
};

const { host, port } = this.options;
this.print(`connecting to ${host}:${port} ..`, true);
return attemptConnect();
});
Expand Down

0 comments on commit 824efbd

Please sign in to comment.