redis-smq-common 3.0.0-rc.10 → 3.0.0-rc.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
 
2
2
 
3
+ ## [3.0.0-rc.12](https://github.com/weyoss/redis-smq-common/compare/v3.0.0-rc.11...v3.0.0-rc.12) (2024-02-03)
4
+
5
+
6
+ ### Codebase Refactoring
7
+
8
+ * improve error handling ([dd0f49c](https://github.com/weyoss/redis-smq-common/commit/dd0f49cc3f62d89c1f621d3d26a269970efe02f3))
9
+
10
+ ## [3.0.0-rc.11](https://github.com/weyoss/redis-smq-common/compare/v3.0.0-rc.10...v3.0.0-rc.11) (2024-02-01)
11
+
12
+
13
+ ### Codebase Refactoring
14
+
15
+ * improve typing ([a3d69ee](https://github.com/weyoss/redis-smq-common/commit/a3d69ee6ba0c5a4745b2ee778f50adeaabf3087a))
16
+
3
17
  ## [3.0.0-rc.10](https://github.com/weyoss/redis-smq-common/compare/v3.0.0-rc.9...v3.0.0-rc.10) (2024-02-01)
4
18
 
5
19
 
package/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var ft=Object.create;var F=Object.defineProperty,Ct=Object.defineProperties,It=Object.getOwnPropertyDescriptor,xt=Object.getOwnPropertyDescriptors,Tt=Object.getOwnPropertyNames,rt=Object.getOwnPropertySymbols,wt=Object.getPrototypeOf,st=Object.prototype.hasOwnProperty,Et=Object.prototype.propertyIsEnumerable;var nt=(o,r,t)=>r in o?F(o,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[r]=t,D=(o,r)=>{for(var t in r||(r={}))st.call(r,t)&&nt(o,t,r[t]);if(rt)for(var t of rt(r))Et.call(r,t)&&nt(o,t,r[t]);return o},ot=(o,r)=>Ct(o,xt(r));var yt=(o,r)=>{for(var t in r)F(o,t,{get:r[t],enumerable:!0})},lt=(o,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Tt(r))!st.call(o,i)&&i!==t&&F(o,i,{get:()=>r[i],enumerable:!(e=It(r,i))||e.enumerable});return o};var J=(o,r,t)=>(t=o!=null?ft(wt(o)):{},lt(r||!o||!o.__esModule?F(t,"default",{value:o,enumerable:!0}):t,o)),Rt=o=>lt(F({},"__esModule",{value:!0}),o);var Ht={};yt(Ht,{CallbackEmptyReplyError:()=>h,CallbackInvalidReplyError:()=>q,ERedisConfigClient:()=>Z,EventEmitter:()=>x,Lock:()=>H,LockAbortError:()=>I,LockAcquireError:()=>w,LockError:()=>m,LockExtendError:()=>M,LockMethodNotAllowedError:()=>A,LockNotAcquiredError:()=>N,LockNotReleasedError:()=>z,LoggerError:()=>O,PanicError:()=>T,PowerSwitch:()=>f,RedisClient:()=>v,RedisClientError:()=>u,RedisSMQError:()=>d,Ticker:()=>R,TickerError:()=>L,WatchedKeysChangedError:()=>E,Worker:()=>X,WorkerError:()=>y,WorkerPool:()=>V,WorkerRunner:()=>G,async:()=>b,getEventBusInstance:()=>p,logger:()=>ht,redis:()=>vt});module.exports=Rt(Ht);var Z=(t=>(t.IOREDIS="ioredis",t.REDIS="redis",t))(Z||{});var d=class extends Error{constructor(r){super(r)}get name(){return this.constructor.name}};var h=class extends d{constructor(){super("Expected a non-empty reply")}};var q=class extends d{constructor(){super("Invalid reply type")}};var T=class extends d{};var O=class extends d{};var L=class extends d{};var m=class extends d{};var I=class extends m{constructor(r="releaseLock() may have been called. Abandoning."){super(r)}};var w=class extends m{constructor(r="Could not acquire a lock"){super(r)}};var M=class extends m{constructor(r="Acquired lock could not be extended"){super(r)}};var A=class extends m{constructor(r="This method can not be used when autoExtend is enabled"){super(r)}};var N=class extends m{constructor(r="Can not extend a lock which has not been yet acquired. Maybe a pending operation is in progress."){super(r)}};var z=class extends m{constructor(r="A lock has been already obtained but not yet released or maybe a pending operation is in progress."){super(r)}};var u=class extends d{};var E=class extends u{constructor(r="One (or more) of the watched keys has been changed"){super(r)}};var y=class extends T{};var gt=require("uuid");var et=J(require("fs"),1),it=require("path");var ut=require("events");var at=(o,r,t)=>{if(o.length){let e=0,i=()=>{r(o[e],e,n=>{e+=1,n||e>=o.length?t(n):setTimeout(()=>i(),0)})};i()}else t()},ct=(o,r,t)=>{let e=Object.keys(o);if(e.length){let i=0,n=()=>{let s=e[i];r(o[s],s,l=>{i+=1,l||i>=e.length?t(l):setTimeout(()=>n(),0)})};n()}else t()},St=(o,r,t)=>{Array.isArray(o)?at(o,r,t):ct(o,r,t)},Lt=(o,r)=>{if(o.length){let t=0,e=(i,...n)=>{t+=1,i?r(i):t<o.length?setTimeout(()=>{n.length?o[t](...n,e):o[t](e)},0):n.length?r(null,n[0]):r()};o[t](e)}else r()},b={each:St,eachIn:ct,eachOf:at,waterfall:Lt};var j=J(require("fs"),1),Y=require("path");var P=class P{constructor(){this.isLoaded=!1;this.scripts=new Map,this.addScript("ZPOPRPUSH",j.default.readFileSync((0,Y.resolve)(__dirname,"./lua/zpoprpush.lua")).toString()),this.addScript("LPOPRPUSH",j.default.readFileSync((0,Y.resolve)(__dirname,"./lua/lpoprpush.lua")).toString())}hasScript(r){return this.scripts.has(r)}addScript(r,t){return this.hasScript(r)?!1:(this.scripts.set(r,{content:t}),this.isLoaded=!1,!0)}loadScripts(r,t){if(this.isLoaded)t();else{let e=[];this.scripts.forEach(i=>e.push(n=>{i.id?n():r.loadScript(i.content,(s,l)=>{s?n(s):l?(i.id=l,n()):n(new h)})})),b.waterfall(e,i=>{i?t(i):(this.isLoaded=!0,t())})}}getScriptId(r){var e;let{id:t}=(e=this.scripts.get(r))!=null?e:{};return t||new u(`ID of script [${r}] is missing`)}static getInstance(){return P.instance||(P.instance=new P),P.instance}};P.instance=null;var U=P;var dt=require("events"),x=class extends dt.EventEmitter{};var tt=null;function p(){return tt||(tt=new x),tt}var Mt=[4,0,0],k=class k extends ut.EventEmitter{constructor(){super(...arguments);this.connectionClosed=!0}validateRedisVersion(t,e=0,i=0){return k.redisServerVersion?k.redisServerVersion[0]>t||k.redisServerVersion[0]===t&&k.redisServerVersion[1]>=e&&k.redisServerVersion[2]>=i:(p().emit("error",new u("UNKNOWN_REDIS_SERVER_VERSION")),!1)}validateRedisServerSupport(t){let e=i=>{let[n,s,l]=Mt;this.validateRedisVersion(n,s,l)?i():i(new u("UNSUPPORTED_REDIS_SERVER_VERSION"))};k.redisServerVersion?e(t):this.updateServerVersion(i=>{i?t(i):e(t)})}sscanAll(t,e,i){let n=new Set,s=l=>{this.sscan(t,l,e,(a,c)=>{a?i(a):c?(c.items.forEach(g=>n.add(g)),c.cursor==="0"?i(null,[...n]):s(c.cursor)):i(new h)})};s("0")}hscanAll(t,e,i){let n={},s=l=>{this.hscan(t,l,e,(a,c)=>{a?i(a):c?(Object.assign(n,c.result),c.cursor==="0"?i(null,n):s(c.cursor)):i(new h)})};s("0")}zpoprpush(t,e,i){this.runScript("ZPOPRPUSH",[t,e],[],(n,s)=>{n?i(n):i(null,typeof s=="string"?s:null)})}lpoprpush(t,e,i){this.validateRedisVersion(6,2)?this.lmove(t,e,"LEFT","RIGHT",i):this.runScript("LPOPRPUSH",[t,e],[],(n,s)=>{n?i(n):i(null,typeof s=="string"?s:null)})}updateServerVersion(t){k.redisServerVersion?t():this.getInfo((e,i)=>{e?t(e):i?(k.redisServerVersion=i.split(`\r
2
- `)[1].split(":")[1].split(".").map(n=>Number(n)),t()):t(new h)})}loadScripts(t){U.getInstance().loadScripts(this,t)}runScript(t,e,i,n){let s=U.getInstance().getScriptId(t);s instanceof Error?n(s):this.evalsha(s,[e.length,...e,...i],(l,a)=>{l?n(l):n(null,a)})}static addScript(t,e){if(!U.getInstance().addScript(t,e))throw new u(`A script with name [${t}] already exists`)}};k.redisServerVersion=null;var v=k;v.addScript("RELEASE_LOCK",et.default.readFileSync((0,it.resolve)(__dirname,"./lua/release-lock.lua")).toString());v.addScript("EXTEND_LOCK",et.default.readFileSync((0,it.resolve)(__dirname,"./lua/extend-lock.lua")).toString());var H=class{constructor(r,t,e,i=!1,n=!1){this.status=0;this.lockingTimer=null;this.autoExtendTimer=null;this.lockKey=t,this.ttl=e,this.retryOnFail=i,this.lockId=(0,gt.v4)(),this.redisClient=r,this.autoExtend=n}resetTimers(){this.lockingTimer&&(clearTimeout(this.lockingTimer),this.lockingTimer=null),this.autoExtendTimer&&(clearTimeout(this.autoExtendTimer),this.autoExtendTimer=null)}setUnlocked(){this.status=0}setLocked(){this.status=2}setExtended(){this.status=5}extend(r){this.isLocked()?(this.status=4,this.redisClient.runScript("EXTEND_LOCK",[this.lockKey],[this.lockId,this.ttl],(t,e)=>{t?r(t):this.status===4?e?(this.setExtended(),r()):(this.setUnlocked(),r(new M)):r(new I)})):r(new N)}runAutoExtendTimer(){let r=Math.ceil(this.ttl/2);this.autoExtendTimer=setTimeout(()=>this.extend(t=>{t?t instanceof I||p().emit("error",t):this.runAutoExtendTimer()}),r)}acquireLock(r){if(!this.isReleased())r(new z);else{this.status=1;let t=()=>{this.status===1?this.redisClient.set(this.lockKey,this.lockId,{expire:{mode:"PX",value:this.ttl},exists:"NX"},(e,i)=>{e?r(e):this.status===1?i?(this.setLocked(),this.autoExtend&&this.runAutoExtendTimer(),r()):this.retryOnFail?this.lockingTimer=setTimeout(t,1e3):(this.setUnlocked(),r(new w)):r(new I)}):r(new I)};t()}}extendLock(r){this.autoExtend?r(new A):this.extend(r)}releaseLock(r){this.status===0?r():this.isLocked()?(this.resetTimers(),this.status=3,this.redisClient.runScript("RELEASE_LOCK",[this.lockKey],[this.lockId],e=>{e?r(e):(this.setUnlocked(),r())})):r(new N)}acquireOrExtend(r){if(this.autoExtend)r(new A);else{let t=()=>{this.acquireLock(e=>{e?r(e):r(null,2)})};this.isLocked()?this.extend(e=>{e?e instanceof M?t():r(e):r(null,5)}):t()}}isLocked(){return this.status===2||this.status===5}isReleased(){return this.status===0}getId(){return this.lockId}};var f=class{constructor(){this.isPowered=!1;this.pendingState=null}switch(r){return this.pendingState!==null||r===this.isPowered?!1:(this.pendingState=r,!0)}isUp(){return this.isPowered}isDown(){return!this.isPowered}isGoingUp(){return this.pendingState===!0}isGoingDown(){return this.pendingState===!1}isRunning(){return this.isUp()&&this.pendingState===null}goingUp(){return this.switch(!0)}goingDown(){return this.switch(!1)}commit(){return this.pendingState===null?!1:(this.isPowered=this.pendingState,this.pendingState=null,!0)}rollback(){return this.pendingState===null?!1:(this.pendingState=null,!0)}};var R=class extends x{constructor(t=()=>{},e=1e3){super();this.powerManager=new f;this.onNextTickFn=null;this.timeout=null;this.interval=null;this.shutdownTimeout=null;this.aborted=!1;this.onTickFn=t,this.time=e,this.powerManager.goingUp()}shutdown(){this.shutdownTimeout&&clearTimeout(this.shutdownTimeout),this.powerManager.commit(),this.emit("down")}onTick(){var t;if(this.powerManager.isGoingDown())this.shutdown();else if(this.powerManager.isRunning()){let e=(t=this.onNextTickFn)!=null?t:this.onTickFn;this.onNextTickFn=null,e()}else p().emit("error",new T("Unexpected call"))}abort(){this.aborted||(this.aborted=!0,this.powerManager.isGoingDown()?this.shutdown():this.quit())}quit(){this.powerManager.isGoingUp()?(this.powerManager.rollback(),this.emit("down")):this.aborted&&this.powerManager.isDown()?this.emit("down"):(this.powerManager.goingDown(),this.timeout?(clearTimeout(this.timeout),this.shutdown()):this.interval?(clearInterval(this.interval),this.shutdown()):this.aborted?this.shutdown():this.shutdownTimeout=setTimeout(()=>{this.powerManager.isGoingDown()&&this.shutdown()},6e4))}isTicking(){return!!(this.timeout||this.interval)}nextTick(){this.isTicking()?p().emit("error",new L("A timer is already running")):this.powerManager.isGoingDown()?this.shutdown():(this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.timeout=setTimeout(()=>{this.timeout=null,this.onTick()},this.time)))}nextTickFn(t){this.onNextTickFn=t,this.nextTick()}runTimer(){this.isTicking()?p().emit("error",new L("A timer is already running")):(this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.interval=setInterval(()=>this.onTick(),this.time)))}};var X=class{constructor(r,t=1e3){this.ticker=null;this.powerManager=null;this.getTicker=()=>{if(!this.ticker)throw new y("Expected an instance of Ticker");return this.ticker};this.onTick=()=>{this.work(r=>{r?p().emit("error",r):this.getTicker().nextTick()})};this.run=r=>{if(this.managed)r(new y("You can not run a managed worker"));else{let t=this.getPowerManager();t.goingUp(),this.getTicker().nextTick(),t.commit(),r()}};this.quit=r=>{if(this.managed)r();else{let t=this.getPowerManager();t.goingDown();let e=this.getTicker();e.on("down",()=>{t.commit(),r()}),e.quit()}};this.managed=r,r||(this.ticker=new R(this.onTick,t),this.powerManager=new f)}getPowerManager(){if(!this.powerManager)throw new y("Expected an instance of PowerSwitch");return this.powerManager}};var G=class extends x{constructor(t,e,i,n){super();this.onTick=()=>{b.waterfall([t=>{this.lock.acquireOrExtend((e,i)=>{i===2&&this.logger.info(`Workers are exclusively running from this instance (Lock ID ${this.lock.getId()}).`),t(e)})},t=>{this.workerPool.work(t)}],t=>{!t||t instanceof w?this.ticker.nextTick():this.emit("error",t)})};this.clearWorkerPool=t=>{this.workerPool.clear(t)};this.stopTicker=t=>{this.ticker.once("down",t),this.ticker.quit()};this.releaseLock=t=>{this.lock.releaseLock(t)};this.run=t=>{this.ticker.nextTick(),this.emit("up"),t()};this.quit=t=>{b.waterfall([this.stopTicker,this.clearWorkerPool,this.releaseLock],()=>{this.emit("down"),t()})};this.powerManager=new f,this.redisClient=t,this.logger=n,this.lock=new H(t,e,6e4),this.ticker=new R(this.onTick),this.workerPool=i}addWorker(t){this.workerPool.add(t)}};var V=class{constructor(){this.pool=[];this.work=r=>{if(this.pool.length){let t=this.pool.map(e=>i=>e.work(i));b.waterfall(t,r)}else r()};this.add=r=>(this.pool.push(r),this.pool.length);this.clear=r=>{b.each(this.pool,(t,e,i)=>{t.quit(i)},()=>{this.pool=[],r()})}}};var mt=require("bunyan");var W=()=>{},At={debug:W,warn:W,info:W,error:W},C=null;function Nt(){C=null}function Pt(o){if(C)throw new O("Logger has been already initialized.");C=o}function Ot(o,r){var t;if(!o.enabled)return At;if(C||(C=(0,mt.createLogger)(ot(D({},(t=o.options)!=null?t:{}),{name:"redis-smq"}))),r){let e=(i,n)=>(s,...l)=>{let a=typeof s=="string"?`${r} | ${s}`:s;return n[i](a,...l)};return{info:e("info",C),warn:e("warn",C),debug:e("debug",C),error:e("error",C)}}return C}var ht={getLogger:Ot,setLogger:Pt,destroy:Nt};var pt=require("@redis/client");var bt=require("@redis/client");var K=class{constructor(r){this.multi=r.multi()}lrem(r,t,e){return this.multi.lRem(r,t,e),this}lpop(r){return this.multi.lPop(r),this}lpush(r,t){return this.multi.lPush(r,t),this}ltrim(r,t,e){return this.multi.lTrim(r,t,e),this}rpop(r){return this.multi.rPop(r),this}rpush(r,t){return this.multi.rPush(r,t),this}zadd(r,t,e){return this.multi.zAdd(r,{score:t,value:e}),this}zrem(r,t){return this.multi.zRem(r,t),this}sadd(r,t){return this.multi.sAdd(r,t),this}srem(r,t){return this.multi.sRem(r,t),this}hset(r,t,e){return this.multi.hSet(r,t,e),this}hdel(r,t){return this.multi.hDel(r,t),this}hincrby(r,t,e){return this.multi.hIncrBy(r,t,e),this}pexpire(r,t){return this.multi.pExpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rPopLPush(r,t),this}del(r){return this.multi.del(r),this}exec(r){this.multi.exec().then(t=>r(null,t)).catch(t=>{t instanceof bt.WatchError?r(new E):r(t)})}};var B=class extends v{constructor(t={}){super();this.client=(0,pt.createClient)(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")}),this.client.connect()}set(t,e,i,n){this.client.set(t,e,D(D({},i.expire?{[i.expire.mode]:i.expire.value}:{}),i.exists?{[i.exists]:!0}:{})).then(s=>n(null,s)).catch(n)}zadd(t,e,i,n){this.client.zAdd(t,{score:e,value:i}).then(s=>n(null,s)).catch(n)}multi(){return new K(this.client)}watch(t,e){this.client.watch(t).then(i=>e(null,i)).catch(e)}unwatch(t){this.client.unwatch().then(e=>t(null,e)).catch(t)}sismember(t,e,i){this.client.sIsMember(t,e).then(n=>i(null,Number(n))).catch(i)}zcard(t,e){this.client.zCard(t).then(i=>e(null,i)).catch(e)}zrange(t,e,i,n){this.client.zRange(t,e,i).then(s=>n(null,(Array.isArray(s)?s:[]).map(l=>String(l)))).catch(n)}zrevrange(t,e,i,n){this.client.sendCommand(["ZREVRANGE",t,String(e),String(i)]).then(s=>n(null,(Array.isArray(s)?s:[]).map(l=>String(l)))).catch(n)}zrem(t,e,i){this.client.zRem(t,e).then(n=>i(null,n)).catch(i)}psubscribe(t){this.client.pSubscribe(t,(e,i)=>{this.client.emit("pmessage",t,i,e)})}punsubscribe(t){this.client.pUnsubscribe(t).catch(()=>{})}subscribe(t){this.client.subscribe(t,(e,i)=>{this.client.emit("message",i,e)})}unsubscribe(t){this.client.unsubscribe(t).catch(()=>{})}zrangebyscore(t,e,i,n,s,l){this.client.zRangeByScore(t,e,i,{LIMIT:{offset:n,count:s}}).then(a=>l(null,a)).catch(l)}smembers(t,e){this.client.sMembers(t).then(i=>e(null,i)).catch(e)}sscan(t,e,i,n){let s=[t,Number(e),i];this.client.sScan(...s).then(({cursor:l,members:a})=>{n(null,{cursor:String(l),items:a})}).catch(n)}zscan(t,e,i,n){let s=[t,Number(e),i];this.client.zScan(...s).then(({cursor:l,members:a})=>{let c=new Set;for(let g of a)c.add(g.value);n(null,{cursor:String(l),items:[...c]})}).catch(n)}sadd(t,e,i){this.client.sAdd(t,e).then(n=>i(null,n)).catch(i)}srem(t,e,i){this.client.sRem(t,e).then(n=>i(null,n)).catch(i)}hgetall(t,e){this.client.hGetAll(t).then(i=>e(null,i)).catch(e)}hscan(t,e,i,n){let s=[t,Number(e),i];this.client.hScan(...s).then(({cursor:l,tuples:a})=>{let c={};for(;a.length;){let g=a.shift();g&&(c[g.field]=g.value)}n(null,{cursor:String(l),result:c})}).catch(n)}hget(t,e,i){this.client.hGet(t,e).then(n=>i(null,n!=null?n:null)).catch(i)}hset(t,e,i,n){this.client.hSet(t,e,i).then(s=>n(null,s)).catch(n)}hdel(t,e,i){this.client.hDel(t,e).then(n=>i(null,Number(n))).catch(i)}lrange(t,e,i,n){this.client.lRange(t,e,i).then(s=>n(null,s)).catch(n)}hkeys(t,e){this.client.hKeys(t).then(i=>e(null,i)).catch(e)}hlen(t,e){this.client.hLen(t).then(i=>e(null,i)).catch(e)}brpoplpush(t,e,i,n){this.client.brPopLPush(t,e,i).then(s=>n(null,s)).catch(n)}rpoplpush(t,e,i){this.client.rPopLPush(t,e).then(n=>i(null,n)).catch(i)}zrangebyscorewithscores(t,e,i,n){this.client.zRangeByScoreWithScores(t,e,i).then(s=>{let l={};for(let{score:a,value:c}of s)l[a]=c;n(null,l)}).catch(n)}rpop(t,e){this.client.rPop(t).then(i=>e(null,i)).catch(e)}lrem(t,e,i,n){this.client.lRem(t,e,i).then(s=>n(null,s)).catch(n)}publish(t,e,i){this.client.publish(t,e).then(n=>i(null,n)).catch(i)}flushall(t){this.client.flushAll().then(e=>t(null,e)).catch(t)}loadScript(t,e){this.client.sendCommand(["SCRIPT","LOAD",t]).then(i=>e(null,typeof i=="string"?i:String(i))).catch(e)}evalsha(t,e,i){let n=[t],s=Array.isArray(e)?e:[e];this.client.sendCommand(["evalsha",...n.concat(s).map(l=>String(l))]).then(l=>{Array.isArray(l)?i(null,l.map(a=>a instanceof Buffer?a.toString():a)):l instanceof Buffer?i(null,l.toString()):i(null,l)}).catch(i)}get(t,e){this.client.sendCommand(["get",t]).then(i=>e(null,typeof i=="string"?i:null)).catch(e)}del(t,e){this.client.del(t).then(i=>e(null,i)).catch(e)}llen(t,e){this.client.sendCommand(["llen",t]).then(i=>e(null,Number(i))).catch(e)}lmove(t,e,i,n,s){this.validateRedisVersion(6,2)?this.client.lMove(t,e,i,n).then(l=>s(null,l)).catch(s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,e,i,n){this.client.sendCommand(["zremrangebyscore",t,`${e}`,`${i}`]).then(s=>n(null,Number(s))).catch(n)}hmget(t,e,i){this.client.hmGet(t,e).then(n=>i(null,n)).catch(i)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect().catch(()=>{})}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info().then(e=>t(null,e)).catch(t)}on(t,e){return this.client.on(t,e),this}};var kt=J(require("ioredis"),1);var _=class{constructor(r){this.multi=r.multi()}lrem(r,t,e){return this.multi.lrem(r,t,e),this}lpop(r){return this.multi.lpop(r),this}lpush(r,t){return this.multi.lpush(r,t),this}ltrim(r,t,e){return this.multi.ltrim(r,t,e),this}rpop(r){return this.multi.rpop(r),this}rpush(r,t){return this.multi.rpush(r,t),this}zadd(r,t,e){return this.multi.zadd(r,t,e),this}zrem(r,t){return this.multi.zrem(r,...typeof t=="string"?[t]:t),this}sadd(r,t){return this.multi.sadd(r,t),this}srem(r,t){return this.multi.srem(r,...typeof t=="string"?[t]:t),this}hset(r,t,e){return this.multi.hset(r,t,e),this}hdel(r,t){return this.multi.hdel(r,...typeof t=="string"?[t]:t),this}hincrby(r,t,e){return this.multi.hincrby(r,t,e),this}pexpire(r,t){return this.multi.pexpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rpoplpush(r,t),this}del(r){return this.multi.del(...typeof r=="string"?[r]:r),this}exec(r){this.multi.exec((t,e)=>{if(t)r(t);else if(!e)r(new E);else{let i=[],n=null;for(let s of e){if(!Array.isArray(s)){n=new u("Expected an array reply from multi.exec()");break}let[l,a]=s;if(l instanceof Error){n=l;break}i.push(a)}n?r(n):r(null,i)}})}};var Q=class extends v{constructor(t={}){super();this.client=new kt.default(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")})}set(t,e,i,n){i.exists&&i.expire?this.client.set(t,e,i.expire.mode,i.expire.value,i.exists,n):i.expire?this.client.set(t,e,i.expire.mode,i.expire.value,n):i.exists?this.client.set(t,e,i.exists,n):this.client.set(t,e,n)}zadd(t,e,i,n){this.client.zadd(t,e,i,n)}multi(){return new _(this.client)}watch(t,e){this.client.watch(t,e)}unwatch(t){this.client.unwatch(t)}sismember(t,e,i){this.client.sismember(t,e,i)}sscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.sscan(...s,(l,[a,c])=>{l?n(l):n(null,{cursor:a,items:c})})}zcard(t,e){this.client.zcard(t,e)}zrange(t,e,i,n){this.client.zrange(t,e,i,n)}zscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.zscan(...s,(l,a)=>{if(l)n(l);else if(!a)n(new h);else{let c=new Set,[g,S]=a;for(;S.length;){let $=String(S.shift()),Ft=String(S.shift());c.add($)}n(null,{cursor:g,items:[...c]})}})}zrevrange(t,e,i,n){this.client.zrevrange(t,e,i,n)}zrem(t,e,i){this.client.zrem(t,e,i)}psubscribe(t){this.client.psubscribe(t)}punsubscribe(t){this.client.punsubscribe(t)}subscribe(t){this.client.subscribe(t)}unsubscribe(t){this.client.unsubscribe(t)}zrangebyscore(t,e,i,n,s,l){this.client.zrangebyscore(t,e,i,"LIMIT",n,s,l)}smembers(t,e){this.client.smembers(t,e)}sadd(t,e,i){this.client.sadd(t,e,i)}srem(t,e,i){this.client.srem(t,e,i)}hgetall(t,e){this.client.hgetall(t,e)}hscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.hscan(...s,(l,[a,c])=>{if(l)n(l);else{let g={};for(;c.length;){let S=String(c.shift());g[S]=String(c.shift())}n(null,{cursor:a,result:g})}})}hget(t,e,i){this.client.hget(t,e,i)}hset(t,e,i,n){this.client.hset(t,e,i,n)}hdel(t,e,i){this.client.hdel(t,e,i)}lrange(t,e,i,n){this.client.lrange(t,e,i,n)}hkeys(t,e){this.client.hkeys(t,e)}hlen(t,e){this.client.hlen(t,e)}brpoplpush(t,e,i,n){this.client.brpoplpush(t,e,i,n)}rpoplpush(t,e,i){this.client.rpoplpush(t,e,i)}zrangebyscorewithscores(t,e,i,n){this.client.zrangebyscore(t,e,i,"WITHSCORES",(s,l)=>{if(s)n(s);else{let a=l!=null?l:[],c={};for(let g=a.splice(0,2);g.length>0;g=a.splice(0,2)){let[S,$]=g;c[$]=S}n(null,c)}})}rpop(t,e){this.client.rpop(t,e)}lrem(t,e,i,n){this.client.lrem(t,e,i,n)}publish(t,e,i){this.client.publish(t,e,i)}flushall(t){this.client.flushall(t)}loadScript(t,e){this.client.script("load",t,e)}evalsha(t,e,i){let n=[t],s=Array.isArray(e)?e:[e];this.client.evalsha(n.concat(s),i)}get(t,e){this.client.get(t,e)}del(t,e){this.client.del(t,e)}llen(t,e){this.client.llen(t,e)}lmove(t,e,i,n,s){this.validateRedisVersion(6,2)?this.client.lmove(t,e,i,n,s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,e,i,n){this.client.zremrangebyscore(t,e,i,n)}hmget(t,e,i){this.client.hmget(t,e,i)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect(!1)}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info(t)}on(t,e){return this.client.on(t,e),this}};function zt(o){return o.client==="redis"?new B(o.options):new Q(o.options)}function Ut(o,r){let t=zt(o);t.once("ready",()=>{b.waterfall([e=>t.validateRedisServerSupport(e),e=>t.loadScripts(e)],e=>{e?r(e):r(null,t)})})}var vt={createInstance:Ut};0&&(module.exports={CallbackEmptyReplyError,CallbackInvalidReplyError,ERedisConfigClient,EventEmitter,Lock,LockAbortError,LockAcquireError,LockError,LockExtendError,LockMethodNotAllowedError,LockNotAcquiredError,LockNotReleasedError,LoggerError,PanicError,PowerSwitch,RedisClient,RedisClientError,RedisSMQError,Ticker,TickerError,WatchedKeysChangedError,Worker,WorkerError,WorkerPool,WorkerRunner,async,getEventBusInstance,logger,redis});
1
+ "use strict";var kt=Object.create;var H=Object.defineProperty,vt=Object.defineProperties,ft=Object.getOwnPropertyDescriptor,Ct=Object.getOwnPropertyDescriptors,It=Object.getOwnPropertyNames,it=Object.getOwnPropertySymbols,xt=Object.getPrototypeOf,nt=Object.prototype.hasOwnProperty,Tt=Object.prototype.propertyIsEnumerable;var rt=(o,r,t)=>r in o?H(o,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[r]=t,F=(o,r)=>{for(var t in r||(r={}))nt.call(r,t)&&rt(o,t,r[t]);if(it)for(var t of it(r))Tt.call(r,t)&&rt(o,t,r[t]);return o},st=(o,r)=>vt(o,Ct(r));var wt=(o,r)=>{for(var t in r)H(o,t,{get:r[t],enumerable:!0})},ot=(o,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of It(r))!nt.call(o,i)&&i!==t&&H(o,i,{get:()=>r[i],enumerable:!(e=ft(r,i))||e.enumerable});return o};var $=(o,r,t)=>(t=o!=null?kt(xt(o)):{},ot(r||!o||!o.__esModule?H(t,"default",{value:o,enumerable:!0}):t,o)),Et=o=>ot(H({},"__esModule",{value:!0}),o);var Ut={};wt(Ut,{CallbackEmptyReplyError:()=>b,CallbackInvalidReplyError:()=>D,ERedisConfigClient:()=>J,EventEmitter:()=>h,Lock:()=>U,LockAbortError:()=>I,LockAcquireError:()=>T,LockError:()=>m,LockExtendError:()=>L,LockMethodNotAllowedError:()=>M,LockNotAcquiredError:()=>A,LockNotReleasedError:()=>O,LoggerError:()=>P,PanicError:()=>x,PowerSwitch:()=>f,RedisClient:()=>v,RedisClientError:()=>u,RedisSMQError:()=>d,Ticker:()=>y,TickerError:()=>S,WatchedKeysChangedError:()=>w,Worker:()=>q,WorkerError:()=>E,WorkerPool:()=>G,WorkerRunner:()=>X,async:()=>p,getEventBusInstance:()=>St,logger:()=>gt,redis:()=>pt});module.exports=Et(Ut);var J=(t=>(t.IOREDIS="ioredis",t.REDIS="redis",t))(J||{});var d=class extends Error{constructor(r){super(r)}get name(){return this.constructor.name}};var b=class extends d{constructor(){super("Expected a non-empty reply")}};var D=class extends d{constructor(){super("Invalid reply type")}};var x=class extends d{};var P=class extends d{};var S=class extends d{};var m=class extends d{};var I=class extends m{constructor(r="releaseLock() may have been called. Abandoning."){super(r)}};var T=class extends m{constructor(r="Could not acquire a lock"){super(r)}};var L=class extends m{constructor(r="Acquired lock could not be extended"){super(r)}};var M=class extends m{constructor(r="This method can not be used when autoExtend is enabled"){super(r)}};var A=class extends m{constructor(r="Can not extend a lock which has not been yet acquired. Maybe a pending operation is in progress."){super(r)}};var O=class extends m{constructor(r="A lock has been already obtained but not yet released or maybe a pending operation is in progress."){super(r)}};var u=class extends d{};var w=class extends u{constructor(r="One (or more) of the watched keys has been changed"){super(r)}};var E=class extends x{};var dt=require("uuid");var tt=$(require("fs"),1),et=require("path");var lt=(o,r,t)=>{if(o.length){let e=0,i=()=>{r(o[e],e,n=>{e+=1,n||e>=o.length?t(n):setTimeout(()=>i(),0)})};i()}else t()},at=(o,r,t)=>{let e=Object.keys(o);if(e.length){let i=0,n=()=>{let s=e[i];r(o[s],s,l=>{i+=1,l||i>=e.length?t(l):setTimeout(()=>n(),0)})};n()}else t()},yt=(o,r,t)=>{Array.isArray(o)?lt(o,r,t):at(o,r,t)},Rt=(o,r)=>{if(o.length){let t=0,e=(i,...n)=>{t+=1,i?r(i):t<o.length?setTimeout(()=>{n.length?o[t](...n,e):o[t](e)},0):n.length?r(null,n[0]):r()};o[t](e)}else r()},p={each:yt,eachIn:at,eachOf:lt,waterfall:Rt};var Z=$(require("fs"),1),j=require("path");var N=class N{constructor(){this.isLoaded=!1;this.scripts=new Map,this.addScript("ZPOPRPUSH",Z.default.readFileSync((0,j.resolve)(__dirname,"./lua/zpoprpush.lua")).toString()),this.addScript("LPOPRPUSH",Z.default.readFileSync((0,j.resolve)(__dirname,"./lua/lpoprpush.lua")).toString())}hasScript(r){return this.scripts.has(r)}addScript(r,t){return this.hasScript(r)?!1:(this.scripts.set(r,{content:t}),this.isLoaded=!1,!0)}loadScripts(r,t){if(this.isLoaded)t();else{let e=[];this.scripts.forEach(i=>e.push(n=>{i.id?n():r.loadScript(i.content,(s,l)=>{s?n(s):l?(i.id=l,n()):n(new b)})})),p.waterfall(e,i=>{i?t(i):(this.isLoaded=!0,t())})}}getScriptId(r){var e;let{id:t}=(e=this.scripts.get(r))!=null?e:{};return t||new u(`ID of script [${r}] is missing`)}static getInstance(){return N.instance||(N.instance=new N),N.instance}};N.instance=null;var z=N;var ct=require("events"),h=class extends ct.EventEmitter{};var Y=null;function St(){return Y||(Y=new h),Y}var Lt=[4,0,0],k=class k extends h{constructor(){super(...arguments);this.connectionClosed=!0}validateRedisVersion(t,e=0,i=0){return k.redisServerVersion?k.redisServerVersion[0]>t||k.redisServerVersion[0]===t&&k.redisServerVersion[1]>=e&&k.redisServerVersion[2]>=i:(this.emit("error",new u("UNKNOWN_REDIS_SERVER_VERSION")),!1)}validateRedisServerSupport(t){let e=i=>{let[n,s,l]=Lt;this.validateRedisVersion(n,s,l)?i():i(new u("UNSUPPORTED_REDIS_SERVER_VERSION"))};k.redisServerVersion?e(t):this.updateServerVersion(i=>{i?t(i):e(t)})}sscanAll(t,e,i){let n=new Set,s=l=>{this.sscan(t,l,e,(a,c)=>{a?i(a):c?(c.items.forEach(g=>n.add(g)),c.cursor==="0"?i(null,[...n]):s(c.cursor)):i(new b)})};s("0")}hscanAll(t,e,i){let n={},s=l=>{this.hscan(t,l,e,(a,c)=>{a?i(a):c?(Object.assign(n,c.result),c.cursor==="0"?i(null,n):s(c.cursor)):i(new b)})};s("0")}zpoprpush(t,e,i){this.runScript("ZPOPRPUSH",[t,e],[],(n,s)=>{n?i(n):i(null,typeof s=="string"?s:null)})}lpoprpush(t,e,i){this.validateRedisVersion(6,2)?this.lmove(t,e,"LEFT","RIGHT",i):this.runScript("LPOPRPUSH",[t,e],[],(n,s)=>{n?i(n):i(null,typeof s=="string"?s:null)})}updateServerVersion(t){k.redisServerVersion?t():this.getInfo((e,i)=>{e?t(e):i?(k.redisServerVersion=i.split(`\r
2
+ `)[1].split(":")[1].split(".").map(n=>Number(n)),t()):t(new b)})}loadScripts(t){z.getInstance().loadScripts(this,t)}runScript(t,e,i,n){let s=z.getInstance().getScriptId(t);s instanceof Error?n(s):this.evalsha(s,[e.length,...e,...i],(l,a)=>{l?n(l):n(null,a)})}static addScript(t,e){if(!z.getInstance().addScript(t,e))throw new u(`A script with name [${t}] already exists`)}};k.redisServerVersion=null;var v=k;v.addScript("RELEASE_LOCK",tt.default.readFileSync((0,et.resolve)(__dirname,"./lua/release-lock.lua")).toString());v.addScript("EXTEND_LOCK",tt.default.readFileSync((0,et.resolve)(__dirname,"./lua/extend-lock.lua")).toString());var U=class extends h{constructor(t,e,i,n=!1,s=!1){super();this.status=0;this.lockingTimer=null;this.autoExtendTimer=null;this.lockKey=e,this.ttl=i,this.retryOnFail=n,this.lockId=(0,dt.v4)(),this.redisClient=t,this.autoExtend=s}resetTimers(){this.lockingTimer&&(clearTimeout(this.lockingTimer),this.lockingTimer=null),this.autoExtendTimer&&(clearTimeout(this.autoExtendTimer),this.autoExtendTimer=null)}setUnlocked(){this.status=0}setLocked(){this.status=2}setExtended(){this.status=5}extend(t){this.isLocked()?(this.status=4,this.redisClient.runScript("EXTEND_LOCK",[this.lockKey],[this.lockId,this.ttl],(e,i)=>{e?t(e):this.status===4?i!==1?(this.setUnlocked(),t(new L)):(this.setExtended(),t()):t(new I)})):t(new A)}runAutoExtendTimer(){let t=Math.ceil(this.ttl/2);this.autoExtendTimer=setTimeout(()=>this.extend(e=>{e?e instanceof I||this.emit("error",e):this.runAutoExtendTimer()}),t)}acquireLock(t){if(!this.isReleased())t(new O);else{this.status=1;let e=()=>{this.status===1?this.redisClient.set(this.lockKey,this.lockId,{expire:{mode:"PX",value:this.ttl},exists:"NX"},(i,n)=>{i?t(i):this.status===1?n?(this.setLocked(),this.autoExtend&&this.runAutoExtendTimer(),t()):this.retryOnFail?this.lockingTimer=setTimeout(e,1e3):(this.setUnlocked(),t(new T)):t(new I)}):t(new I)};e()}}extendLock(t){this.autoExtend?t(new M):this.extend(t)}releaseLock(t){this.status===0?t():this.isLocked()?(this.resetTimers(),this.status=3,this.redisClient.runScript("RELEASE_LOCK",[this.lockKey],[this.lockId],i=>{i?t(i):(this.setUnlocked(),t())})):t(new A)}acquireOrExtend(t){if(this.autoExtend)t(new M);else{let e=()=>{this.acquireLock(i=>{i?t(i):t(null,2)})};this.isLocked()?this.extend(i=>{i?i instanceof L?e():t(i):t(null,5)}):e()}}isLocked(){return this.status===2||this.status===5}isReleased(){return this.status===0}getId(){return this.lockId}};var f=class{constructor(){this.isPowered=!1;this.pendingState=null}switch(r){return this.pendingState!==null||r===this.isPowered?!1:(this.pendingState=r,!0)}isUp(){return this.isPowered}isDown(){return!this.isPowered}isGoingUp(){return this.pendingState===!0}isGoingDown(){return this.pendingState===!1}isRunning(){return this.isUp()&&this.pendingState===null}goingUp(){return this.switch(!0)}goingDown(){return this.switch(!1)}commit(){return this.pendingState===null?!1:(this.isPowered=this.pendingState,this.pendingState=null,!0)}rollback(){return this.pendingState===null?!1:(this.pendingState=null,!0)}};var y=class extends h{constructor(t=()=>{},e=1e3){super();this.powerManager=new f;this.onNextTickFn=null;this.timeout=null;this.interval=null;this.shutdownTimeout=null;this.aborted=!1;this.onTickFn=t,this.time=e,this.powerManager.goingUp()}shutdown(){this.shutdownTimeout&&clearTimeout(this.shutdownTimeout),this.powerManager.commit(),this.emit("down")}onTick(){var t;if(this.powerManager.isGoingDown())this.shutdown();else if(this.powerManager.isRunning()){let e=(t=this.onNextTickFn)!=null?t:this.onTickFn;this.onNextTickFn=null,e()}else this.emit("error",new x("Unexpected call"))}abort(){this.aborted||(this.aborted=!0,this.powerManager.isGoingDown()?this.shutdown():this.quit())}quit(){this.powerManager.isGoingUp()?(this.powerManager.rollback(),this.emit("down")):this.aborted&&this.powerManager.isDown()?this.emit("down"):(this.powerManager.goingDown(),this.timeout?(clearTimeout(this.timeout),this.shutdown()):this.interval?(clearInterval(this.interval),this.shutdown()):this.aborted?this.shutdown():this.shutdownTimeout=setTimeout(()=>{this.powerManager.isGoingDown()&&this.shutdown()},6e4))}isTicking(){return!!(this.timeout||this.interval)}nextTick(){this.isTicking()?this.emit("error",new S("A timer is already running")):this.powerManager.isGoingDown()?this.shutdown():(this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.timeout=setTimeout(()=>{this.timeout=null,this.onTick()},this.time)))}nextTickFn(t){this.onNextTickFn=t,this.nextTick()}runTimer(){this.isTicking()?this.emit("error",new S("A timer is already running")):(this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.interval=setInterval(()=>this.onTick(),this.time)))}};var q=class extends h{constructor(t,e=1e3){super();this.ticker=null;this.powerManager=null;this.getTicker=()=>{if(!this.ticker)throw new E("Expected an instance of Ticker");return this.ticker};this.onTick=()=>{this.work(t=>{t?this.emit("error",t):this.getTicker().nextTick()})};this.run=t=>{if(this.managed)t(new E("You can not run a managed worker"));else{let e=this.getPowerManager();e.goingUp(),this.getTicker().nextTick(),e.commit(),t()}};this.quit=t=>{if(this.managed)t();else{let e=this.getPowerManager();e.goingDown();let i=this.getTicker();i.on("down",()=>{e.commit(),t()}),i.quit()}};this.managed=t,t||(this.ticker=new y(this.onTick,e),this.powerManager=new f)}getPowerManager(){if(!this.powerManager)throw new E("Expected an instance of PowerSwitch");return this.powerManager}};var X=class extends h{constructor(t,e,i,n){super();this.onTick=()=>{p.waterfall([t=>{this.lock.acquireOrExtend((e,i)=>{i===2&&this.logger.info(`Workers are exclusively running from this instance (Lock ID ${this.lock.getId()}).`),t(e)})},t=>{this.workerPool.work(t)}],t=>{!t||t instanceof T?this.ticker.nextTick():this.emit("error",t)})};this.clearWorkerPool=t=>{this.workerPool.clear(t)};this.stopTicker=t=>{this.ticker.once("down",t),this.ticker.quit()};this.releaseLock=t=>{this.lock.releaseLock(t)};this.run=t=>{this.ticker.nextTick(),this.emit("up"),t()};this.quit=t=>{p.waterfall([this.stopTicker,this.clearWorkerPool,this.releaseLock],()=>{this.emit("down"),t()})};this.powerManager=new f,this.redisClient=t,this.logger=n,this.lock=new U(t,e,6e4),this.ticker=new y(this.onTick),this.workerPool=i}addWorker(t){this.workerPool.add(t)}};var G=class{constructor(){this.pool=[];this.work=r=>{if(this.pool.length){let t=this.pool.map(e=>i=>e.work(i));p.waterfall(t,r)}else r()};this.add=r=>(this.pool.push(r),this.pool.length);this.clear=r=>{p.each(this.pool,(t,e,i)=>{t.quit(i)},()=>{this.pool=[],r()})}}};var ut=require("bunyan");var V=()=>{},Mt={debug:V,warn:V,info:V,error:V},C=null;function At(){C=null}function Nt(o){if(C)throw new P("Logger has been already initialized.");C=o}function Pt(o,r){var t;if(!o.enabled)return Mt;if(C||(C=(0,ut.createLogger)(st(F({},(t=o.options)!=null?t:{}),{name:"redis-smq"}))),r){let e=(i,n)=>(s,...l)=>{let a=typeof s=="string"?`${r} | ${s}`:s;return n[i](a,...l)};return{info:e("info",C),warn:e("warn",C),debug:e("debug",C),error:e("error",C)}}return C}var gt={getLogger:Pt,setLogger:Nt,destroy:At};var ht=require("@redis/client");var mt=require("@redis/client");var W=class{constructor(r){this.multi=r.multi()}lrem(r,t,e){return this.multi.lRem(r,t,e),this}lpop(r){return this.multi.lPop(r),this}lpush(r,t){return this.multi.lPush(r,t),this}ltrim(r,t,e){return this.multi.lTrim(r,t,e),this}rpop(r){return this.multi.rPop(r),this}rpush(r,t){return this.multi.rPush(r,t),this}zadd(r,t,e){return this.multi.zAdd(r,{score:t,value:e}),this}zrem(r,t){return this.multi.zRem(r,t),this}sadd(r,t){return this.multi.sAdd(r,t),this}srem(r,t){return this.multi.sRem(r,t),this}hset(r,t,e){return this.multi.hSet(r,t,e),this}hdel(r,t){return this.multi.hDel(r,t),this}hincrby(r,t,e){return this.multi.hIncrBy(r,t,e),this}pexpire(r,t){return this.multi.pExpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rPopLPush(r,t),this}del(r){return this.multi.del(r),this}exec(r){this.multi.exec().then(t=>r(null,t)).catch(t=>{t instanceof mt.WatchError?r(new w):r(t)})}};var K=class extends v{constructor(t={}){super();this.client=(0,ht.createClient)(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")}),this.client.connect()}set(t,e,i,n){this.client.set(t,e,F(F({},i.expire?{[i.expire.mode]:i.expire.value}:{}),i.exists?{[i.exists]:!0}:{})).then(s=>n(null,s)).catch(n)}zadd(t,e,i,n){this.client.zAdd(t,{score:e,value:i}).then(s=>n(null,s)).catch(n)}multi(){return new W(this.client)}watch(t,e){this.client.watch(t).then(i=>e(null,i)).catch(e)}unwatch(t){this.client.unwatch().then(e=>t(null,e)).catch(t)}sismember(t,e,i){this.client.sIsMember(t,e).then(n=>i(null,Number(n))).catch(i)}zcard(t,e){this.client.zCard(t).then(i=>e(null,i)).catch(e)}zrange(t,e,i,n){this.client.zRange(t,e,i).then(s=>n(null,(Array.isArray(s)?s:[]).map(l=>String(l)))).catch(n)}zrevrange(t,e,i,n){this.client.sendCommand(["ZREVRANGE",t,String(e),String(i)]).then(s=>n(null,(Array.isArray(s)?s:[]).map(l=>String(l)))).catch(n)}zrem(t,e,i){this.client.zRem(t,e).then(n=>i(null,n)).catch(i)}psubscribe(t){this.client.pSubscribe(t,(e,i)=>{this.client.emit("pmessage",t,i,e)})}punsubscribe(t){this.client.pUnsubscribe(t).catch(()=>{})}subscribe(t){this.client.subscribe(t,(e,i)=>{this.client.emit("message",i,e)})}unsubscribe(t){this.client.unsubscribe(t).catch(()=>{})}zrangebyscore(t,e,i,n,s,l){this.client.zRangeByScore(t,e,i,{LIMIT:{offset:n,count:s}}).then(a=>l(null,a)).catch(l)}smembers(t,e){this.client.sMembers(t).then(i=>e(null,i)).catch(e)}sscan(t,e,i,n){let s=[t,Number(e),i];this.client.sScan(...s).then(({cursor:l,members:a})=>{n(null,{cursor:String(l),items:a})}).catch(n)}zscan(t,e,i,n){let s=[t,Number(e),i];this.client.zScan(...s).then(({cursor:l,members:a})=>{let c=new Set;for(let g of a)c.add(g.value);n(null,{cursor:String(l),items:[...c]})}).catch(n)}sadd(t,e,i){this.client.sAdd(t,e).then(n=>i(null,n)).catch(i)}srem(t,e,i){this.client.sRem(t,e).then(n=>i(null,n)).catch(i)}hgetall(t,e){this.client.hGetAll(t).then(i=>e(null,i)).catch(e)}hscan(t,e,i,n){let s=[t,Number(e),i];this.client.hScan(...s).then(({cursor:l,tuples:a})=>{let c={};for(;a.length;){let g=a.shift();g&&(c[g.field]=g.value)}n(null,{cursor:String(l),result:c})}).catch(n)}hget(t,e,i){this.client.hGet(t,e).then(n=>i(null,n!=null?n:null)).catch(i)}hset(t,e,i,n){this.client.hSet(t,e,i).then(s=>n(null,s)).catch(n)}hdel(t,e,i){this.client.hDel(t,e).then(n=>i(null,Number(n))).catch(i)}lrange(t,e,i,n){this.client.lRange(t,e,i).then(s=>n(null,s)).catch(n)}hkeys(t,e){this.client.hKeys(t).then(i=>e(null,i)).catch(e)}hlen(t,e){this.client.hLen(t).then(i=>e(null,i)).catch(e)}brpoplpush(t,e,i,n){this.client.brPopLPush(t,e,i).then(s=>n(null,s)).catch(n)}rpoplpush(t,e,i){this.client.rPopLPush(t,e).then(n=>i(null,n)).catch(i)}zrangebyscorewithscores(t,e,i,n){this.client.zRangeByScoreWithScores(t,e,i).then(s=>{let l={};for(let{score:a,value:c}of s)l[a]=c;n(null,l)}).catch(n)}rpop(t,e){this.client.rPop(t).then(i=>e(null,i)).catch(e)}lrem(t,e,i,n){this.client.lRem(t,e,i).then(s=>n(null,s)).catch(n)}publish(t,e,i){this.client.publish(t,e).then(n=>i(null,n)).catch(i)}flushall(t){this.client.flushAll().then(e=>t(null,e)).catch(t)}loadScript(t,e){this.client.sendCommand(["SCRIPT","LOAD",t]).then(i=>e(null,typeof i=="string"?i:String(i))).catch(e)}evalsha(t,e,i){let n=[t],s=Array.isArray(e)?e:[e];this.client.sendCommand(["evalsha",...n.concat(s).map(l=>String(l))]).then(l=>{Array.isArray(l)?i(null,l.map(a=>a instanceof Buffer?a.toString():a)):l instanceof Buffer?i(null,l.toString()):i(null,l)}).catch(i)}get(t,e){this.client.sendCommand(["get",t]).then(i=>e(null,typeof i=="string"?i:null)).catch(e)}del(t,e){this.client.del(t).then(i=>e(null,i)).catch(e)}llen(t,e){this.client.sendCommand(["llen",t]).then(i=>e(null,Number(i))).catch(e)}lmove(t,e,i,n,s){this.validateRedisVersion(6,2)?this.client.lMove(t,e,i,n).then(l=>s(null,l)).catch(s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,e,i,n){this.client.sendCommand(["zremrangebyscore",t,`${e}`,`${i}`]).then(s=>n(null,Number(s))).catch(n)}hmget(t,e,i){this.client.hmGet(t,e).then(n=>i(null,n)).catch(i)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect().catch(()=>{})}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info().then(e=>t(null,e)).catch(t)}on(t,e){return this.client.on(t,e),this}};var bt=$(require("ioredis"),1);var _=class{constructor(r){this.multi=r.multi()}lrem(r,t,e){return this.multi.lrem(r,t,e),this}lpop(r){return this.multi.lpop(r),this}lpush(r,t){return this.multi.lpush(r,t),this}ltrim(r,t,e){return this.multi.ltrim(r,t,e),this}rpop(r){return this.multi.rpop(r),this}rpush(r,t){return this.multi.rpush(r,t),this}zadd(r,t,e){return this.multi.zadd(r,t,e),this}zrem(r,t){return this.multi.zrem(r,...typeof t=="string"?[t]:t),this}sadd(r,t){return this.multi.sadd(r,t),this}srem(r,t){return this.multi.srem(r,...typeof t=="string"?[t]:t),this}hset(r,t,e){return this.multi.hset(r,t,e),this}hdel(r,t){return this.multi.hdel(r,...typeof t=="string"?[t]:t),this}hincrby(r,t,e){return this.multi.hincrby(r,t,e),this}pexpire(r,t){return this.multi.pexpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rpoplpush(r,t),this}del(r){return this.multi.del(...typeof r=="string"?[r]:r),this}exec(r){this.multi.exec((t,e)=>{if(t)r(t);else if(!e)r(new w);else{let i=[],n=null;for(let s of e){if(!Array.isArray(s)){n=new u("Expected an array reply from multi.exec()");break}let[l,a]=s;if(l instanceof Error){n=l;break}i.push(a)}n?r(n):r(null,i)}})}};var B=class extends v{constructor(t={}){super();this.client=new bt.default(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")})}set(t,e,i,n){i.exists&&i.expire?this.client.set(t,e,i.expire.mode,i.expire.value,i.exists,n):i.expire?this.client.set(t,e,i.expire.mode,i.expire.value,n):i.exists?this.client.set(t,e,i.exists,n):this.client.set(t,e,n)}zadd(t,e,i,n){this.client.zadd(t,e,i,n)}multi(){return new _(this.client)}watch(t,e){this.client.watch(t,e)}unwatch(t){this.client.unwatch(t)}sismember(t,e,i){this.client.sismember(t,e,i)}sscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.sscan(...s,(l,[a,c])=>{l?n(l):n(null,{cursor:a,items:c})})}zcard(t,e){this.client.zcard(t,e)}zrange(t,e,i,n){this.client.zrange(t,e,i,n)}zscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.zscan(...s,(l,a)=>{if(l)n(l);else if(!a)n(new b);else{let c=new Set,[g,R]=a;for(;R.length;){let Q=String(R.shift()),Ht=String(R.shift());c.add(Q)}n(null,{cursor:g,items:[...c]})}})}zrevrange(t,e,i,n){this.client.zrevrange(t,e,i,n)}zrem(t,e,i){this.client.zrem(t,e,i)}psubscribe(t){this.client.psubscribe(t)}punsubscribe(t){this.client.punsubscribe(t)}subscribe(t){this.client.subscribe(t)}unsubscribe(t){this.client.unsubscribe(t)}zrangebyscore(t,e,i,n,s,l){this.client.zrangebyscore(t,e,i,"LIMIT",n,s,l)}smembers(t,e){this.client.smembers(t,e)}sadd(t,e,i){this.client.sadd(t,e,i)}srem(t,e,i){this.client.srem(t,e,i)}hgetall(t,e){this.client.hgetall(t,e)}hscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.hscan(...s,(l,[a,c])=>{if(l)n(l);else{let g={};for(;c.length;){let R=String(c.shift());g[R]=String(c.shift())}n(null,{cursor:a,result:g})}})}hget(t,e,i){this.client.hget(t,e,i)}hset(t,e,i,n){this.client.hset(t,e,i,n)}hdel(t,e,i){this.client.hdel(t,e,i)}lrange(t,e,i,n){this.client.lrange(t,e,i,n)}hkeys(t,e){this.client.hkeys(t,e)}hlen(t,e){this.client.hlen(t,e)}brpoplpush(t,e,i,n){this.client.brpoplpush(t,e,i,n)}rpoplpush(t,e,i){this.client.rpoplpush(t,e,i)}zrangebyscorewithscores(t,e,i,n){this.client.zrangebyscore(t,e,i,"WITHSCORES",(s,l)=>{if(s)n(s);else{let a=l!=null?l:[],c={};for(let g=a.splice(0,2);g.length>0;g=a.splice(0,2)){let[R,Q]=g;c[Q]=R}n(null,c)}})}rpop(t,e){this.client.rpop(t,e)}lrem(t,e,i,n){this.client.lrem(t,e,i,n)}publish(t,e,i){this.client.publish(t,e,i)}flushall(t){this.client.flushall(t)}loadScript(t,e){this.client.script("load",t,e)}evalsha(t,e,i){let n=[t],s=Array.isArray(e)?e:[e];this.client.evalsha(n.concat(s),i)}get(t,e){this.client.get(t,e)}del(t,e){this.client.del(t,e)}llen(t,e){this.client.llen(t,e)}lmove(t,e,i,n,s){this.validateRedisVersion(6,2)?this.client.lmove(t,e,i,n,s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,e,i,n){this.client.zremrangebyscore(t,e,i,n)}hmget(t,e,i){this.client.hmget(t,e,i)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect(!1)}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info(t)}on(t,e){return this.client.on(t,e),this}};function Ot(o){return o.client==="redis"?new K(o.options):new B(o.options)}function zt(o,r){let t=Ot(o);t.once("ready",()=>{p.waterfall([e=>t.validateRedisServerSupport(e),e=>t.loadScripts(e)],e=>{e?r(e):r(null,t)})})}var pt={createInstance:zt};0&&(module.exports={CallbackEmptyReplyError,CallbackInvalidReplyError,ERedisConfigClient,EventEmitter,Lock,LockAbortError,LockAcquireError,LockError,LockExtendError,LockMethodNotAllowedError,LockNotAcquiredError,LockNotReleasedError,LoggerError,PanicError,PowerSwitch,RedisClient,RedisClientError,RedisSMQError,Ticker,TickerError,WatchedKeysChangedError,Worker,WorkerError,WorkerPool,WorkerRunner,async,getEventBusInstance,logger,redis});
3
3
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.cts CHANGED
@@ -25,6 +25,13 @@ interface IRedisConfigNodeRedis {
25
25
  }
