1 | 'use strict';
|
2 |
|
3 | var net = require('net');
|
4 | var tls = require('tls');
|
5 | var util = require('util');
|
6 | var utils = require('./lib/utils');
|
7 | var Command = require('./lib/command');
|
8 | var Queue = require('double-ended-queue');
|
9 | var errorClasses = require('./lib/customErrors');
|
10 | var EventEmitter = require('events');
|
11 | var Parser = require('redis-parser');
|
12 | var commands = require('redis-commands');
|
13 | var debug = require('./lib/debug');
|
14 | var unifyOptions = require('./lib/createClient');
|
15 | var SUBSCRIBE_COMMANDS = {
|
16 | subscribe: true,
|
17 | unsubscribe: true,
|
18 | psubscribe: true,
|
19 | punsubscribe: true
|
20 | };
|
21 |
|
22 |
|
23 | if (typeof EventEmitter !== 'function') {
|
24 | EventEmitter = EventEmitter.EventEmitter;
|
25 | }
|
26 |
|
27 | function noop () {}
|
28 |
|
29 | function handle_detect_buffers_reply (reply, command, buffer_args) {
|
30 | if (buffer_args === false || this.message_buffers) {
|
31 |
|
32 |
|
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 |
|
42 | exports.debug_mode = /\bredis\b/i.test(process.env.NODE_DEBUG);
|
43 |
|
44 |
|
45 |
|
46 | function RedisClient (options, stream) {
|
47 |
|
48 | options = utils.clone(options);
|
49 | EventEmitter.call(this);
|
50 | var cnx_options = {};
|
51 | var self = this;
|
52 |
|
53 | for (var tls_option in options.tls) {
|
54 | cnx_options[tls_option] = options.tls[tls_option];
|
55 |
|
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 |
|
62 |
|
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 |
|
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 |
|
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 |
|
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) {
|
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 |
|
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 |
|
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();
|
128 | this.offline_queue = new Queue();
|
129 | this.pipeline_queue = new Queue();
|
130 |
|
131 |
|
132 | this.connect_timeout = +options.connect_timeout || 3600000;
|
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;
|
151 | this.old_state = null;
|
152 | this.fire_strings = true;
|
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';
|
159 |
|
160 | this.reply_parser = create_parser(this);
|
161 | this.create_stream();
|
162 |
|
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 | }
|
181 | util.inherits(RedisClient, EventEmitter);
|
182 |
|
183 | RedisClient.connection_id = 0;
|
184 |
|
185 | function create_parser (self) {
|
186 | return new Parser({
|
187 | returnReply: function (data) {
|
188 | self.return_reply(data);
|
189 | },
|
190 | returnError: function (err) {
|
191 |
|
192 | self.return_error(err);
|
193 | },
|
194 | returnFatalError: function (err) {
|
195 |
|
196 |
|
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 |
|
218 |
|
219 |
|
220 |
|
221 |
|
222 |
|
223 |
|
224 | RedisClient.prototype.create_stream = function () {
|
225 | var self = this;
|
226 |
|
227 | if (this.options.stream) {
|
228 |
|
229 | if (this.stream) {
|
230 | return;
|
231 | }
|
232 | this.stream = this.options.stream;
|
233 | } else {
|
234 |
|
235 | if (this.stream) {
|
236 | this.stream.removeAllListeners();
|
237 | this.stream.destroy();
|
238 | }
|
239 |
|
240 |
|
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 |
|
251 | self.retry_totaltime = self.connect_timeout;
|
252 | self.connection_gone('timeout');
|
253 | });
|
254 | }
|
255 |
|
256 |
|
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 |
|
266 | debug('Net read ' + self.address + ' id ' + self.connection_id);
|
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 |
|
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 |
|
298 | if (this.auth_pass !== undefined) {
|
299 | this.ready = true;
|
300 | this.auth(this.auth_pass);
|
301 | this.ready = false;
|
302 | }
|
303 | };
|
304 |
|
305 | RedisClient.prototype.handle_reply = function (reply, command) {
|
306 | if (command === 'hgetall') {
|
307 | reply = utils.reply_to_object(reply);
|
308 | }
|
309 | return reply;
|
310 | };
|
311 |
|
312 | RedisClient.prototype.cork = noop;
|
313 | RedisClient.prototype.uncork = noop;
|
314 |
|
315 | RedisClient.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 |
|
323 | RedisClient.prototype.warn = function (msg) {
|
324 | var self = this;
|
325 |
|
326 |
|
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 |
|
337 | RedisClient.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'];
|
341 | for (var i = 0; i < queue_names.length; i++) {
|
342 |
|
343 | if (queue_names[i] === 'command_queue') {
|
344 | error_attributes.message += ' It might have been processed.';
|
345 | } else {
|
346 | error_attributes.message = error_attributes.message.replace(' It might have been processed.', '');
|
347 | }
|
348 |
|
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 |
|
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 |
|
382 | RedisClient.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 |
|
393 | if (!this.options.retry_strategy) {
|
394 | this.emit('error', err);
|
395 | }
|
396 |
|
397 |
|
398 | this.connection_gone('error', err);
|
399 | };
|
400 |
|
401 | RedisClient.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 |
|
420 | RedisClient.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 |
|
442 | self.stream.uncork();
|
443 | }
|
444 | };
|
445 |
|
446 |
|
447 | if (this.selected_db !== undefined) {
|
448 | this.internal_send_command(new Command('select', [this.selected_db]));
|
449 | }
|
450 | if (this.monitoring) {
|
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 |
|
456 |
|
457 |
|
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 |
|
477 | RedisClient.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 |
|
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 |
|
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 |
|
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 |
|
517 | RedisClient.prototype.ready_check = function () {
|
518 | var self = this;
|
519 | debug('Checking server ready state...');
|
520 |
|
521 | this.ready = true;
|
522 | this.info(function (err, res) {
|
523 | self.on_info_cmd(err, res);
|
524 | });
|
525 | this.ready = false;
|
526 | };
|
527 |
|
528 | RedisClient.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 |
|
536 | var 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 |
|
560 | RedisClient.prototype.connection_gone = function (why, error) {
|
561 |
|
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 |
|
571 | this.cork = noop;
|
572 | this.uncork = noop;
|
573 | this.pipeline = false;
|
574 | this.pub_sub_mode = 0;
|
575 |
|
576 |
|
577 | if (!this.emitted_end) {
|
578 | this.emit('end');
|
579 | this.emitted_end = true;
|
580 | }
|
581 |
|
582 |
|
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 |
|
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 |
|
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 |
|
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 |
|
673 | RedisClient.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 |
|
684 | if (this.pub_sub_mode > 1) {
|
685 | this.pub_sub_mode--;
|
686 | }
|
687 |
|
688 | var match = err.message.match(utils.err_code);
|
689 |
|
690 | if (match) {
|
691 | err.code = match[1];
|
692 | }
|
693 |
|
694 | utils.callback_or_emit(this, command_obj.callback, err);
|
695 | };
|
696 |
|
697 | RedisClient.prototype.drain = function () {
|
698 | this.emit('drain');
|
699 | this.should_buffer = false;
|
700 | };
|
701 |
|
702 | RedisClient.prototype.emit_idle = function () {
|
703 | if (this.command_queue.length === 0 && this.pub_sub_mode === 0) {
|
704 | this.emit('idle');
|
705 | }
|
706 | };
|
707 |
|
708 | function 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 |
|
720 | function subscribe_unsubscribe (self, reply, type) {
|
721 |
|
722 |
|
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];
|
727 | debug(type, channel);
|
728 |
|
729 |
|
730 | if (channel !== null) {
|
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';
|
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) {
|
742 | var running_command;
|
743 | var i = 1;
|
744 | self.pub_sub_mode = 0;
|
745 |
|
746 | while (running_command = self.command_queue.get(i)) {
|
747 | if (SUBSCRIBE_COMMANDS[running_command.command]) {
|
748 | self.pub_sub_mode = i;
|
749 | break;
|
750 | }
|
751 | i++;
|
752 | }
|
753 | }
|
754 | self.command_queue.shift();
|
755 | if (typeof command_obj.callback === 'function') {
|
756 |
|
757 |
|
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 |
|
770 | function return_pub_sub (self, reply) {
|
771 | var type = reply[0].toString();
|
772 | if (type === 'message') {
|
773 | if (!self.options.return_buffers || self.message_buffers) {
|
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') {
|
781 | if (!self.options.return_buffers || self.message_buffers) {
|
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 |
|
793 | RedisClient.prototype.return_reply = function (reply) {
|
794 |
|
795 |
|
796 |
|
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 |
|
805 |
|
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 |
|
822 |
|
823 | normal_reply(this, reply);
|
824 | } else {
|
825 | return_pub_sub(this, reply);
|
826 | }
|
827 | };
|
828 |
|
829 | function 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 |
|
860 |
|
861 | RedisClient.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 |
|
877 | handle_offline_command(this, command_obj);
|
878 | return false;
|
879 | }
|
880 |
|
881 | for (i = 0; i < len; i += 1) {
|
882 | if (typeof args[i] === 'string') {
|
883 |
|
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') {
|
891 | if (args[i] instanceof Date) {
|
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';
|
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();
|
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';
|
919 | } else {
|
920 |
|
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 |
|
935 |
|
936 | command_str = '*' + (len + 1) + '\r\n$' + command.length + '\r\n' + command + '\r\n';
|
937 |
|
938 | if (big_data === false) {
|
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 {
|
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 |
|
966 |
|
967 |
|
968 | if (this.reply === 'ON') {
|
969 | this.command_queue.push(command_obj);
|
970 | } else {
|
971 |
|
972 |
|
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 |
|
985 | RedisClient.prototype.write_strings = function () {
|
986 | var str = '';
|
987 | for (var command = this.pipeline_queue.shift(); command; command = this.pipeline_queue.shift()) {
|
988 |
|
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 |
|
1000 | RedisClient.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 |
|
1006 | RedisClient.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 |
|
1014 | Object.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 |
|
1024 | Object.defineProperty(RedisClient.prototype, 'command_queue_length', {
|
1025 | get: function () {
|
1026 | return this.command_queue.length;
|
1027 | }
|
1028 | });
|
1029 |
|
1030 | Object.defineProperty(RedisClient.prototype, 'offline_queue_length', {
|
1031 | get: function () {
|
1032 | return this.offline_queue.length;
|
1033 | }
|
1034 | });
|
1035 |
|
1036 |
|
1037 |
|
1038 | Object.defineProperty(RedisClient.prototype, 'retryDelay', {
|
1039 | get: function () {
|
1040 | return this.retry_delay;
|
1041 | }
|
1042 | });
|
1043 |
|
1044 | Object.defineProperty(RedisClient.prototype, 'retryBackoff', {
|
1045 | get: function () {
|
1046 | return this.retry_backoff;
|
1047 | }
|
1048 | });
|
1049 |
|
1050 | Object.defineProperty(RedisClient.prototype, 'commandQueueLength', {
|
1051 | get: function () {
|
1052 | return this.command_queue.length;
|
1053 | }
|
1054 | });
|
1055 |
|
1056 | Object.defineProperty(RedisClient.prototype, 'offlineQueueLength', {
|
1057 | get: function () {
|
1058 | return this.offline_queue.length;
|
1059 | }
|
1060 | });
|
1061 |
|
1062 | Object.defineProperty(RedisClient.prototype, 'shouldBuffer', {
|
1063 | get: function () {
|
1064 | return this.should_buffer;
|
1065 | }
|
1066 | });
|
1067 |
|
1068 | Object.defineProperty(RedisClient.prototype, 'connectionId', {
|
1069 | get: function () {
|
1070 | return this.connection_id;
|
1071 | }
|
1072 | });
|
1073 |
|
1074 | Object.defineProperty(RedisClient.prototype, 'serverInfo', {
|
1075 | get: function () {
|
1076 | return this.server_info;
|
1077 | }
|
1078 | });
|
1079 |
|
1080 | exports.createClient = function () {
|
1081 | return new RedisClient(unifyOptions.apply(null, arguments));
|
1082 | };
|
1083 | exports.RedisClient = RedisClient;
|
1084 | exports.print = utils.print;
|
1085 | exports.Multi = require('./lib/multi');
|
1086 | exports.AbortError = errorClasses.AbortError;
|
1087 | exports.ReplyError = Parser.ReplyError;
|
1088 | exports.AggregateError = errorClasses.AggregateError;
|
1089 |
|
1090 |
|
1091 | require('./lib/individualCommands');
|
1092 | require('./lib/extendedApi');
|
1093 | require('./lib/commands');
|