Skip to content

Commit

Permalink
feat: introduce timeout (#45)
Browse files Browse the repository at this point in the history
Co-authored-by: Ivan Shumkov <[email protected]>
  • Loading branch information
strophy and shumkov authored Jun 30, 2022
1 parent 93b3768 commit f417f4c
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ var client = new RPCclient({
user: 'dash',
pass: 'local321',
host: '127.0.0.1',
port: 19998
port: 19998,
timeout: 1000
});
var cb = function (err, data) {
Expand Down
14 changes: 14 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ function RpcClient(opts) {
this.port = opts.port || 9998;
this.user = opts.user || 'user';
this.pass = opts.pass || 'pass';
this.timeout = opts.timeout;
this.protocol = opts.protocol === 'http' ? http : https;
this.batchedCalls = null;
this.disableAgent = opts.disableAgent || false;
Expand Down Expand Up @@ -74,6 +75,10 @@ function innerRpc(request, callback) {
port: self.port,
rejectUnauthorized: self.rejectUnauthorized,
agent: self.disableAgent ? false : undefined,
};

if (self.timeout) {
options.timeout = self.timeout;
};

if (self.httpOptions) {
Expand Down Expand Up @@ -142,6 +147,11 @@ function innerRpc(request, callback) {
}
});

req.on('timeout', () => {
const err = new Error(`Timeout Error: ${options.timeout}ms exceeded`);
callback(err);
});

req.setHeader('Content-Length', request.length);
req.setHeader('Content-Type', 'application/json');
req.setHeader('Authorization', `Basic ${auth}`);
Expand All @@ -156,6 +166,10 @@ RpcClient.prototype.batch = function (batchCallback, resultCallback) {
this.batchedCalls = null;
};

RpcClient.prototype.setTimeout = function (timeout) {
this.timeout = timeout;
}

// For definitions of RPC calls, see various files in: https://github.com/dashpay/dash/tree/master/src
RpcClient.callspec = {
abandonTransaction: 'str',
Expand Down
30 changes: 29 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -525,4 +525,32 @@ describe('RpcClient', function() {

});

});
it('should throw error when timeout is triggered', (done) => {
var client = new RpcClient({
user: 'user',
pass: 'pass',
host: 'localhost',
port: 8332,
});

client.httpOptions = {
timeout: 100
};

var requestStub = sinon.stub(client.protocol, 'request').callsFake(function (options, callback) {
var req = new FakeRequest();
setTimeout(function () {
req.emit('timeout');
}, options.timeout);
return req;
});

client.getDifficulty((error, parsedBuf) => {
should.exist(error);
should.not.exist(parsedBuf);
error.message.should.equal(`Timeout Error: ${client.httpOptions.timeout}ms exceeded`);
requestStub.restore();
done();
})
});
})

0 comments on commit f417f4c

Please sign in to comment.