Skip to content

Commit

Permalink
Improve parsers
Browse files Browse the repository at this point in the history
These changes are based on BridgeAR's recent efforts
for the node_redis library.

The changes does the following things:

1. Use pure functions instead of EventEmitter;
2. Remove unnecessary detections
  • Loading branch information
luin committed Oct 13, 2015
1 parent 8e64c56 commit 48d9701
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 138 deletions.
12 changes: 4 additions & 8 deletions lib/parsers/hiredis.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
'use strict';

var events = require('events');
var util = require('util');
var hiredis = require('hiredis');
var ReplyError = require('../reply_error');

function HiredisReplyParser(options) {
this.options = options || {};
this.reset();
events.EventEmitter.call(this);
}

util.inherits(HiredisReplyParser, events.EventEmitter);

module.exports = HiredisReplyParser;

HiredisReplyParser.prototype.reset = function () {
this.reader = new hiredis.Reader({
return_buffers: this.options.returnBuffers || false
return_buffers: true
});
};

Expand All @@ -28,7 +24,7 @@ HiredisReplyParser.prototype.execute = function (data) {
try {
reply = this.reader.get();
} catch (err) {
this.emit('error', err);
this.sendFatalError(err);
break;
}

Expand All @@ -37,9 +33,9 @@ HiredisReplyParser.prototype.execute = function (data) {
}

if (reply && reply instanceof Error) {
this.emit('reply error', new ReplyError(reply.message));
this.sendError(new ReplyError(reply.message));
} else {
this.emit('reply', reply);
this.sendReply(reply);
}
}
};
136 changes: 43 additions & 93 deletions lib/parsers/javascript.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,26 @@
'use strict';

var events = require('events');
/*
Copyright (c) by NodeRedis
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Originally developed by Matthew Ranney, http://ranney.com/
*/

var util = require('util');
var utils = require('../utils');
var ReplyError = require('../reply_error');

function Packet(type, size) {
this.type = type;
this.size = +size;
}