26
26
  type IRedisConfig = IRedisConfigIORedis | IRedisConfigNodeRedis;
27
27
 
28
+ type TRedisClientEvent = {
29
+ error: (err: Error) => void;
30
+ ready: () => void;
31
+ end: () => void;
32
+ message: (channel: string, message: string) => void;
33
+ pmessage: (pattern: string, channel: string, message: string) => void;
34
+ };
28
35
  type TRedisTransactionNodeRedis = RedisClientMultiCommandType<RedisModules, RedisFunctions, RedisScripts>;
29
36
  type TRedisClientNodeRedis = RedisClientType<RedisModules, RedisFunctions, RedisScripts>;
30
37
  interface IRedisClient {
@@ -155,7 +162,6 @@ interface ILogger {
155
162
 
156
163
  type TEvent = {
157
164
  error: (err: Error) => void;
158
- next: () => void;
159
165
  up: () => void;
160
166
  down: () => void;
161
167
  goingUp: () => void;
@@ -222,7 +228,19 @@ declare class WatchedKeysChangedError extends RedisClientError {
222
228
  declare class WorkerError extends PanicError {
223
229
  }
224
230
 
225
- declare abstract class RedisClient extends EventEmitter$1 implements IRedisClient {
231
+ type TEventEmitterEvent = Record<string | symbol, (...args: any) => any>;
232
+ declare interface EventEmitter<Events extends TEventEmitterEvent> extends EventEmitter$1 {
233
+ on<E extends keyof Events>(event: E, listener: Events[E]): this;
234
+ once<E extends keyof Events>(event: E, listener: Events[E]): this;
235
+ emit<E extends keyof Events>(event: E, ...args: Parameters<Events[E]>): boolean;
236
+ removeAllListeners<E extends keyof Events>(event?: E): this;
237
+ }
238
+ declare class EventEmitter<Events extends TEventEmitterEvent> extends EventEmitter$1 {
239
+ }
240
+
241
+ declare function getEventBusInstance<T extends TEvent>(): EventEmitter<T>;
242
+
243
+ declare abstract class RedisClient extends EventEmitter<TRedisClientEvent> implements IRedisClient {
226
244
  protected static redisServerVersion: number[] | null;
227
245
  protected connectionClosed: boolean;
228
246
  validateRedisVersion(major: number, feature?: number, minor?: number): boolean;
@@ -322,7 +340,7 @@ declare enum ELockStatus {
322
340
  extending = 4,
323
341
  extended = 5
324
342
  }
325
- declare class Lock {
343
+ declare class Lock extends EventEmitter<TEvent> {
326
344
  protected readonly lockId: string;
327
345
  protected readonly lockKey: string;
328
346
  protected readonly retryOnFail: boolean;
@@ -363,18 +381,6 @@ declare class PowerSwitch {
363
381
  rollback(): boolean;
364
382
  }
365
383
 
366
- type TEventEmitterEvent = Record<string | symbol, (...args: any) => any>;
367
- declare interface EventEmitter<Events extends TEventEmitterEvent> extends EventEmitter$1 {
368
- on<E extends keyof Events>(event: E, listener: Events[E]): this;
369
- once<E extends keyof Events>(event: E, listener: Events[E]): this;
370
- emit<E extends keyof Events>(event: E, ...args: Parameters<Events[E]>): boolean;
371
- removeAllListeners<E extends keyof Events>(event?: E): this;
372
- }
373
- declare class EventEmitter<Events extends TEventEmitterEvent> extends EventEmitter$1 {
374
- }
375
-
376
- declare function getEventBusInstance<T extends TEvent>(): EventEmitter<TEvent>;
377
-
378
384
  declare class Ticker extends EventEmitter<TEvent> {
379
385
  protected powerManager: PowerSwitch;
380
386
  protected onTickFn: TFunction;
@@ -395,7 +401,7 @@ declare class Ticker extends EventEmitter<TEvent> {
395
401
  runTimer(): void;
396
402
  }
397
403
 
398
- declare abstract class Worker {
404
+ declare abstract class Worker extends EventEmitter<TEvent> {
399
405
  private readonly ticker;
400
406
  private readonly powerManager;
401
407
  private readonly managed;
@@ -453,4 +459,4 @@ declare const redis: {
453
459
  createInstance: typeof createInstance;
454
460
  };
455
461
 
456
- export { CallbackEmptyReplyError, CallbackInvalidReplyError, ERedisConfigClient, EventEmitter, type ICallback, type ILogger, type ILoggerConfig, type IRedisClient, type IRedisConfig, type IRedisConfigIORedis, type IRedisConfigNodeRedis, type IRedisTransaction, Lock, LockAbortError, LockAcquireError, LockError, LockExtendError, LockMethodNotAllowedError, LockNotAcquiredError, LockNotReleasedError, LoggerError, PanicError, PowerSwitch, RedisClient, RedisClientError, RedisSMQError, type TEvent, type TEventEmitterEvent, type TFunction, type TRedisClientNodeRedis, type TRedisTransactionNodeRedis, type TUnaryFunction, Ticker, TickerError, WatchedKeysChangedError, Worker, WorkerError, WorkerPool, WorkerRunner, async, getEventBusInstance, logger, redis };
462
+ export { CallbackEmptyReplyError, CallbackInvalidReplyError, ERedisConfigClient, EventEmitter, type ICallback, type ILogger, type ILoggerConfig, type IRedisClient, type IRedisConfig, type IRedisConfigIORedis, type IRedisConfigNodeRedis, type IRedisTransaction, Lock, LockAbortError, LockAcquireError, LockError, LockExtendError, LockMethodNotAllowedError, LockNotAcquiredError, LockNotReleasedError, LoggerError, PanicError, PowerSwitch, RedisClient, RedisClientError, RedisSMQError, type TEvent, type TEventEmitterEvent, type TFunction, type TRedisClientEvent, type TRedisClientNodeRedis, type TRedisTransactionNodeRedis, type TUnaryFunction, Ticker, TickerError, WatchedKeysChangedError, Worker, WorkerError, WorkerPool, WorkerRunner, async, getEventBusInstance, logger, redis };
package/dist/index.d.ts CHANGED
@@ -25,6 +25,13 @@ interface IRedisConfigNodeRedis {
25
25
  }
26
26
  type IRedisConfig = IRedisConfigIORedis | IRedisConfigNodeRedis;
27
27
 
28
+ type TRedisClientEvent = {
29
+ error: (err: Error) => void;
30
+ ready: () => void;
31
+ end: () => void;
32
+ message: (channel: string, message: string) => void;
33
+ pmessage: (pattern: string, channel: string, message: string) => void;
34
+ };
28
35
  type TRedisTransactionNodeRedis = RedisClientMultiCommandType<RedisModules, RedisFunctions, RedisScripts>;
29
36
  type TRedisClientNodeRedis = RedisClientType<RedisModules, RedisFunctions, RedisScripts>;
30
37
  interface IRedisClient {
@@ -155,7 +162,6 @@ interface ILogger {
155
162
 
156
163
  type TEvent = {
157
164
  error: (err: Error) => void;
158
- next: () => void;
159
165
  up: () => void;
160
166
  down: () => void;
161
167
  goingUp: () => void;
@@ -222,7 +228,19 @@ declare class WatchedKeysChangedError extends RedisClientError {
222
228
  declare class WorkerError extends PanicError {
223
229
  }
224
230
 
225
- declare abstract class RedisClient extends EventEmitter$1 implements IRedisClient {
231
+ type TEventEmitterEvent = Record<string | symbol, (...args: any) => any>;
232
+ declare interface EventEmitter<Events extends TEventEmitterEvent> extends EventEmitter$1 {
233
+ on<E extends keyof Events>(event: E, listener: Events[E]): this;
234
+ once<E extends keyof Events>(event: E, listener: Events[E]): this;
235
+ emit<E extends keyof Events>(event: E, ...args: Parameters<Events[E]>): boolean;
236
+ removeAllListeners<E extends keyof Events>(event?: E): this;
237
+ }
238
+ declare class EventEmitter<Events extends TEventEmitterEvent> extends EventEmitter$1 {
239
+ }
240
+
241
+ declare function getEventBusInstance<T extends TEvent>(): EventEmitter<T>;
242
+
243
+ declare abstract class RedisClient extends EventEmitter<TRedisClientEvent> implements IRedisClient {
226
244
  protected static redisServerVersion: number[] | null;
227
245
  protected connectionClosed: boolean;
228
246
  validateRedisVersion(major: number, feature?: number, minor?: number): boolean;
@@ -322,7 +340,7 @@ declare enum ELockStatus {
322
340
  extending = 4,
323
341
  extended = 5
324
342
  }
325
- declare class Lock {
343
+ declare class Lock extends EventEmitter<TEvent> {
326
344
  protected readonly lockId: string;
327
345
  protected readonly lockKey: string;
328
346
  protected readonly retryOnFail: boolean;
@@ -363,18 +381,6 @@ declare class PowerSwitch {
363
381
  rollback(): boolean;
364
382
  }
365
383
 
366
- type TEventEmitterEvent = Record<string | symbol, (...args: any) => any>;
367
- declare interface EventEmitter<Events extends TEventEmitterEvent> extends EventEmitter$1 {
368
- on<E extends keyof Events>(event: E, listener: Events[E]): this;
369
- once<E extends keyof Events>(event: E, listener: Events[E]): this;
370
- emit<E extends keyof Events>(event: E, ...args: Parameters<Events[E]>): boolean;
371
- removeAllListeners<E extends keyof Events>(event?: E): this;
372
- }
373
- declare class EventEmitter<Events extends TEventEmitterEvent> extends EventEmitter$1 {
374
- }
375
-
376
- declare function getEventBusInstance<T extends TEvent>(): EventEmitter<TEvent>;
377
-
378
384
  declare class Ticker extends EventEmitter<TEvent> {
379
385
  protected powerManager: PowerSwitch;
380
386
  protected onTickFn: TFunction;
@@ -395,7 +401,7 @@ declare class Ticker extends EventEmitter<TEvent> {
395
401
  runTimer(): void;
396
402
  }
397
403
 
398
- declare abstract class Worker {
404
+ declare abstract class Worker extends EventEmitter<TEvent> {
399
405
  private readonly ticker;
400
406
  private readonly powerManager;
401
407
  private readonly managed;
@@ -453,4 +459,4 @@ declare const redis: {
453
459
  createInstance: typeof createInstance;
454
460
  };
455
461
 
456
- export { CallbackEmptyReplyError, CallbackInvalidReplyError, ERedisConfigClient, EventEmitter, type ICallback, type ILogger, type ILoggerConfig, type IRedisClient, type IRedisConfig, type IRedisConfigIORedis, type IRedisConfigNodeRedis, type IRedisTransaction, Lock, LockAbortError, LockAcquireError, LockError, LockExtendError, LockMethodNotAllowedError, LockNotAcquiredError, LockNotReleasedError, LoggerError, PanicError, PowerSwitch, RedisClient, RedisClientError, RedisSMQError, type TEvent, type TEventEmitterEvent, type TFunction, type TRedisClientNodeRedis, type TRedisTransactionNodeRedis, type TUnaryFunction, Ticker, TickerError, WatchedKeysChangedError, Worker, WorkerError, WorkerPool, WorkerRunner, async, getEventBusInstance, logger, redis };
462
+ export { CallbackEmptyReplyError, CallbackInvalidReplyError, ERedisConfigClient, EventEmitter, type ICallback, type ILogger, type ILoggerConfig, type IRedisClient, type IRedisConfig, type IRedisConfigIORedis, type IRedisConfigNodeRedis, type IRedisTransaction, Lock, LockAbortError, LockAcquireError, LockError, LockExtendError, LockMethodNotAllowedError, LockNotAcquiredError, LockNotReleasedError, LoggerError, PanicError, PowerSwitch, RedisClient, RedisClientError, RedisSMQError, type TEvent, type TEventEmitterEvent, type TFunction, type TRedisClientEvent, type TRedisClientNodeRedis, type TRedisTransactionNodeRedis, type TUnaryFunction, Ticker, TickerError, WatchedKeysChangedError, Worker, WorkerError, WorkerPool, WorkerRunner, async, getEventBusInstance, logger, redis };
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- var ot=Object.defineProperty,lt=Object.defineProperties;var at=Object.getOwnPropertyDescriptors;var J=Object.getOwnPropertySymbols;var ct=Object.prototype.hasOwnProperty,dt=Object.prototype.propertyIsEnumerable;var Z=(o,r,t)=>r in o?ot(o,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[r]=t,z=(o,r)=>{for(var t in r||(r={}))ct.call(r,t)&&Z(o,t,r[t]);if(J)for(var t of J(r))dt.call(r,t)&&Z(o,t,r[t]);return o},j=(o,r)=>lt(o,at(r));var Y=(t=>(t.IOREDIS="ioredis",t.REDIS="redis",t))(Y||{});var d=class extends Error{constructor(r){super(r)}get name(){return this.constructor.name}};var h=class extends d{constructor(){super("Expected a non-empty reply")}};var K=class extends d{constructor(){super("Invalid reply type")}};var w=class extends d{};var U=class extends d{};var M=class extends d{};var m=class extends d{};var I=class extends m{constructor(r="releaseLock() may have been called. Abandoning."){super(r)}};var E=class extends m{constructor(r="Could not acquire a lock"){super(r)}};var A=class extends m{constructor(r="Acquired lock could not be extended"){super(r)}};var N=class extends m{constructor(r="This method can not be used when autoExtend is enabled"){super(r)}};var P=class extends m{constructor(r="Can not extend a lock which has not been yet acquired. Maybe a pending operation is in progress."){super(r)}};var H=class extends m{constructor(r="A lock has been already obtained but not yet released or maybe a pending operation is in progress."){super(r)}};var u=class extends d{};var y=class extends u{constructor(r="One (or more) of the watched keys has been changed"){super(r)}};var R=class extends w{};import{v4 as pt}from"uuid";import nt from"fs";import{resolve as st}from"path";import{EventEmitter as ht}from"events";var tt=(o,r,t)=>{if(o.length){let e=0,i=()=>{r(o[e],e,n=>{e+=1,n||e>=o.length?t(n):setTimeout(()=>i(),0)})};i()}else t()},et=(o,r,t)=>{let e=Object.keys(o);if(e.length){let i=0,n=()=>{let s=e[i];r(o[s],s,l=>{i+=1,l||i>=e.length?t(l):setTimeout(()=>n(),0)})};n()}else t()},ut=(o,r,t)=>{Array.isArray(o)?tt(o,r,t):et(o,r,t)},gt=(o,r)=>{if(o.length){let t=0,e=(i,...n)=>{t+=1,i?r(i):t<o.length?setTimeout(()=>{n.length?o[t](...n,e):o[t](e)},0):n.length?r(null,n[0]):r()};o[t](e)}else r()},b={each:ut,eachIn:et,eachOf:tt,waterfall:gt};import it from"fs";import{resolve as rt}from"path";var S=class S{constructor(){this.isLoaded=!1;this.scripts=new Map,this.addScript("ZPOPRPUSH",it.readFileSync(rt(__dirname,"./lua/zpoprpush.lua")).toString()),this.addScript("LPOPRPUSH",it.readFileSync(rt(__dirname,"./lua/lpoprpush.lua")).toString())}hasScript(r){return this.scripts.has(r)}addScript(r,t){return this.hasScript(r)?!1:(this.scripts.set(r,{content:t}),this.isLoaded=!1,!0)}loadScripts(r,t){if(this.isLoaded)t();else{let e=[];this.scripts.forEach(i=>e.push(n=>{i.id?n():r.loadScript(i.content,(s,l)=>{s?n(s):l?(i.id=l,n()):n(new h)})})),b.waterfall(e,i=>{i?t(i):(this.isLoaded=!0,t())})}}getScriptId(r){var e;let{id:t}=(e=this.scripts.get(r))!=null?e:{};return t||new u(`ID of script [${r}] is missing`)}static getInstance(){return S.instance||(S.instance=new S),S.instance}};S.instance=null;var O=S;import{EventEmitter as mt}from"events";var x=class extends mt{};var B=null;function k(){return B||(B=new x),B}var bt=[4,0,0],p=class p extends ht{constructor(){super(...arguments);this.connectionClosed=!0}validateRedisVersion(t,e=0,i=0){return p.redisServerVersion?p.redisServerVersion[0]>t||p.redisServerVersion[0]===t&&p.redisServerVersion[1]>=e&&p.redisServerVersion[2]>=i:(k().emit("error",new u("UNKNOWN_REDIS_SERVER_VERSION")),!1)}validateRedisServerSupport(t){let e=i=>{let[n,s,l]=bt;this.validateRedisVersion(n,s,l)?i():i(new u("UNSUPPORTED_REDIS_SERVER_VERSION"))};p.redisServerVersion?e(t):this.updateServerVersion(i=>{i?t(i):e(t)})}sscanAll(t,e,i){let n=new Set,s=l=>{this.sscan(t,l,e,(a,c)=>{a?i(a):c?(c.items.forEach(g=>n.add(g)),c.cursor==="0"?i(null,[...n]):s(c.cursor)):i(new h)})};s("0")}hscanAll(t,e,i){let n={},s=l=>{this.hscan(t,l,e,(a,c)=>{a?i(a):c?(Object.assign(n,c.result),c.cursor==="0"?i(null,n):s(c.cursor)):i(new h)})};s("0")}zpoprpush(t,e,i){this.runScript("ZPOPRPUSH",[t,e],[],(n,s)=>{n?i(n):i(null,typeof s=="string"?s:null)})}lpoprpush(t,e,i){this.validateRedisVersion(6,2)?this.lmove(t,e,"LEFT","RIGHT",i):this.runScript("LPOPRPUSH",[t,e],[],(n,s)=>{n?i(n):i(null,typeof s=="string"?s:null)})}updateServerVersion(t){p.redisServerVersion?t():this.getInfo((e,i)=>{e?t(e):i?(p.redisServerVersion=i.split(`\r
2
- `)[1].split(":")[1].split(".").map(n=>Number(n)),t()):t(new h)})}loadScripts(t){O.getInstance().loadScripts(this,t)}runScript(t,e,i,n){let s=O.getInstance().getScriptId(t);s instanceof Error?n(s):this.evalsha(s,[e.length,...e,...i],(l,a)=>{l?n(l):n(null,a)})}static addScript(t,e){if(!O.getInstance().addScript(t,e))throw new u(`A script with name [${t}] already exists`)}};p.redisServerVersion=null;var v=p;v.addScript("RELEASE_LOCK",nt.readFileSync(st(__dirname,"./lua/release-lock.lua")).toString());v.addScript("EXTEND_LOCK",nt.readFileSync(st(__dirname,"./lua/extend-lock.lua")).toString());var F=class{constructor(r,t,e,i=!1,n=!1){this.status=0;this.lockingTimer=null;this.autoExtendTimer=null;this.lockKey=t,this.ttl=e,this.retryOnFail=i,this.lockId=pt(),this.redisClient=r,this.autoExtend=n}resetTimers(){this.lockingTimer&&(clearTimeout(this.lockingTimer),this.lockingTimer=null),this.autoExtendTimer&&(clearTimeout(this.autoExtendTimer),this.autoExtendTimer=null)}setUnlocked(){this.status=0}setLocked(){this.status=2}setExtended(){this.status=5}extend(r){this.isLocked()?(this.status=4,this.redisClient.runScript("EXTEND_LOCK",[this.lockKey],[this.lockId,this.ttl],(t,e)=>{t?r(t):this.status===4?e?(this.setExtended(),r()):(this.setUnlocked(),r(new A)):r(new I)})):r(new P)}runAutoExtendTimer(){let r=Math.ceil(this.ttl/2);this.autoExtendTimer=setTimeout(()=>this.extend(t=>{t?t instanceof I||k().emit("error",t):this.runAutoExtendTimer()}),r)}acquireLock(r){if(!this.isReleased())r(new H);else{this.status=1;let t=()=>{this.status===1?this.redisClient.set(this.lockKey,this.lockId,{expire:{mode:"PX",value:this.ttl},exists:"NX"},(e,i)=>{e?r(e):this.status===1?i?(this.setLocked(),this.autoExtend&&this.runAutoExtendTimer(),r()):this.retryOnFail?this.lockingTimer=setTimeout(t,1e3):(this.setUnlocked(),r(new E)):r(new I)}):r(new I)};t()}}extendLock(r){this.autoExtend?r(new N):this.extend(r)}releaseLock(r){this.status===0?r():this.isLocked()?(this.resetTimers(),this.status=3,this.redisClient.runScript("RELEASE_LOCK",[this.lockKey],[this.lockId],e=>{e?r(e):(this.setUnlocked(),r())})):r(new P)}acquireOrExtend(r){if(this.autoExtend)r(new N);else{let t=()=>{this.acquireLock(e=>{e?r(e):r(null,2)})};this.isLocked()?this.extend(e=>{e?e instanceof A?t():r(e):r(null,5)}):t()}}isLocked(){return this.status===2||this.status===5}isReleased(){return this.status===0}getId(){return this.lockId}};var C=class{constructor(){this.isPowered=!1;this.pendingState=null}switch(r){return this.pendingState!==null||r===this.isPowered?!1:(this.pendingState=r,!0)}isUp(){return this.isPowered}isDown(){return!this.isPowered}isGoingUp(){return this.pendingState===!0}isGoingDown(){return this.pendingState===!1}isRunning(){return this.isUp()&&this.pendingState===null}goingUp(){return this.switch(!0)}goingDown(){return this.switch(!1)}commit(){return this.pendingState===null?!1:(this.isPowered=this.pendingState,this.pendingState=null,!0)}rollback(){return this.pendingState===null?!1:(this.pendingState=null,!0)}};var L=class extends x{constructor(t=()=>{},e=1e3){super();this.powerManager=new C;this.onNextTickFn=null;this.timeout=null;this.interval=null;this.shutdownTimeout=null;this.aborted=!1;this.onTickFn=t,this.time=e,this.powerManager.goingUp()}shutdown(){this.shutdownTimeout&&clearTimeout(this.shutdownTimeout),this.powerManager.commit(),this.emit("down")}onTick(){var t;if(this.powerManager.isGoingDown())this.shutdown();else if(this.powerManager.isRunning()){let e=(t=this.onNextTickFn)!=null?t:this.onTickFn;this.onNextTickFn=null,e()}else k().emit("error",new w("Unexpected call"))}abort(){this.aborted||(this.aborted=!0,this.powerManager.isGoingDown()?this.shutdown():this.quit())}quit(){this.powerManager.isGoingUp()?(this.powerManager.rollback(),this.emit("down")):this.aborted&&this.powerManager.isDown()?this.emit("down"):(this.powerManager.goingDown(),this.timeout?(clearTimeout(this.timeout),this.shutdown()):this.interval?(clearInterval(this.interval),this.shutdown()):this.aborted?this.shutdown():this.shutdownTimeout=setTimeout(()=>{this.powerManager.isGoingDown()&&this.shutdown()},6e4))}isTicking(){return!!(this.timeout||this.interval)}nextTick(){this.isTicking()?k().emit("error",new M("A timer is already running")):this.powerManager.isGoingDown()?this.shutdown():(this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.timeout=setTimeout(()=>{this.timeout=null,this.onTick()},this.time)))}nextTickFn(t){this.onNextTickFn=t,this.nextTick()}runTimer(){this.isTicking()?k().emit("error",new M("A timer is already running")):(this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.interval=setInterval(()=>this.onTick(),this.time)))}};var _=class{constructor(r,t=1e3){this.ticker=null;this.powerManager=null;this.getTicker=()=>{if(!this.ticker)throw new R("Expected an instance of Ticker");return this.ticker};this.onTick=()=>{this.work(r=>{r?k().emit("error",r):this.getTicker().nextTick()})};this.run=r=>{if(this.managed)r(new R("You can not run a managed worker"));else{let t=this.getPowerManager();t.goingUp(),this.getTicker().nextTick(),t.commit(),r()}};this.quit=r=>{if(this.managed)r();else{let t=this.getPowerManager();t.goingDown();let e=this.getTicker();e.on("down",()=>{t.commit(),r()}),e.quit()}};this.managed=r,r||(this.ticker=new L(this.onTick,t),this.powerManager=new C)}getPowerManager(){if(!this.powerManager)throw new R("Expected an instance of PowerSwitch");return this.powerManager}};var Q=class extends x{constructor(t,e,i,n){super();this.onTick=()=>{b.waterfall([t=>{this.lock.acquireOrExtend((e,i)=>{i===2&&this.logger.info(`Workers are exclusively running from this instance (Lock ID ${this.lock.getId()}).`),t(e)})},t=>{this.workerPool.work(t)}],t=>{!t||t instanceof E?this.ticker.nextTick():this.emit("error",t)})};this.clearWorkerPool=t=>{this.workerPool.clear(t)};this.stopTicker=t=>{this.ticker.once("down",t),this.ticker.quit()};this.releaseLock=t=>{this.lock.releaseLock(t)};this.run=t=>{this.ticker.nextTick(),this.emit("up"),t()};this.quit=t=>{b.waterfall([this.stopTicker,this.clearWorkerPool,this.releaseLock],()=>{this.emit("down"),t()})};this.powerManager=new C,this.redisClient=t,this.logger=n,this.lock=new F(t,e,6e4),this.ticker=new L(this.onTick),this.workerPool=i}addWorker(t){this.workerPool.add(t)}};var $=class{constructor(){this.pool=[];this.work=r=>{if(this.pool.length){let t=this.pool.map(e=>i=>e.work(i));b.waterfall(t,r)}else r()};this.add=r=>(this.pool.push(r),this.pool.length);this.clear=r=>{b.each(this.pool,(t,e,i)=>{t.quit(i)},()=>{this.pool=[],r()})}}};import{createLogger as kt}from"bunyan";var D=()=>{},vt={debug:D,warn:D,info:D,error:D},f=null;function ft(){f=null}function Ct(o){if(f)throw new U("Logger has been already initialized.");f=o}function It(o,r){var t;if(!o.enabled)return vt;if(f||(f=kt(j(z({},(t=o.options)!=null?t:{}),{name:"redis-smq"}))),r){let e=(i,n)=>(s,...l)=>{let a=typeof s=="string"?`${r} | ${s}`:s;return n[i](a,...l)};return{info:e("info",f),warn:e("warn",f),debug:e("debug",f),error:e("error",f)}}return f}var xt={getLogger:It,setLogger:Ct,destroy:ft};import{createClient as wt}from"@redis/client";import{WatchError as Tt}from"@redis/client";var q=class{constructor(r){this.multi=r.multi()}lrem(r,t,e){return this.multi.lRem(r,t,e),this}lpop(r){return this.multi.lPop(r),this}lpush(r,t){return this.multi.lPush(r,t),this}ltrim(r,t,e){return this.multi.lTrim(r,t,e),this}rpop(r){return this.multi.rPop(r),this}rpush(r,t){return this.multi.rPush(r,t),this}zadd(r,t,e){return this.multi.zAdd(r,{score:t,value:e}),this}zrem(r,t){return this.multi.zRem(r,t),this}sadd(r,t){return this.multi.sAdd(r,t),this}srem(r,t){return this.multi.sRem(r,t),this}hset(r,t,e){return this.multi.hSet(r,t,e),this}hdel(r,t){return this.multi.hDel(r,t),this}hincrby(r,t,e){return this.multi.hIncrBy(r,t,e),this}pexpire(r,t){return this.multi.pExpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rPopLPush(r,t),this}del(r){return this.multi.del(r),this}exec(r){this.multi.exec().then(t=>r(null,t)).catch(t=>{t instanceof Tt?r(new y):r(t)})}};var X=class extends v{constructor(t={}){super();this.client=wt(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")}),this.client.connect()}set(t,e,i,n){this.client.set(t,e,z(z({},i.expire?{[i.expire.mode]:i.expire.value}:{}),i.exists?{[i.exists]:!0}:{})).then(s=>n(null,s)).catch(n)}zadd(t,e,i,n){this.client.zAdd(t,{score:e,value:i}).then(s=>n(null,s)).catch(n)}multi(){return new q(this.client)}watch(t,e){this.client.watch(t).then(i=>e(null,i)).catch(e)}unwatch(t){this.client.unwatch().then(e=>t(null,e)).catch(t)}sismember(t,e,i){this.client.sIsMember(t,e).then(n=>i(null,Number(n))).catch(i)}zcard(t,e){this.client.zCard(t).then(i=>e(null,i)).catch(e)}zrange(t,e,i,n){this.client.zRange(t,e,i).then(s=>n(null,(Array.isArray(s)?s:[]).map(l=>String(l)))).catch(n)}zrevrange(t,e,i,n){this.client.sendCommand(["ZREVRANGE",t,String(e),String(i)]).then(s=>n(null,(Array.isArray(s)?s:[]).map(l=>String(l)))).catch(n)}zrem(t,e,i){this.client.zRem(t,e).then(n=>i(null,n)).catch(i)}psubscribe(t){this.client.pSubscribe(t,(e,i)=>{this.client.emit("pmessage",t,i,e)})}punsubscribe(t){this.client.pUnsubscribe(t).catch(()=>{})}subscribe(t){this.client.subscribe(t,(e,i)=>{this.client.emit("message",i,e)})}unsubscribe(t){this.client.unsubscribe(t).catch(()=>{})}zrangebyscore(t,e,i,n,s,l){this.client.zRangeByScore(t,e,i,{LIMIT:{offset:n,count:s}}).then(a=>l(null,a)).catch(l)}smembers(t,e){this.client.sMembers(t).then(i=>e(null,i)).catch(e)}sscan(t,e,i,n){let s=[t,Number(e),i];this.client.sScan(...s).then(({cursor:l,members:a})=>{n(null,{cursor:String(l),items:a})}).catch(n)}zscan(t,e,i,n){let s=[t,Number(e),i];this.client.zScan(...s).then(({cursor:l,members:a})=>{let c=new Set;for(let g of a)c.add(g.value);n(null,{cursor:String(l),items:[...c]})}).catch(n)}sadd(t,e,i){this.client.sAdd(t,e).then(n=>i(null,n)).catch(i)}srem(t,e,i){this.client.sRem(t,e).then(n=>i(null,n)).catch(i)}hgetall(t,e){this.client.hGetAll(t).then(i=>e(null,i)).catch(e)}hscan(t,e,i,n){let s=[t,Number(e),i];this.client.hScan(...s).then(({cursor:l,tuples:a})=>{let c={};for(;a.length;){let g=a.shift();g&&(c[g.field]=g.value)}n(null,{cursor:String(l),result:c})}).catch(n)}hget(t,e,i){this.client.hGet(t,e).then(n=>i(null,n!=null?n:null)).catch(i)}hset(t,e,i,n){this.client.hSet(t,e,i).then(s=>n(null,s)).catch(n)}hdel(t,e,i){this.client.hDel(t,e).then(n=>i(null,Number(n))).catch(i)}lrange(t,e,i,n){this.client.lRange(t,e,i).then(s=>n(null,s)).catch(n)}hkeys(t,e){this.client.hKeys(t).then(i=>e(null,i)).catch(e)}hlen(t,e){this.client.hLen(t).then(i=>e(null,i)).catch(e)}brpoplpush(t,e,i,n){this.client.brPopLPush(t,e,i).then(s=>n(null,s)).catch(n)}rpoplpush(t,e,i){this.client.rPopLPush(t,e).then(n=>i(null,n)).catch(i)}zrangebyscorewithscores(t,e,i,n){this.client.zRangeByScoreWithScores(t,e,i).then(s=>{let l={};for(let{score:a,value:c}of s)l[a]=c;n(null,l)}).catch(n)}rpop(t,e){this.client.rPop(t).then(i=>e(null,i)).catch(e)}lrem(t,e,i,n){this.client.lRem(t,e,i).then(s=>n(null,s)).catch(n)}publish(t,e,i){this.client.publish(t,e).then(n=>i(null,n)).catch(i)}flushall(t){this.client.flushAll().then(e=>t(null,e)).catch(t)}loadScript(t,e){this.client.sendCommand(["SCRIPT","LOAD",t]).then(i=>e(null,typeof i=="string"?i:String(i))).catch(e)}evalsha(t,e,i){let n=[t],s=Array.isArray(e)?e:[e];this.client.sendCommand(["evalsha",...n.concat(s).map(l=>String(l))]).then(l=>{Array.isArray(l)?i(null,l.map(a=>a instanceof Buffer?a.toString():a)):l instanceof Buffer?i(null,l.toString()):i(null,l)}).catch(i)}get(t,e){this.client.sendCommand(["get",t]).then(i=>e(null,typeof i=="string"?i:null)).catch(e)}del(t,e){this.client.del(t).then(i=>e(null,i)).catch(e)}llen(t,e){this.client.sendCommand(["llen",t]).then(i=>e(null,Number(i))).catch(e)}lmove(t,e,i,n,s){this.validateRedisVersion(6,2)?this.client.lMove(t,e,i,n).then(l=>s(null,l)).catch(s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,e,i,n){this.client.sendCommand(["zremrangebyscore",t,`${e}`,`${i}`]).then(s=>n(null,Number(s))).catch(n)}hmget(t,e,i){this.client.hmGet(t,e).then(n=>i(null,n)).catch(i)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect().catch(()=>{})}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info().then(e=>t(null,e)).catch(t)}on(t,e){return this.client.on(t,e),this}};import Et from"ioredis";var G=class{constructor(r){this.multi=r.multi()}lrem(r,t,e){return this.multi.lrem(r,t,e),this}lpop(r){return this.multi.lpop(r),this}lpush(r,t){return this.multi.lpush(r,t),this}ltrim(r,t,e){return this.multi.ltrim(r,t,e),this}rpop(r){return this.multi.rpop(r),this}rpush(r,t){return this.multi.rpush(r,t),this}zadd(r,t,e){return this.multi.zadd(r,t,e),this}zrem(r,t){return this.multi.zrem(r,...typeof t=="string"?[t]:t),this}sadd(r,t){return this.multi.sadd(r,t),this}srem(r,t){return this.multi.srem(r,...typeof t=="string"?[t]:t),this}hset(r,t,e){return this.multi.hset(r,t,e),this}hdel(r,t){return this.multi.hdel(r,...typeof t=="string"?[t]:t),this}hincrby(r,t,e){return this.multi.hincrby(r,t,e),this}pexpire(r,t){return this.multi.pexpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rpoplpush(r,t),this}del(r){return this.multi.del(...typeof r=="string"?[r]:r),this}exec(r){this.multi.exec((t,e)=>{if(t)r(t);else if(!e)r(new y);else{let i=[],n=null;for(let s of e){if(!Array.isArray(s)){n=new u("Expected an array reply from multi.exec()");break}let[l,a]=s;if(l instanceof Error){n=l;break}i.push(a)}n?r(n):r(null,i)}})}};var V=class extends v{constructor(t={}){super();this.client=new Et(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")})}set(t,e,i,n){i.exists&&i.expire?this.client.set(t,e,i.expire.mode,i.expire.value,i.exists,n):i.expire?this.client.set(t,e,i.expire.mode,i.expire.value,n):i.exists?this.client.set(t,e,i.exists,n):this.client.set(t,e,n)}zadd(t,e,i,n){this.client.zadd(t,e,i,n)}multi(){return new G(this.client)}watch(t,e){this.client.watch(t,e)}unwatch(t){this.client.unwatch(t)}sismember(t,e,i){this.client.sismember(t,e,i)}sscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.sscan(...s,(l,[a,c])=>{l?n(l):n(null,{cursor:a,items:c})})}zcard(t,e){this.client.zcard(t,e)}zrange(t,e,i,n){this.client.zrange(t,e,i,n)}zscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.zscan(...s,(l,a)=>{if(l)n(l);else if(!a)n(new h);else{let c=new Set,[g,T]=a;for(;T.length;){let W=String(T.shift()),Lt=String(T.shift());c.add(W)}n(null,{cursor:g,items:[...c]})}})}zrevrange(t,e,i,n){this.client.zrevrange(t,e,i,n)}zrem(t,e,i){this.client.zrem(t,e,i)}psubscribe(t){this.client.psubscribe(t)}punsubscribe(t){this.client.punsubscribe(t)}subscribe(t){this.client.subscribe(t)}unsubscribe(t){this.client.unsubscribe(t)}zrangebyscore(t,e,i,n,s,l){this.client.zrangebyscore(t,e,i,"LIMIT",n,s,l)}smembers(t,e){this.client.smembers(t,e)}sadd(t,e,i){this.client.sadd(t,e,i)}srem(t,e,i){this.client.srem(t,e,i)}hgetall(t,e){this.client.hgetall(t,e)}hscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.hscan(...s,(l,[a,c])=>{if(l)n(l);else{let g={};for(;c.length;){let T=String(c.shift());g[T]=String(c.shift())}n(null,{cursor:a,result:g})}})}hget(t,e,i){this.client.hget(t,e,i)}hset(t,e,i,n){this.client.hset(t,e,i,n)}hdel(t,e,i){this.client.hdel(t,e,i)}lrange(t,e,i,n){this.client.lrange(t,e,i,n)}hkeys(t,e){this.client.hkeys(t,e)}hlen(t,e){this.client.hlen(t,e)}brpoplpush(t,e,i,n){this.client.brpoplpush(t,e,i,n)}rpoplpush(t,e,i){this.client.rpoplpush(t,e,i)}zrangebyscorewithscores(t,e,i,n){this.client.zrangebyscore(t,e,i,"WITHSCORES",(s,l)=>{if(s)n(s);else{let a=l!=null?l:[],c={};for(let g=a.splice(0,2);g.length>0;g=a.splice(0,2)){let[T,W]=g;c[W]=T}n(null,c)}})}rpop(t,e){this.client.rpop(t,e)}lrem(t,e,i,n){this.client.lrem(t,e,i,n)}publish(t,e,i){this.client.publish(t,e,i)}flushall(t){this.client.flushall(t)}loadScript(t,e){this.client.script("load",t,e)}evalsha(t,e,i){let n=[t],s=Array.isArray(e)?e:[e];this.client.evalsha(n.concat(s),i)}get(t,e){this.client.get(t,e)}del(t,e){this.client.del(t,e)}llen(t,e){this.client.llen(t,e)}lmove(t,e,i,n,s){this.validateRedisVersion(6,2)?this.client.lmove(t,e,i,n,s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,e,i,n){this.client.zremrangebyscore(t,e,i,n)}hmget(t,e,i){this.client.hmget(t,e,i)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect(!1)}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info(t)}on(t,e){return this.client.on(t,e),this}};function yt(o){return o.client==="redis"?new X(o.options):new V(o.options)}function Rt(o,r){let t=yt(o);t.once("ready",()=>{b.waterfall([e=>t.validateRedisServerSupport(e),e=>t.loadScripts(e)],e=>{e?r(e):r(null,t)})})}var St={createInstance:Rt};export{h as CallbackEmptyReplyError,K as CallbackInvalidReplyError,Y as ERedisConfigClient,x as EventEmitter,F as Lock,I as LockAbortError,E as LockAcquireError,m as LockError,A as LockExtendError,N as LockMethodNotAllowedError,P as LockNotAcquiredError,H as LockNotReleasedError,U as LoggerError,w as PanicError,C as PowerSwitch,v as RedisClient,u as RedisClientError,d as RedisSMQError,L as Ticker,M as TickerError,y as WatchedKeysChangedError,_ as Worker,R as WorkerError,$ as WorkerPool,Q as WorkerRunner,b as async,k as getEventBusInstance,xt as logger,St as redis};
1
+ var st=Object.defineProperty,ot=Object.defineProperties;var lt=Object.getOwnPropertyDescriptors;var $=Object.getOwnPropertySymbols;var at=Object.prototype.hasOwnProperty,ct=Object.prototype.propertyIsEnumerable;var J=(o,r,t)=>r in o?st(o,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[r]=t,O=(o,r)=>{for(var t in r||(r={}))at.call(r,t)&&J(o,t,r[t]);if($)for(var t of $(r))ct.call(r,t)&&J(o,t,r[t]);return o},Z=(o,r)=>ot(o,lt(r));var j=(t=>(t.IOREDIS="ioredis",t.REDIS="redis",t))(j||{});var d=class extends Error{constructor(r){super(r)}get name(){return this.constructor.name}};var b=class extends d{constructor(){super("Expected a non-empty reply")}};var W=class extends d{constructor(){super("Invalid reply type")}};var T=class extends d{};var z=class extends d{};var L=class extends d{};var m=class extends d{};var I=class extends m{constructor(r="releaseLock() may have been called. Abandoning."){super(r)}};var w=class extends m{constructor(r="Could not acquire a lock"){super(r)}};var M=class extends m{constructor(r="Acquired lock could not be extended"){super(r)}};var A=class extends m{constructor(r="This method can not be used when autoExtend is enabled"){super(r)}};var N=class extends m{constructor(r="Can not extend a lock which has not been yet acquired. Maybe a pending operation is in progress."){super(r)}};var U=class extends m{constructor(r="A lock has been already obtained but not yet released or maybe a pending operation is in progress."){super(r)}};var u=class extends d{};var E=class extends u{constructor(r="One (or more) of the watched keys has been changed"){super(r)}};var y=class extends T{};import{v4 as ht}from"uuid";import rt from"fs";import{resolve as nt}from"path";var Y=(o,r,t)=>{if(o.length){let e=0,i=()=>{r(o[e],e,n=>{e+=1,n||e>=o.length?t(n):setTimeout(()=>i(),0)})};i()}else t()},tt=(o,r,t)=>{let e=Object.keys(o);if(e.length){let i=0,n=()=>{let s=e[i];r(o[s],s,l=>{i+=1,l||i>=e.length?t(l):setTimeout(()=>n(),0)})};n()}else t()},dt=(o,r,t)=>{Array.isArray(o)?Y(o,r,t):tt(o,r,t)},ut=(o,r)=>{if(o.length){let t=0,e=(i,...n)=>{t+=1,i?r(i):t<o.length?setTimeout(()=>{n.length?o[t](...n,e):o[t](e)},0):n.length?r(null,n[0]):r()};o[t](e)}else r()},p={each:dt,eachIn:tt,eachOf:Y,waterfall:ut};import et from"fs";import{resolve as it}from"path";var R=class R{constructor(){this.isLoaded=!1;this.scripts=new Map,this.addScript("ZPOPRPUSH",et.readFileSync(it(__dirname,"./lua/zpoprpush.lua")).toString()),this.addScript("LPOPRPUSH",et.readFileSync(it(__dirname,"./lua/lpoprpush.lua")).toString())}hasScript(r){return this.scripts.has(r)}addScript(r,t){return this.hasScript(r)?!1:(this.scripts.set(r,{content:t}),this.isLoaded=!1,!0)}loadScripts(r,t){if(this.isLoaded)t();else{let e=[];this.scripts.forEach(i=>e.push(n=>{i.id?n():r.loadScript(i.content,(s,l)=>{s?n(s):l?(i.id=l,n()):n(new b)})})),p.waterfall(e,i=>{i?t(i):(this.isLoaded=!0,t())})}}getScriptId(r){var e;let{id:t}=(e=this.scripts.get(r))!=null?e:{};return t||new u(`ID of script [${r}] is missing`)}static getInstance(){return R.instance||(R.instance=new R),R.instance}};R.instance=null;var P=R;import{EventEmitter as gt}from"events";var h=class extends gt{};var K=null;function Qe(){return K||(K=new h),K}var mt=[4,0,0],k=class k extends h{constructor(){super(...arguments);this.connectionClosed=!0}validateRedisVersion(t,e=0,i=0){return k.redisServerVersion?k.redisServerVersion[0]>t||k.redisServerVersion[0]===t&&k.redisServerVersion[1]>=e&&k.redisServerVersion[2]>=i:(this.emit("error",new u("UNKNOWN_REDIS_SERVER_VERSION")),!1)}validateRedisServerSupport(t){let e=i=>{let[n,s,l]=mt;this.validateRedisVersion(n,s,l)?i():i(new u("UNSUPPORTED_REDIS_SERVER_VERSION"))};k.redisServerVersion?e(t):this.updateServerVersion(i=>{i?t(i):e(t)})}sscanAll(t,e,i){let n=new Set,s=l=>{this.sscan(t,l,e,(a,c)=>{a?i(a):c?(c.items.forEach(g=>n.add(g)),c.cursor==="0"?i(null,[...n]):s(c.cursor)):i(new b)})};s("0")}hscanAll(t,e,i){let n={},s=l=>{this.hscan(t,l,e,(a,c)=>{a?i(a):c?(Object.assign(n,c.result),c.cursor==="0"?i(null,n):s(c.cursor)):i(new b)})};s("0")}zpoprpush(t,e,i){this.runScript("ZPOPRPUSH",[t,e],[],(n,s)=>{n?i(n):i(null,typeof s=="string"?s:null)})}lpoprpush(t,e,i){this.validateRedisVersion(6,2)?this.lmove(t,e,"LEFT","RIGHT",i):this.runScript("LPOPRPUSH",[t,e],[],(n,s)=>{n?i(n):i(null,typeof s=="string"?s:null)})}updateServerVersion(t){k.redisServerVersion?t():this.getInfo((e,i)=>{e?t(e):i?(k.redisServerVersion=i.split(`\r
2
+ `)[1].split(":")[1].split(".").map(n=>Number(n)),t()):t(new b)})}loadScripts(t){P.getInstance().loadScripts(this,t)}runScript(t,e,i,n){let s=P.getInstance().getScriptId(t);s instanceof Error?n(s):this.evalsha(s,[e.length,...e,...i],(l,a)=>{l?n(l):n(null,a)})}static addScript(t,e){if(!P.getInstance().addScript(t,e))throw new u(`A script with name [${t}] already exists`)}};k.redisServerVersion=null;var v=k;v.addScript("RELEASE_LOCK",rt.readFileSync(nt(__dirname,"./lua/release-lock.lua")).toString());v.addScript("EXTEND_LOCK",rt.readFileSync(nt(__dirname,"./lua/extend-lock.lua")).toString());var H=class extends h{constructor(t,e,i,n=!1,s=!1){super();this.status=0;this.lockingTimer=null;this.autoExtendTimer=null;this.lockKey=e,this.ttl=i,this.retryOnFail=n,this.lockId=ht(),this.redisClient=t,this.autoExtend=s}resetTimers(){this.lockingTimer&&(clearTimeout(this.lockingTimer),this.lockingTimer=null),this.autoExtendTimer&&(clearTimeout(this.autoExtendTimer),this.autoExtendTimer=null)}setUnlocked(){this.status=0}setLocked(){this.status=2}setExtended(){this.status=5}extend(t){this.isLocked()?(this.status=4,this.redisClient.runScript("EXTEND_LOCK",[this.lockKey],[this.lockId,this.ttl],(e,i)=>{e?t(e):this.status===4?i!==1?(this.setUnlocked(),t(new M)):(this.setExtended(),t()):t(new I)})):t(new N)}runAutoExtendTimer(){let t=Math.ceil(this.ttl/2);this.autoExtendTimer=setTimeout(()=>this.extend(e=>{e?e instanceof I||this.emit("error",e):this.runAutoExtendTimer()}),t)}acquireLock(t){if(!this.isReleased())t(new U);else{this.status=1;let e=()=>{this.status===1?this.redisClient.set(this.lockKey,this.lockId,{expire:{mode:"PX",value:this.ttl},exists:"NX"},(i,n)=>{i?t(i):this.status===1?n?(this.setLocked(),this.autoExtend&&this.runAutoExtendTimer(),t()):this.retryOnFail?this.lockingTimer=setTimeout(e,1e3):(this.setUnlocked(),t(new w)):t(new I)}):t(new I)};e()}}extendLock(t){this.autoExtend?t(new A):this.extend(t)}releaseLock(t){this.status===0?t():this.isLocked()?(this.resetTimers(),this.status=3,this.redisClient.runScript("RELEASE_LOCK",[this.lockKey],[this.lockId],i=>{i?t(i):(this.setUnlocked(),t())})):t(new N)}acquireOrExtend(t){if(this.autoExtend)t(new A);else{let e=()=>{this.acquireLock(i=>{i?t(i):t(null,2)})};this.isLocked()?this.extend(i=>{i?i instanceof M?e():t(i):t(null,5)}):e()}}isLocked(){return this.status===2||this.status===5}isReleased(){return this.status===0}getId(){return this.lockId}};var C=class{constructor(){this.isPowered=!1;this.pendingState=null}switch(r){return this.pendingState!==null||r===this.isPowered?!1:(this.pendingState=r,!0)}isUp(){return this.isPowered}isDown(){return!this.isPowered}isGoingUp(){return this.pendingState===!0}isGoingDown(){return this.pendingState===!1}isRunning(){return this.isUp()&&this.pendingState===null}goingUp(){return this.switch(!0)}goingDown(){return this.switch(!1)}commit(){return this.pendingState===null?!1:(this.isPowered=this.pendingState,this.pendingState=null,!0)}rollback(){return this.pendingState===null?!1:(this.pendingState=null,!0)}};var S=class extends h{constructor(t=()=>{},e=1e3){super();this.powerManager=new C;this.onNextTickFn=null;this.timeout=null;this.interval=null;this.shutdownTimeout=null;this.aborted=!1;this.onTickFn=t,this.time=e,this.powerManager.goingUp()}shutdown(){this.shutdownTimeout&&clearTimeout(this.shutdownTimeout),this.powerManager.commit(),this.emit("down")}onTick(){var t;if(this.powerManager.isGoingDown())this.shutdown();else if(this.powerManager.isRunning()){let e=(t=this.onNextTickFn)!=null?t:this.onTickFn;this.onNextTickFn=null,e()}else this.emit("error",new T("Unexpected call"))}abort(){this.aborted||(this.aborted=!0,this.powerManager.isGoingDown()?this.shutdown():this.quit())}quit(){this.powerManager.isGoingUp()?(this.powerManager.rollback(),this.emit("down")):this.aborted&&this.powerManager.isDown()?this.emit("down"):(this.powerManager.goingDown(),this.timeout?(clearTimeout(this.timeout),this.shutdown()):this.interval?(clearInterval(this.interval),this.shutdown()):this.aborted?this.shutdown():this.shutdownTimeout=setTimeout(()=>{this.powerManager.isGoingDown()&&this.shutdown()},6e4))}isTicking(){return!!(this.timeout||this.interval)}nextTick(){this.isTicking()?this.emit("error",new L("A timer is already running")):this.powerManager.isGoingDown()?this.shutdown():(this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.timeout=setTimeout(()=>{this.timeout=null,this.onTick()},this.time)))}nextTickFn(t){this.onNextTickFn=t,this.nextTick()}runTimer(){this.isTicking()?this.emit("error",new L("A timer is already running")):(this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.interval=setInterval(()=>this.onTick(),this.time)))}};var _=class extends h{constructor(t,e=1e3){super();this.ticker=null;this.powerManager=null;this.getTicker=()=>{if(!this.ticker)throw new y("Expected an instance of Ticker");return this.ticker};this.onTick=()=>{this.work(t=>{t?this.emit("error",t):this.getTicker().nextTick()})};this.run=t=>{if(this.managed)t(new y("You can not run a managed worker"));else{let e=this.getPowerManager();e.goingUp(),this.getTicker().nextTick(),e.commit(),t()}};this.quit=t=>{if(this.managed)t();else{let e=this.getPowerManager();e.goingDown();let i=this.getTicker();i.on("down",()=>{e.commit(),t()}),i.quit()}};this.managed=t,t||(this.ticker=new S(this.onTick,e),this.powerManager=new C)}getPowerManager(){if(!this.powerManager)throw new y("Expected an instance of PowerSwitch");return this.powerManager}};var B=class extends h{constructor(t,e,i,n){super();this.onTick=()=>{p.waterfall([t=>{this.lock.acquireOrExtend((e,i)=>{i===2&&this.logger.info(`Workers are exclusively running from this instance (Lock ID ${this.lock.getId()}).`),t(e)})},t=>{this.workerPool.work(t)}],t=>{!t||t instanceof w?this.ticker.nextTick():this.emit("error",t)})};this.clearWorkerPool=t=>{this.workerPool.clear(t)};this.stopTicker=t=>{this.ticker.once("down",t),this.ticker.quit()};this.releaseLock=t=>{this.lock.releaseLock(t)};this.run=t=>{this.ticker.nextTick(),this.emit("up"),t()};this.quit=t=>{p.waterfall([this.stopTicker,this.clearWorkerPool,this.releaseLock],()=>{this.emit("down"),t()})};this.powerManager=new C,this.redisClient=t,this.logger=n,this.lock=new H(t,e,6e4),this.ticker=new S(this.onTick),this.workerPool=i}addWorker(t){this.workerPool.add(t)}};var Q=class{constructor(){this.pool=[];this.work=r=>{if(this.pool.length){let t=this.pool.map(e=>i=>e.work(i));p.waterfall(t,r)}else r()};this.add=r=>(this.pool.push(r),this.pool.length);this.clear=r=>{p.each(this.pool,(t,e,i)=>{t.quit(i)},()=>{this.pool=[],r()})}}};import{createLogger as bt}from"bunyan";var F=()=>{},pt={debug:F,warn:F,info:F,error:F},f=null;function kt(){f=null}function vt(o){if(f)throw new z("Logger has been already initialized.");f=o}function ft(o,r){var t;if(!o.enabled)return pt;if(f||(f=bt(Z(O({},(t=o.options)!=null?t:{}),{name:"redis-smq"}))),r){let e=(i,n)=>(s,...l)=>{let a=typeof s=="string"?`${r} | ${s}`:s;return n[i](a,...l)};return{info:e("info",f),warn:e("warn",f),debug:e("debug",f),error:e("error",f)}}return f}var Ct={getLogger:ft,setLogger:vt,destroy:kt};import{createClient as xt}from"@redis/client";import{WatchError as It}from"@redis/client";var D=class{constructor(r){this.multi=r.multi()}lrem(r,t,e){return this.multi.lRem(r,t,e),this}lpop(r){return this.multi.lPop(r),this}lpush(r,t){return this.multi.lPush(r,t),this}ltrim(r,t,e){return this.multi.lTrim(r,t,e),this}rpop(r){return this.multi.rPop(r),this}rpush(r,t){return this.multi.rPush(r,t),this}zadd(r,t,e){return this.multi.zAdd(r,{score:t,value:e}),this}zrem(r,t){return this.multi.zRem(r,t),this}sadd(r,t){return this.multi.sAdd(r,t),this}srem(r,t){return this.multi.sRem(r,t),this}hset(r,t,e){return this.multi.hSet(r,t,e),this}hdel(r,t){return this.multi.hDel(r,t),this}hincrby(r,t,e){return this.multi.hIncrBy(r,t,e),this}pexpire(r,t){return this.multi.pExpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rPopLPush(r,t),this}del(r){return this.multi.del(r),this}exec(r){this.multi.exec().then(t=>r(null,t)).catch(t=>{t instanceof It?r(new E):r(t)})}};var q=class extends v{constructor(t={}){super();this.client=xt(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")}),this.client.connect()}set(t,e,i,n){this.client.set(t,e,O(O({},i.expire?{[i.expire.mode]:i.expire.value}:{}),i.exists?{[i.exists]:!0}:{})).then(s=>n(null,s)).catch(n)}zadd(t,e,i,n){this.client.zAdd(t,{score:e,value:i}).then(s=>n(null,s)).catch(n)}multi(){return new D(this.client)}watch(t,e){this.client.watch(t).then(i=>e(null,i)).catch(e)}unwatch(t){this.client.unwatch().then(e=>t(null,e)).catch(t)}sismember(t,e,i){this.client.sIsMember(t,e).then(n=>i(null,Number(n))).catch(i)}zcard(t,e){this.client.zCard(t).then(i=>e(null,i)).catch(e)}zrange(t,e,i,n){this.client.zRange(t,e,i).then(s=>n(null,(Array.isArray(s)?s:[]).map(l=>String(l)))).catch(n)}zrevrange(t,e,i,n){this.client.sendCommand(["ZREVRANGE",t,String(e),String(i)]).then(s=>n(null,(Array.isArray(s)?s:[]).map(l=>String(l)))).catch(n)}zrem(t,e,i){this.client.zRem(t,e).then(n=>i(null,n)).catch(i)}psubscribe(t){this.client.pSubscribe(t,(e,i)=>{this.client.emit("pmessage",t,i,e)})}punsubscribe(t){this.client.pUnsubscribe(t).catch(()=>{})}subscribe(t){this.client.subscribe(t,(e,i)=>{this.client.emit("message",i,e)})}unsubscribe(t){this.client.unsubscribe(t).catch(()=>{})}zrangebyscore(t,e,i,n,s,l){this.client.zRangeByScore(t,e,i,{LIMIT:{offset:n,count:s}}).then(a=>l(null,a)).catch(l)}smembers(t,e){this.client.sMembers(t).then(i=>e(null,i)).catch(e)}sscan(t,e,i,n){let s=[t,Number(e),i];this.client.sScan(...s).then(({cursor:l,members:a})=>{n(null,{cursor:String(l),items:a})}).catch(n)}zscan(t,e,i,n){let s=[t,Number(e),i];this.client.zScan(...s).then(({cursor:l,members:a})=>{let c=new Set;for(let g of a)c.add(g.value);n(null,{cursor:String(l),items:[...c]})}).catch(n)}sadd(t,e,i){this.client.sAdd(t,e).then(n=>i(null,n)).catch(i)}srem(t,e,i){this.client.sRem(t,e).then(n=>i(null,n)).catch(i)}hgetall(t,e){this.client.hGetAll(t).then(i=>e(null,i)).catch(e)}hscan(t,e,i,n){let s=[t,Number(e),i];this.client.hScan(...s).then(({cursor:l,tuples:a})=>{let c={};for(;a.length;){let g=a.shift();g&&(c[g.field]=g.value)}n(null,{cursor:String(l),result:c})}).catch(n)}hget(t,e,i){this.client.hGet(t,e).then(n=>i(null,n!=null?n:null)).catch(i)}hset(t,e,i,n){this.client.hSet(t,e,i).then(s=>n(null,s)).catch(n)}hdel(t,e,i){this.client.hDel(t,e).then(n=>i(null,Number(n))).catch(i)}lrange(t,e,i,n){this.client.lRange(t,e,i).then(s=>n(null,s)).catch(n)}hkeys(t,e){this.client.hKeys(t).then(i=>e(null,i)).catch(e)}hlen(t,e){this.client.hLen(t).then(i=>e(null,i)).catch(e)}brpoplpush(t,e,i,n){this.client.brPopLPush(t,e,i).then(s=>n(null,s)).catch(n)}rpoplpush(t,e,i){this.client.rPopLPush(t,e).then(n=>i(null,n)).catch(i)}zrangebyscorewithscores(t,e,i,n){this.client.zRangeByScoreWithScores(t,e,i).then(s=>{let l={};for(let{score:a,value:c}of s)l[a]=c;n(null,l)}).catch(n)}rpop(t,e){this.client.rPop(t).then(i=>e(null,i)).catch(e)}lrem(t,e,i,n){this.client.lRem(t,e,i).then(s=>n(null,s)).catch(n)}publish(t,e,i){this.client.publish(t,e).then(n=>i(null,n)).catch(i)}flushall(t){this.client.flushAll().then(e=>t(null,e)).catch(t)}loadScript(t,e){this.client.sendCommand(["SCRIPT","LOAD",t]).then(i=>e(null,typeof i=="string"?i:String(i))).catch(e)}evalsha(t,e,i){let n=[t],s=Array.isArray(e)?e:[e];this.client.sendCommand(["evalsha",...n.concat(s).map(l=>String(l))]).then(l=>{Array.isArray(l)?i(null,l.map(a=>a instanceof Buffer?a.toString():a)):l instanceof Buffer?i(null,l.toString()):i(null,l)}).catch(i)}get(t,e){this.client.sendCommand(["get",t]).then(i=>e(null,typeof i=="string"?i:null)).catch(e)}del(t,e){this.client.del(t).then(i=>e(null,i)).catch(e)}llen(t,e){this.client.sendCommand(["llen",t]).then(i=>e(null,Number(i))).catch(e)}lmove(t,e,i,n,s){this.validateRedisVersion(6,2)?this.client.lMove(t,e,i,n).then(l=>s(null,l)).catch(s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,e,i,n){this.client.sendCommand(["zremrangebyscore",t,`${e}`,`${i}`]).then(s=>n(null,Number(s))).catch(n)}hmget(t,e,i){this.client.hmGet(t,e).then(n=>i(null,n)).catch(i)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect().catch(()=>{})}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info().then(e=>t(null,e)).catch(t)}on(t,e){return this.client.on(t,e),this}};import Tt from"ioredis";var X=class{constructor(r){this.multi=r.multi()}lrem(r,t,e){return this.multi.lrem(r,t,e),this}lpop(r){return this.multi.lpop(r),this}lpush(r,t){return this.multi.lpush(r,t),this}ltrim(r,t,e){return this.multi.ltrim(r,t,e),this}rpop(r){return this.multi.rpop(r),this}rpush(r,t){return this.multi.rpush(r,t),this}zadd(r,t,e){return this.multi.zadd(r,t,e),this}zrem(r,t){return this.multi.zrem(r,...typeof t=="string"?[t]:t),this}sadd(r,t){return this.multi.sadd(r,t),this}srem(r,t){return this.multi.srem(r,...typeof t=="string"?[t]:t),this}hset(r,t,e){return this.multi.hset(r,t,e),this}hdel(r,t){return this.multi.hdel(r,...typeof t=="string"?[t]:t),this}hincrby(r,t,e){return this.multi.hincrby(r,t,e),this}pexpire(r,t){return this.multi.pexpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rpoplpush(r,t),this}del(r){return this.multi.del(...typeof r=="string"?[r]:r),this}exec(r){this.multi.exec((t,e)=>{if(t)r(t);else if(!e)r(new E);else{let i=[],n=null;for(let s of e){if(!Array.isArray(s)){n=new u("Expected an array reply from multi.exec()");break}let[l,a]=s;if(l instanceof Error){n=l;break}i.push(a)}n?r(n):r(null,i)}})}};var G=class extends v{constructor(t={}){super();this.client=new Tt(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")})}set(t,e,i,n){i.exists&&i.expire?this.client.set(t,e,i.expire.mode,i.expire.value,i.exists,n):i.expire?this.client.set(t,e,i.expire.mode,i.expire.value,n):i.exists?this.client.set(t,e,i.exists,n):this.client.set(t,e,n)}zadd(t,e,i,n){this.client.zadd(t,e,i,n)}multi(){return new X(this.client)}watch(t,e){this.client.watch(t,e)}unwatch(t){this.client.unwatch(t)}sismember(t,e,i){this.client.sismember(t,e,i)}sscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.sscan(...s,(l,[a,c])=>{l?n(l):n(null,{cursor:a,items:c})})}zcard(t,e){this.client.zcard(t,e)}zrange(t,e,i,n){this.client.zrange(t,e,i,n)}zscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.zscan(...s,(l,a)=>{if(l)n(l);else if(!a)n(new b);else{let c=new Set,[g,x]=a;for(;x.length;){let V=String(x.shift()),Rt=String(x.shift());c.add(V)}n(null,{cursor:g,items:[...c]})}})}zrevrange(t,e,i,n){this.client.zrevrange(t,e,i,n)}zrem(t,e,i){this.client.zrem(t,e,i)}psubscribe(t){this.client.psubscribe(t)}punsubscribe(t){this.client.punsubscribe(t)}subscribe(t){this.client.subscribe(t)}unsubscribe(t){this.client.unsubscribe(t)}zrangebyscore(t,e,i,n,s,l){this.client.zrangebyscore(t,e,i,"LIMIT",n,s,l)}smembers(t,e){this.client.smembers(t,e)}sadd(t,e,i){this.client.sadd(t,e,i)}srem(t,e,i){this.client.srem(t,e,i)}hgetall(t,e){this.client.hgetall(t,e)}hscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.hscan(...s,(l,[a,c])=>{if(l)n(l);else{let g={};for(;c.length;){let x=String(c.shift());g[x]=String(c.shift())}n(null,{cursor:a,result:g})}})}hget(t,e,i){this.client.hget(t,e,i)}hset(t,e,i,n){this.client.hset(t,e,i,n)}hdel(t,e,i){this.client.hdel(t,e,i)}lrange(t,e,i,n){this.client.lrange(t,e,i,n)}hkeys(t,e){this.client.hkeys(t,e)}hlen(t,e){this.client.hlen(t,e)}brpoplpush(t,e,i,n){this.client.brpoplpush(t,e,i,n)}rpoplpush(t,e,i){this.client.rpoplpush(t,e,i)}zrangebyscorewithscores(t,e,i,n){this.client.zrangebyscore(t,e,i,"WITHSCORES",(s,l)=>{if(s)n(s);else{let a=l!=null?l:[],c={};for(let g=a.splice(0,2);g.length>0;g=a.splice(0,2)){let[x,V]=g;c[V]=x}n(null,c)}})}rpop(t,e){this.client.rpop(t,e)}lrem(t,e,i,n){this.client.lrem(t,e,i,n)}publish(t,e,i){this.client.publish(t,e,i)}flushall(t){this.client.flushall(t)}loadScript(t,e){this.client.script("load",t,e)}evalsha(t,e,i){let n=[t],s=Array.isArray(e)?e:[e];this.client.evalsha(n.concat(s),i)}get(t,e){this.client.get(t,e)}del(t,e){this.client.del(t,e)}llen(t,e){this.client.llen(t,e)}lmove(t,e,i,n,s){this.validateRedisVersion(6,2)?this.client.lmove(t,e,i,n,s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,e,i,n){this.client.zremrangebyscore(t,e,i,n)}hmget(t,e,i){this.client.hmget(t,e,i)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect(!1)}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info(t)}on(t,e){return this.client.on(t,e),this}};function wt(o){return o.client==="redis"?new q(o.options):new G(o.options)}function Et(o,r){let t=wt(o);t.once("ready",()=>{p.waterfall([e=>t.validateRedisServerSupport(e),e=>t.loadScripts(e)],e=>{e?r(e):r(null,t)})})}var yt={createInstance:Et};export{b as CallbackEmptyReplyError,W as CallbackInvalidReplyError,j as ERedisConfigClient,h as EventEmitter,H as Lock,I as LockAbortError,w as LockAcquireError,m as LockError,M as LockExtendError,A as LockMethodNotAllowedError,N as LockNotAcquiredError,U as LockNotReleasedError,z as LoggerError,T as PanicError,C as PowerSwitch,v as RedisClient,u as RedisClientError,d as RedisSMQError,S as Ticker,L as TickerError,E as WatchedKeysChangedError,_ as Worker,y as WorkerError,Q as WorkerPool,B as WorkerRunner,p as async,Qe as getEventBusInstance,Ct as logger,yt as redis};
3
3
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "redis-smq-common",
3
- "version": "3.0.0-rc.10",
3
+ "version": "3.0.0-rc.12",
4
4
  "description": "RedisSMQ Common Library provides many components that are mainly used by RedisSMQ and RedisSMQ Monitor.",
5
5
  "author": "Weyoss <weyoss@protonmail.com>",
6
6
  "license": "MIT",