Skip to content

Commit bbef4ca

Browse files
committed
Merge branch 'BenHall-connection-timeout'
2 parents 4ea0bbb + 36b3522 commit bbef4ca

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

lib/modem.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ var Modem = function(options) {
6767
this.cert = opts.cert;
6868
this.ca = opts.ca;
6969
this.timeout = opts.timeout;
70+
this.connectionTimeout = opts.connectionTimeout;
7071
this.checkServerIdentity = opts.checkServerIdentity;
7172
this.agent = opts.agent;
7273
this.headers = opts.headers || {};
@@ -188,6 +189,8 @@ Modem.prototype.dial = function(options, callback) {
188189

189190
Modem.prototype.buildRequest = function(options, context, data, callback) {
190191
var self = this;
192+
var connectionTimeoutTimer;
193+
191194
var opts = self.protocol === 'ssh' ? Object.assign(options, {
192195
agent: ssh({'host': self.host, 'port': self.port}),
193196
protocol: 'http'
@@ -200,6 +203,13 @@ Modem.prototype.buildRequest = function(options, context, data, callback) {
200203
depth: null
201204
}));
202205

206+
if (self.connectionTimeout) {
207+
connectionTimeoutTimer = setTimeout(function() {
208+
debug('Connection Timeout of %s ms exceeded', self.connectionTimeout);
209+
req.abort();
210+
}, self.connectionTimeout);
211+
}
212+
203213
if (self.timeout) {
204214
req.on('socket', function(socket) {
205215
socket.setTimeout(self.timeout);
@@ -211,12 +221,22 @@ Modem.prototype.buildRequest = function(options, context, data, callback) {
211221
}
212222

213223
if (context.hijack === true) {
224+
clearTimeout(connectionTimeoutTimer);
214225
req.on('upgrade', function(res, sock, head) {
215226
return callback(null, sock);
216227
});
217228
}
218229

230+
req.on('connect', function() {
231+
clearTimeout(connectionTimeoutTimer);
232+
});
233+
234+
req.on('disconnect', function() {
235+
clearTimeout(connectionTimeoutTimer);
236+
});
237+
219238
req.on('response', function(res) {
239+
clearTimeout(connectionTimeoutTimer);
220240
if (context.isStream === true) {
221241
self.buildPayload(null, context.isStream, context.statusCodes, context.openStdin, req, res, null, callback);
222242
} else {
@@ -238,6 +258,7 @@ Modem.prototype.buildRequest = function(options, context, data, callback) {
238258
});
239259

240260
req.on('error', function(error) {
261+
clearTimeout(connectionTimeoutTimer);
241262
self.buildPayload(error, context.isStream, context.statusCodes, false, {}, {}, null, callback);
242263
});
243264

0 commit comments

Comments
 (0)