Skip to content

Add option for connect timeout #726

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 4, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ you spot any mistakes.

## HEAD

* Add `connectTimeout` option to specify a timeout for establishing a connection #726

## v2.0.1

* internal parser speed improvement #702
Expand Down
2 changes: 2 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ When establishing a connection, you can set the following options:
* `database`: Name of the database to use for this connection (Optional).
* `charset`: The charset for the connection. (Default: `'UTF8_GENERAL_CI'`. Value needs to be all in upper case letters!)
* `timezone`: The timezone used to store local dates. (Default: `'local'`)
* `connectTimeout`: The milliseconds before a timeout occurs during the initial connection
to the MySQL server. (Default: no timeout)
* `stringifyObjects`: Stringify objects instead of converting to values. See
issue [#501](https://github.com/felixge/node-mysql/issues/501). (Default: `'false'`)
* `insecureAuth`: Allow connecting to MySQL instances that ask for the old
Expand Down
23 changes: 23 additions & 0 deletions lib/Connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,15 @@ Connection.prototype.connect = function(cb) {
this._protocol.on('unhandledError', this._handleProtocolError.bind(this));
this._protocol.on('drain', this._handleProtocolDrain.bind(this));
this._protocol.on('end', this._handleProtocolEnd.bind(this));

if (this.config.connectTimeout) {
var handleConnectTimeout = this._handleConnectTimeout.bind(this);

this._socket.setTimeout(this.config.connectTimeout, handleConnectTimeout);
this._socket.once('connect', function() {
this.setTimeout(0, handleConnectTimeout);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do you need to pass handler as argument here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is needed to remove the specific timeout listener. this.setTimeout(0, handleConnectTimeout); is the same as this.setTimeout(0); this.removeListener('timeout', handleConnectTimeout). The timeout listener needs to be removed so it does not trigger after we have established a connection, since this is just a timeout for connecting.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This if block could also be written as:

if (this.config.connectTimeout) {
  var handleConnectTimeout = this._handleConnectTimeout.bind(this);

  this._socket.setTimeout(this.config.connectTimeout);
  this._socket.once('timeout', handleConnectTimeout);
  this._socket.once('connect', function() {
    this.setTimeout(0);
    this.removeListener('timeout', handleConnectTimeout);
  });
}

if that makes it clearer.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just checked setTimeout(0) without handler and previous timer is not called

var net = require('net');
var s = net.connect(80, 'stackoverflow.com');
s.setTimeout(1000, function() { console.log('timeout');  });
s.on('connect', function() {
  console.log('connected!');
  s.setTimeout(0);
});

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, because when you run a.setTimeout(0) the socket will never emit a timeout event any more, because the timeout timers are unenrolled. But if some user-land code is setting a timeout on our socket, our timeout listener will then suddenly trigger. We need to remove our listener to be safe. Try:

var net = require('net');
var s = net.connect(80, 'stackoverflow.com');
s.setTimeout(1000, function() { console.log('timeout');  });
s.on('connect', function() {
  console.log('connected!');
  s.setTimeout(0);
  setTimeout(function(){
    // Sometime later some user code does
    s.setTimeout(2);
    // Which didn't do anything before, or maybe they are adding their own
    // timeout listener for some reason
    // Our timeout listener is now triggered since we never removed it
  },100);
});

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am just trying to make sure that this timeout function is only triggered for a timeout during the connection establishment and not at any possible later point, which is why I went through extra effort to remove the timeout listener we added.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point

});
}
}

this._protocol.handshake(cb);
Expand Down Expand Up @@ -191,6 +200,20 @@ Connection.prototype.format = function(sql, values) {
return SqlString.format(sql, values, this.config.stringifyObjects, this.config.timezone);
};

Connection.prototype._handleConnectTimeout = function() {
if (this._socket) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this where _socket.destroy() supposed to be?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. I actually just pushed the change, so you can see it now :)

this._socket.setTimeout(0);
this._socket.destroy();
}

var err = new Error('connect ETIMEDOUT');
err.errorno = 'ETIMEDOUT';
err.code = 'ETIMEDOUT';
err.syscall = 'connect';

this._handleNetworkError(err);
};

Connection.prototype._handleNetworkError = function(err) {
this._protocol.handleNetworkError(err);
};
Expand Down
1 change: 1 addition & 0 deletions lib/ConnectionConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ function ConnectionConfig(options) {
this.user = options.user || undefined;
this.password = options.password || undefined;
this.database = options.database;
this.connectTimeout = options.connectTimeout || undefined;
this.insecureAuth = options.insecureAuth || false;
this.supportBigNumbers = options.supportBigNumbers || false;
this.bigNumberStrings = options.bigNumberStrings || false;
Expand Down
22 changes: 22 additions & 0 deletions test/integration/connection/test-connect-timeout-only.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
var common = require('../../common');
var connection = common.createConnection({connectTimeout: 1000});
var assert = require('assert');

connection.connect();

var connectErr;
var rows = undefined;
var fields = undefined;
connection.query('SELECT SLEEP(3)', function(err, _rows, _fields) {
connectErr = err;
rows = _rows;
fields = _fields;
});

connection.end();

process.on('exit', function() {
assert.ifError(connectErr);
assert.deepEqual(rows, [{'SLEEP(3)': 0}]);
assert.equal(fields[0].name, 'SLEEP(3)');
});
20 changes: 20 additions & 0 deletions test/integration/connection/test-connect-timeout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
var common = require('../../common');
var connection = common.createConnection({host: '1.1.1.1', port: common.fakeServerPort, connectTimeout: 500});
var assert = require('assert');

var testTimeout = setTimeout(function() {
connection.destroy();
}, 5000);

var connectErr;
connection.connect(function(err) {
connectErr = err;
clearTimeout(testTimeout);
});

process.on('exit', function() {
assert.ok(connectErr);
assert.equal(connectErr.code, 'ETIMEDOUT');
assert.equal(connectErr.syscall, 'connect');
assert.equal(connectErr.fatal, true);
});