UNPKG

@apiratorjs/locking-redis

Version:

An extension to the core @apiratorjs/locking library, providing Redis-based implementations of distributed mutexes and semaphores for true cross-process concurrency control in Node.js.

69 lines 2.72 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.RedisScript = void 0; const crypto = __importStar(require("node:crypto")); /** * A Lua script kept in the server-side script cache and invoked by its SHA1, * so the source is not sent on every call. * * Falls back to EVAL whenever the server does not know the script - a fresh * server, SCRIPT FLUSH, a restart, a failover, or another node of a cluster. * That fallback re-populates the cache, so the next call is an EVALSHA again. */ class RedisScript { constructor(source) { this.source = source; // Redis keys its script cache by the SHA1 of the body, so the digest can be // computed locally instead of paying a SCRIPT LOAD round-trip up front. this.sha1 = crypto.createHash("sha1").update(source).digest("hex"); } async run(client, options) { try { return await client.evalSha(this.sha1, options); } catch (error) { if (!RedisScript.isNoScriptError(error)) { throw error; } return await client.eval(this.source, options); } } static isNoScriptError(error) { return error instanceof Error && error.message.startsWith("NOSCRIPT"); } } exports.RedisScript = RedisScript; //# sourceMappingURL=redis-script.js.map