index.js 42 KB

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