Skip to content

Commit

Permalink
lib: fix multiple calls of callback in connect
Browse files Browse the repository at this point in the history
This fixes bug introduced in #281.

PR-URL: #293
Reviewed-By: Dmytro Nechai <nechaido@gmail.com>
Reviewed-By: Denys Otrishko <shishugi@gmail.com>
  • Loading branch information
belochub committed Aug 4, 2017
1 parent 7340774 commit c563b4c
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
7 changes: 4 additions & 3 deletions lib/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,15 +86,16 @@ const socketFactory = (connect) => {
const resultConnectFn = (...options) => {
const callback = common.extractCallback(options);
const socket = connect(...options);
socket.once('error', (error) => {
const onceErrorListener = (error) => {
if (error.code !== 'EAGAIN') {
callback(error);
return;
}
process.nextTick(resultConnectFn, ...options, callback);
});
};
socket.once('error', onceErrorListener);
socket.once('connect', () => {
socket.removeListener('error', callback);
socket.removeListener('error', onceErrorListener);
callback(null, socket);
});
};
Expand Down
41 changes: 41 additions & 0 deletions test/node/connection-callback-multiple-calls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use strict';

const test = require('tap');
const jstp = require('../..');

const app = new jstp.Application('app', {});

let server;

test.beforeEach((done) => {
server = jstp.net.createServer({ applications: [app] });
server.listen(0, done);
});

test.afterEach((done) => {
server.close(done);
});

test.test('must call connect callback once on successful connect', (test) => {
test.plan(1);
const port = server.address().port;
jstp.net.connect(app.name, null, port, (error, connection) => {
test.assertNot(error, 'must not return error');
connection.getTransport().destroy();
connection.on('error', () => {
// dismiss
});
connection.emitRemoteEvent('someService', 'someEvent', []);
});
});

const invalidAddress = {
host: '__invalid_host__',
};

test.test('must call connect callback once on error on connect', (test) => {
test.plan(1);
jstp.net.connect(app.name, null, invalidAddress, (error) => {
test.assert(error, 'must return error');
});
});

0 comments on commit c563b4c

Please sign in to comment.