UNPKG

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