UNPKG

node-redisson

Version:

Distributed lock with Redis implementation for Node.js

50 lines (49 loc) 2.17 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.StreamsCommandExecutor = void 0; const CommandExecutor_1 = require("./CommandExecutor"); const node_events_1 = __importDefault(require("node:events")); const REDIS_STREAMS_KEY = 'redisson:events'; const STREAMS_MAX_LEN = '100'; class StreamsCommandExecutor extends CommandExecutor_1.CommandExecutor { constructor(config) { super(config); this.eventEmitter = new node_events_1.default(); this.listenForMessage(); } async listenForMessage(lastId = '$') { let nextId = lastId; const results = await this.subscribeRedis.xread('BLOCK', 0, 'STREAMS', REDIS_STREAMS_KEY, lastId); if (results) { const [_, messages] = results[0]; nextId = messages[messages.length - 1][0]; messages.forEach(([_, [eventName, e]]) => this.eventEmitter.emit(eventName, e)); } await this.listenForMessage(nextId); } async subscribe(eventName, listener) { this.eventEmitter.on(eventName, listener); } async unsubscribe(eventName, listener) { this.eventEmitter.off(eventName, listener); } async subscribeOnce(eventName, listener) { this.eventEmitter.once(eventName, listener); } async publish(eventName, e) { const id = await this.redis.xadd(REDIS_STREAMS_KEY, 'MAXLEN', '~', STREAMS_MAX_LEN, '*', eventName, e); // console.log('publish', eventName, e, id); return id; } getRedisScripts() { const unlockCommand = `redis.call('xadd', '${REDIS_STREAMS_KEY}', 'MAXLEN', '~', ${STREAMS_MAX_LEN}, '*', KEYS[2], ARGV[1]);`; return { rUnlockInner: CommandExecutor_1.DEFAULT_REDIS_SCRIPTS.rUnlockInner.lua.replace('#PUB_UNLOCK_REPLACE#', unlockCommand), rForceUnlock: CommandExecutor_1.DEFAULT_REDIS_SCRIPTS.rForceUnlock.lua.replace('#PUB_UNLOCK_REPLACE#', unlockCommand), }; } } exports.StreamsCommandExecutor = StreamsCommandExecutor;