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('denque');
|
9 | var errorClasses = require('./lib/customErrors');
|
10 | var EventEmitter = require('events');
|
11 | var Parser = require('redis-parser');
|
12 | var RedisErrors = require('redis-errors');
|
13 | var commands = require('redis-commands');
|
14 | var debug = require('./lib/debug');
|
15 | var unifyOptions = require('./lib/createClient');
|
16 | var SUBSCRIBE_COMMANDS = {
|
17 | subscribe: true,
|
18 | unsubscribe: true,
|
19 | psubscribe: true,
|
20 | punsubscribe: true
|
21 | };
|
22 |
|
23 | function noop () {}
|
24 |
|
25 | function handle_detect_buffers_reply (reply, command, buffer_args) {
|
26 | if (buffer_args === false || this.message_buffers) {
|
27 |
|
28 |
|
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 |
|
38 | exports.debug_mode = /\bredis\b/i.test(process.env.NODE_DEBUG);
|
39 |
|
40 |
|
41 |
|
42 | function RedisClient (options, stream) {
|
43 |
|
44 | options = utils.clone(options);
|
45 | EventEmitter.call(this);
|
46 | var cnx_options = {};
|
47 | var self = this;
|
48 |
|
49 | for (var tls_option in options.tls) {
|
50 | cnx_options[tls_option] = options.tls[tls_option];
|
51 |
|
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 |
|
58 |
|
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 |
|
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 |
|
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 |
|
94 | this.handle_reply = handle_detect_buffers_reply;
|
95 | }
|
96 | this.should_buffer = false;
|
97 | this.command_queue = new Queue();
|
98 | this.offline_queue = new Queue();
|
99 | this.pipeline_queue = new Queue();
|
100 |
|
101 |
|
102 | this.connect_timeout = +options.connect_timeout || 3600000;
|
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;
|
113 | this.fire_strings = true;
|
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';
|
120 | this.create_stream();
|
121 |
|
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 | }
|
130 | util.inherits(RedisClient, EventEmitter);
|
131 |
|
132 | RedisClient.connection_id = 0;
|
133 |
|
134 | function create_parser (self) {
|
135 | return new Parser({
|
136 | returnReply: function (data) {
|
137 | self.return_reply(data);
|
138 | },
|
139 | returnError: function (err) {
|
140 |
|
141 | self.return_error(err);
|
142 | },
|
143 | returnFatalError: function (err) {
|
144 |
|
145 |
|
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 |
|
166 |
|
167 |
|
168 |
|
169 |
|
170 |
|
171 |
|
172 | RedisClient.prototype.create_stream = function () {
|
173 | var self = this;
|
174 |
|
175 |
|
176 | this.reply_parser = create_parser(this);
|
177 |
|
178 | if (this.options.stream) {
|
179 |
|
180 | if (this.stream) {
|
181 | return;
|
182 | }
|
183 | this.stream = this.options.stream;
|
184 | } else {
|
185 |
|
186 | if (this.stream) {
|
187 | this.stream.removeAllListeners();
|
188 | this.stream.destroy();
|
189 | }
|
190 |
|
191 |
|
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 |
|
202 | self.retry_totaltime = self.connect_timeout;
|
203 | self.connection_gone('timeout');
|
204 | });
|
205 | }
|
206 |
|
207 |
|
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 |
|
217 | debug('Net read ' + self.address + ' id ' + self.connection_id);
|
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 |
|
240 | if (this.auth_pass !== undefined) {
|
241 | this.ready = true;
|
242 |
|
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 |
|
252 | RedisClient.prototype.handle_reply = function (reply, command) {
|
253 | if (command === 'hgetall') {
|
254 | reply = utils.reply_to_object(reply);
|
255 | }
|
256 | return reply;
|
257 | };
|
258 |
|
259 | RedisClient.prototype.cork = noop;
|
260 | RedisClient.prototype.uncork = noop;
|
261 |
|
262 | RedisClient.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 |
|
270 | RedisClient.prototype.warn = function (msg) {
|
271 | var self = this;
|
272 |
|
273 |
|
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 |
|
284 | RedisClient.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'];
|
288 | for (var i = 0; i < queue_names.length; i++) {
|
289 |
|
290 | if (queue_names[i] === 'command_queue') {
|
291 | error_attributes.message += ' It might have been processed.';
|
292 | } else {
|
293 | error_attributes.message = error_attributes.message.replace(' It might have been processed.', '');
|
294 | }
|
295 |
|
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 |
|
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 |
|
329 | RedisClient.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 |
|
340 | if (!this.options.retry_strategy) {
|
341 | this.emit('error', err);
|
342 | }
|
343 |
|
344 |
|
345 | this.connection_gone('error', err);
|
346 | };
|
347 |
|
348 | RedisClient.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 |
|
367 | RedisClient.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 |
|
389 | self.stream.uncork();
|
390 | }
|
391 | };
|
392 |
|
393 |
|
394 | if (this.selected_db !== undefined) {
|
395 | this.internal_send_command(new Command('select', [this.selected_db]));
|
396 | }
|
397 | if (this.monitoring) {
|
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 |
|
403 |
|
404 |
|
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 |
|
424 | RedisClient.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 |
|
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 |
|
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 |
|
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 |
|
464 | RedisClient.prototype.ready_check = function () {
|
465 | var self = this;
|
466 | debug('Checking server ready state...');
|
467 |
|
468 | this.ready = true;
|
469 | this.info(function (err, res) {
|
470 | self.on_info_cmd(err, res);
|
471 | });
|
472 | this.ready = false;
|
473 | };
|
474 |
|
475 | RedisClient.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 |
|
483 | var 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 |
|
507 | RedisClient.prototype.connection_gone = function (why, error) {
|
508 |
|
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 |
|
518 | this.cork = noop;
|
519 | this.uncork = noop;
|
520 | this.pipeline = false;
|
521 | this.pub_sub_mode = 0;
|
522 |
|
523 |
|
524 | if (!this.emitted_end) {
|
525 | this.emit('end');
|
526 | this.emitted_end = true;
|
527 | }
|
528 |
|
529 |
|
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 |
|
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 |
|
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 |
|
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 |
|
630 | RedisClient.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 |
|
641 | if (this.pub_sub_mode > 1) {
|
642 | this.pub_sub_mode--;
|
643 | }
|
644 |
|
645 | var match = err.message.match(utils.err_code);
|
646 |
|
647 | if (match) {
|
648 | err.code = match[1];
|
649 | }
|
650 |
|
651 | utils.callback_or_emit(this, command_obj.callback, err);
|
652 | };
|
653 |
|
654 | RedisClient.prototype.drain = function () {
|
655 | this.should_buffer = false;
|
656 | };
|
657 |
|
658 | function 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 |
|
670 | function subscribe_unsubscribe (self, reply, type) {
|
671 |
|
672 |
|
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];
|
677 | debug(type, channel);
|
678 |
|
679 |
|
680 | if (channel !== null) {
|
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';
|
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) {
|
692 | var running_command;
|
693 | var i = 1;
|
694 | self.pub_sub_mode = 0;
|
695 |
|
696 | while (running_command = self.command_queue.get(i)) {
|
697 | if (SUBSCRIBE_COMMANDS[running_command.command]) {
|
698 | self.pub_sub_mode = i;
|
699 | break;
|
700 | }
|
701 | i++;
|
702 | }
|
703 | }
|
704 | self.command_queue.shift();
|
705 | if (typeof command_obj.callback === 'function') {
|
706 |
|
707 |
|
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 |
|
720 | function return_pub_sub (self, reply) {
|
721 | var type = reply[0].toString();
|
722 | if (type === 'message') {
|
723 | if (!self.options.return_buffers || self.message_buffers) {
|
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') {
|
731 | if (!self.options.return_buffers || self.message_buffers) {
|
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 |
|
743 | RedisClient.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 |
|
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 |
|
768 |
|
769 | normal_reply(this, reply);
|
770 | } else {
|
771 | return_pub_sub(this, reply);
|
772 | }
|
773 | };
|
774 |
|
775 | function 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 |
|
806 |
|
807 | RedisClient.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 |
|
823 | handle_offline_command(this, command_obj);
|
824 | return false;
|
825 | }
|
826 |
|
827 | for (i = 0; i < len; i += 1) {
|
828 | if (typeof args[i] === 'string') {
|
829 |
|
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') {
|
837 | if (args[i] instanceof Date) {
|
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 |
|
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 |
|
888 |
|
889 | command_str = '*' + (len + 1) + '\r\n$' + command.length + '\r\n' + command + '\r\n';
|
890 |
|
891 | if (big_data === false) {
|
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 {
|
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 |
|
919 |
|
920 |
|
921 | if (this.reply === 'ON') {
|
922 | this.command_queue.push(command_obj);
|
923 | } else {
|
924 |
|
925 |
|
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 |
|
938 | RedisClient.prototype.write_strings = function () {
|
939 | var str = '';
|
940 | for (var command = this.pipeline_queue.shift(); command; command = this.pipeline_queue.shift()) {
|
941 |
|
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 |
|
953 | RedisClient.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 |
|
959 | RedisClient.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 |
|
967 | Object.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 |
|
977 | Object.defineProperty(RedisClient.prototype, 'command_queue_length', {
|
978 | get: function () {
|
979 | return this.command_queue.length;
|
980 | }
|
981 | });
|
982 |
|
983 | Object.defineProperty(RedisClient.prototype, 'offline_queue_length', {
|
984 | get: function () {
|
985 | return this.offline_queue.length;
|
986 | }
|
987 | });
|
988 |
|
989 |
|
990 |
|
991 | Object.defineProperty(RedisClient.prototype, 'retryDelay', {
|
992 | get: function () {
|
993 | return this.retry_delay;
|
994 | }
|
995 | });
|
996 |
|
997 | Object.defineProperty(RedisClient.prototype, 'retryBackoff', {
|
998 | get: function () {
|
999 | return this.retry_backoff;
|
1000 | }
|
1001 | });
|
1002 |
|
1003 | Object.defineProperty(RedisClient.prototype, 'commandQueueLength', {
|
1004 | get: function () {
|
1005 | return this.command_queue.length;
|
1006 | }
|
1007 | });
|
1008 |
|
1009 | Object.defineProperty(RedisClient.prototype, 'offlineQueueLength', {
|
1010 | get: function () {
|
1011 | return this.offline_queue.length;
|
1012 | }
|
1013 | });
|
1014 |
|
1015 | Object.defineProperty(RedisClient.prototype, 'shouldBuffer', {
|
1016 | get: function () {
|
1017 | return this.should_buffer;
|
1018 | }
|
1019 | });
|
1020 |
|
1021 | Object.defineProperty(RedisClient.prototype, 'connectionId', {
|
1022 | get: function () {
|
1023 | return this.connection_id;
|
1024 | }
|
1025 | });
|
1026 |
|
1027 | Object.defineProperty(RedisClient.prototype, 'serverInfo', {
|
1028 | get: function () {
|
1029 | return this.server_info;
|
1030 | }
|
1031 | });
|
1032 |
|
1033 | exports.createClient = function () {
|
1034 | return new RedisClient(unifyOptions.apply(null, arguments));
|
1035 | };
|
1036 | exports.RedisClient = RedisClient;
|
1037 | exports.print = utils.print;
|
1038 | exports.Multi = require('./lib/multi');
|
1039 | exports.AbortError = errorClasses.AbortError;
|
1040 | exports.RedisError = RedisErrors.RedisError;
|
1041 | exports.ParserError = RedisErrors.ParserError;
|
1042 | exports.ReplyError = RedisErrors.ReplyError;
|
1043 | exports.AggregateError = errorClasses.AggregateError;
|
1044 |
|
1045 |
|
1046 | require('./lib/individualCommands');
|
1047 | require('./lib/extendedApi');
|
1048 |
|
1049 |
|
1050 | exports.addCommand = exports.add_command = require('./lib/commands');
|