function ReplyParser(options) {
this.options = options || { };

this._buffer = null;
this._offset = 0;
this._encoding = 'utf-8';
this._reply_type = null;
function ReplyParser() {
this._buffer = new Buffer(0);
this._offset = 0;
}

util.inherits(ReplyParser, events.EventEmitter);

module.exports = ReplyParser;

var IncompleteReadBuffer = utils.extendsError('IncompleteReadBuffer');

// Buffer.toString() is quite slow for small strings
function smallToString(buf, start, end) {
var tmp = '', i;

for (i = start; i < end; i++) {
tmp += String.fromCharCode(buf[i]);
}

return tmp;
}

ReplyParser.prototype._parseResult = function (type) {
var start, end, offset, packetHeader;

Expand All @@ -44,83 +29,64 @@ ReplyParser.prototype._parseResult = function (type) {
end = this._packetEndOffset() - 1;
start = this._offset;

// include the delimiter
this._offset = end + 2;

if (end > this._buffer.length) {
this._offset = start;
throw new IncompleteReadBuffer('Wait for more data.');
}

// include the delimiter
this._offset = end + 2;

if (type === 45) {
return new ReplyError(this._buffer.toString(this._encoding, start, end));
}
if (this.options.returnBuffers) {
return this._buffer.slice(start, end);
} else {
if (end - start < 65536) { // completely arbitrary
return smallToString(this._buffer, start, end);
} else {
return this._buffer.toString(this._encoding, start, end);
}
return new ReplyError(this._buffer.toString('utf-8', start, end));
}
return this._buffer.slice(start, end);
} else if (type === 58) { // :
// up to the delimiter
end = this._packetEndOffset() - 1;
start = this._offset;

// include the delimiter
this._offset = end + 2;

if (end > this._buffer.length) {
this._offset = start;
throw new IncompleteReadBuffer('Wait for more data.');
}

// TODO number?
// if (this.options.returnBuffers) {
// return this._buffer.slice(start, end);
// }
// include the delimiter
this._offset = end + 2;

// TODO number?
// return the coerced numeric value
return +smallToString(this._buffer, start, end);
return +this._buffer.toString('ascii', start, end);
} else if (type === 36) { // $
// set a rewind point, as the packet could be larger than the
// buffer in memory
offset = this._offset - 1;

packetHeader = new Packet(type, this.parseHeader());
packetHeader = this.parseHeader();

// packets with a size of -1 are considered null
if (packetHeader.size === -1) {
if (packetHeader === -1) {
return undefined;
}

end = this._offset + packetHeader.size;
end = this._offset + packetHeader;
start = this._offset;

// set the offset to after the delimiter
this._offset = end + 2;

if (end > this._buffer.length) {
this._offset = offset;
throw new IncompleteReadBuffer('Wait for more data.');
}

if (this.options.returnBuffers) {
return this._buffer.slice(start, end);
} else {
return this._buffer.toString(this._encoding, start, end);
}
// set the offset to after the delimiter
this._offset = end + 2;

return this._buffer.slice(start, end);
} else if (type === 42) { // *
offset = this._offset;
packetHeader = new Packet(type, this.parseHeader());
packetHeader = this.parseHeader();

if (packetHeader.size < 0) {
if (packetHeader < 0) {
return null;
}

if (packetHeader.size > this._bytesRemaining()) {
if (packetHeader > this._bytesRemaining()) {
this._offset = offset - 1;
throw new IncompleteReadBuffer('Wait for more data.');
}
Expand All @@ -130,7 +96,7 @@ ReplyParser.prototype._parseResult = function (type) {

offset = this._offset - 1;

for (i = 0; i < packetHeader.size; i++) {
for (i = 0; i < packetHeader; i++) {
ntype = this._buffer[this._offset++];

if (this._offset > this._buffer.length) {
Expand Down Expand Up @@ -162,31 +128,31 @@ ReplyParser.prototype.execute = function (buffer) {

type = this._buffer[this._offset++];

if (type === 43) { // +
if (type === 43) { // Strings +
ret = this._parseResult(type);

if (ret === null) {
break;
}

this.send_reply(ret);
} else if (type === 45) { // -
this.sendReply(ret);
} else if (type === 45) { // Errors -
ret = this._parseResult(type);

if (ret === null) {
break;
}

this.send_error(ret);
} else if (type === 58) { // :
this.sendError(ret);
} else if (type === 58) { // Integers :
ret = this._parseResult(type);

if (ret === null) {
break;
}

this.send_reply(ret);
} else if (type === 36) { // $
this.sendReply(ret);
} else if (type === 36) { // Bulk strings $
ret = this._parseResult(type);

if (ret === null) {
Expand All @@ -199,15 +165,15 @@ ReplyParser.prototype.execute = function (buffer) {
ret = null;
}

this.send_reply(ret);
} else if (type === 42) { // *
this.sendReply(ret);
} else if (type === 42) { // Arrays *
// set a rewind point. if a failure occurs,
// wait for the next execute()/append() and try again
offset = this._offset - 1;

ret = this._parseResult(type);

this.send_reply(ret);
this.sendReply(ret);
}
} catch (err) {
// catch the error (not enough data), rewind, and wait
Expand All @@ -226,18 +192,10 @@ ReplyParser.prototype.append = function (newBuffer) {
return;
}

// first run
if (this._buffer === null) {
this._buffer = newBuffer;

return;
}

// out of data
if (this._offset >= this._buffer.length) {
this._buffer = newBuffer;
this._offset = 0;

return;
}

Expand All @@ -246,8 +204,8 @@ ReplyParser.prototype.append = function (newBuffer) {
};

ReplyParser.prototype.parseHeader = function () {
var end = this._packetEndOffset(),
value = smallToString(this._buffer, this._offset, end - 1);
var end = this._packetEndOffset(),
value = this._buffer.toString('ascii', this._offset, end - 1) | 0;

this._offset = end + 1;

Expand All @@ -272,11 +230,3 @@ ReplyParser.prototype._packetEndOffset = function () {
ReplyParser.prototype._bytesRemaining = function () {
return (this._buffer.length - this._offset) < 0 ? 0 : (this._buffer.length - this._offset);
};

ReplyParser.prototype.send_error = function (reply) {
this.emit('reply error', reply);
};

ReplyParser.prototype.send_reply = function (reply) {
this.emit('reply', reply);
};
16 changes: 7 additions & 9 deletions lib/redis/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,18 @@ var debug = require('debug')('ioredis:reply');
exports.initParser = function () {
var self = this;

this.replyParser = new this.Parser({
returnBuffers: true
});
this.replyParser = new this.Parser();

// "reply error" is an error sent back by Redis
this.replyParser.on('reply error', function (reply) {
this.replyParser.sendError = function (reply) {
self.returnError(reply);
});
this.replyParser.on('reply', function (reply) {
};
this.replyParser.sendReply = function (reply) {
self.returnReply(reply);
});
this.replyParser.on('error', function (err) {
};
this.replyParser.sendFatalError = function (err) {
self.emit('error', new Error('Redis reply parser error: ' + err.stack));
});
};
};

exports.returnError = function (err) {
Expand Down
10 changes: 6 additions & 4 deletions test/helpers/mock_server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

var net = require('net');
var util = require('util');
var utils = require('../../lib/utils');
var EventEmitter = require('events').EventEmitter;
var enableDestroy = require('server-destroy');
var Parser = require('../../lib/parsers/javascript');
Expand All @@ -27,14 +28,15 @@ MockServer.prototype.connect = function () {
_this.emit('connect', c);
});

var parser = new Parser({ returnBuffer: false });
parser.on('reply', function (args) {
var parser = new Parser();
parser.sendReply = function (reply) {
reply = utils.convertBufferToString(reply);
if (_this.handler) {
_this.write(c, _this.handler(args));
_this.write(c, _this.handler(reply));
} else {
_this.write(c, MockServer.REDIS_OK);
}
});
};

c.on('end', function () {
_this.clients[clientIndex] = null;
Expand Down

0 comments on commit 48d9701

Please sign in to comment.