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 number of options and to 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 | this.create_stream();
|
160 |
|
161 | this.on('newListener', function (event) {
|
162 | if (event === 'idle') {
|
163 | this.warn(
|
164 | 'The idle event listener is deprecated and will likely be removed in v.3.0.0.\n' +
|
165 | 'If you rely on this feature please open a new ticket in node_redis with your use case'
|
166 | );
|
167 | } else if (event === 'drain') {
|
168 | this.warn(
|
169 | 'The drain event listener is deprecated and will be removed in v.3.0.0.\n' +
|
170 | 'If you want to keep on listening to this event please listen to the stream drain event directly.'
|
171 | );
|
172 | } else if ((event === 'message_buffer' || event === 'pmessage_buffer' || event === 'messageBuffer' || event === 'pmessageBuffer') && !this.buffers && !this.message_buffers) {
|
173 | if (this.reply_parser.name !== 'javascript') {
|
174 | return this.warn(
|
175 | 'You attached the "' + event + '" listener without the returnBuffers option set to true.\n' +
|
176 | 'Please use the JavaScript parser or set the returnBuffers option to true to return buffers.'
|
177 | );
|
178 | }
|
179 | this.reply_parser.optionReturnBuffers = true;
|
180 | this.message_buffers = true;
|
181 | this.handle_reply = handle_detect_buffers_reply;
|
182 | }
|
183 | });
|
184 | }
|
185 | util.inherits(RedisClient, EventEmitter);
|
186 |
|
187 | RedisClient.connection_id = 0;
|
188 |
|
189 | function create_parser (self) {
|
190 | return new Parser({
|
191 | returnReply: function (data) {
|
192 | self.return_reply(data);
|
193 | },
|
194 | returnError: function (err) {
|
195 |
|
196 | self.return_error(err);
|
197 | },
|
198 | returnFatalError: function (err) {
|
199 |
|
200 |
|
201 | err.message += '. Please report this.';
|
202 | self.ready = false;
|
203 | self.flush_and_error({
|
204 | message: 'Fatal error encountert. Command aborted.',
|
205 | code: 'NR_FATAL'
|
206 | }, {
|
207 | error: err,
|
208 | queues: ['command_queue']
|
209 | });
|
210 | self.emit('error', err);
|
211 | self.create_stream();
|
212 | },
|
213 | returnBuffers: self.buffers || self.message_buffers,
|
214 | name: self.options.parser || 'javascript',
|
215 | stringNumbers: self.options.string_numbers || false
|
216 | });
|
217 | }
|
218 |
|
219 |
|
220 |
|
221 |
|
222 |
|
223 |
|
224 |
|
225 |
|
226 |
|
227 |
|
228 | RedisClient.prototype.create_stream = function () {
|
229 | var self = this;
|
230 |
|
231 |
|
232 | this.reply_parser = create_parser(this);
|
233 |
|
234 | if (this.options.stream) {
|
235 |
|
236 | if (this.stream) {
|
237 | return;
|
238 | }
|
239 | this.stream = this.options.stream;
|
240 | } else {
|
241 |
|
242 | if (this.stream) {
|
243 | this.stream.removeAllListeners();
|
244 | this.stream.destroy();
|
245 | }
|
246 |
|
247 |
|
248 | if (this.options.tls) {
|
249 | this.stream = tls.connect(this.connection_options);
|
250 | } else {
|
251 | this.stream = net.createConnection(this.connection_options);
|
252 | }
|
253 | }
|
254 |
|
255 | if (this.options.connect_timeout) {
|
256 | this.stream.setTimeout(this.connect_timeout, function () {
|
257 |
|
258 | self.retry_totaltime = self.connect_timeout;
|
259 | self.connection_gone('timeout');
|
260 | });
|
261 | }
|
262 |
|
263 |
|
264 | var connect_event = this.options.tls ? 'secureConnect' : 'connect';
|
265 | this.stream.once(connect_event, function () {
|
266 | this.removeAllListeners('timeout');
|
267 | self.times_connected++;
|
268 | self.on_connect();
|
269 | });
|
270 |
|
271 | this.stream.on('data', function (buffer_from_socket) {
|
272 |
|
273 | debug('Net read ' + self.address + ' id ' + self.connection_id);
|
274 | self.reply_parser.execute(buffer_from_socket);
|
275 | self.emit_idle();
|
276 | });
|
277 |
|
278 | this.stream.on('error', function (err) {
|
279 | self.on_error(err);
|
280 | });
|
281 |
|
282 |
|
283 | this.stream.on('clientError', function (err) {
|
284 | debug('clientError occured');
|
285 | self.on_error(err);
|
286 | });
|
287 |
|
288 | this.stream.once('close', function (hadError) {
|
289 | self.connection_gone('close');
|
290 | });
|
291 |
|
292 | this.stream.once('end', function () {
|
293 | self.connection_gone('end');
|
294 | });
|
295 |
|
296 | this.stream.on('drain', function () {
|
297 | self.drain();
|
298 | });
|
299 |
|
300 | if (this.options.socket_nodelay) {
|
301 | this.stream.setNoDelay();
|
302 | }
|
303 |
|
304 |
|
305 | if (this.auth_pass !== undefined) {
|
306 | this.ready = true;
|
307 |
|
308 | this.auth(this.auth_pass, function (err) {
|
309 | if (err && err.code !== 'UNCERTAIN_STATE') {
|
310 | self.emit('error', err);
|
311 | }
|
312 | });
|
313 | this.ready = false;
|
314 | }
|
315 | };
|
316 |
|
317 | RedisClient.prototype.handle_reply = function (reply, command) {
|
318 | if (command === 'hgetall') {
|
319 | reply = utils.reply_to_object(reply);
|
320 | }
|
321 | return reply;
|
322 | };
|
323 |
|
324 | RedisClient.prototype.cork = noop;
|
325 | RedisClient.prototype.uncork = noop;
|
326 |
|
327 | RedisClient.prototype.initialize_retry_vars = function () {
|
328 | this.retry_timer = null;
|
329 | this.retry_totaltime = 0;
|
330 | this.retry_delay = 200;
|
331 | this.retry_backoff = 1.7;
|
332 | this.attempts = 1;
|
333 | };
|
334 |
|
335 | RedisClient.prototype.warn = function (msg) {
|
336 | var self = this;
|
337 |
|
338 |
|
339 | process.nextTick(function () {
|
340 | if (self.listeners('warning').length !== 0) {
|
341 | self.emit('warning', msg);
|
342 | } else {
|
343 | console.warn('node_redis:', msg);
|
344 | }
|
345 | });
|
346 | };
|
347 |
|
348 |
|
349 | RedisClient.prototype.flush_and_error = function (error_attributes, options) {
|
350 | options = options || {};
|
351 | var aggregated_errors = [];
|
352 | var queue_names = options.queues || ['command_queue', 'offline_queue'];
|
353 | for (var i = 0; i < queue_names.length; i++) {
|
354 |
|
355 | if (queue_names[i] === 'command_queue') {
|
356 | error_attributes.message += ' It might have been processed.';
|
357 | } else {
|
358 | error_attributes.message = error_attributes.message.replace(' It might have been processed.', '');
|
359 | }
|
360 |
|
361 | for (var command_obj = this[queue_names[i]].shift(); command_obj; command_obj = this[queue_names[i]].shift()) {
|
362 | var err = new errorClasses.AbortError(error_attributes);
|
363 | if (command_obj.error) {
|
364 | err.stack = err.stack + command_obj.error.stack.replace(/^Error.*?\n/, '\n');
|
365 | }
|
366 | err.command = command_obj.command.toUpperCase();
|
367 | if (command_obj.args && command_obj.args.length) {
|
368 | err.args = command_obj.args;
|
369 | }
|
370 | if (options.error) {
|
371 | err.origin = options.error;
|
372 | }
|
373 | if (typeof command_obj.callback === 'function') {
|
374 | command_obj.callback(err);
|
375 | } else {
|
376 | aggregated_errors.push(err);
|
377 | }
|
378 | }
|
379 | }
|
380 |
|
381 | if (exports.debug_mode && aggregated_errors.length) {
|
382 | var error;
|
383 | if (aggregated_errors.length === 1) {
|
384 | error = aggregated_errors[0];
|
385 | } else {
|
386 | error_attributes.message = error_attributes.message.replace('It', 'They').replace(/command/i, '$&s');
|
387 | error = new errorClasses.AggregateError(error_attributes);
|
388 | error.errors = aggregated_errors;
|
389 | }
|
390 | this.emit('error', error);
|
391 | }
|
392 | };
|
393 |
|
394 | RedisClient.prototype.on_error = function (err) {
|
395 | if (this.closing) {
|
396 | return;
|
397 | }
|
398 |
|
399 | err.message = 'Redis connection to ' + this.address + ' failed - ' + err.message;
|
400 | debug(err.message);
|
401 | this.connected = false;
|
402 | this.ready = false;
|
403 |
|
404 |
|
405 | if (!this.options.retry_strategy) {
|
406 | this.emit('error', err);
|
407 | }
|
408 |
|
409 |
|
410 | this.connection_gone('error', err);
|
411 | };
|
412 |
|
413 | RedisClient.prototype.on_connect = function () {
|
414 | debug('Stream connected ' + this.address + ' id ' + this.connection_id);
|
415 |
|
416 | this.connected = true;
|
417 | this.ready = false;
|
418 | this.emitted_end = false;
|
419 | this.stream.setKeepAlive(this.options.socket_keepalive);
|
420 | this.stream.setTimeout(0);
|
421 |
|
422 | this.emit('connect');
|
423 | this.initialize_retry_vars();
|
424 |
|
425 | if (this.options.no_ready_check) {
|
426 | this.on_ready();
|
427 | } else {
|
428 | this.ready_check();
|
429 | }
|
430 | };
|
431 |
|
432 | RedisClient.prototype.on_ready = function () {
|
433 | var self = this;
|
434 |
|
435 | debug('on_ready called ' + this.address + ' id ' + this.connection_id);
|
436 | this.ready = true;
|
437 |
|
438 | this.cork = function () {
|
439 | self.pipeline = true;
|
440 | if (self.stream.cork) {
|
441 | self.stream.cork();
|
442 | }
|
443 | };
|
444 | this.uncork = function () {
|
445 | if (self.fire_strings) {
|
446 | self.write_strings();
|
447 | } else {
|
448 | self.write_buffers();
|
449 | }
|
450 | self.pipeline = false;
|
451 | self.fire_strings = true;
|
452 | if (self.stream.uncork) {
|
453 |
|
454 | self.stream.uncork();
|
455 | }
|
456 | };
|
457 |
|
458 |
|
459 | if (this.selected_db !== undefined) {
|
460 | this.internal_send_command(new Command('select', [this.selected_db]));
|
461 | }
|
462 | if (this.monitoring) {
|
463 | this.internal_send_command(new Command('monitor', []));
|
464 | }
|
465 | var callback_count = Object.keys(this.subscription_set).length;
|
466 | if (!this.options.disable_resubscribing && callback_count) {
|
467 |
|
468 |
|
469 |
|
470 | var callback = function () {
|
471 | callback_count--;
|
472 | if (callback_count === 0) {
|
473 | self.emit('ready');
|
474 | }
|
475 | };
|
476 | debug('Sending pub/sub on_ready commands');
|
477 | for (var key in this.subscription_set) {
|
478 | var command = key.slice(0, key.indexOf('_'));
|
479 | var args = this.subscription_set[key];
|
480 | this[command]([args], callback);
|
481 | }
|
482 | this.send_offline_queue();
|
483 | return;
|
484 | }
|
485 | this.send_offline_queue();
|
486 | this.emit('ready');
|
487 | };
|
488 |
|
489 | RedisClient.prototype.on_info_cmd = function (err, res) {
|
490 | if (err) {
|
491 | if (err.message === "ERR unknown command 'info'") {
|
492 | this.on_ready();
|
493 | return;
|
494 | }
|
495 | err.message = 'Ready check failed: ' + err.message;
|
496 | this.emit('error', err);
|
497 | return;
|
498 | }
|
499 |
|
500 |
|
501 | if (!res) {
|
502 | debug('The info command returned without any data.');
|
503 | this.on_ready();
|
504 | return;
|
505 | }
|
506 |
|
507 | if (!this.server_info.loading || this.server_info.loading === '0') {
|
508 |
|
509 | if (this.server_info.master_link_status && this.server_info.master_link_status !== 'up') {
|
510 | this.server_info.loading_eta_seconds = 0.05;
|
511 | } else {
|
512 |
|
513 | debug('Redis server ready.');
|
514 | this.on_ready();
|
515 | return;
|
516 | }
|
517 | }
|
518 |
|
519 | var retry_time = +this.server_info.loading_eta_seconds * 1000;
|
520 | if (retry_time > 1000) {
|
521 | retry_time = 1000;
|
522 | }
|
523 | debug('Redis server still loading, trying again in ' + retry_time);
|
524 | setTimeout(function (self) {
|
525 | self.ready_check();
|
526 | }, retry_time, this);
|
527 | };
|
528 |
|
529 | RedisClient.prototype.ready_check = function () {
|
530 | var self = this;
|
531 | debug('Checking server ready state...');
|
532 |
|
533 | this.ready = true;
|
534 | this.info(function (err, res) {
|
535 | self.on_info_cmd(err, res);
|
536 | });
|
537 | this.ready = false;
|
538 | };
|
539 |
|
540 | RedisClient.prototype.send_offline_queue = function () {
|
541 | for (var command_obj = this.offline_queue.shift(); command_obj; command_obj = this.offline_queue.shift()) {
|
542 | debug('Sending offline command: ' + command_obj.command);
|
543 | this.internal_send_command(command_obj);
|
544 | }
|
545 | this.drain();
|
546 | };
|
547 |
|
548 | var retry_connection = function (self, error) {
|
549 | debug('Retrying connection...');
|
550 |
|
551 | var reconnect_params = {
|
552 | delay: self.retry_delay,
|
553 | attempt: self.attempts,
|
554 | error: error
|
555 | };
|
556 | if (self.options.camel_case) {
|
557 | reconnect_params.totalRetryTime = self.retry_totaltime;
|
558 | reconnect_params.timesConnected = self.times_connected;
|
559 | } else {
|
560 | reconnect_params.total_retry_time = self.retry_totaltime;
|
561 | reconnect_params.times_connected = self.times_connected;
|
562 | }
|
563 | self.emit('reconnecting', reconnect_params);
|
564 |
|
565 | self.retry_totaltime += self.retry_delay;
|
566 | self.attempts += 1;
|
567 | self.retry_delay = Math.round(self.retry_delay * self.retry_backoff);
|
568 | self.create_stream();
|
569 | self.retry_timer = null;
|
570 | };
|
571 |
|
572 | RedisClient.prototype.connection_gone = function (why, error) {
|
573 |
|
574 | if (this.retry_timer) {
|
575 | return;
|
576 | }
|
577 | error = error || null;
|
578 |
|
579 | debug('Redis connection is gone from ' + why + ' event.');
|
580 | this.connected = false;
|
581 | this.ready = false;
|
582 |
|
583 | this.cork = noop;
|
584 | this.uncork = noop;
|
585 | this.pipeline = false;
|
586 | this.pub_sub_mode = 0;
|
587 |
|
588 |
|
589 | if (!this.emitted_end) {
|
590 | this.emit('end');
|
591 | this.emitted_end = true;
|
592 | }
|
593 |
|
594 |
|
595 | if (this.closing) {
|
596 | debug('Connection ended by quit / end command, not retrying.');
|
597 | this.flush_and_error({
|
598 | message: 'Stream connection ended and command aborted.',
|
599 | code: 'NR_CLOSED'
|
600 | }, {
|
601 | error: error
|
602 | });
|
603 | return;
|
604 | }
|
605 |
|
606 | if (typeof this.options.retry_strategy === 'function') {
|
607 | var retry_params = {
|
608 | attempt: this.attempts,
|
609 | error: error
|
610 | };
|
611 | if (this.options.camel_case) {
|
612 | retry_params.totalRetryTime = this.retry_totaltime;
|
613 | retry_params.timesConnected = this.times_connected;
|
614 | } else {
|
615 | retry_params.total_retry_time = this.retry_totaltime;
|
616 | retry_params.times_connected = this.times_connected;
|
617 | }
|
618 | this.retry_delay = this.options.retry_strategy(retry_params);
|
619 | if (typeof this.retry_delay !== 'number') {
|
620 |
|
621 | if (this.retry_delay instanceof Error) {
|
622 | error = this.retry_delay;
|
623 | }
|
624 | this.flush_and_error({
|
625 | message: 'Stream connection ended and command aborted.',
|
626 | code: 'NR_CLOSED'
|
627 | }, {
|
628 | error: error
|
629 | });
|
630 | this.end(false);
|
631 | return;
|
632 | }
|
633 | }
|
634 |
|
635 | if (this.max_attempts !== 0 && this.attempts >= this.max_attempts || this.retry_totaltime >= this.connect_timeout) {
|
636 | var message = 'Redis connection in broken state: ';
|
637 | if (this.retry_totaltime >= this.connect_timeout) {
|
638 | message += 'connection timeout exceeded.';
|
639 | } else {
|
640 | message += 'maximum connection attempts exceeded.';
|
641 | }
|
642 |
|
643 | this.flush_and_error({
|
644 | message: message,
|
645 | code: 'CONNECTION_BROKEN',
|
646 | }, {
|
647 | error: error
|
648 | });
|
649 | var err = new Error(message);
|
650 | err.code = 'CONNECTION_BROKEN';
|
651 | if (error) {
|
652 | err.origin = error;
|
653 | }
|
654 | this.emit('error', err);
|
655 | this.end(false);
|
656 | return;
|
657 | }
|
658 |
|
659 |
|
660 | if (this.options.retry_unfulfilled_commands) {
|
661 | this.offline_queue.unshift.apply(this.offline_queue, this.command_queue.toArray());
|
662 | this.command_queue.clear();
|
663 | } else if (this.command_queue.length !== 0) {
|
664 | this.flush_and_error({
|
665 | message: 'Redis connection lost and command aborted.',
|
666 | code: 'UNCERTAIN_STATE'
|
667 | }, {
|
668 | error: error,
|
669 | queues: ['command_queue']
|
670 | });
|
671 | }
|
672 |
|
673 | if (this.retry_max_delay !== null && this.retry_delay > this.retry_max_delay) {
|
674 | this.retry_delay = this.retry_max_delay;
|
675 | } else if (this.retry_totaltime + this.retry_delay > this.connect_timeout) {
|
676 |
|
677 | this.retry_delay = this.connect_timeout - this.retry_totaltime;
|
678 | }
|
679 |
|
680 | debug('Retry connection in ' + this.retry_delay + ' ms');
|
681 |
|
682 | this.retry_timer = setTimeout(retry_connection, this.retry_delay, this, error);
|
683 | };
|
684 |
|
685 | RedisClient.prototype.return_error = function (err) {
|
686 | var command_obj = this.command_queue.shift();
|
687 | if (command_obj.error) {
|
688 | err.stack = command_obj.error.stack.replace(/^Error.*?\n/, 'ReplyError: ' + err.message + '\n');
|
689 | }
|
690 | err.command = command_obj.command.toUpperCase();
|
691 | if (command_obj.args && command_obj.args.length) {
|
692 | err.args = command_obj.args;
|
693 | }
|
694 |
|
695 |
|
696 | if (this.pub_sub_mode > 1) {
|
697 | this.pub_sub_mode--;
|
698 | }
|
699 |
|
700 | var match = err.message.match(utils.err_code);
|
701 |
|
702 | if (match) {
|
703 | err.code = match[1];
|
704 | }
|
705 |
|
706 | utils.callback_or_emit(this, command_obj.callback, err);
|
707 | };
|
708 |
|
709 | RedisClient.prototype.drain = function () {
|
710 | this.emit('drain');
|
711 | this.should_buffer = false;
|
712 | };
|
713 |
|
714 | RedisClient.prototype.emit_idle = function () {
|
715 | if (this.command_queue.length === 0 && this.pub_sub_mode === 0) {
|
716 | this.emit('idle');
|
717 | }
|
718 | };
|
719 |
|
720 | function normal_reply (self, reply) {
|
721 | var command_obj = self.command_queue.shift();
|
722 | if (typeof command_obj.callback === 'function') {
|
723 | if (command_obj.command !== 'exec') {
|
724 | reply = self.handle_reply(reply, command_obj.command, command_obj.buffer_args);
|
725 | }
|
726 | command_obj.callback(null, reply);
|
727 | } else {
|
728 | debug('No callback for reply');
|
729 | }
|
730 | }
|
731 |
|
732 | function subscribe_unsubscribe (self, reply, type) {
|
733 |
|
734 |
|
735 | var command_obj = self.command_queue.get(0);
|
736 | var buffer = self.options.return_buffers || self.options.detect_buffers && command_obj.buffer_args;
|
737 | var channel = (buffer || reply[1] === null) ? reply[1] : reply[1].toString();
|
738 | var count = +reply[2];
|
739 | debug(type, channel);
|
740 |
|
741 |
|
742 | if (channel !== null) {
|
743 | self.emit(type, channel, count);
|
744 | if (type === 'subscribe' || type === 'psubscribe') {
|
745 | self.subscription_set[type + '_' + channel] = channel;
|
746 | } else {
|
747 | type = type === 'unsubscribe' ? 'subscribe' : 'psubscribe';
|
748 | delete self.subscription_set[type + '_' + channel];
|
749 | }
|
750 | }
|
751 |
|
752 | if (command_obj.args.length === 1 || self.sub_commands_left === 1 || command_obj.args.length === 0 && (count === 0 || channel === null)) {
|
753 | if (count === 0) {
|
754 | var running_command;
|
755 | var i = 1;
|
756 | self.pub_sub_mode = 0;
|
757 |
|
758 | while (running_command = self.command_queue.get(i)) {
|
759 | if (SUBSCRIBE_COMMANDS[running_command.command]) {
|
760 | self.pub_sub_mode = i;
|
761 | break;
|
762 | }
|
763 | i++;
|
764 | }
|
765 | }
|
766 | self.command_queue.shift();
|
767 | if (typeof command_obj.callback === 'function') {
|
768 |
|
769 |
|
770 | command_obj.callback(null, channel);
|
771 | }
|
772 | self.sub_commands_left = 0;
|
773 | } else {
|
774 | if (self.sub_commands_left !== 0) {
|
775 | self.sub_commands_left--;
|
776 | } else {
|
777 | self.sub_commands_left = command_obj.args.length ? command_obj.args.length - 1 : count;
|
778 | }
|
779 | }
|
780 | }
|
781 |
|
782 | function return_pub_sub (self, reply) {
|
783 | var type = reply[0].toString();
|
784 | if (type === 'message') {
|
785 | if (!self.options.return_buffers || self.message_buffers) {
|
786 | self.emit('message', reply[1].toString(), reply[2].toString());
|
787 | self.emit('message_buffer', reply[1], reply[2]);
|
788 | self.emit('messageBuffer', reply[1], reply[2]);
|
789 | } else {
|
790 | self.emit('message', reply[1], reply[2]);
|
791 | }
|
792 | } else if (type === 'pmessage') {
|
793 | if (!self.options.return_buffers || self.message_buffers) {
|
794 | self.emit('pmessage', reply[1].toString(), reply[2].toString(), reply[3].toString());
|
795 | self.emit('pmessage_buffer', reply[1], reply[2], reply[3]);
|
796 | self.emit('pmessageBuffer', reply[1], reply[2], reply[3]);
|
797 | } else {
|
798 | self.emit('pmessage', reply[1], reply[2], reply[3]);
|
799 | }
|
800 | } else {
|
801 | subscribe_unsubscribe(self, reply, type);
|
802 | }
|
803 | }
|
804 |
|
805 | RedisClient.prototype.return_reply = function (reply) {
|
806 | if (this.monitoring) {
|
807 | var replyStr;
|
808 | if (this.buffers && Buffer.isBuffer(reply)) {
|
809 | replyStr = reply.toString();
|
810 | } else {
|
811 | replyStr = reply;
|
812 | }
|
813 |
|
814 | if (typeof replyStr === 'string' && utils.monitor_regex.test(replyStr)) {
|
815 | var timestamp = replyStr.slice(0, replyStr.indexOf(' '));
|
816 | var args = replyStr.slice(replyStr.indexOf('"') + 1, -1).split('" "').map(function (elem) {
|
817 | return elem.replace(/\\"/g, '"');
|
818 | });
|
819 | this.emit('monitor', timestamp, args, replyStr);
|
820 | return;
|
821 | }
|
822 | }
|
823 | if (this.pub_sub_mode === 0) {
|
824 | normal_reply(this, reply);
|
825 | } else if (this.pub_sub_mode !== 1) {
|
826 | this.pub_sub_mode--;
|
827 | normal_reply(this, reply);
|
828 | } else if (!(reply instanceof Array) || reply.length <= 2) {
|
829 |
|
830 |
|
831 | normal_reply(this, reply);
|
832 | } else {
|
833 | return_pub_sub(this, reply);
|
834 | }
|
835 | };
|
836 |
|
837 | function handle_offline_command (self, command_obj) {
|
838 | var command = command_obj.command;
|
839 | var err, msg;
|
840 | if (self.closing || !self.enable_offline_queue) {
|
841 | command = command.toUpperCase();
|
842 | if (!self.closing) {
|
843 | if (self.stream.writable) {
|
844 | msg = 'The connection is not yet established and the offline queue is deactivated.';
|
845 | } else {
|
846 | msg = 'Stream not writeable.';
|
847 | }
|
848 | } else {
|
849 | msg = 'The connection is already closed.';
|
850 | }
|
851 | err = new errorClasses.AbortError({
|
852 | message: command + " can't be processed. " + msg,
|
853 | code: 'NR_CLOSED',
|
854 | command: command
|
855 | });
|
856 | if (command_obj.args.length) {
|
857 | err.args = command_obj.args;
|
858 | }
|
859 | utils.reply_in_order(self, command_obj.callback, err);
|
860 | } else {
|
861 | debug('Queueing ' + command + ' for next server connection.');
|
862 | self.offline_queue.push(command_obj);
|
863 | }
|
864 | self.should_buffer = true;
|
865 | }
|
866 |
|
867 |
|
868 |
|
869 | RedisClient.prototype.internal_send_command = function (command_obj) {
|
870 | var arg, prefix_keys;
|
871 | var i = 0;
|
872 | var command_str = '';
|
873 | var args = command_obj.args;
|
874 | var command = command_obj.command;
|
875 | var len = args.length;
|
876 | var big_data = false;
|
877 | var args_copy = new Array(len);
|
878 |
|
879 | if (process.domain && command_obj.callback) {
|
880 | command_obj.callback = process.domain.bind(command_obj.callback);
|
881 | }
|
882 |
|
883 | if (this.ready === false || this.stream.writable === false) {
|
884 |
|
885 | handle_offline_command(this, command_obj);
|
886 | return false;
|
887 | }
|
888 |
|
889 | for (i = 0; i < len; i += 1) {
|
890 | if (typeof args[i] === 'string') {
|
891 |
|
892 | if (args[i].length > 30000) {
|
893 | big_data = true;
|
894 | args_copy[i] = new Buffer(args[i], 'utf8');
|
895 | } else {
|
896 | args_copy[i] = args[i];
|
897 | }
|
898 | } else if (typeof args[i] === 'object') {
|
899 | if (args[i] instanceof Date) {
|
900 | args_copy[i] = args[i].toString();
|
901 | } else if (args[i] === null) {
|
902 | this.warn(
|
903 | 'Deprecated: The ' + command.toUpperCase() + ' command contains a "null" argument.\n' +
|
904 | 'This is converted to a "null" string now and will return an error from v.3.0 on.\n' +
|
905 | 'Please handle this in your code to make sure everything works as you intended it to.'
|
906 | );
|
907 | args_copy[i] = 'null';
|
908 | } else if (Buffer.isBuffer(args[i])) {
|
909 | args_copy[i] = args[i];
|
910 | command_obj.buffer_args = true;
|
911 | big_data = true;
|
912 | } else {
|
913 | this.warn(
|
914 | 'Deprecated: The ' + command.toUpperCase() + ' command contains a argument of type ' + args[i].constructor.name + '.\n' +
|
915 | 'This is converted to "' + args[i].toString() + '" by using .toString() 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] = args[i].toString();
|
919 | }
|
920 | } else if (typeof args[i] === 'undefined') {
|
921 | this.warn(
|
922 | 'Deprecated: The ' + command.toUpperCase() + ' command contains a "undefined" argument.\n' +
|
923 | 'This is converted to a "undefined" string now and will return an error from v.3.0 on.\n' +
|
924 | 'Please handle this in your code to make sure everything works as you intended it to.'
|
925 | );
|
926 | args_copy[i] = 'undefined';
|
927 | } else {
|
928 |
|
929 | args_copy[i] = '' + args[i];
|
930 | }
|
931 | }
|
932 |
|
933 | if (this.options.prefix) {
|
934 | prefix_keys = commands.getKeyIndexes(command, args_copy);
|
935 | for (i = prefix_keys.pop(); i !== undefined; i = prefix_keys.pop()) {
|
936 | args_copy[i] = this.options.prefix + args_copy[i];
|
937 | }
|
938 | }
|
939 | if (this.options.rename_commands && this.options.rename_commands[command]) {
|
940 | command = this.options.rename_commands[command];
|
941 | }
|
942 |
|
943 |
|
944 | command_str = '*' + (len + 1) + '\r\n$' + command.length + '\r\n' + command + '\r\n';
|
945 |
|
946 | if (big_data === false) {
|
947 | for (i = 0; i < len; i += 1) {
|
948 | arg = args_copy[i];
|
949 | command_str += '$' + Buffer.byteLength(arg) + '\r\n' + arg + '\r\n';
|
950 | }
|
951 | debug('Send ' + this.address + ' id ' + this.connection_id + ': ' + command_str);
|
952 | this.write(command_str);
|
953 | } else {
|
954 | debug('Send command (' + command_str + ') has Buffer arguments');
|
955 | this.fire_strings = false;
|
956 | this.write(command_str);
|
957 |
|
958 | for (i = 0; i < len; i += 1) {
|
959 | arg = args_copy[i];
|
960 | if (typeof arg === 'string') {
|
961 | this.write('$' + Buffer.byteLength(arg) + '\r\n' + arg + '\r\n');
|
962 | } else {
|
963 | this.write('$' + arg.length + '\r\n');
|
964 | this.write(arg);
|
965 | this.write('\r\n');
|
966 | }
|
967 | debug('send_command: buffer send ' + arg.length + ' bytes');
|
968 | }
|
969 | }
|
970 | if (command_obj.call_on_write) {
|
971 | command_obj.call_on_write();
|
972 | }
|
973 |
|
974 |
|
975 |
|
976 | if (this.reply === 'ON') {
|
977 | this.command_queue.push(command_obj);
|
978 | } else {
|
979 |
|
980 |
|
981 | if (command_obj.callback) {
|
982 | utils.reply_in_order(this, command_obj.callback, null, undefined, this.command_queue);
|
983 | }
|
984 | if (this.reply === 'SKIP') {
|
985 | this.reply = 'SKIP_ONE_MORE';
|
986 | } else if (this.reply === 'SKIP_ONE_MORE') {
|
987 | this.reply = 'ON';
|
988 | }
|
989 | }
|
990 | return !this.should_buffer;
|
991 | };
|
992 |
|
993 | RedisClient.prototype.write_strings = function () {
|
994 | var str = '';
|
995 | for (var command = this.pipeline_queue.shift(); command; command = this.pipeline_queue.shift()) {
|
996 |
|
997 | if (str.length + command.length > 4 * 1024 * 1024) {
|
998 | this.should_buffer = !this.stream.write(str);
|
999 | str = '';
|
1000 | }
|
1001 | str += command;
|
1002 | }
|
1003 | if (str !== '') {
|
1004 | this.should_buffer = !this.stream.write(str);
|
1005 | }
|
1006 | };
|
1007 |
|
1008 | RedisClient.prototype.write_buffers = function () {
|
1009 | for (var command = this.pipeline_queue.shift(); command; command = this.pipeline_queue.shift()) {
|
1010 | this.should_buffer = !this.stream.write(command);
|
1011 | }
|
1012 | };
|
1013 |
|
1014 | RedisClient.prototype.write = function (data) {
|
1015 | if (this.pipeline === false) {
|
1016 | this.should_buffer = !this.stream.write(data);
|
1017 | return;
|
1018 | }
|
1019 | this.pipeline_queue.push(data);
|
1020 | };
|
1021 |
|
1022 | Object.defineProperty(exports, 'debugMode', {
|
1023 | get: function () {
|
1024 | return this.debug_mode;
|
1025 | },
|
1026 | set: function (val) {
|
1027 | this.debug_mode = val;
|
1028 | }
|
1029 | });
|
1030 |
|
1031 |
|
1032 | Object.defineProperty(RedisClient.prototype, 'command_queue_length', {
|
1033 | get: function () {
|
1034 | return this.command_queue.length;
|
1035 | }
|
1036 | });
|
1037 |
|
1038 | Object.defineProperty(RedisClient.prototype, 'offline_queue_length', {
|
1039 | get: function () {
|
1040 | return this.offline_queue.length;
|
1041 | }
|
1042 | });
|
1043 |
|
1044 |
|
1045 |
|
1046 | Object.defineProperty(RedisClient.prototype, 'retryDelay', {
|
1047 | get: function () {
|
1048 | return this.retry_delay;
|
1049 | }
|
1050 | });
|
1051 |
|
1052 | Object.defineProperty(RedisClient.prototype, 'retryBackoff', {
|
1053 | get: function () {
|
1054 | return this.retry_backoff;
|
1055 | }
|
1056 | });
|
1057 |
|
1058 | Object.defineProperty(RedisClient.prototype, 'commandQueueLength', {
|
1059 | get: function () {
|
1060 | return this.command_queue.length;
|
1061 | }
|
1062 | });
|
1063 |
|
1064 | Object.defineProperty(RedisClient.prototype, 'offlineQueueLength', {
|
1065 | get: function () {
|
1066 | return this.offline_queue.length;
|
1067 | }
|
1068 | });
|
1069 |
|
1070 | Object.defineProperty(RedisClient.prototype, 'shouldBuffer', {
|
1071 | get: function () {
|
1072 | return this.should_buffer;
|
1073 | }
|
1074 | });
|
1075 |
|
1076 | Object.defineProperty(RedisClient.prototype, 'connectionId', {
|
1077 | get: function () {
|
1078 | return this.connection_id;
|
1079 | }
|
1080 | });
|
1081 |
|
1082 | Object.defineProperty(RedisClient.prototype, 'serverInfo', {
|
1083 | get: function () {
|
1084 | return this.server_info;
|
1085 | }
|
1086 | });
|
1087 |
|
1088 | exports.createClient = function () {
|
1089 | return new RedisClient(unifyOptions.apply(null, arguments));
|
1090 | };
|
1091 | exports.RedisClient = RedisClient;
|
1092 | exports.print = utils.print;
|
1093 | exports.Multi = require('./lib/multi');
|
1094 | exports.AbortError = errorClasses.AbortError;
|
1095 | exports.RedisError = Parser.RedisError;
|
1096 | exports.ParserError = Parser.ParserError;
|
1097 | exports.ReplyError = Parser.ReplyError;
|
1098 | exports.AggregateError = errorClasses.AggregateError;
|
1099 |
|
1100 |
|
1101 | require('./lib/individualCommands');
|
1102 | require('./lib/extendedApi');
|
1103 |
|
1104 |
|
1105 | exports.addCommand = exports.add_command = require('./lib/commands'); |
\ | No newline at end of file |