From 10a539ef002d1ec32552d22821232f57d59219a0 Mon Sep 17 00:00:00 2001 From: Cristian Carlesso Date: Thu, 1 Dec 2016 12:54:11 +0000 Subject: [PATCH] Fixes race condition on yarn install mutex network (#2092) * Fixes race condition on yarn install mutex network * Better comment on as per @bestander request --- src/cli/index.js | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/src/cli/index.js b/src/cli/index.js index 209c07258c..91156b3d07 100644 --- a/src/cli/index.js +++ b/src/cli/index.js @@ -265,26 +265,28 @@ const runEventuallyWithNetwork = (mutexPort: ?string): Promise => { port: +mutexPort || constants.SINGLE_INSTANCE_PORT, }; - const clients = []; - const server = net.createServer((client: net$Socket) => { - clients.push(client); - }); + const server = net.createServer(); server.on('error', () => { - // another yarnn instance exists, let's connect to it to know when it dies. + // another Yarn instance exists, let's connect to it to know when it dies. reporter.warn(reporter.lang('waitingInstance')); const socket = net.createConnection(connectionOptions); socket - .on('data', () => { - // the server has informed us he's going to die soon™. - socket.unref(); // let it die - process.nextTick(() => { - ok(runEventuallyWithNetwork(mutexPort)); - }); + .on('connect', () => { + // Allow the program to exit if this is the only active server in the event system. + socket.unref(); + }) + .on('close', (hadError?: boolean) => { + // the `close` event gets always called after the `error` event + if (!hadError) { + process.nextTick(() => { + ok(runEventuallyWithNetwork(mutexPort)); + }); + } }) .on('error', () => { - // No server to listen to ? :O let's retry to become the next server then. + // No server to listen to ? Let's retry to become the next server then. process.nextTick(() => { ok(runEventuallyWithNetwork(mutexPort)); }); @@ -292,9 +294,6 @@ const runEventuallyWithNetwork = (mutexPort: ?string): Promise => { }); const onServerEnd = (): Promise => { - clients.forEach((client) => { - client.write('closing. kthanx, bye.'); - }); server.close(); return Promise.resolve(); };