[react-packager] Fix races

Summary:
A few potential races to fix:

1. Multiple clients maybe racing to delete a zombie socket
2. Servers who should die because other servers are already listening are taking the socket with them (move `process.on('exit'` code to after the server is listening
3. Servers which are redundant should immediatly die
This commit is contained in:
Amjad Masad 2015-08-27 01:52:56 -07:00
parent 1892f4aba4
commit 3c3af9c609
2 changed files with 14 additions and 4 deletions

View File

@ -32,6 +32,7 @@ class SocketServer {
options options
); );
resolve(this); resolve(this);
process.on('exit', () => fs.unlinkSync(sockPath));
}); });
}); });
this._server.on('connection', (sock) => this._handleConnection(sock)); this._server.on('connection', (sock) => this._handleConnection(sock));
@ -41,8 +42,6 @@ class SocketServer {
this._packagerServer = new Server(options); this._packagerServer = new Server(options);
this._jobs = 0; this._jobs = 0;
this._dieEventually(); this._dieEventually();
process.on('exit', () => fs.unlinkSync(sockPath));
} }
onReady() { onReady() {
@ -138,12 +137,17 @@ class SocketServer {
process.send({ type: 'createdServer' }); process.send({ type: 'createdServer' });
}, },
error => { error => {
debug('error creating server', error.code);
if (error.code === 'EADDRINUSE') { if (error.code === 'EADDRINUSE') {
// Server already listening, this may happen if multiple // Server already listening, this may happen if multiple
// clients where started in quick succussion (buck). // clients where started in quick succussion (buck).
process.send({ type: 'createdServer' }); process.send({ type: 'createdServer' });
// Kill this server because some other server with the same
// config and socket already started.
debug('server already started');
setImmediate(() => process.exit());
} else { } else {
debug('error creating server', error.code);
throw error; throw error;
} }
} }

View File

@ -13,6 +13,7 @@ const SocketClient = require('./SocketClient');
const SocketServer = require('./SocketServer'); const SocketServer = require('./SocketServer');
const _ = require('underscore'); const _ = require('underscore');
const crypto = require('crypto'); const crypto = require('crypto');
const debug = require('debug')('ReactPackager:SocketInterface');
const fs = require('fs'); const fs = require('fs');
const net = require('net'); const net = require('net');
const path = require('path'); const path = require('path');
@ -45,7 +46,12 @@ const SocketInterface = {
resolve(SocketClient.create(sockPath)); resolve(SocketClient.create(sockPath));
}); });
sock.on('error', (e) => { sock.on('error', (e) => {
fs.unlinkSync(sockPath); try {
debug('deleting socket for not responding', sockPath);
fs.unlinkSync(sockPath);
} catch (err) {
// Another client might have deleted it first.
}
createServer(resolve, reject, options, sockPath); createServer(resolve, reject, options, sockPath);
}); });
} else { } else {