From 5519ecdfecf43730aac4c96676f41bb801665ae1 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Mon, 15 Aug 2016 04:25:08 -0700 Subject: [PATCH] request: add timeout. --- lib/bcoin/http/request.js | 25 +++++++++++++++++++++++++ lib/bcoin/pool.js | 6 ++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/lib/bcoin/http/request.js b/lib/bcoin/http/request.js index a77edfcb..5d7c9159 100644 --- a/lib/bcoin/http/request.js +++ b/lib/bcoin/http/request.js @@ -196,6 +196,8 @@ function request(options, callback, stream) { if (res.socket) res.socket.removeListener('end', done); + stream.finish(); + if (err) { stream.destroy(); stream.emit('error', err); @@ -315,8 +317,22 @@ function ReqStream(options) { this.type = null; this._redirects = 0; this.maxRedirects = options.maxRedirects || 5; + this.timeout = options.timeout; + this._timeout = null; + + this._init(); } +ReqStream.prototype._init = function _init() { + var self = this; + if (this.timeout) { + this._timeout = setTimeout(function() { + self.emit('error', new Error('Request timed out.')); + self.destroy(); + }, this.timeout); + } +}; + ReqStream.prototype.__proto__ = Stream.prototype; ReqStream.prototype.destroy = function destroy() { @@ -337,6 +353,15 @@ ReqStream.prototype.destroy = function destroy() { } catch (e) { ; } + + this.finish(); +}; + +ReqStream.prototype.finish = function finish() { + if (this._timeout != null) { + clearTimeout(this._timeout); + this._timeout = null; + } }; /* diff --git a/lib/bcoin/pool.js b/lib/bcoin/pool.js index 39a10e18..7add51d8 100644 --- a/lib/bcoin/pool.js +++ b/lib/bcoin/pool.js @@ -1992,7 +1992,8 @@ Pool.prototype.getIP = function getIP(callback) { request({ method: 'GET', uri: 'http://icanhazip.com', - expect: 'text' + expect: 'text', + timeout: 3000 }, function(err, res, body) { if (err) return self.getIP2(callback); @@ -2021,7 +2022,8 @@ Pool.prototype.getIP2 = function getIP2(callback) { request({ method: 'GET', uri: 'http://checkip.dyndns.org', - expect: 'html' + expect: 'html', + timeout: 3000 }, function(err, res, body) { if (err) return callback(err);