Pipeline.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const calculateSlot = require("cluster-key-slot");
  4. const commands_1 = require("@ioredis/commands");
  5. const standard_as_callback_1 = require("standard-as-callback");
  6. const util_1 = require("util");
  7. const Command_1 = require("./Command");
  8. const utils_1 = require("./utils");
  9. const Commander_1 = require("./utils/Commander");
  10. /*
  11. This function derives from the cluster-key-slot implementation.
  12. Instead of checking that all keys have the same slot, it checks that all slots are served by the same set of nodes.
  13. If this is satisfied, it returns the first key's slot.
  14. */
  15. function generateMultiWithNodes(redis, keys) {
  16. const slot = calculateSlot(keys[0]);
  17. const target = redis._groupsBySlot[slot];
  18. for (let i = 1; i < keys.length; i++) {
  19. if (redis._groupsBySlot[calculateSlot(keys[i])] !== target) {
  20. return -1;
  21. }
  22. }
  23. return slot;
  24. }
  25. class Pipeline extends Commander_1.default {
  26. constructor(redis) {
  27. super();
  28. this.redis = redis;
  29. this.isPipeline = true;
  30. this.replyPending = 0;
  31. this._queue = [];
  32. this._result = [];
  33. this._transactions = 0;
  34. this._shaToScript = {};
  35. this.isCluster =
  36. this.redis.constructor.name === "Cluster" || this.redis.isCluster;
  37. this.options = redis.options;
  38. Object.keys(redis.scriptsSet).forEach((name) => {
  39. const script = redis.scriptsSet[name];
  40. this._shaToScript[script.sha] = script;
  41. this[name] = redis[name];
  42. this[name + "Buffer"] = redis[name + "Buffer"];
  43. });
  44. redis.addedBuiltinSet.forEach((name) => {
  45. this[name] = redis[name];
  46. this[name + "Buffer"] = redis[name + "Buffer"];
  47. });
  48. this.promise = new Promise((resolve, reject) => {
  49. this.resolve = resolve;
  50. this.reject = reject;
  51. });
  52. const _this = this;
  53. Object.defineProperty(this, "length", {
  54. get: function () {
  55. return _this._queue.length;
  56. },
  57. });
  58. }
  59. fillResult(value, position) {
  60. if (this._queue[position].name === "exec" && Array.isArray(value[1])) {
  61. const execLength = value[1].length;
  62. for (let i = 0; i < execLength; i++) {
  63. if (value[1][i] instanceof Error) {
  64. continue;
  65. }
  66. const cmd = this._queue[position - (execLength - i)];
  67. try {
  68. value[1][i] = cmd.transformReply(value[1][i]);
  69. }
  70. catch (err) {
  71. value[1][i] = err;
  72. }
  73. }
  74. }
  75. this._result[position] = value;
  76. if (--this.replyPending) {
  77. return;
  78. }
  79. if (this.isCluster) {
  80. let retriable = true;
  81. let commonError;
  82. for (let i = 0; i < this._result.length; ++i) {
  83. const error = this._result[i][0];
  84. const command = this._queue[i];
  85. if (error) {
  86. if (command.name === "exec" &&
  87. error.message ===
  88. "EXECABORT Transaction discarded because of previous errors.") {
  89. continue;
  90. }
  91. if (!commonError) {
  92. commonError = {
  93. name: error.name,
  94. message: error.message,
  95. };
  96. }
  97. else if (commonError.name !== error.name ||
  98. commonError.message !== error.message) {
  99. retriable = false;
  100. break;
  101. }
  102. }
  103. else if (!command.inTransaction) {
  104. const isReadOnly = (0, commands_1.exists)(command.name, { caseInsensitive: true }) &&
  105. (0, commands_1.hasFlag)(command.name, "readonly", { nameCaseInsensitive: true });
  106. if (!isReadOnly) {
  107. retriable = false;
  108. break;
  109. }
  110. }
  111. }
  112. if (commonError && retriable) {
  113. const _this = this;
  114. const errv = commonError.message.split(" ");
  115. const queue = this._queue;
  116. let inTransaction = false;
  117. this._queue = [];
  118. for (let i = 0; i < queue.length; ++i) {
  119. if (errv[0] === "ASK" &&
  120. !inTransaction &&
  121. queue[i].name !== "asking" &&
  122. (!queue[i - 1] || queue[i - 1].name !== "asking")) {
  123. const asking = new Command_1.default("asking");
  124. asking.ignore = true;
  125. this.sendCommand(asking);
  126. }
  127. queue[i].initPromise();
  128. this.sendCommand(queue[i]);
  129. inTransaction = queue[i].inTransaction;
  130. }
  131. let matched = true;
  132. if (typeof this.leftRedirections === "undefined") {
  133. this.leftRedirections = {};
  134. }
  135. const exec = function () {
  136. _this.exec();
  137. };
  138. const cluster = this.redis;
  139. cluster.handleError(commonError, this.leftRedirections, {
  140. moved: function (_slot, key) {
  141. _this.preferKey = key;
  142. if (cluster.slots[errv[1]]) {
  143. if (cluster.slots[errv[1]][0] !== key) {
  144. cluster.slots[errv[1]] = [key];
  145. }
  146. }
  147. else {
  148. cluster.slots[errv[1]] = [key];
  149. }
  150. cluster._groupsBySlot[errv[1]] =
  151. cluster._groupsIds[cluster.slots[errv[1]].join(";")];
  152. cluster.refreshSlotsCache();
  153. _this.exec();
  154. },
  155. ask: function (_slot, key) {
  156. _this.preferKey = key;
  157. _this.exec();
  158. },
  159. tryagain: exec,
  160. clusterDown: exec,
  161. connectionClosed: exec,
  162. maxRedirections: () => {
  163. matched = false;
  164. },
  165. defaults: () => {
  166. matched = false;
  167. },
  168. });
  169. if (matched) {
  170. return;
  171. }
  172. }
  173. }
  174. let ignoredCount = 0;
  175. for (let i = 0; i < this._queue.length - ignoredCount; ++i) {
  176. if (this._queue[i + ignoredCount].ignore) {
  177. ignoredCount += 1;
  178. }
  179. this._result[i] = this._result[i + ignoredCount];
  180. }
  181. this.resolve(this._result.slice(0, this._result.length - ignoredCount));
  182. }
  183. sendCommand(command) {
  184. if (this._transactions > 0) {
  185. command.inTransaction = true;
  186. }
  187. const position = this._queue.length;
  188. command.pipelineIndex = position;
  189. command.promise
  190. .then((result) => {
  191. this.fillResult([null, result], position);
  192. })
  193. .catch((error) => {
  194. this.fillResult([error], position);
  195. });
  196. this._queue.push(command);
  197. return this;
  198. }
  199. addBatch(commands) {
  200. let command, commandName, args;
  201. for (let i = 0; i < commands.length; ++i) {
  202. command = commands[i];
  203. commandName = command[0];
  204. args = command.slice(1);
  205. this[commandName].apply(this, args);
  206. }
  207. return this;
  208. }
  209. }
  210. exports.default = Pipeline;
  211. // @ts-expect-error
  212. const multi = Pipeline.prototype.multi;
  213. // @ts-expect-error
  214. Pipeline.prototype.multi = function () {
  215. this._transactions += 1;
  216. return multi.apply(this, arguments);
  217. };
  218. // @ts-expect-error
  219. const execBuffer = Pipeline.prototype.execBuffer;
  220. // @ts-expect-error
  221. Pipeline.prototype.execBuffer = (0, util_1.deprecate)(function () {
  222. if (this._transactions > 0) {
  223. this._transactions -= 1;
  224. }
  225. return execBuffer.apply(this, arguments);
  226. }, "Pipeline#execBuffer: Use Pipeline#exec instead");
  227. // NOTE: To avoid an unhandled promise rejection, this will unconditionally always return this.promise,
  228. // which always has the rejection handled by standard-as-callback
  229. // adding the provided rejection callback.
  230. //
  231. // If a different promise instance were returned, that promise would cause its own unhandled promise rejection
  232. // errors, even if that promise unconditionally resolved to **the resolved value of** this.promise.
  233. Pipeline.prototype.exec = function (callback) {
  234. // Wait for the cluster to be connected, since we need nodes information before continuing
  235. if (this.isCluster && !this.redis.slots.length) {
  236. if (this.redis.status === "wait")
  237. this.redis.connect().catch(utils_1.noop);
  238. if (callback && !this.nodeifiedPromise) {
  239. this.nodeifiedPromise = true;
  240. (0, standard_as_callback_1.default)(this.promise, callback);
  241. }
  242. this.redis.delayUntilReady((err) => {
  243. if (err) {
  244. this.reject(err);
  245. return;
  246. }
  247. this.exec(callback);
  248. });
  249. return this.promise;
  250. }
  251. if (this._transactions > 0) {
  252. this._transactions -= 1;
  253. return execBuffer.apply(this, arguments);
  254. }
  255. if (!this.nodeifiedPromise) {
  256. this.nodeifiedPromise = true;
  257. (0, standard_as_callback_1.default)(this.promise, callback);
  258. }
  259. if (!this._queue.length) {
  260. this.resolve([]);
  261. }
  262. let pipelineSlot;
  263. if (this.isCluster) {
  264. // List of the first key for each command
  265. const sampleKeys = [];
  266. for (let i = 0; i < this._queue.length; i++) {
  267. const keys = this._queue[i].getKeys();
  268. if (keys.length) {
  269. sampleKeys.push(keys[0]);
  270. }
  271. // For each command, check that the keys belong to the same slot
  272. if (keys.length && calculateSlot.generateMulti(keys) < 0) {
  273. this.reject(new Error("All the keys in a pipeline command should belong to the same slot"));
  274. return this.promise;
  275. }
  276. }
  277. if (sampleKeys.length) {
  278. pipelineSlot = generateMultiWithNodes(this.redis, sampleKeys);
  279. if (pipelineSlot < 0) {
  280. this.reject(new Error("All keys in the pipeline should belong to the same slots allocation group"));
  281. return this.promise;
  282. }
  283. }
  284. else {
  285. // Send the pipeline to a random node
  286. pipelineSlot = (Math.random() * 16384) | 0;
  287. }
  288. }
  289. const _this = this;
  290. execPipeline();
  291. return this.promise;
  292. function execPipeline() {
  293. let writePending = (_this.replyPending = _this._queue.length);
  294. let node;
  295. if (_this.isCluster) {
  296. node = {
  297. slot: pipelineSlot,
  298. redis: _this.redis.connectionPool.nodes.all[_this.preferKey],
  299. };
  300. }
  301. let data = "";
  302. let buffers;
  303. const stream = {
  304. isPipeline: true,
  305. destination: _this.isCluster ? node : { redis: _this.redis },
  306. write(writable) {
  307. if (typeof writable !== "string") {
  308. if (!buffers) {
  309. buffers = [];
  310. }
  311. if (data) {
  312. buffers.push(Buffer.from(data, "utf8"));
  313. data = "";
  314. }
  315. buffers.push(writable);
  316. }
  317. else {
  318. data += writable;
  319. }
  320. if (!--writePending) {
  321. if (buffers) {
  322. if (data) {
  323. buffers.push(Buffer.from(data, "utf8"));
  324. }
  325. stream.destination.redis.stream.write(Buffer.concat(buffers));
  326. }
  327. else {
  328. stream.destination.redis.stream.write(data);
  329. }
  330. // Reset writePending for resending
  331. writePending = _this._queue.length;
  332. data = "";
  333. buffers = undefined;
  334. }
  335. },
  336. };
  337. for (let i = 0; i < _this._queue.length; ++i) {
  338. _this.redis.sendCommand(_this._queue[i], stream, node);
  339. }
  340. return _this.promise;
  341. }
  342. };