Skip to content

Commit

Permalink
feat: add "timeoutPerCommand" option to detect dead connection
Browse files Browse the repository at this point in the history
  • Loading branch information
luin committed Jul 6, 2018
1 parent b8eef3a commit a8afd00
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/redis.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,8 @@ Redis.defaultOptions = {
reconnectOnError: null,
readOnly: false,
stringNumbers: false,
maxRetriesPerRequest: 20
maxRetriesPerRequest: 20,
timeoutPerCommand: null
};

Redis.prototype.resetCommandQueue = function () {
Expand Down Expand Up @@ -611,6 +612,8 @@ Redis.prototype.sendCommand = function (command, stream) {
select: this.condition.select
});

this.lastWriteTime = Date.now()

if (Command.checkFlag('WILL_DISCONNECT', command.name)) {
this.manuallyClosing = true;
}
Expand Down
24 changes: 24 additions & 0 deletions lib/redis/event_handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,25 @@ exports.connectHandler = function (self) {

self.initParser();

self.lastWriteTime = null;
if (typeof self.options.timeoutPerCommand === 'number') {
var timeoutPerCommand = self.options.timeoutPerCommand;
debug('Per-command timeout set to %s', self.options.timeoutPerCommand);
self.timeoutPerCommand = setInterval(() => {
var commandQueueLength = self.commandQueue.length;
if (
commandQueueLength > 0 &&
Date.now() - self.lastWriteTime > self.options.timeoutPerCommand
) {
debug('Command timed out. Pending commands: %s', commandQueueLength);
var err = new Error('Command timed out');
self.flushQueue(err, { offlineQueue: false });
self.silentEmit('error', err);
self.disconnect(true);
}
}, 500);
}

if (self.options.enableReadyCheck) {
self._readyCheck(function (err, info) {
if (err) {
Expand Down Expand Up @@ -71,6 +90,11 @@ exports.closeHandler = function (self) {
self.prevCommandQueue = self.commandQueue;
}

if (self.timeoutPerCommand) {
clearInterval(self.timeoutPerCommand);
self.timeoutPerCommand = null;
}

if (self.manuallyClosing) {
self.manuallyClosing = false;
debug('skip reconnecting since the connection is manually closed.');
Expand Down

0 comments on commit a8afd00

Please sign in to comment.