UNPKG

40.1 kBJavaScriptView Raw
1'use strict';
2
3var net = require('net');
4var tls = require('tls');
5var util = require('util');
6var utils = require('./lib/utils');
7var Command = require('./lib/command');
8var Queue = require('denque');
9var errorClasses = require('./lib/customErrors');
10var EventEmitter = require('events');
11var Parser = require('redis-parser');
12var RedisErrors = require('redis-errors');
13var commands = require('redis-commands');
14var debug = require('./lib/debug');
15var unifyOptions = require('./lib/createClient');
16var SUBSCRIBE_COMMANDS = {
17 subscribe: true,
18 unsubscribe: true,
19 psubscribe: true,
20 punsubscribe: true
21};
22
23function noop () {}
24
25function handle_detect_buffers_reply (reply, command, buffer_args) {
26 if (buffer_args === false || this.message_buffers) {
27 // If detect_buffers option was specified, then the reply from the parser will be a buffer.
28 // If this command did not use Buffer arguments, then convert the reply to Strings here.
29 reply = utils.reply_to_strings(reply);
30 }
31
32 if (command === 'hgetall') {
33 reply = utils.reply_to_object(reply);
34 }
35 return reply;
36}
37
38exports.debug_mode = /\bredis\b/i.test(process.env.NODE_DEBUG);
39
40// Attention: The second parameter might be removed at will and is not officially supported.
41// Do not rely on this
42function RedisClient (options, stream) {
43 // Copy the options so they are not mutated
44 options = utils.clone(options);
45 EventEmitter.call(this);
46 var cnx_options = {};
47 var self = this;
48 /* istanbul ignore next: travis does not work with stunnel atm. Therefore the tls tests are skipped on travis */
49 for (var tls_option in options.tls) {
50 cnx_options[tls_option] = options.tls[tls_option];
51 // Copy the tls options into the general options to make sure the address is set right
52 if (tls_option === 'port' || tls_option === 'host' || tls_option === 'path' || tls_option === 'family') {
53 options[tls_option] = options.tls[tls_option];
54 }
55 }
56 if (stream) {
57 // The stream from the outside is used so no connection from this side is triggered but from the server this client should talk to
58 // Reconnect etc won't work with this. This requires monkey patching to work, so it is not officially supported
59 options.stream = stream;
60 this.address = '"Private stream"';
61 } else if (options.path) {
62 cnx_options.path = options.path;
63 this.address = options.path;
64 } else {
65 cnx_options.port = +options.port || 6379;
66 cnx_options.host = options.host || '127.0.0.1';
67 cnx_options.family = (!options.family && net.isIP(cnx_options.host)) || (options.family === 'IPv6' ? 6 : 4);
68 this.address = cnx_options.host + ':' + cnx_options.port;
69 }
70
71 this.connection_options = cnx_options;
72 this.connection_id = RedisClient.connection_id++;
73 this.connected = false;
74 this.ready = false;
75 if (options.socket_keepalive === undefined) {
76 options.socket_keepalive = true;
77 }
78 if (options.socket_initial_delay === undefined) {
79 options.socket_initial_delay = 0;
80 // set default to 0, which is aligned to https://nodejs.org/api/net.html#net_socket_setkeepalive_enable_initialdelay
81 }
82 for (var command in options.rename_commands) {
83 options.rename_commands[command.toLowerCase()] = options.rename_commands[command];
84 }
85 options.return_buffers = !!options.return_buffers;
86 options.detect_buffers = !!options.detect_buffers;
87 // Override the detect_buffers setting if return_buffers is active and print a warning
88 if (options.return_buffers && options.detect_buffers) {
89 self.warn('WARNING: You activated return_buffers and detect_buffers at the same time. The return value is always going to be a buffer.');
90 options.detect_buffers = false;
91 }
92 if (options.detect_buffers) {
93 // We only need to look at the arguments if we do not know what we have to return
94 this.handle_reply = handle_detect_buffers_reply;
95 }
96 this.should_buffer = false;
97 this.command_queue = new Queue(); // Holds sent commands to de-pipeline them
98 this.offline_queue = new Queue(); // Holds commands issued but not able to be sent
99 this.pipeline_queue = new Queue(); // Holds all pipelined commands
100 // ATTENTION: connect_timeout should change in v.3.0 so it does not count towards ending reconnection attempts after x seconds
101 // This should be done by the retry_strategy. Instead it should only be the timeout for connecting to redis
102 this.connect_timeout = +options.connect_timeout || 3600000; // 60 * 60 * 1000 ms
103 this.enable_offline_queue = options.enable_offline_queue === false ? false : true;
104 this.initialize_retry_vars();
105 this.pub_sub_mode = 0;
106 this.subscription_set = {};
107 this.monitoring = false;
108 this.message_buffers = false;
109 this.closing = false;
110 this.server_info = {};
111 this.auth_pass = options.auth_pass || options.password;
112 this.selected_db = options.db; // Save the selected db here, used when reconnecting
113 this.fire_strings = true; // Determine if strings or buffers should be written to the stream
114 this.pipeline = false;
115 this.sub_commands_left = 0;
116 this.times_connected = 0;
117 this.buffers = options.return_buffers || options.detect_buffers;
118 this.options = options;
119 this.reply = 'ON'; // Returning replies is the default
120 this.create_stream();
121 // The listeners will not be attached right away, so let's print the deprecation message while the listener is attached
122 this.on('newListener', function (event) {
123 if ((event === 'message_buffer' || event === 'pmessage_buffer' || event === 'messageBuffer' || event === 'pmessageBuffer') && !this.buffers && !this.message_buffers) {
124 this.reply_parser.optionReturnBuffers = true;
125 this.message_buffers = true;
126 this.handle_reply = handle_detect_buffers_reply;
127 }
128 });
129}
130util.inherits(RedisClient, EventEmitter);
131
132RedisClient.connection_id = 0;
133
134function create_parser (self) {
135 return new Parser({
136 returnReply: function (data) {
137 self.return_reply(data);
138 },
139 returnError: function (err) {
140 // Return a ReplyError to indicate Redis returned an error
141 self.return_error(err);
142 },
143 returnFatalError: function (err) {
144 // Error out all fired commands. Otherwise they might rely on faulty data. We have to reconnect to get in a working state again
145 // Note: the execution order is important. First flush and emit, then create the stream
146 err.message += '. Please report this.';
147 self.ready = false;
148 self.flush_and_error({
149 message: 'Fatal error encountered. Command aborted.',
150 code: 'NR_FATAL'
151 }, {
152 error: err,
153 queues: ['command_queue']
154 });
155 self.emit('error', err);
156 self.create_stream();
157 },
158 returnBuffers: self.buffers || self.message_buffers,
159 stringNumbers: self.options.string_numbers || false
160 });
161}
162
163/******************************************************************************
164
165 All functions in here are internal besides the RedisClient constructor
166 and the exported functions. Don't rely on them as they will be private
167 functions in node_redis v.3
168
169******************************************************************************/
170
171// Attention: the function name "create_stream" should not be changed, as other libraries need this to mock the stream (e.g. fakeredis)
172RedisClient.prototype.create_stream = function () {
173 var self = this;
174
175 // Init parser
176 this.reply_parser = create_parser(this);
177
178 if (this.options.stream) {
179 // Only add the listeners once in case of a reconnect try (that won't work)
180 if (this.stream) {
181 return;
182 }
183 this.stream = this.options.stream;
184 } else {
185 // On a reconnect destroy the former stream and retry
186 if (this.stream) {
187 this.stream.removeAllListeners();
188 this.stream.destroy();
189 }
190
191 /* istanbul ignore if: travis does not work with stunnel atm. Therefore the tls tests are skipped on travis */
192 if (this.options.tls) {
193 this.stream = tls.connect(this.connection_options);
194 } else {
195 this.stream = net.createConnection(this.connection_options);
196 }
197 }
198
199 if (this.options.connect_timeout) {
200 this.stream.setTimeout(this.connect_timeout, function () {
201 // Note: This is only tested if a internet connection is established
202 self.retry_totaltime = self.connect_timeout;
203 self.connection_gone('timeout');
204 });
205 }
206
207 /* istanbul ignore next: travis does not work with stunnel atm. Therefore the tls tests are skipped on travis */
208 var connect_event = this.options.tls ? 'secureConnect' : 'connect';
209 this.stream.once(connect_event, function () {
210 this.removeAllListeners('timeout');
211 self.times_connected++;
212 self.on_connect();
213 });
214
215 this.stream.on('data', function (buffer_from_socket) {
216 // The buffer_from_socket.toString() has a significant impact on big chunks and therefore this should only be used if necessary
217 debug('Net read ' + self.address + ' id ' + self.connection_id); // + ': ' + buffer_from_socket.toString());
218 self.reply_parser.execute(buffer_from_socket);
219 });
220
221 this.stream.on('error', function (err) {
222 self.on_error(err);
223 });
224
225 this.stream.once('close', function (hadError) {
226 self.connection_gone('close');
227 });
228
229 this.stream.once('end', function () {
230 self.connection_gone('end');
231 });
232
233 this.stream.on('drain', function () {
234 self.drain();
235 });
236
237 this.stream.setNoDelay();
238
239 // Fire the command before redis is connected to be sure it's the first fired command
240 if (this.auth_pass !== undefined) {
241 this.ready = true;
242 // Fail silently as we might not be able to connect
243 this.auth(this.auth_pass, function (err) {
244 if (err && err.code !== 'UNCERTAIN_STATE') {
245 self.emit('error', err);
246 }
247 });
248 this.ready = false;
249 }
250};
251
252RedisClient.prototype.handle_reply = function (reply, command) {
253 if (command === 'hgetall') {
254 reply = utils.reply_to_object(reply);
255 }
256 return reply;
257};
258
259RedisClient.prototype.cork = noop;
260RedisClient.prototype.uncork = noop;
261
262RedisClient.prototype.initialize_retry_vars = function () {
263 this.retry_timer = null;
264 this.retry_totaltime = 0;
265 this.retry_delay = 200;
266 this.retry_backoff = 1.7;
267 this.attempts = 1;
268};
269
270RedisClient.prototype.warn = function (msg) {
271 var self = this;
272 // Warn on the next tick. Otherwise no event listener can be added
273 // for warnings that are emitted in the redis client constructor
274 process.nextTick(function () {
275 if (self.listeners('warning').length !== 0) {
276 self.emit('warning', msg);
277 } else {
278 console.warn('node_redis:', msg);
279 }
280 });
281};
282
283// Flush provided queues, erroring any items with a callback first
284RedisClient.prototype.flush_and_error = function (error_attributes, options) {
285 options = options || {};
286 var aggregated_errors = [];
287 var queue_names = options.queues || ['command_queue', 'offline_queue']; // Flush the command_queue first to keep the order intakt
288 for (var i = 0; i < queue_names.length; i++) {
289 // If the command was fired it might have been processed so far
290 if (queue_names[i] === 'command_queue') {
291 error_attributes.message += ' It might have been processed.';
292 } else { // As the command_queue is flushed first, remove this for the offline queue
293 error_attributes.message = error_attributes.message.replace(' It might have been processed.', '');
294 }
295 // Don't flush everything from the queue
296 for (var command_obj = this[queue_names[i]].shift(); command_obj; command_obj = this[queue_names[i]].shift()) {
297 var err = new errorClasses.AbortError(error_attributes);
298 if (command_obj.error) {
299 err.stack = err.stack + command_obj.error.stack.replace(/^Error.*?\n/, '\n');
300 }
301 err.command = command_obj.command.toUpperCase();
302 if (command_obj.args && command_obj.args.length) {
303 err.args = command_obj.args;
304 }
305 if (options.error) {
306 err.origin = options.error;
307 }
308 if (typeof command_obj.callback === 'function') {
309 command_obj.callback(err);
310 } else {
311 aggregated_errors.push(err);
312 }
313 }
314 }
315 // Currently this would be a breaking change, therefore it's only emitted in debug_mode
316 if (exports.debug_mode && aggregated_errors.length) {
317 var error;
318 if (aggregated_errors.length === 1) {
319 error = aggregated_errors[0];
320 } else {
321 error_attributes.message = error_attributes.message.replace('It', 'They').replace(/command/i, '$&s');
322 error = new errorClasses.AggregateError(error_attributes);
323 error.errors = aggregated_errors;
324 }
325 this.emit('error', error);
326 }
327};
328
329RedisClient.prototype.on_error = function (err) {
330 if (this.closing) {
331 return;
332 }
333
334 err.message = 'Redis connection to ' + this.address + ' failed - ' + err.message;
335 debug(err.message);
336 this.connected = false;
337 this.ready = false;
338
339 // Only emit the error if the retry_strategy option is not set
340 if (!this.options.retry_strategy) {
341 this.emit('error', err);
342 }
343 // 'error' events get turned into exceptions if they aren't listened for. If the user handled this error
344 // then we should try to reconnect.
345 this.connection_gone('error', err);
346};
347
348RedisClient.prototype.on_connect = function () {
349 debug('Stream connected ' + this.address + ' id ' + this.connection_id);
350
351 this.connected = true;
352 this.ready = false;
353 this.emitted_end = false;
354 this.stream.setKeepAlive(this.options.socket_keepalive, this.options.socket_initial_delay);
355 this.stream.setTimeout(0);
356
357 this.emit('connect');
358 this.initialize_retry_vars();
359
360 if (this.options.no_ready_check) {
361 this.on_ready();
362 } else {
363 this.ready_check();
364 }
365};
366
367RedisClient.prototype.on_ready = function () {
368 var self = this;
369
370 debug('on_ready called ' + this.address + ' id ' + this.connection_id);
371 this.ready = true;
372
373 this.cork = function () {
374 self.pipeline = true;
375 if (self.stream.cork) {
376 self.stream.cork();
377 }
378 };
379 this.uncork = function () {
380 if (self.fire_strings) {
381 self.write_strings();
382 } else {
383 self.write_buffers();
384 }
385 self.pipeline = false;
386 self.fire_strings = true;
387 if (self.stream.uncork) {
388 // TODO: Consider using next tick here. See https://github.com/NodeRedis/node_redis/issues/1033
389 self.stream.uncork();
390 }
391 };
392
393 // Restore modal commands from previous connection. The order of the commands is important
394 if (this.selected_db !== undefined) {
395 this.internal_send_command(new Command('select', [this.selected_db]));
396 }
397 if (this.monitoring) { // Monitor has to be fired before pub sub commands
398 this.internal_send_command(new Command('monitor', []));
399 }
400 var callback_count = Object.keys(this.subscription_set).length;
401 if (!this.options.disable_resubscribing && callback_count) {
402 // only emit 'ready' when all subscriptions were made again
403 // TODO: Remove the countdown for ready here. This is not coherent with all other modes and should therefore not be handled special
404 // We know we are ready as soon as all commands were fired
405 var callback = function () {
406 callback_count--;
407 if (callback_count === 0) {
408 self.emit('ready');
409 }
410 };
411 debug('Sending pub/sub on_ready commands');
412 for (var key in this.subscription_set) {
413 var command = key.slice(0, key.indexOf('_'));
414 var args = this.subscription_set[key];
415 this[command]([args], callback);
416 }
417 this.send_offline_queue();
418 return;
419 }
420 this.send_offline_queue();
421 this.emit('ready');
422};
423
424RedisClient.prototype.on_info_cmd = function (err, res) {
425 if (err) {
426 if (err.message === "ERR unknown command 'info'") {
427 this.on_ready();
428 return;
429 }
430 err.message = 'Ready check failed: ' + err.message;
431 this.emit('error', err);
432 return;
433 }
434
435 /* istanbul ignore if: some servers might not respond with any info data. This is just a safety check that is difficult to test */
436 if (!res) {
437 debug('The info command returned without any data.');
438 this.on_ready();
439 return;
440 }
441
442 if (!this.server_info.loading || this.server_info.loading === '0') {
443 // If the master_link_status exists but the link is not up, try again after 50 ms
444 if (this.server_info.master_link_status && this.server_info.master_link_status !== 'up') {
445 this.server_info.loading_eta_seconds = 0.05;
446 } else {
447 // Eta loading should change
448 debug('Redis server ready.');
449 this.on_ready();
450 return;
451 }
452 }
453
454 var retry_time = +this.server_info.loading_eta_seconds * 1000;
455 if (retry_time > 1000) {
456 retry_time = 1000;
457 }
458 debug('Redis server still loading, trying again in ' + retry_time);
459 setTimeout(function (self) {
460 self.ready_check();
461 }, retry_time, this);
462};
463
464RedisClient.prototype.ready_check = function () {
465 var self = this;
466 debug('Checking server ready state...');
467 // Always fire this info command as first command even if other commands are already queued up
468 this.ready = true;
469 this.info(function (err, res) {
470 self.on_info_cmd(err, res);
471 });
472 this.ready = false;
473};
474
475RedisClient.prototype.send_offline_queue = function () {
476 for (var command_obj = this.offline_queue.shift(); command_obj; command_obj = this.offline_queue.shift()) {
477 debug('Sending offline command: ' + command_obj.command);
478 this.internal_send_command(command_obj);
479 }
480 this.drain();
481};
482
483var retry_connection = function (self, error) {
484 debug('Retrying connection...');
485
486 var reconnect_params = {
487 delay: self.retry_delay,
488 attempt: self.attempts,
489 error: error
490 };
491 if (self.options.camel_case) {
492 reconnect_params.totalRetryTime = self.retry_totaltime;
493 reconnect_params.timesConnected = self.times_connected;
494 } else {
495 reconnect_params.total_retry_time = self.retry_totaltime;
496 reconnect_params.times_connected = self.times_connected;
497 }
498 self.emit('reconnecting', reconnect_params);
499
500 self.retry_totaltime += self.retry_delay;
501 self.attempts += 1;
502 self.retry_delay = Math.round(self.retry_delay * self.retry_backoff);
503 self.create_stream();
504 self.retry_timer = null;
505};
506
507RedisClient.prototype.connection_gone = function (why, error) {
508 // If a retry is already in progress, just let that happen
509 if (this.retry_timer) {
510 return;
511 }
512 error = error || null;
513
514 debug('Redis connection is gone from ' + why + ' event.');
515 this.connected = false;
516 this.ready = false;
517 // Deactivate cork to work with the offline queue
518 this.cork = noop;
519 this.uncork = noop;
520 this.pipeline = false;
521 this.pub_sub_mode = 0;
522
523 // since we are collapsing end and close, users don't expect to be called twice
524 if (!this.emitted_end) {
525 this.emit('end');
526 this.emitted_end = true;
527 }
528
529 // If this is a requested shutdown, then don't retry
530 if (this.closing) {
531 debug('Connection ended by quit / end command, not retrying.');
532 this.flush_and_error({
533 message: 'Stream connection ended and command aborted.',
534 code: 'NR_CLOSED'
535 }, {
536 error: error
537 });
538 return;
539 }
540
541 if (typeof this.options.retry_strategy === 'function') {
542 var retry_params = {
543 attempt: this.attempts,
544 error: error
545 };
546 if (this.options.camel_case) {
547 retry_params.totalRetryTime = this.retry_totaltime;
548 retry_params.timesConnected = this.times_connected;
549 } else {
550 retry_params.total_retry_time = this.retry_totaltime;
551 retry_params.times_connected = this.times_connected;
552 }
553 this.retry_delay = this.options.retry_strategy(retry_params);
554 if (typeof this.retry_delay !== 'number') {
555 // Pass individual error through
556 if (this.retry_delay instanceof Error) {
557 error = this.retry_delay;
558 }
559 var errorMessage = 'Redis connection in broken state: ';
560 if (this.retry_totaltime >= this.connect_timeout) {
561 errorMessage += 'connection timeout exceeded.';
562 } else {
563 errorMessage += 'maximum connection attempts exceeded.';
564 }
565
566 this.flush_and_error({
567 message: errorMessage,
568 code: 'CONNECTION_BROKEN',
569 }, {
570 error: error
571 });
572 var retryError = new Error(errorMessage);
573 retryError.code = 'CONNECTION_BROKEN';
574 if (error) {
575 retryError.origin = error;
576 }
577 this.end(false);
578 this.emit('error', retryError);
579 return;
580 }
581 }
582
583 if (this.retry_totaltime >= this.connect_timeout) {
584 var message = 'Redis connection in broken state: ';
585 if (this.retry_totaltime >= this.connect_timeout) {
586 message += 'connection timeout exceeded.';
587 } else {
588 message += 'maximum connection attempts exceeded.';
589 }
590
591 this.flush_and_error({
592 message: message,
593 code: 'CONNECTION_BROKEN',
594 }, {
595 error: error
596 });
597 var err = new Error(message);
598 err.code = 'CONNECTION_BROKEN';
599 if (error) {
600 err.origin = error;
601 }
602 this.end(false);
603 this.emit('error', err);
604 return;
605 }
606
607 // Retry commands after a reconnect instead of throwing an error. Use this with caution
608 if (this.options.retry_unfulfilled_commands) {
609 this.offline_queue.unshift.apply(this.offline_queue, this.command_queue.toArray());
610 this.command_queue.clear();
611 } else if (this.command_queue.length !== 0) {
612 this.flush_and_error({
613 message: 'Redis connection lost and command aborted.',
614 code: 'UNCERTAIN_STATE'
615 }, {
616 error: error,
617 queues: ['command_queue']
618 });
619 }
620
621 if (this.retry_totaltime + this.retry_delay > this.connect_timeout) {
622 // Do not exceed the maximum
623 this.retry_delay = this.connect_timeout - this.retry_totaltime;
624 }
625
626 debug('Retry connection in ' + this.retry_delay + ' ms');
627 this.retry_timer = setTimeout(retry_connection, this.retry_delay, this, error);
628};
629
630RedisClient.prototype.return_error = function (err) {
631 var command_obj = this.command_queue.shift();
632 if (command_obj.error) {
633 err.stack = command_obj.error.stack.replace(/^Error.*?\n/, 'ReplyError: ' + err.message + '\n');
634 }
635 err.command = command_obj.command.toUpperCase();
636 if (command_obj.args && command_obj.args.length) {
637 err.args = command_obj.args;
638 }
639
640 // Count down pub sub mode if in entering modus
641 if (this.pub_sub_mode > 1) {
642 this.pub_sub_mode--;
643 }
644
645 var match = err.message.match(utils.err_code);
646 // LUA script could return user errors that don't behave like all other errors!
647 if (match) {
648 err.code = match[1];
649 }
650
651 utils.callback_or_emit(this, command_obj.callback, err);
652};
653
654RedisClient.prototype.drain = function () {
655 this.should_buffer = false;
656};
657
658function normal_reply (self, reply) {
659 var command_obj = self.command_queue.shift();
660 if (typeof command_obj.callback === 'function') {
661 if (command_obj.command !== 'exec') {
662 reply = self.handle_reply(reply, command_obj.command, command_obj.buffer_args);
663 }
664 command_obj.callback(null, reply);
665 } else {
666 debug('No callback for reply');
667 }
668}
669
670function subscribe_unsubscribe (self, reply, type) {
671 // Subscribe commands take an optional callback and also emit an event, but only the _last_ response is included in the callback
672 // The pub sub commands return each argument in a separate return value and have to be handled that way
673 var command_obj = self.command_queue.get(0);
674 var buffer = self.options.return_buffers || self.options.detect_buffers && command_obj.buffer_args;
675 var channel = (buffer || reply[1] === null) ? reply[1] : reply[1].toString();
676 var count = +reply[2]; // Return the channel counter as number no matter if `string_numbers` is activated or not
677 debug(type, channel);
678
679 // Emit first, then return the callback
680 if (channel !== null) { // Do not emit or "unsubscribe" something if there was no channel to unsubscribe from
681 self.emit(type, channel, count);
682 if (type === 'subscribe' || type === 'psubscribe') {
683 self.subscription_set[type + '_' + channel] = channel;
684 } else {
685 type = type === 'unsubscribe' ? 'subscribe' : 'psubscribe'; // Make types consistent
686 delete self.subscription_set[type + '_' + channel];
687 }
688 }
689
690 if (command_obj.args.length === 1 || self.sub_commands_left === 1 || command_obj.args.length === 0 && (count === 0 || channel === null)) {
691 if (count === 0) { // unsubscribed from all channels
692 var running_command;
693 var i = 1;
694 self.pub_sub_mode = 0; // Deactivating pub sub mode
695 // This should be a rare case and therefore handling it this way should be good performance wise for the general case
696 while (running_command = self.command_queue.get(i)) {
697 if (SUBSCRIBE_COMMANDS[running_command.command]) {
698 self.pub_sub_mode = i; // Entering pub sub mode again
699 break;
700 }
701 i++;
702 }
703 }
704 self.command_queue.shift();
705 if (typeof command_obj.callback === 'function') {
706 // TODO: The current return value is pretty useless.
707 // Evaluate to change this in v.4 to return all subscribed / unsubscribed channels in an array including the number of channels subscribed too
708 command_obj.callback(null, channel);
709 }
710 self.sub_commands_left = 0;
711 } else {
712 if (self.sub_commands_left !== 0) {
713 self.sub_commands_left--;
714 } else {
715 self.sub_commands_left = command_obj.args.length ? command_obj.args.length - 1 : count;
716 }
717 }
718}
719
720function return_pub_sub (self, reply) {
721 var type = reply[0].toString();
722 if (type === 'message') { // channel, message
723 if (!self.options.return_buffers || self.message_buffers) { // backwards compatible. Refactor this in v.4 to always return a string on the normal emitter
724 self.emit('message', reply[1].toString(), reply[2].toString());
725 self.emit('message_buffer', reply[1], reply[2]);
726 self.emit('messageBuffer', reply[1], reply[2]);
727 } else {
728 self.emit('message', reply[1], reply[2]);
729 }
730 } else if (type === 'pmessage') { // pattern, channel, message
731 if (!self.options.return_buffers || self.message_buffers) { // backwards compatible. Refactor this in v.4 to always return a string on the normal emitter
732 self.emit('pmessage', reply[1].toString(), reply[2].toString(), reply[3].toString());
733 self.emit('pmessage_buffer', reply[1], reply[2], reply[3]);
734 self.emit('pmessageBuffer', reply[1], reply[2], reply[3]);
735 } else {
736 self.emit('pmessage', reply[1], reply[2], reply[3]);
737 }
738 } else {
739 subscribe_unsubscribe(self, reply, type);
740 }
741}
742
743RedisClient.prototype.return_reply = function (reply) {
744 if (this.monitoring) {
745 var replyStr;
746 if (this.buffers && Buffer.isBuffer(reply)) {
747 replyStr = reply.toString();
748 } else {
749 replyStr = reply;
750 }
751 // If in monitor mode, all normal commands are still working and we only want to emit the streamlined commands
752 if (typeof replyStr === 'string' && utils.monitor_regex.test(replyStr)) {
753 var timestamp = replyStr.slice(0, replyStr.indexOf(' '));
754 var args = replyStr.slice(replyStr.indexOf('"') + 1, -1).split('" "').map(function (elem) {
755 return elem.replace(/\\"/g, '"');
756 });
757 this.emit('monitor', timestamp, args, replyStr);
758 return;
759 }
760 }
761 if (this.pub_sub_mode === 0) {
762 normal_reply(this, reply);
763 } else if (this.pub_sub_mode !== 1) {
764 this.pub_sub_mode--;
765 normal_reply(this, reply);
766 } else if (!(reply instanceof Array) || reply.length <= 2) {
767 // Only PING and QUIT are allowed in this context besides the pub sub commands
768 // Ping replies with ['pong', null|value] and quit with 'OK'
769 normal_reply(this, reply);
770 } else {
771 return_pub_sub(this, reply);
772 }
773};
774
775function handle_offline_command (self, command_obj) {
776 var command = command_obj.command;
777 var err, msg;
778 if (self.closing || !self.enable_offline_queue) {
779 command = command.toUpperCase();
780 if (!self.closing) {
781 if (self.stream.writable) {
782 msg = 'The connection is not yet established and the offline queue is deactivated.';
783 } else {
784 msg = 'Stream not writeable.';
785 }
786 } else {
787 msg = 'The connection is already closed.';
788 }
789 err = new errorClasses.AbortError({
790 message: command + " can't be processed. " + msg,
791 code: 'NR_CLOSED',
792 command: command
793 });
794 if (command_obj.args.length) {
795 err.args = command_obj.args;
796 }
797 utils.reply_in_order(self, command_obj.callback, err);
798 } else {
799 debug('Queueing ' + command + ' for next server connection.');
800 self.offline_queue.push(command_obj);
801 }
802 self.should_buffer = true;
803}
804
805// Do not call internal_send_command directly, if you are not absolutly certain it handles everything properly
806// e.g. monitor / info does not work with internal_send_command only
807RedisClient.prototype.internal_send_command = function (command_obj) {
808 var arg, prefix_keys;
809 var i = 0;
810 var command_str = '';
811 var args = command_obj.args;
812 var command = command_obj.command;
813 var len = args.length;
814 var big_data = false;
815 var args_copy = new Array(len);
816
817 if (process.domain && command_obj.callback) {
818 command_obj.callback = process.domain.bind(command_obj.callback);
819 }
820
821 if (this.ready === false || this.stream.writable === false) {
822 // Handle offline commands right away
823 handle_offline_command(this, command_obj);
824 return false; // Indicate buffering
825 }
826
827 for (i = 0; i < len; i += 1) {
828 if (typeof args[i] === 'string') {
829 // 30000 seemed to be a good value to switch to buffers after testing and checking the pros and cons
830 if (args[i].length > 30000) {
831 big_data = true;
832 args_copy[i] = Buffer.from(args[i], 'utf8');
833 } else {
834 args_copy[i] = args[i];
835 }
836 } else if (typeof args[i] === 'object') { // Checking for object instead of Buffer.isBuffer helps us finding data types that we can't handle properly
837 if (args[i] instanceof Date) { // Accept dates as valid input
838 args_copy[i] = args[i].toString();
839 } else if (Buffer.isBuffer(args[i])) {
840 args_copy[i] = args[i];
841 command_obj.buffer_args = true;
842 big_data = true;
843 } else {
844 var invalidArgError = new Error(
845 'node_redis: The ' + command.toUpperCase() + ' command contains a invalid argument type.\n' +
846 'Only strings, dates and buffers are accepted. Please update your code to use valid argument types.'
847 );
848 invalidArgError.command = command_obj.command.toUpperCase();
849 if (command_obj.args && command_obj.args.length) {
850 invalidArgError.args = command_obj.args;
851 }
852 if (command_obj.callback) {
853 command_obj.callback(invalidArgError);
854 return false;
855 }
856 throw invalidArgError;
857 }
858 } else if (typeof args[i] === 'undefined') {
859 var undefinedArgError = new Error(
860 'node_redis: The ' + command.toUpperCase() + ' command contains a invalid argument type of "undefined".\n' +
861 'Only strings, dates and buffers are accepted. Please update your code to use valid argument types.'
862 );
863 undefinedArgError.command = command_obj.command.toUpperCase();
864 if (command_obj.args && command_obj.args.length) {
865 undefinedArgError.args = command_obj.args;
866 }
867 if (command_obj.callback) {
868 command_obj.callback(undefinedArgError);
869 return false;
870 }
871 throw undefinedArgError;
872 } else {
873 // Seems like numbers are converted fast using string concatenation
874 args_copy[i] = '' + args[i];
875 }
876 }
877
878 if (this.options.prefix) {
879 prefix_keys = commands.getKeyIndexes(command, args_copy);
880 for (i = prefix_keys.pop(); i !== undefined; i = prefix_keys.pop()) {
881 args_copy[i] = this.options.prefix + args_copy[i];
882 }
883 }
884 if (this.options.rename_commands && this.options.rename_commands[command]) {
885 command = this.options.rename_commands[command];
886 }
887 // Always use 'Multi bulk commands', but if passed any Buffer args, then do multiple writes, one for each arg.
888 // This means that using Buffers in commands is going to be slower, so use Strings if you don't already have a Buffer.
889 command_str = '*' + (len + 1) + '\r\n$' + command.length + '\r\n' + command + '\r\n';
890
891 if (big_data === false) { // Build up a string and send entire command in one write
892 for (i = 0; i < len; i += 1) {
893 arg = args_copy[i];
894 command_str += '$' + Buffer.byteLength(arg) + '\r\n' + arg + '\r\n';
895 }
896 debug('Send ' + this.address + ' id ' + this.connection_id + ': ' + command_str);
897 this.write(command_str);
898 } else {
899 debug('Send command (' + command_str + ') has Buffer arguments');
900 this.fire_strings = false;
901 this.write(command_str);
902
903 for (i = 0; i < len; i += 1) {
904 arg = args_copy[i];
905 if (typeof arg === 'string') {
906 this.write('$' + Buffer.byteLength(arg) + '\r\n' + arg + '\r\n');
907 } else { // buffer
908 this.write('$' + arg.length + '\r\n');
909 this.write(arg);
910 this.write('\r\n');
911 }
912 debug('send_command: buffer send ' + arg.length + ' bytes');
913 }
914 }
915 if (command_obj.call_on_write) {
916 command_obj.call_on_write();
917 }
918 // Handle `CLIENT REPLY ON|OFF|SKIP`
919 // This has to be checked after call_on_write
920 /* istanbul ignore else: TODO: Remove this as soon as we test Redis 3.2 on travis */
921 if (this.reply === 'ON') {
922 this.command_queue.push(command_obj);
923 } else {
924 // Do not expect a reply
925 // Does this work in combination with the pub sub mode?
926 if (command_obj.callback) {
927 utils.reply_in_order(this, command_obj.callback, null, undefined, this.command_queue);
928 }
929 if (this.reply === 'SKIP') {
930 this.reply = 'SKIP_ONE_MORE';
931 } else if (this.reply === 'SKIP_ONE_MORE') {
932 this.reply = 'ON';
933 }
934 }
935 return !this.should_buffer;
936};
937
938RedisClient.prototype.write_strings = function () {
939 var str = '';
940 for (var command = this.pipeline_queue.shift(); command; command = this.pipeline_queue.shift()) {
941 // Write to stream if the string is bigger than 4mb. The biggest string may be Math.pow(2, 28) - 15 chars long
942 if (str.length + command.length > 4 * 1024 * 1024) {
943 this.should_buffer = !this.stream.write(str);
944 str = '';
945 }
946 str += command;
947 }
948 if (str !== '') {
949 this.should_buffer = !this.stream.write(str);
950 }
951};
952
953RedisClient.prototype.write_buffers = function () {
954 for (var command = this.pipeline_queue.shift(); command; command = this.pipeline_queue.shift()) {
955 this.should_buffer = !this.stream.write(command);
956 }
957};
958
959RedisClient.prototype.write = function (data) {
960 if (this.pipeline === false) {
961 this.should_buffer = !this.stream.write(data);
962 return;
963 }
964 this.pipeline_queue.push(data);
965};
966
967Object.defineProperty(exports, 'debugMode', {
968 get: function () {
969 return this.debug_mode;
970 },
971 set: function (val) {
972 this.debug_mode = val;
973 }
974});
975
976// Don't officially expose the command_queue directly but only the length as read only variable
977Object.defineProperty(RedisClient.prototype, 'command_queue_length', {
978 get: function () {
979 return this.command_queue.length;
980 }
981});
982
983Object.defineProperty(RedisClient.prototype, 'offline_queue_length', {
984 get: function () {
985 return this.offline_queue.length;
986 }
987});
988
989// Add support for camelCase by adding read only properties to the client
990// All known exposed snake_case variables are added here
991Object.defineProperty(RedisClient.prototype, 'retryDelay', {
992 get: function () {
993 return this.retry_delay;
994 }
995});
996
997Object.defineProperty(RedisClient.prototype, 'retryBackoff', {
998 get: function () {
999 return this.retry_backoff;
1000 }
1001});
1002
1003Object.defineProperty(RedisClient.prototype, 'commandQueueLength', {
1004 get: function () {
1005 return this.command_queue.length;
1006 }
1007});
1008
1009Object.defineProperty(RedisClient.prototype, 'offlineQueueLength', {
1010 get: function () {
1011 return this.offline_queue.length;
1012 }
1013});
1014
1015Object.defineProperty(RedisClient.prototype, 'shouldBuffer', {
1016 get: function () {
1017 return this.should_buffer;
1018 }
1019});
1020
1021Object.defineProperty(RedisClient.prototype, 'connectionId', {
1022 get: function () {
1023 return this.connection_id;
1024 }
1025});
1026
1027Object.defineProperty(RedisClient.prototype, 'serverInfo', {
1028 get: function () {
1029 return this.server_info;
1030 }
1031});
1032
1033exports.createClient = function () {
1034 return new RedisClient(unifyOptions.apply(null, arguments));
1035};
1036exports.RedisClient = RedisClient;
1037exports.print = utils.print;
1038exports.Multi = require('./lib/multi');
1039exports.AbortError = errorClasses.AbortError;
1040exports.RedisError = RedisErrors.RedisError;
1041exports.ParserError = RedisErrors.ParserError;
1042exports.ReplyError = RedisErrors.ReplyError;
1043exports.AggregateError = errorClasses.AggregateError;
1044
1045// Add all redis commands / node_redis api to the client
1046require('./lib/individualCommands');
1047require('./lib/extendedApi');
1048
1049//enables adding new commands (for modules and new commands)
1050exports.addCommand = exports.add_command = require('./lib/commands');