@stackone/transport 2.28.2 → 2.29.0

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/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,__name=(e,n)=>t(e,`name`,{value:n,configurable:!0}),n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,__copyProps=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},__toESM=(n,r,a)=>(a=n==null?{}:e(i(n)),__copyProps(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let o=require("@stackone/utils"),s=require("redis");s=__toESM(s);let c=require("@stackone/expressions"),l=require("axios");l=__toESM(l);let u=require("node:https");u=__toESM(u);let d=require("crypto"),f=require("node:timers"),p=require("mathjs"),m=require("jsonpath-plus"),h=require("@stackone/redaction"),g=require("qs");g=__toESM(g);let _=require("fast-xml-parser");const createAuthorizationHeaders=e=>{switch(e.type){case`none`:return{};case`basic`:return createBasicAuthorizationHeader(e);case`bearer`:return createBearerAuthorizationHeader(e);case`oauth2`:return createBearerAuthorizationHeader(e);default:throw Error(`Invalid authentication type`)}},createBasicAuthorizationHeader=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n;return{authorization:`Basic ${Buffer.from(`${e}:${t}`).toString(r)}`}},createBearerAuthorizationHeader=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var LockManager=class{constructor(){this.locks=new Map}async withLock(e,t){await this.lock(e);try{return t()}finally{this.unlock(e)}}async lock(e){let t,n=new Promise(e=>t=e),r=this.locks.has(e),i=this.locks.get(e);r&&i?(i.push({lock:n,unlock:t}),await i[i.length-2].lock):this.locks.set(e,[{lock:n,unlock:t}])}unlock(e){let t=this.locks.has(e),n=this.locks.get(e);if(t&&n&&n.length>0){let e=n.shift()?.unlock;e?.()}this.queueLength(e)===0&&this.locks.delete(e)}queueLength(e){return this.locks.get(e)?.length}close(){this.locks.clear()}};const v=1e3;var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async getDataKeysFromGroup(e){this.isReady()||this.initialize(),this.updateLastAccessedAt();let t=this.groupExpiryMap.get(e);return(0,o.notMissing)(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),[]):Array.from(this.groupMap.get(e)??[])}async setData({key:e,value:t,cacheTTL:n=60,groupKeys:r,groupKeyTTL:i}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),(0,o.notMissing)(this.typeGuard)&&!this.typeGuard(t))return!1;let a=n*v,s=Date.now()+a;if(await this.lockManager.withLock(e,async()=>{((0,o.notMissing)(this.typeGuard)&&this.typeGuard(t)||(0,o.isMissing)(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,s)}),(0,o.notMissing)(r)&&r.length>0){let t=(0,o.notMissing)(i)&&Number.isFinite(i)&&i>0?i*v:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,new Set),this.groupMap.get(n)?.add(e),(0,o.notMissing)(t)&&this.groupExpiryMap.set(n,Date.now()+t)}return!0}typeGuardBypass(e){return this.logger?.debug({category:`MemoryStore`,message:`${this.instantiator} MemoryStore setting data without type guard - you should probably configure one`}),!0}async delete(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{if(this.dispose){let t=this.dataStore.get(e);await this.dispose(e,t)}if((0,o.notMissing)(t)&&t.length>0)for(let n of t)this.groupMap.get(n)?.delete(e);return this.expiryMap.delete(e),this.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=[],i=0;return this.dataStore.forEach((e,a)=>{let o=Date.now(),s=this.expiryMap.get(a)??0,c=this.truncateThreshold*this.truncationPercentage/100;(s<=o||t&&i>=0&&i<=c)&&(r.push(a),n.push(this.lockManager.withLock(a,async()=>(this.dispose&&await this.dispose(a,e),this.expiryMap.delete(a),this.dataStore.delete(a))))),i++}),await Promise.all(n),this.removeKeysFromGroups(r),{dataStoreSize:e,prunedDataStoreSize:this.dataStore.size}}removeKeysFromGroups(e){if(e.length===0)return;let t=new Set(e);for(let e of this.groupMap.values())for(let n of e)t.has(n)&&!this.dataStore.has(n)&&e.delete(n)}startEvictionTask(){if((0,o.notMissing)(this.evictionInterval))return;let executePrune=async()=>{let e;try{if(this.lastAccessedAt+this.staleDataThreshold<Date.now()){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),await this.close();return}e=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}catch(e){e instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:e,code:`MemoryStorePruneError`}),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}finally{if((0,o.notMissing)(e?.dataStoreSize)&&(0,o.notMissing)(e?.prunedDataStoreSize)){let{dataStoreSize:t,prunedDataStoreSize:n}=e,r=t-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&=(clearTimeout(this.evictionInterval),void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return(0,o.notMissing)(this.evictionInterval)&&(0,o.notMissing)(this.dataStore)&&(0,o.notMissing)(this.expiryMap)&&(0,o.notMissing)(this.lockManager)}isAvailable(){return this.isReady()}async setTTL(e,t){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),!this.dataStore.has(e)||!Number.isFinite(t)||t<=0)return!1;let n=t*v;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n)}),!0}async close(){this.stopEvictionTask(),this.dispose&&await Promise.all(Array.from(this.dataStore,async([e,t])=>{try{await this.dispose?.(e,t)}catch(t){this.logger?.error({message:`Failed to dispose entry "${e}" during close`,category:`MemoryStore`,error:t,code:`MemoryStoreDisposeError`})}})),this.dataStore.clear(),this.expiryMap.clear(),this.groupMap.clear(),this.groupExpiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()).filter(t=>t.includes(e)),i=[],a=t?parseInt(t,10):0;for(let e=a;e<n+a;e++){let t=r[e];if(!t)break;let a=await this.getData(t);if(a&&i.push(a),i.length>=n)break}return{items:i,cursor:i.length<n?void 0:(a+n).toString()}}},EventClient=class{constructor(e,t,n){this.executorMethodStore=null,this.promiseStore=null,this.eventClientConfig=null,this.executorMethodStoreConfig=null,this.pendingPromiseStoreConfig=null,this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new MemoryStore(i),this.promiseStore=new MemoryStore(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/1e3;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return(0,o.notMissing)(n)?n:(await this.setPendingEvent(e,t),this.getPendingEvent(e))}async getPendingEvent(e){return this.promiseStore?.getData(e)??null}async deleteEvent(e){return(await Promise.all([this.promiseStore?.delete(e),this.executorMethodStore?.delete(e)])).every(Boolean)}async resolveEvent(e,t){try{let n=await this.executorMethodStore?.getData(e);(0,o.isMissing)(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??6e4),n=await this.executorMethodStore?.getData(e)),n?.resolve?.(t)}catch(t){t instanceof Error&&this.logger.error({message:`Error handling event for key ${e}: ${t.message}`,category:this.constructor.name,context:{eventKey:e},error:t,code:`EventClientResolveError`})}}async defaultExecutorMethodDispose(e,t){(0,o.notMissing)(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):(0,o.notMissing)(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return(0,o.isObject)(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[]}getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:((0,o.isMissing)(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,(0,o.isMissing)(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await y.build(e,t,n)??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:`RedisClientError`,category:n??`buildRedisClientInstance`});return}};var y=class RedisClient{#e;#t;static async build({getRedisClient:e=s.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o},c,l){let u=new RedisClient;u.#t=c;try{u.#e=e({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:t,port:n,keepAlive:i,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,disableOfflineQueue:!0});let s=getDefaultRedisListeners(l??`RedisClient`,u.#t);return addRedisEventHandlers(u.#e,s),await u.#e.connect(),u}catch(e){let t=e;return u.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:l??`RedisClient`}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}async getData(e){if(!this.#i())return null;try{let t=await this.#e.get(e);if(!t)return null;let n=this.#n(t);return(0,o.isString)(n)?t:n}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getDataKeysFromGroup(e){if(!this.#i())return null;try{return await this.#e.sMembers(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting data from group`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i}){if(!this.#i())return!1;try{let a=(0,o.isString)(t)?t:JSON.stringify(t);if(await this.#e.set(e,a,{EX:n}),(0,o.notMissing)(r)&&r.length>0)for(let t of r)await this.#e.sAdd(t,[e]),(0,o.notMissing)(i)&&Number.isFinite(i)&&i>0&&await this.#e.expire(t,i);return!0}catch(e){let t=e;return this.#t?.error({message:`Error setting data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async setTTL(e,t){if(!this.#i())return!1;if(!Number.isFinite(t)||t<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;try{let n=await this.#e.expire(e,t);return n||this.#t?.debug({message:`No keys updated for ${e}`,category:RedisClient.name}),n}catch(e){let t=e;return this.#t?.error({message:`Error resetting data TTL`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async executeScript({sha1:e,keys:t,args:n}){if(!this.#i())return null;try{return await this.#e.evalSha(e,{keys:t,arguments:n})}catch(e){let t=e;throw this.#t?.error({message:`Error executing script`,error:t,code:`RedisClientScriptExecuteError`,category:RedisClient.name}),t}}async loadScript(e){if(!this.#i())return null;try{return await this.#e.scriptLoad(e)}catch(e){let t=e;return this.#t?.error({message:`Error loading script`,error:t,code:`RedisClientScriptLoadError`,category:RedisClient.name}),null}}async scriptExists(e){if(!this.#i())return e.map(()=>!1);try{return(await this.#e.scriptExists(e)).map(e=>!!e)}catch(t){let n=t;return this.#t?.error({message:`Error checking script existence`,error:n,code:`RedisClientScriptError`,category:RedisClient.name}),e.map(()=>!1)}}async#r(e,t,n){if(!this.#i())return null;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),null;try{let r=[{args:[e,t]},{args:[`expire`,t,n.toString()]}],i=(await this.#e.multiExecutor(r))?.[0];return typeof i==`number`?i:null}catch(t){let n=t;return this.#t?.error({message:`Error executing ${e} operation`,error:n,code:`RedisClientCommandError`,category:RedisClient.name}),null}}async increment(e,t){return this.#r(`incr`,e,t)}async decrement(e,t){return this.#r(`decr`,e,t)}async subscribe(e,t){if(!this.#i())return!1;try{return await this.#e.pSubscribe(e,t),!0}catch(t){let n=t;return this.#t?.error({message:`Error subscribing to ${e}`,error:n,code:`RedisClientSubscribeError`,category:RedisClient.name}),!1}}async unsubscribe(e){if(!this.#i())return!1;try{return await this.#e.pUnsubscribe(e),!0}catch(t){let n=t;return this.#t?.error({message:`Error unsubscribing from ${e}`,error:n,code:`RedisClientUnsubscribeError`,category:RedisClient.name}),!1}}async publish(e,t){if(!this.#i())return null;try{let n=await this.#e.publish(e,t);return n===0&&this.#t?.debug({message:`No subscribers found for channel ${e}`,category:RedisClient.name}),n}catch(t){let n=t;return this.#t?.error({message:`Error publishing to ${e}`,error:n,code:`RedisClientPublishError`,category:RedisClient.name}),null}}getClient(){return this.#i()?this.#e:null}isAvailable(){return this.#e.isReady&&this.#e.isOpen}async close(){try{this.#e.isOpen&&await this.#e.quit()}catch(e){try{await this.#e.disconnect()}catch{}this.#t?.error({message:`Error gracefully closing Redis client, forced disconnect`,error:e,code:`RedisClientError`,category:RedisClient.name})}}#i(){let e=this.isAvailable();return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:`RedisClientRedisNotReady`}),e}async listData({partialKey:e,limit:t,cursor:n}){try{let r=n?parseInt(n,10):0,i=await this.#e.sScan(e,r,{COUNT:t}),a=[];for(let e of i.members){let t=await this.getData(e);(0,o.notMissing)(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(e){let t=e;return this.#t?.error({message:`Error listing data`,error:t,code:`RedisClientListError`,category:RedisClient.name}),{items:null}}}async deleteData(e,t){try{if(!this.#i())return!1;let n=await this.#e.del(e);return n===0&&this.#t?.debug({message:`No keys deleted for ${e}`,category:RedisClient.name}),(0,o.notMissing)(t)&&t.length>0&&(await Promise.allSettled(t.map(t=>this.#e.sRem(t,e)))).forEach((e,n)=>{e.status===`rejected`&&this.#t?.error({message:`Error removing key from group set ${t[n]}`,error:e.reason,code:`RedisClientDeleteError`,category:RedisClient.name})}),n>0}catch(e){let t=e;return this.#t?.error({message:`Error deleting data`,error:t,code:`RedisClientDeleteError`,category:RedisClient.name}),!1}}};const addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:`RedisClientError`,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0}async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let s=t??await buildRedisClientInstance(e,i,this.name);if((0,o.isMissing)(s))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=s,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();(0,o.notMissing)(e)&&(e.on(`ready`,async()=>{this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){if((0,o.notMissing)(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!((0,o.isMissing)(this.scripts)||Object.keys(this.scripts).length===0)){this.reloadInProgress=this.performReload();try{await this.reloadInProgress}finally{this.reloadInProgress=null}}}async performReload(){this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts),this.lastReloadTime=Date.now()}async loadScripts(e,t){if((0,o.notMissing)(t))for(let[e,n]of t)this.scriptMap.set(e,n);let n=Object.entries(e),r=n.map(([e])=>this.scriptMap.get(e)).filter(o.notMissing),i=new Map;if(r.length>0&&(0,o.notMissing)(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if((0,o.notMissing)(e)){r.forEach((t,n)=>{i.set(t,e[n]??!1)});let t=e.filter(Boolean).length;t>0&&this.logger?.info({message:`${t}/${r.length} scripts already exist in Redis; skipping load for existing scripts`,category:this.name})}}for(let[e,t]of n){let n=this.scriptMap.get(e);if(n&&i.get(n))continue;let r=await this.cacheClient?.loadScript?.(t);(0,o.notMissing)(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:`ScriptManagerLoadingError`})}}async executeScript(e,t,n){if(!this.isRedisReady())return this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:t,args:n}}),null;let r=this.scriptMap?.get(e);if((0,o.isMissing)(r))throw this.logger?.error({message:`Script for ${e} not found in script map`,category:this.name,code:`ScriptManagerExecutionError`}),Error(`Script for ${e} not found`);try{return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}catch(i){if(i instanceof Error&&i.message.includes(`NOSCRIPT`)){let i=Date.now()-this.lastReloadTime;if(i<1500){let t=1500-i;this.logger?.info({message:`Script ${e} not found, reload occurred ${i}ms ago. Waiting ${t}ms before reloading`,category:this.name}),await(0,o.delay)(t)}if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),r=this.scriptMap?.get(e),(0,o.isMissing)(r))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}throw i instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${i.message}`,category:this.name,context:{keys:t,args:n},error:i,code:`ScriptManagerExecutionError`}),i}}isRedisReady(){let e=this.cacheClient?.getClient?.();if((0,o.notMissing)(this.cacheClient)&&(0,o.isMissing)(e))return this.logger?.warning({message:`Cache client exists but getClient() returned null - cannot verify Redis readiness`,category:this.name}),!1;let t=e?.isReady&&e?.isOpen;return this.isReady()&&(0,o.notMissing)(this.cacheClient)&&(t??!1)}},SubscriptionManager=class{constructor(e){this.options={getCacheClient:buildRedisClientInstance},this.subscriptionMap=null,this.subscriptionClient=null,this.name=`SubscriptionManager`,this.options={...this.options,...e}}async initialize(e=this.options){let{config:t,getCacheClient:n,logger:r}=e;if(this.logger=r,this.subscriptionMap=new MemoryStore({instantiator:`${e?.instantiator}(${this.name})`,evictionFrequency:e?.subscriptionTTL,staleDataThreshold:e?.staleSubscriptionsThreshold,truncateThreshold:e?.truncateThreshold,truncationPercentage:e?.truncationPercentage,typeGuard:e=>typeof e==`string`,dispose:async e=>{await this.subscriptionClient?.unsubscribe?.(e)}}),(0,o.notMissing)(t))this.subscriptionClient=await n?.(t,this.logger,e?.instantiator)??null,this.logger?.info({message:`${this.name} initialized for ${e.instantiator}.`,category:this.name});else throw Error(`SubscriptionManager requires a Redis client configuration.`)}async subscribe(e,t){this.isReady()||await this.initialize(this.options);let n=await this.subscriptionMap?.getData(e),r=(0,o.getContentHash)(t.toString());return await this.subscriptionMap?.setData({key:e,value:r}),n===r?!0:await this.subscriptionClient?.subscribe?.(e,t)??!1}async unsubscribe(e){return this.isReady()||await this.initialize(this.options),this.subscriptionClient?.unsubscribe?.(e)??!1}isReady(){return(0,o.notMissing)(this.subscriptionClient)&&(0,o.notMissing)(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionClient?.close?.(),this.subscriptionMap=null,this.subscriptionClient=null}};const b=15e3,x=15e3,S=1e4;var QueueManager=class extends ScriptManager{constructor(...e){super(...e),this.subscriptionManager=null,this.eventClient=null,this.name=`QueueManager`}async additionalInitialization(){if((0,o.isMissing)(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:6e4,truncateThreshold:S,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:x,truncateThreshold:S,truncationPercentage:1},{instantiator:this.name,evictionFrequency:x,truncateThreshold:S,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=b,o){try{let s=`${e}:${t}`;await this.subscriptionManager?.subscribe(s,async(n,r)=>{if(r.includes(s)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let c=await this.executeScript(n?`lPush`:`rPush`,[e],[t,`60000`])===1,l=!i||!c?await this.waitForTurnOrAbort(s,a,o):o?.aborted===!0;return await this.eventClient?.deleteEvent(s),l||o?.aborted===!0?null:await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:`QueueManagerJoinAndWaitTurnError`,context:{queueName:e,value:t}}),n}}async waitForTurnOrAbort(e,t,n){if((0,o.notMissing)(n)&&n.aborted)return!0;let r=this.eventClient?.waitForEvent(e,t);return(0,o.isMissing)(n)?(await r,!1):await new Promise((e,t)=>{let onAbort=()=>{n.removeEventListener(`abort`,onAbort),e(!0)};n.addEventListener(`abort`,onAbort,{once:!0}),n.aborted&&onAbort(),Promise.resolve(r).then(()=>{n.removeEventListener(`abort`,onAbort),e(!1)},e=>{n.removeEventListener(`abort`,onAbort),t(e)})})}async remove(e,t){try{return(await this.executeScript(`remove`,[e],[t])??0)>0}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error removing item from queue`,category:this.name,error:n,code:`QueueManagerRemoveError`,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(`lPop`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:`QueueManagerPopError`,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(`llen`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:`QueueManagerLengthError`,context:{queueName:e}}),t}}isReady(){return(0,o.notMissing)(this.subscriptionManager)&&(0,o.notMissing)(this.cacheClient)&&(0,o.notMissing)(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const C=`__keyevent@0__:`,w=`${C}set`,T=`${C}expire`,E=`${C}expired`,D=`${C}srem`,O=[w,T,E],k={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,A={tryConcurrency:`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,__name=(e,n)=>t(e,`name`,{value:n,configurable:!0}),n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,__copyProps=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},__toESM=(n,r,a)=>(a=n==null?{}:e(i(n)),__copyProps(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let o=require("@stackone/utils"),s=require("redis");s=__toESM(s);let c=require("@stackone/expressions"),l=require("axios");l=__toESM(l);let u=require("node:https");u=__toESM(u);let d=require("crypto"),f=require("node:timers"),p=require("mathjs"),m=require("jsonpath-plus"),h=require("@stackone/redaction"),g=require("qs");g=__toESM(g);let _=require("fast-xml-parser");const createAuthorizationHeaders=e=>{switch(e.type){case`none`:return{};case`basic`:return createBasicAuthorizationHeader(e);case`bearer`:return createBearerAuthorizationHeader(e);case`oauth2`:return createBearerAuthorizationHeader(e);default:throw Error(`Invalid authentication type`)}},createBasicAuthorizationHeader=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n;return{authorization:`Basic ${Buffer.from(`${e}:${t}`).toString(r)}`}},createBearerAuthorizationHeader=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var LockManager=class{constructor(){this.locks=new Map}async withLock(e,t){await this.lock(e);try{return t()}finally{this.unlock(e)}}async lock(e){let t,n=new Promise(e=>t=e),r=this.locks.has(e),i=this.locks.get(e);r&&i?(i.push({lock:n,unlock:t}),await i[i.length-2].lock):this.locks.set(e,[{lock:n,unlock:t}])}unlock(e){let t=this.locks.has(e),n=this.locks.get(e);if(t&&n&&n.length>0){let e=n.shift()?.unlock;e?.()}this.queueLength(e)===0&&this.locks.delete(e)}queueLength(e){return this.locks.get(e)?.length}close(){this.locks.clear()}};const v=1e3;var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.hashStore=new Map,this.hashExpiryMap=new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async getDataKeysFromGroup(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),Array.from(this.getLiveGroup(e)??[])}async deleteDataKeyFromGroup(e,t){this.isReady()||this.initialize(),this.updateLastAccessedAt();let n=this.getLiveGroup(e);if((0,o.isMissing)(n))return!1;let r=n.delete(t);return n.size===0&&(this.groupMap.delete(e),this.groupExpiryMap.delete(e)),r}getLiveGroup(e){let t=this.groupExpiryMap.get(e);return(0,o.notMissing)(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),null):this.groupMap.get(e)??null}async setData({key:e,value:t,cacheTTL:n=60,groupKeys:r,groupKeyTTL:i}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),(0,o.notMissing)(this.typeGuard)&&!this.typeGuard(t))return!1;let a=n*v,s=Date.now()+a;if(await this.lockManager.withLock(e,async()=>{((0,o.notMissing)(this.typeGuard)&&this.typeGuard(t)||(0,o.isMissing)(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,s)}),(0,o.notMissing)(r)&&r.length>0){let t=(0,o.notMissing)(i)&&Number.isFinite(i)&&i>0?i*v:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,new Set),this.groupMap.get(n)?.add(e),(0,o.notMissing)(t)&&this.groupExpiryMap.set(n,Date.now()+t)}return!0}typeGuardBypass(e){return this.logger?.debug({category:`MemoryStore`,message:`${this.instantiator} MemoryStore setting data without type guard - you should probably configure one`}),!0}async delete(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{if(this.dispose){let t=this.dataStore.get(e);await this.dispose(e,t)}if((0,o.notMissing)(t)&&t.length>0)for(let n of t)this.groupMap.get(n)?.delete(e);return this.expiryMap.delete(e),this.dataStore.delete(e)})}async pruneExpiredKeys(){this.pruneExpiredHashes();let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=[],i=0;return this.dataStore.forEach((e,a)=>{let o=Date.now(),s=this.expiryMap.get(a)??0,c=this.truncateThreshold*this.truncationPercentage/100;(s<=o||t&&i>=0&&i<=c)&&(r.push(a),n.push(this.lockManager.withLock(a,async()=>(this.dispose&&await this.dispose(a,e),this.expiryMap.delete(a),this.dataStore.delete(a))))),i++}),await Promise.all(n),this.removeKeysFromGroups(r),{dataStoreSize:e,prunedDataStoreSize:this.dataStore.size}}removeKeysFromGroups(e){if(e.length===0)return;let t=new Set(e);for(let e of this.groupMap.values())for(let n of e)t.has(n)&&!this.dataStore.has(n)&&e.delete(n)}startEvictionTask(){if((0,o.notMissing)(this.evictionInterval))return;let executePrune=async()=>{let e;try{if(this.lastAccessedAt+this.staleDataThreshold<Date.now()){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),await this.close();return}e=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}catch(e){e instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:e,code:`MemoryStorePruneError`}),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}finally{if((0,o.notMissing)(e?.dataStoreSize)&&(0,o.notMissing)(e?.prunedDataStoreSize)){let{dataStoreSize:t,prunedDataStoreSize:n}=e,r=t-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&=(clearTimeout(this.evictionInterval),void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return(0,o.notMissing)(this.evictionInterval)&&(0,o.notMissing)(this.dataStore)&&(0,o.notMissing)(this.expiryMap)&&(0,o.notMissing)(this.lockManager)}isAvailable(){return this.isReady()}async setTTL(e,t){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),!this.dataStore.has(e)||!Number.isFinite(t)||t<=0)return!1;let n=t*v;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n)}),!0}pruneExpiredHashes(){let e=Date.now();for(let[t,n]of this.hashExpiryMap)n<=e&&(this.hashStore.delete(t),this.hashExpiryMap.delete(t))}getLiveHash(e){let t=this.hashExpiryMap.get(e);return(0,o.notMissing)(t)&&t<=Date.now()?(this.hashStore.delete(e),this.hashExpiryMap.delete(e),null):this.hashStore.get(e)??null}async setHashData({key:e,entries:t,cacheTTL:n}){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),!Number.isFinite(n)||n<=0||Object.keys(t).length===0?!1:this.lockManager.withLock(e,async()=>{let r=this.getLiveHash(e)??new Map;return Object.entries(t).forEach(([e,t])=>{r.set(e,t)}),this.hashStore.set(e,r),this.hashExpiryMap.set(e,Date.now()+n*v),!0})}async getHashData(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.getLiveHash(e)?.get(t)??null)}async getAllHashData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{let t=this.getLiveHash(e);return(0,o.isMissing)(t)||t.size===0?null:Object.fromEntries(t)})}async deleteHashData(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{let n=this.getLiveHash(e);if((0,o.isMissing)(n))return 0;let r=t.filter(e=>n.delete(e)).length;return n.size===0&&(this.hashStore.delete(e),this.hashExpiryMap.delete(e)),r})}async close(){this.stopEvictionTask(),this.dispose&&await Promise.all(Array.from(this.dataStore,async([e,t])=>{try{await this.dispose?.(e,t)}catch(t){this.logger?.error({message:`Failed to dispose entry "${e}" during close`,category:`MemoryStore`,error:t,code:`MemoryStoreDisposeError`})}})),this.dataStore.clear(),this.expiryMap.clear(),this.hashStore.clear(),this.hashExpiryMap.clear(),this.groupMap.clear(),this.groupExpiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()).filter(t=>t.includes(e)),i=[],a=t?parseInt(t,10):0;for(let e=a;e<n+a;e++){let t=r[e];if(!t)break;let a=await this.getData(t);if(a&&i.push(a),i.length>=n)break}return{items:i,cursor:i.length<n?void 0:(a+n).toString()}}},EventClient=class{constructor(e,t,n){this.executorMethodStore=null,this.promiseStore=null,this.eventClientConfig=null,this.executorMethodStoreConfig=null,this.pendingPromiseStoreConfig=null,this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new MemoryStore(i),this.promiseStore=new MemoryStore(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/1e3;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return(0,o.notMissing)(n)?n:(await this.setPendingEvent(e,t),this.getPendingEvent(e))}async getPendingEvent(e){return this.promiseStore?.getData(e)??null}async deleteEvent(e){return(await Promise.all([this.promiseStore?.delete(e),this.executorMethodStore?.delete(e)])).every(Boolean)}async resolveEvent(e,t){try{let n=await this.executorMethodStore?.getData(e);(0,o.isMissing)(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??6e4),n=await this.executorMethodStore?.getData(e)),n?.resolve?.(t)}catch(t){t instanceof Error&&this.logger.error({message:`Error handling event for key ${e}: ${t.message}`,category:this.constructor.name,context:{eventKey:e},error:t,code:`EventClientResolveError`})}}async defaultExecutorMethodDispose(e,t){(0,o.notMissing)(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):(0,o.notMissing)(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return(0,o.isObject)(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[]}getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:((0,o.isMissing)(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,(0,o.isMissing)(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await y.build(e,t,n)??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:`RedisClientError`,category:n??`buildRedisClientInstance`});return}};var y=class RedisClient{#e;#t;static async build({getRedisClient:e=s.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o},c,l){let u=new RedisClient;u.#t=c;try{u.#e=e({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:t,port:n,keepAlive:i,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,disableOfflineQueue:!0});let s=getDefaultRedisListeners(l??`RedisClient`,u.#t);return addRedisEventHandlers(u.#e,s),await u.#e.connect(),u}catch(e){let t=e;return u.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:l??`RedisClient`}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}async getData(e){if(!this.#i())return null;try{let t=await this.#e.get(e);if(!t)return null;let n=this.#n(t);return(0,o.isString)(n)?t:n}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getDataKeysFromGroup(e){if(!this.#i())return null;try{return await this.#e.sMembers(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting data from group`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i}){if(!this.#i())return!1;try{let a=(0,o.isString)(t)?t:JSON.stringify(t);if(await this.#e.set(e,a,{EX:n}),(0,o.notMissing)(r)&&r.length>0)for(let t of r)await this.#e.sAdd(t,[e]),(0,o.notMissing)(i)&&Number.isFinite(i)&&i>0&&await this.#e.expire(t,i);return!0}catch(e){let t=e;return this.#t?.error({message:`Error setting data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async setTTL(e,t){if(!this.#i())return!1;if(!Number.isFinite(t)||t<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;try{let n=await this.#e.expire(e,t);return n||this.#t?.debug({message:`No keys updated for ${e}`,category:RedisClient.name}),n}catch(e){let t=e;return this.#t?.error({message:`Error resetting data TTL`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async executeScript({sha1:e,keys:t,args:n}){if(!this.#i())return null;try{return await this.#e.evalSha(e,{keys:t,arguments:n})}catch(e){let t=e;throw this.#t?.error({message:`Error executing script`,error:t,code:`RedisClientScriptExecuteError`,category:RedisClient.name}),t}}async loadScript(e){if(!this.#i())return null;try{return await this.#e.scriptLoad(e)}catch(e){let t=e;return this.#t?.error({message:`Error loading script`,error:t,code:`RedisClientScriptLoadError`,category:RedisClient.name}),null}}async scriptExists(e){if(!this.#i())return e.map(()=>!1);try{return(await this.#e.scriptExists(e)).map(e=>!!e)}catch(t){let n=t;return this.#t?.error({message:`Error checking script existence`,error:n,code:`RedisClientScriptError`,category:RedisClient.name}),e.map(()=>!1)}}async#r(e,t,n){if(!this.#i())return null;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),null;try{let r=[{args:[e,t]},{args:[`expire`,t,n.toString()]}],i=(await this.#e.multiExecutor(r))?.[0];return typeof i==`number`?i:null}catch(t){let n=t;return this.#t?.error({message:`Error executing ${e} operation`,error:n,code:`RedisClientCommandError`,category:RedisClient.name}),null}}async increment(e,t){return this.#r(`incr`,e,t)}async decrement(e,t){return this.#r(`decr`,e,t)}async subscribe(e,t){if(!this.#i())return!1;try{return await this.#e.pSubscribe(e,t),!0}catch(t){let n=t;return this.#t?.error({message:`Error subscribing to ${e}`,error:n,code:`RedisClientSubscribeError`,category:RedisClient.name}),!1}}async unsubscribe(e){if(!this.#i())return!1;try{return await this.#e.pUnsubscribe(e),!0}catch(t){let n=t;return this.#t?.error({message:`Error unsubscribing from ${e}`,error:n,code:`RedisClientUnsubscribeError`,category:RedisClient.name}),!1}}async publish(e,t){if(!this.#i())return null;try{let n=await this.#e.publish(e,t);return n===0&&this.#t?.debug({message:`No subscribers found for channel ${e}`,category:RedisClient.name}),n}catch(t){let n=t;return this.#t?.error({message:`Error publishing to ${e}`,error:n,code:`RedisClientPublishError`,category:RedisClient.name}),null}}getClient(){return this.#i()?this.#e:null}isAvailable(){return this.#e.isReady&&this.#e.isOpen}async close(){try{this.#e.isOpen&&await this.#e.quit()}catch(e){try{await this.#e.disconnect()}catch{}this.#t?.error({message:`Error gracefully closing Redis client, forced disconnect`,error:e,code:`RedisClientError`,category:RedisClient.name})}}#i(){let e=this.isAvailable();return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:`RedisClientRedisNotReady`}),e}async listData({partialKey:e,limit:t,cursor:n}){try{let r=n?parseInt(n,10):0,i=await this.#e.sScan(e,r,{COUNT:t}),a=[];for(let e of i.members){let t=await this.getData(e);(0,o.notMissing)(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(e){let t=e;return this.#t?.error({message:`Error listing data`,error:t,code:`RedisClientListError`,category:RedisClient.name}),{items:null}}}async deleteData(e,t){try{if(!this.#i())return!1;let n=await this.#e.del(e);return n===0&&this.#t?.debug({message:`No keys deleted for ${e}`,category:RedisClient.name}),(0,o.notMissing)(t)&&t.length>0&&(await Promise.allSettled(t.map(t=>this.#e.sRem(t,e)))).forEach((e,n)=>{e.status===`rejected`&&this.#t?.error({message:`Error removing key from group set ${t[n]}`,error:e.reason,code:`RedisClientDeleteError`,category:RedisClient.name})}),n>0}catch(e){let t=e;return this.#t?.error({message:`Error deleting data`,error:t,code:`RedisClientDeleteError`,category:RedisClient.name}),!1}}async deleteDataKeyFromGroup(e,t){if(!this.#i())return!1;try{let n=await this.#e.sRem(e,t);return n===0&&this.#t?.debug({message:`No keys removed from group ${e}`,category:RedisClient.name}),n>0}catch(t){let n=t;return this.#t?.error({message:`Error removing key from group set ${e}`,error:n,code:`RedisClientDeleteError`,category:RedisClient.name}),!1}}async setHashData({key:e,entries:t,cacheTTL:n}){if(!this.#i())return!1;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;let r=Object.entries(t);if(r.length===0)return!1;try{let t=r.flatMap(([e,t])=>[e,(0,o.isString)(t)?t:JSON.stringify(t)]);return await this.#e.multiExecutor([{args:[`hset`,e,...t]},{args:[`expire`,e,n.toString()]}]),!0}catch(e){let t=e;return this.#t?.error({message:`Error setting hash data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async getHashData(e,t){if(!this.#i())return null;try{let n=await this.#e.hGet(e,t);if(n!==``&&(0,o.isMissing)(n))return null;let r=this.#n(n);return(0,o.isString)(r)?n:r}catch(e){let t=e;return this.#t?.error({message:`Error getting hash data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getAllHashData(e){if(!this.#i())return null;try{let t=await this.#e.hGetAll(e);return Object.keys(t).length===0?null:Object.fromEntries(Object.entries(t).map(([e,t])=>{let n=this.#n(t);return[e,(0,o.isString)(n)?t:n]}))}catch(e){let t=e;return this.#t?.error({message:`Error getting all hash data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async deleteHashData(e,t){if(!this.#i())return null;if(t.length===0)return 0;try{return await this.#e.hDel(e,t)}catch(e){let t=e;return this.#t?.error({message:`Error deleting hash data`,error:t,code:`RedisClientDeleteError`,category:RedisClient.name}),null}}};const addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:`RedisClientError`,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0}async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let s=t??await buildRedisClientInstance(e,i,this.name);if((0,o.isMissing)(s))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=s,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();(0,o.notMissing)(e)&&(e.on(`ready`,async()=>{this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){if((0,o.notMissing)(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!((0,o.isMissing)(this.scripts)||Object.keys(this.scripts).length===0)){this.reloadInProgress=this.performReload();try{await this.reloadInProgress}finally{this.reloadInProgress=null}}}async performReload(){this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts),this.lastReloadTime=Date.now()}async loadScripts(e,t){if((0,o.notMissing)(t))for(let[e,n]of t)this.scriptMap.set(e,n);let n=Object.entries(e),r=n.map(([e])=>this.scriptMap.get(e)).filter(o.notMissing),i=new Map;if(r.length>0&&(0,o.notMissing)(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if((0,o.notMissing)(e)){r.forEach((t,n)=>{i.set(t,e[n]??!1)});let t=e.filter(Boolean).length;t>0&&this.logger?.info({message:`${t}/${r.length} scripts already exist in Redis; skipping load for existing scripts`,category:this.name})}}for(let[e,t]of n){let n=this.scriptMap.get(e);if(n&&i.get(n))continue;let r=await this.cacheClient?.loadScript?.(t);(0,o.notMissing)(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:`ScriptManagerLoadingError`})}}async executeScript(e,t,n){if(!this.isRedisReady())return this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:t,args:n}}),null;let r=this.scriptMap?.get(e);if((0,o.isMissing)(r))throw this.logger?.error({message:`Script for ${e} not found in script map`,category:this.name,code:`ScriptManagerExecutionError`}),Error(`Script for ${e} not found`);try{return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}catch(i){if(i instanceof Error&&i.message.includes(`NOSCRIPT`)){let i=Date.now()-this.lastReloadTime;if(i<1500){let t=1500-i;this.logger?.info({message:`Script ${e} not found, reload occurred ${i}ms ago. Waiting ${t}ms before reloading`,category:this.name}),await(0,o.delay)(t)}if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),r=this.scriptMap?.get(e),(0,o.isMissing)(r))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}throw i instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${i.message}`,category:this.name,context:{keys:t,args:n},error:i,code:`ScriptManagerExecutionError`}),i}}isRedisReady(){let e=this.cacheClient?.getClient?.();if((0,o.notMissing)(this.cacheClient)&&(0,o.isMissing)(e))return this.logger?.warning({message:`Cache client exists but getClient() returned null - cannot verify Redis readiness`,category:this.name}),!1;let t=e?.isReady&&e?.isOpen;return this.isReady()&&(0,o.notMissing)(this.cacheClient)&&(t??!1)}},SubscriptionManager=class{constructor(e){this.options={getCacheClient:buildRedisClientInstance},this.subscriptionMap=null,this.subscriptionClient=null,this.name=`SubscriptionManager`,this.options={...this.options,...e}}async initialize(e=this.options){let{config:t,getCacheClient:n,logger:r}=e;if(this.logger=r,this.subscriptionMap=new MemoryStore({instantiator:`${e?.instantiator}(${this.name})`,evictionFrequency:e?.subscriptionTTL,staleDataThreshold:e?.staleSubscriptionsThreshold,truncateThreshold:e?.truncateThreshold,truncationPercentage:e?.truncationPercentage,typeGuard:e=>typeof e==`string`,dispose:async e=>{await this.subscriptionClient?.unsubscribe?.(e)}}),(0,o.notMissing)(t))this.subscriptionClient=await n?.(t,this.logger,e?.instantiator)??null,this.logger?.info({message:`${this.name} initialized for ${e.instantiator}.`,category:this.name});else throw Error(`SubscriptionManager requires a Redis client configuration.`)}async subscribe(e,t){this.isReady()||await this.initialize(this.options);let n=await this.subscriptionMap?.getData(e),r=(0,o.getContentHash)(t.toString());return await this.subscriptionMap?.setData({key:e,value:r}),n===r?!0:await this.subscriptionClient?.subscribe?.(e,t)??!1}async unsubscribe(e){return this.isReady()||await this.initialize(this.options),this.subscriptionClient?.unsubscribe?.(e)??!1}isReady(){return(0,o.notMissing)(this.subscriptionClient)&&(0,o.notMissing)(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionClient?.close?.(),this.subscriptionMap=null,this.subscriptionClient=null}};const b=15e3,x=15e3,S=1e4;var QueueManager=class extends ScriptManager{constructor(...e){super(...e),this.subscriptionManager=null,this.eventClient=null,this.name=`QueueManager`}async additionalInitialization(){if((0,o.isMissing)(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:6e4,truncateThreshold:S,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:x,truncateThreshold:S,truncationPercentage:1},{instantiator:this.name,evictionFrequency:x,truncateThreshold:S,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=b,o){try{let s=`${e}:${t}`;await this.subscriptionManager?.subscribe(s,async(n,r)=>{if(r.includes(s)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let c=await this.executeScript(n?`lPush`:`rPush`,[e],[t,`60000`])===1,l=!i||!c?await this.waitForTurnOrAbort(s,a,o):o?.aborted===!0;return await this.eventClient?.deleteEvent(s),l||o?.aborted===!0?null:await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:`QueueManagerJoinAndWaitTurnError`,context:{queueName:e,value:t}}),n}}async waitForTurnOrAbort(e,t,n){if((0,o.notMissing)(n)&&n.aborted)return!0;let r=this.eventClient?.waitForEvent(e,t);return(0,o.isMissing)(n)?(await r,!1):await new Promise((e,t)=>{let onAbort=()=>{n.removeEventListener(`abort`,onAbort),e(!0)};n.addEventListener(`abort`,onAbort,{once:!0}),n.aborted&&onAbort(),Promise.resolve(r).then(()=>{n.removeEventListener(`abort`,onAbort),e(!1)},e=>{n.removeEventListener(`abort`,onAbort),t(e)})})}async remove(e,t){try{return(await this.executeScript(`remove`,[e],[t])??0)>0}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error removing item from queue`,category:this.name,error:n,code:`QueueManagerRemoveError`,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(`lPop`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:`QueueManagerPopError`,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(`llen`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:`QueueManagerLengthError`,context:{queueName:e}}),t}}isReady(){return(0,o.notMissing)(this.subscriptionManager)&&(0,o.notMissing)(this.cacheClient)&&(0,o.notMissing)(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const C=`__keyevent@0__:`,w=`${C}set`,T=`${C}expire`,E=`${C}expired`,D=`${C}srem`,O=[w,T,E],k={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,A={tryConcurrency:`
2
2
  local requestId = KEYS[1]
3
3
  local targetKey = KEYS[2]
4
4
  local queueKey = KEYS[3]
package/dist/index.d.cts CHANGED
@@ -78,6 +78,19 @@ interface ICacheClient<ClientType = unknown> {
78
78
  publish?(channel: string, message: string): Promise<number | null>;
79
79
  getClient?(): ClientType | null;
80
80
  deleteData?(key: string, groupKeys?: string[]): Promise<boolean>;
81
+ deleteDataKeyFromGroup(groupKey: string, key: string): Promise<boolean>;
82
+ setHashData<T>({
83
+ key,
84
+ entries,
85
+ cacheTTL
86
+ }: {
87
+ key: string;
88
+ entries: Record<string, T>;
89
+ cacheTTL: number;
90
+ }): Promise<boolean>;
91
+ getHashData<T>(key: string, field: string): Promise<T | null>;
92
+ getAllHashData<T>(key: string): Promise<Record<string, T> | null>;
93
+ deleteHashData(key: string, fields: string[]): Promise<number | null>;
81
94
  close?(): Promise<void> | void;
82
95
  }
83
96
  type PubSubListener<ReturnsBuffer extends boolean = false> = <T extends (ReturnsBuffer extends true ? Buffer : string)>(message: T, channel: T) => unknown;
@@ -156,6 +169,19 @@ declare class RedisClient implements ICacheClient<RedisClientType> {
156
169
  cursor?: string;
157
170
  }>;
158
171
  deleteData(key: string, groupKeys?: string[]): Promise<boolean>;
172
+ deleteDataKeyFromGroup(groupKey: string, key: string): Promise<boolean>;
173
+ setHashData<T>({
174
+ key,
175
+ entries,
176
+ cacheTTL
177
+ }: {
178
+ key: string;
179
+ entries: Record<string, T>;
180
+ cacheTTL: number;
181
+ }): Promise<boolean>;
182
+ getHashData<T>(key: string, field: string): Promise<T | null>;
183
+ getAllHashData<T>(key: string): Promise<Record<string, T> | null>;
184
+ deleteHashData(key: string, fields: string[]): Promise<number | null>;
159
185
  }
160
186
  //#endregion
161
187
  //#region src/scriptManager/types.d.ts
@@ -943,6 +969,8 @@ declare class MemoryStore<T> implements ICacheClient {
943
969
  private dataStore;
944
970
  private lockManager;
945
971
  private expiryMap;
972
+ private hashStore;
973
+ private hashExpiryMap;
946
974
  private groupMap;
947
975
  private groupExpiryMap;
948
976
  private evictionFrequency;
@@ -957,7 +985,9 @@ declare class MemoryStore<T> implements ICacheClient {
957
985
  constructor(config?: MemoryStoreConfig<T>);
958
986
  private initialize;
959
987
  getData<U = T>(key: string): Promise<U | null>;
960
- getDataKeysFromGroup(groupKey: string): Promise<string[] | null>;
988
+ getDataKeysFromGroup(groupKey: string): Promise<string[]>;
989
+ deleteDataKeyFromGroup(groupKey: string, key: string): Promise<boolean>;
990
+ private getLiveGroup;
961
991
  setData<U = T>({
962
992
  key,
963
993
  value,
@@ -981,6 +1011,20 @@ declare class MemoryStore<T> implements ICacheClient {
981
1011
  isReady(): boolean;
982
1012
  isAvailable(): boolean;
983
1013
  setTTL(key: string, cacheTTL: number): Promise<boolean>;
1014
+ private pruneExpiredHashes;
1015
+ private getLiveHash;
1016
+ setHashData<U>({
1017
+ key,
1018
+ entries,
1019
+ cacheTTL
1020
+ }: {
1021
+ key: string;
1022
+ entries: Record<string, U>;
1023
+ cacheTTL: number;
1024
+ }): Promise<boolean>;
1025
+ getHashData<U>(key: string, field: string): Promise<U | null>;
1026
+ getAllHashData<U>(key: string): Promise<Record<string, U> | null>;
1027
+ deleteHashData(key: string, fields: string[]): Promise<number | null>;
984
1028
  close(): Promise<void>;
985
1029
  listData<T>({
986
1030
  partialKey,
package/dist/index.d.mts CHANGED
@@ -77,6 +77,19 @@ interface ICacheClient<ClientType = unknown> {
77
77
  publish?(channel: string, message: string): Promise<number | null>;
78
78
  getClient?(): ClientType | null;
79
79
  deleteData?(key: string, groupKeys?: string[]): Promise<boolean>;
80
+ deleteDataKeyFromGroup(groupKey: string, key: string): Promise<boolean>;
81
+ setHashData<T>({
82
+ key,
83
+ entries,
84
+ cacheTTL
85
+ }: {
86
+ key: string;
87
+ entries: Record<string, T>;
88
+ cacheTTL: number;
89
+ }): Promise<boolean>;
90
+ getHashData<T>(key: string, field: string): Promise<T | null>;
91
+ getAllHashData<T>(key: string): Promise<Record<string, T> | null>;
92
+ deleteHashData(key: string, fields: string[]): Promise<number | null>;
80
93
  close?(): Promise<void> | void;
81
94
  }
82
95
  type PubSubListener<ReturnsBuffer extends boolean = false> = <T extends (ReturnsBuffer extends true ? Buffer : string)>(message: T, channel: T) => unknown;
@@ -155,6 +168,19 @@ declare class RedisClient implements ICacheClient<RedisClientType> {
155
168
  cursor?: string;
156
169
  }>;
157
170
  deleteData(key: string, groupKeys?: string[]): Promise<boolean>;
171
+ deleteDataKeyFromGroup(groupKey: string, key: string): Promise<boolean>;
172
+ setHashData<T>({
173
+ key,
174
+ entries,
175
+ cacheTTL
176
+ }: {
177
+ key: string;
178
+ entries: Record<string, T>;
179
+ cacheTTL: number;
180
+ }): Promise<boolean>;
181
+ getHashData<T>(key: string, field: string): Promise<T | null>;
182
+ getAllHashData<T>(key: string): Promise<Record<string, T> | null>;
183
+ deleteHashData(key: string, fields: string[]): Promise<number | null>;
158
184
  }
159
185
  //#endregion
160
186
  //#region src/scriptManager/types.d.ts
@@ -942,6 +968,8 @@ declare class MemoryStore<T> implements ICacheClient {
942
968
  private dataStore;
943
969
  private lockManager;
944
970
  private expiryMap;
971
+ private hashStore;
972
+ private hashExpiryMap;
945
973
  private groupMap;
946
974
  private groupExpiryMap;
947
975
  private evictionFrequency;
@@ -956,7 +984,9 @@ declare class MemoryStore<T> implements ICacheClient {
956
984
  constructor(config?: MemoryStoreConfig<T>);
957
985
  private initialize;
958
986
  getData<U = T>(key: string): Promise<U | null>;
959
- getDataKeysFromGroup(groupKey: string): Promise<string[] | null>;
987
+ getDataKeysFromGroup(groupKey: string): Promise<string[]>;
988
+ deleteDataKeyFromGroup(groupKey: string, key: string): Promise<boolean>;
989
+ private getLiveGroup;
960
990
  setData<U = T>({
961
991
  key,
962
992
  value,
@@ -980,6 +1010,20 @@ declare class MemoryStore<T> implements ICacheClient {
980
1010
  isReady(): boolean;
981
1011
  isAvailable(): boolean;
982
1012
  setTTL(key: string, cacheTTL: number): Promise<boolean>;
1013
+ private pruneExpiredHashes;
1014
+ private getLiveHash;
1015
+ setHashData<U>({
1016
+ key,
1017
+ entries,
1018
+ cacheTTL
1019
+ }: {
1020
+ key: string;
1021
+ entries: Record<string, U>;
1022
+ cacheTTL: number;
1023
+ }): Promise<boolean>;
1024
+ getHashData<U>(key: string, field: string): Promise<U | null>;
1025
+ getAllHashData<U>(key: string): Promise<Record<string, U> | null>;
1026
+ deleteHashData(key: string, fields: string[]): Promise<number | null>;
983
1027
  close(): Promise<void>;
984
1028
  listData<T>({
985
1029
  partialKey,
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{t as e}from"./chunk-BhWHdk3m.mjs";import{delay as t,exponentialBackoffInMS as n,generateRequestId as r,getContentHash as i,isFunction as a,isFutureUnixTimestamp as o,isMissing as s,isNumber as c,isObject as l,isString as u,notMissing as d,z as f,zStrictObject as p}from"@stackone/utils";import*as m from"redis";import{evaluate as h,safeEvaluate as g}from"@stackone/expressions";import _,{isAxiosError as v}from"axios";import y from"node:https";import{createHash as b,createHmac as x,randomUUID as S}from"crypto";import{clearTimeout as C}from"node:timers";import{hasNumericValue as w,isString as T}from"mathjs";import{JSONPath as E}from"jsonpath-plus";import{redactFields as D,redactUrl as O}from"@stackone/redaction";import k from"qs";import{XMLBuilder as A,XMLParser as j,XMLValidator as M}from"fast-xml-parser";const createAuthorizationHeaders=e=>{switch(e.type){case`none`:return{};case`basic`:return createBasicAuthorizationHeader(e);case`bearer`:return createBearerAuthorizationHeader(e);case`oauth2`:return createBearerAuthorizationHeader(e);default:throw Error(`Invalid authentication type`)}},createBasicAuthorizationHeader=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n;return{authorization:`Basic ${Buffer.from(`${e}:${t}`).toString(r)}`}},createBearerAuthorizationHeader=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var LockManager=class{constructor(){this.locks=new Map}async withLock(e,t){await this.lock(e);try{return t()}finally{this.unlock(e)}}async lock(e){let t,n=new Promise(e=>t=e),r=this.locks.has(e),i=this.locks.get(e);r&&i?(i.push({lock:n,unlock:t}),await i[i.length-2].lock):this.locks.set(e,[{lock:n,unlock:t}])}unlock(e){let t=this.locks.has(e),n=this.locks.get(e);if(t&&n&&n.length>0){let e=n.shift()?.unlock;e?.()}this.queueLength(e)===0&&this.locks.delete(e)}queueLength(e){return this.locks.get(e)?.length}close(){this.locks.clear()}};const N=1e3;var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async getDataKeysFromGroup(e){this.isReady()||this.initialize(),this.updateLastAccessedAt();let t=this.groupExpiryMap.get(e);return d(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),[]):Array.from(this.groupMap.get(e)??[])}async setData({key:e,value:t,cacheTTL:n=60,groupKeys:r,groupKeyTTL:i}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),d(this.typeGuard)&&!this.typeGuard(t))return!1;let a=n*N,o=Date.now()+a;if(await this.lockManager.withLock(e,async()=>{(d(this.typeGuard)&&this.typeGuard(t)||s(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,o)}),d(r)&&r.length>0){let t=d(i)&&Number.isFinite(i)&&i>0?i*N:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,new Set),this.groupMap.get(n)?.add(e),d(t)&&this.groupExpiryMap.set(n,Date.now()+t)}return!0}typeGuardBypass(e){return this.logger?.debug({category:`MemoryStore`,message:`${this.instantiator} MemoryStore setting data without type guard - you should probably configure one`}),!0}async delete(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{if(this.dispose){let t=this.dataStore.get(e);await this.dispose(e,t)}if(d(t)&&t.length>0)for(let n of t)this.groupMap.get(n)?.delete(e);return this.expiryMap.delete(e),this.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=[],i=0;return this.dataStore.forEach((e,a)=>{let o=Date.now(),s=this.expiryMap.get(a)??0,c=this.truncateThreshold*this.truncationPercentage/100;(s<=o||t&&i>=0&&i<=c)&&(r.push(a),n.push(this.lockManager.withLock(a,async()=>(this.dispose&&await this.dispose(a,e),this.expiryMap.delete(a),this.dataStore.delete(a))))),i++}),await Promise.all(n),this.removeKeysFromGroups(r),{dataStoreSize:e,prunedDataStoreSize:this.dataStore.size}}removeKeysFromGroups(e){if(e.length===0)return;let t=new Set(e);for(let e of this.groupMap.values())for(let n of e)t.has(n)&&!this.dataStore.has(n)&&e.delete(n)}startEvictionTask(){if(d(this.evictionInterval))return;let executePrune=async()=>{let e;try{if(this.lastAccessedAt+this.staleDataThreshold<Date.now()){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),await this.close();return}e=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}catch(e){e instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:e,code:`MemoryStorePruneError`}),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}finally{if(d(e?.dataStoreSize)&&d(e?.prunedDataStoreSize)){let{dataStoreSize:t,prunedDataStoreSize:n}=e,r=t-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&=(clearTimeout(this.evictionInterval),void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return d(this.evictionInterval)&&d(this.dataStore)&&d(this.expiryMap)&&d(this.lockManager)}isAvailable(){return this.isReady()}async setTTL(e,t){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),!this.dataStore.has(e)||!Number.isFinite(t)||t<=0)return!1;let n=t*N;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n)}),!0}async close(){this.stopEvictionTask(),this.dispose&&await Promise.all(Array.from(this.dataStore,async([e,t])=>{try{await this.dispose?.(e,t)}catch(t){this.logger?.error({message:`Failed to dispose entry "${e}" during close`,category:`MemoryStore`,error:t,code:`MemoryStoreDisposeError`})}})),this.dataStore.clear(),this.expiryMap.clear(),this.groupMap.clear(),this.groupExpiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()).filter(t=>t.includes(e)),i=[],a=t?parseInt(t,10):0;for(let e=a;e<n+a;e++){let t=r[e];if(!t)break;let a=await this.getData(t);if(a&&i.push(a),i.length>=n)break}return{items:i,cursor:i.length<n?void 0:(a+n).toString()}}},EventClient=class{constructor(e,t,n){this.executorMethodStore=null,this.promiseStore=null,this.eventClientConfig=null,this.executorMethodStoreConfig=null,this.pendingPromiseStoreConfig=null,this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new MemoryStore(i),this.promiseStore=new MemoryStore(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/1e3;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return d(n)?n:(await this.setPendingEvent(e,t),this.getPendingEvent(e))}async getPendingEvent(e){return this.promiseStore?.getData(e)??null}async deleteEvent(e){return(await Promise.all([this.promiseStore?.delete(e),this.executorMethodStore?.delete(e)])).every(Boolean)}async resolveEvent(e,t){try{let n=await this.executorMethodStore?.getData(e);s(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??6e4),n=await this.executorMethodStore?.getData(e)),n?.resolve?.(t)}catch(t){t instanceof Error&&this.logger.error({message:`Error handling event for key ${e}: ${t.message}`,category:this.constructor.name,context:{eventKey:e},error:t,code:`EventClientResolveError`})}}async defaultExecutorMethodDispose(e,t){d(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):d(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return l(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[]}getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:(s(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,s(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await P.build(e,t,n)??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:`RedisClientError`,category:n??`buildRedisClientInstance`});return}};var P=class RedisClient{#e;#t;static async build({getRedisClient:e=m.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o},s,c){let l=new RedisClient;l.#t=s;try{l.#e=e({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:t,port:n,keepAlive:i,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,disableOfflineQueue:!0});let s=getDefaultRedisListeners(c??`RedisClient`,l.#t);return addRedisEventHandlers(l.#e,s),await l.#e.connect(),l}catch(e){let t=e;return l.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:c??`RedisClient`}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}async getData(e){if(!this.#i())return null;try{let t=await this.#e.get(e);if(!t)return null;let n=this.#n(t);return u(n)?t:n}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getDataKeysFromGroup(e){if(!this.#i())return null;try{return await this.#e.sMembers(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting data from group`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i}){if(!this.#i())return!1;try{let a=u(t)?t:JSON.stringify(t);if(await this.#e.set(e,a,{EX:n}),d(r)&&r.length>0)for(let t of r)await this.#e.sAdd(t,[e]),d(i)&&Number.isFinite(i)&&i>0&&await this.#e.expire(t,i);return!0}catch(e){let t=e;return this.#t?.error({message:`Error setting data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async setTTL(e,t){if(!this.#i())return!1;if(!Number.isFinite(t)||t<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;try{let n=await this.#e.expire(e,t);return n||this.#t?.debug({message:`No keys updated for ${e}`,category:RedisClient.name}),n}catch(e){let t=e;return this.#t?.error({message:`Error resetting data TTL`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async executeScript({sha1:e,keys:t,args:n}){if(!this.#i())return null;try{return await this.#e.evalSha(e,{keys:t,arguments:n})}catch(e){let t=e;throw this.#t?.error({message:`Error executing script`,error:t,code:`RedisClientScriptExecuteError`,category:RedisClient.name}),t}}async loadScript(e){if(!this.#i())return null;try{return await this.#e.scriptLoad(e)}catch(e){let t=e;return this.#t?.error({message:`Error loading script`,error:t,code:`RedisClientScriptLoadError`,category:RedisClient.name}),null}}async scriptExists(e){if(!this.#i())return e.map(()=>!1);try{return(await this.#e.scriptExists(e)).map(e=>!!e)}catch(t){let n=t;return this.#t?.error({message:`Error checking script existence`,error:n,code:`RedisClientScriptError`,category:RedisClient.name}),e.map(()=>!1)}}async#r(e,t,n){if(!this.#i())return null;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),null;try{let r=[{args:[e,t]},{args:[`expire`,t,n.toString()]}],i=(await this.#e.multiExecutor(r))?.[0];return typeof i==`number`?i:null}catch(t){let n=t;return this.#t?.error({message:`Error executing ${e} operation`,error:n,code:`RedisClientCommandError`,category:RedisClient.name}),null}}async increment(e,t){return this.#r(`incr`,e,t)}async decrement(e,t){return this.#r(`decr`,e,t)}async subscribe(e,t){if(!this.#i())return!1;try{return await this.#e.pSubscribe(e,t),!0}catch(t){let n=t;return this.#t?.error({message:`Error subscribing to ${e}`,error:n,code:`RedisClientSubscribeError`,category:RedisClient.name}),!1}}async unsubscribe(e){if(!this.#i())return!1;try{return await this.#e.pUnsubscribe(e),!0}catch(t){let n=t;return this.#t?.error({message:`Error unsubscribing from ${e}`,error:n,code:`RedisClientUnsubscribeError`,category:RedisClient.name}),!1}}async publish(e,t){if(!this.#i())return null;try{let n=await this.#e.publish(e,t);return n===0&&this.#t?.debug({message:`No subscribers found for channel ${e}`,category:RedisClient.name}),n}catch(t){let n=t;return this.#t?.error({message:`Error publishing to ${e}`,error:n,code:`RedisClientPublishError`,category:RedisClient.name}),null}}getClient(){return this.#i()?this.#e:null}isAvailable(){return this.#e.isReady&&this.#e.isOpen}async close(){try{this.#e.isOpen&&await this.#e.quit()}catch(e){try{await this.#e.disconnect()}catch{}this.#t?.error({message:`Error gracefully closing Redis client, forced disconnect`,error:e,code:`RedisClientError`,category:RedisClient.name})}}#i(){let e=this.isAvailable();return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:`RedisClientRedisNotReady`}),e}async listData({partialKey:e,limit:t,cursor:n}){try{let r=n?parseInt(n,10):0,i=await this.#e.sScan(e,r,{COUNT:t}),a=[];for(let e of i.members){let t=await this.getData(e);d(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(e){let t=e;return this.#t?.error({message:`Error listing data`,error:t,code:`RedisClientListError`,category:RedisClient.name}),{items:null}}}async deleteData(e,t){try{if(!this.#i())return!1;let n=await this.#e.del(e);return n===0&&this.#t?.debug({message:`No keys deleted for ${e}`,category:RedisClient.name}),d(t)&&t.length>0&&(await Promise.allSettled(t.map(t=>this.#e.sRem(t,e)))).forEach((e,n)=>{e.status===`rejected`&&this.#t?.error({message:`Error removing key from group set ${t[n]}`,error:e.reason,code:`RedisClientDeleteError`,category:RedisClient.name})}),n>0}catch(e){let t=e;return this.#t?.error({message:`Error deleting data`,error:t,code:`RedisClientDeleteError`,category:RedisClient.name}),!1}}};const addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:`RedisClientError`,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0}async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let o=t??await buildRedisClientInstance(e,i,this.name);if(s(o))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=o,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();d(e)&&(e.on(`ready`,async()=>{this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){if(d(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!(s(this.scripts)||Object.keys(this.scripts).length===0)){this.reloadInProgress=this.performReload();try{await this.reloadInProgress}finally{this.reloadInProgress=null}}}async performReload(){this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts),this.lastReloadTime=Date.now()}async loadScripts(e,t){if(d(t))for(let[e,n]of t)this.scriptMap.set(e,n);let n=Object.entries(e),r=n.map(([e])=>this.scriptMap.get(e)).filter(d),i=new Map;if(r.length>0&&d(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if(d(e)){r.forEach((t,n)=>{i.set(t,e[n]??!1)});let t=e.filter(Boolean).length;t>0&&this.logger?.info({message:`${t}/${r.length} scripts already exist in Redis; skipping load for existing scripts`,category:this.name})}}for(let[e,t]of n){let n=this.scriptMap.get(e);if(n&&i.get(n))continue;let r=await this.cacheClient?.loadScript?.(t);d(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:`ScriptManagerLoadingError`})}}async executeScript(e,n,r){if(!this.isRedisReady())return this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:n,args:r}}),null;let i=this.scriptMap?.get(e);if(s(i))throw this.logger?.error({message:`Script for ${e} not found in script map`,category:this.name,code:`ScriptManagerExecutionError`}),Error(`Script for ${e} not found`);try{return await this.cacheClient?.executeScript?.({sha1:i,keys:n,args:r})??null}catch(a){if(a instanceof Error&&a.message.includes(`NOSCRIPT`)){let a=Date.now()-this.lastReloadTime;if(a<1500){let n=1500-a;this.logger?.info({message:`Script ${e} not found, reload occurred ${a}ms ago. Waiting ${n}ms before reloading`,category:this.name}),await t(n)}if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),i=this.scriptMap?.get(e),s(i))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:i,keys:n,args:r})??null}throw a instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${a.message}`,category:this.name,context:{keys:n,args:r},error:a,code:`ScriptManagerExecutionError`}),a}}isRedisReady(){let e=this.cacheClient?.getClient?.();if(d(this.cacheClient)&&s(e))return this.logger?.warning({message:`Cache client exists but getClient() returned null - cannot verify Redis readiness`,category:this.name}),!1;let t=e?.isReady&&e?.isOpen;return this.isReady()&&d(this.cacheClient)&&(t??!1)}},SubscriptionManager=class{constructor(e){this.options={getCacheClient:buildRedisClientInstance},this.subscriptionMap=null,this.subscriptionClient=null,this.name=`SubscriptionManager`,this.options={...this.options,...e}}async initialize(e=this.options){let{config:t,getCacheClient:n,logger:r}=e;if(this.logger=r,this.subscriptionMap=new MemoryStore({instantiator:`${e?.instantiator}(${this.name})`,evictionFrequency:e?.subscriptionTTL,staleDataThreshold:e?.staleSubscriptionsThreshold,truncateThreshold:e?.truncateThreshold,truncationPercentage:e?.truncationPercentage,typeGuard:e=>typeof e==`string`,dispose:async e=>{await this.subscriptionClient?.unsubscribe?.(e)}}),d(t))this.subscriptionClient=await n?.(t,this.logger,e?.instantiator)??null,this.logger?.info({message:`${this.name} initialized for ${e.instantiator}.`,category:this.name});else throw Error(`SubscriptionManager requires a Redis client configuration.`)}async subscribe(e,t){this.isReady()||await this.initialize(this.options);let n=await this.subscriptionMap?.getData(e),r=i(t.toString());return await this.subscriptionMap?.setData({key:e,value:r}),n===r?!0:await this.subscriptionClient?.subscribe?.(e,t)??!1}async unsubscribe(e){return this.isReady()||await this.initialize(this.options),this.subscriptionClient?.unsubscribe?.(e)??!1}isReady(){return d(this.subscriptionClient)&&d(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionClient?.close?.(),this.subscriptionMap=null,this.subscriptionClient=null}};const F=15e3,I=15e3,L=1e4;var QueueManager=class extends ScriptManager{constructor(...e){super(...e),this.subscriptionManager=null,this.eventClient=null,this.name=`QueueManager`}async additionalInitialization(){if(s(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:6e4,truncateThreshold:L,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:I,truncateThreshold:L,truncationPercentage:1},{instantiator:this.name,evictionFrequency:I,truncateThreshold:L,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=F,o){try{let s=`${e}:${t}`;await this.subscriptionManager?.subscribe(s,async(n,r)=>{if(r.includes(s)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let c=await this.executeScript(n?`lPush`:`rPush`,[e],[t,`60000`])===1,l=!i||!c?await this.waitForTurnOrAbort(s,a,o):o?.aborted===!0;return await this.eventClient?.deleteEvent(s),l||o?.aborted===!0?null:await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:`QueueManagerJoinAndWaitTurnError`,context:{queueName:e,value:t}}),n}}async waitForTurnOrAbort(e,t,n){if(d(n)&&n.aborted)return!0;let r=this.eventClient?.waitForEvent(e,t);return s(n)?(await r,!1):await new Promise((e,t)=>{let onAbort=()=>{n.removeEventListener(`abort`,onAbort),e(!0)};n.addEventListener(`abort`,onAbort,{once:!0}),n.aborted&&onAbort(),Promise.resolve(r).then(()=>{n.removeEventListener(`abort`,onAbort),e(!1)},e=>{n.removeEventListener(`abort`,onAbort),t(e)})})}async remove(e,t){try{return(await this.executeScript(`remove`,[e],[t])??0)>0}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error removing item from queue`,category:this.name,error:n,code:`QueueManagerRemoveError`,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(`lPop`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:`QueueManagerPopError`,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(`llen`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:`QueueManagerLengthError`,context:{queueName:e}}),t}}isReady(){return d(this.subscriptionManager)&&d(this.cacheClient)&&d(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const R=`__keyevent@0__:`,z=`${R}set`,ee=`${R}expire`,B=`${R}expired`,V=`${R}srem`,te=[z,ee,B],ne={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,re={tryConcurrency:`
1
+ import{t as e}from"./chunk-BhWHdk3m.mjs";import{delay as t,exponentialBackoffInMS as n,generateRequestId as r,getContentHash as i,isFunction as a,isFutureUnixTimestamp as o,isMissing as s,isNumber as c,isObject as l,isString as u,notMissing as d,z as f,zStrictObject as p}from"@stackone/utils";import*as m from"redis";import{evaluate as h,safeEvaluate as g}from"@stackone/expressions";import _,{isAxiosError as v}from"axios";import y from"node:https";import{createHash as b,createHmac as x,randomUUID as S}from"crypto";import{clearTimeout as C}from"node:timers";import{hasNumericValue as w,isString as T}from"mathjs";import{JSONPath as E}from"jsonpath-plus";import{redactFields as D,redactUrl as O}from"@stackone/redaction";import k from"qs";import{XMLBuilder as A,XMLParser as j,XMLValidator as M}from"fast-xml-parser";const createAuthorizationHeaders=e=>{switch(e.type){case`none`:return{};case`basic`:return createBasicAuthorizationHeader(e);case`bearer`:return createBearerAuthorizationHeader(e);case`oauth2`:return createBearerAuthorizationHeader(e);default:throw Error(`Invalid authentication type`)}},createBasicAuthorizationHeader=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n;return{authorization:`Basic ${Buffer.from(`${e}:${t}`).toString(r)}`}},createBearerAuthorizationHeader=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var LockManager=class{constructor(){this.locks=new Map}async withLock(e,t){await this.lock(e);try{return t()}finally{this.unlock(e)}}async lock(e){let t,n=new Promise(e=>t=e),r=this.locks.has(e),i=this.locks.get(e);r&&i?(i.push({lock:n,unlock:t}),await i[i.length-2].lock):this.locks.set(e,[{lock:n,unlock:t}])}unlock(e){let t=this.locks.has(e),n=this.locks.get(e);if(t&&n&&n.length>0){let e=n.shift()?.unlock;e?.()}this.queueLength(e)===0&&this.locks.delete(e)}queueLength(e){return this.locks.get(e)?.length}close(){this.locks.clear()}};const N=1e3;var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.hashStore=new Map,this.hashExpiryMap=new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async getDataKeysFromGroup(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),Array.from(this.getLiveGroup(e)??[])}async deleteDataKeyFromGroup(e,t){this.isReady()||this.initialize(),this.updateLastAccessedAt();let n=this.getLiveGroup(e);if(s(n))return!1;let r=n.delete(t);return n.size===0&&(this.groupMap.delete(e),this.groupExpiryMap.delete(e)),r}getLiveGroup(e){let t=this.groupExpiryMap.get(e);return d(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),null):this.groupMap.get(e)??null}async setData({key:e,value:t,cacheTTL:n=60,groupKeys:r,groupKeyTTL:i}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),d(this.typeGuard)&&!this.typeGuard(t))return!1;let a=n*N,o=Date.now()+a;if(await this.lockManager.withLock(e,async()=>{(d(this.typeGuard)&&this.typeGuard(t)||s(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,o)}),d(r)&&r.length>0){let t=d(i)&&Number.isFinite(i)&&i>0?i*N:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,new Set),this.groupMap.get(n)?.add(e),d(t)&&this.groupExpiryMap.set(n,Date.now()+t)}return!0}typeGuardBypass(e){return this.logger?.debug({category:`MemoryStore`,message:`${this.instantiator} MemoryStore setting data without type guard - you should probably configure one`}),!0}async delete(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{if(this.dispose){let t=this.dataStore.get(e);await this.dispose(e,t)}if(d(t)&&t.length>0)for(let n of t)this.groupMap.get(n)?.delete(e);return this.expiryMap.delete(e),this.dataStore.delete(e)})}async pruneExpiredKeys(){this.pruneExpiredHashes();let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=[],i=0;return this.dataStore.forEach((e,a)=>{let o=Date.now(),s=this.expiryMap.get(a)??0,c=this.truncateThreshold*this.truncationPercentage/100;(s<=o||t&&i>=0&&i<=c)&&(r.push(a),n.push(this.lockManager.withLock(a,async()=>(this.dispose&&await this.dispose(a,e),this.expiryMap.delete(a),this.dataStore.delete(a))))),i++}),await Promise.all(n),this.removeKeysFromGroups(r),{dataStoreSize:e,prunedDataStoreSize:this.dataStore.size}}removeKeysFromGroups(e){if(e.length===0)return;let t=new Set(e);for(let e of this.groupMap.values())for(let n of e)t.has(n)&&!this.dataStore.has(n)&&e.delete(n)}startEvictionTask(){if(d(this.evictionInterval))return;let executePrune=async()=>{let e;try{if(this.lastAccessedAt+this.staleDataThreshold<Date.now()){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),await this.close();return}e=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}catch(e){e instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:e,code:`MemoryStorePruneError`}),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}finally{if(d(e?.dataStoreSize)&&d(e?.prunedDataStoreSize)){let{dataStoreSize:t,prunedDataStoreSize:n}=e,r=t-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&=(clearTimeout(this.evictionInterval),void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return d(this.evictionInterval)&&d(this.dataStore)&&d(this.expiryMap)&&d(this.lockManager)}isAvailable(){return this.isReady()}async setTTL(e,t){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),!this.dataStore.has(e)||!Number.isFinite(t)||t<=0)return!1;let n=t*N;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n)}),!0}pruneExpiredHashes(){let e=Date.now();for(let[t,n]of this.hashExpiryMap)n<=e&&(this.hashStore.delete(t),this.hashExpiryMap.delete(t))}getLiveHash(e){let t=this.hashExpiryMap.get(e);return d(t)&&t<=Date.now()?(this.hashStore.delete(e),this.hashExpiryMap.delete(e),null):this.hashStore.get(e)??null}async setHashData({key:e,entries:t,cacheTTL:n}){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),!Number.isFinite(n)||n<=0||Object.keys(t).length===0?!1:this.lockManager.withLock(e,async()=>{let r=this.getLiveHash(e)??new Map;return Object.entries(t).forEach(([e,t])=>{r.set(e,t)}),this.hashStore.set(e,r),this.hashExpiryMap.set(e,Date.now()+n*N),!0})}async getHashData(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.getLiveHash(e)?.get(t)??null)}async getAllHashData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{let t=this.getLiveHash(e);return s(t)||t.size===0?null:Object.fromEntries(t)})}async deleteHashData(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{let n=this.getLiveHash(e);if(s(n))return 0;let r=t.filter(e=>n.delete(e)).length;return n.size===0&&(this.hashStore.delete(e),this.hashExpiryMap.delete(e)),r})}async close(){this.stopEvictionTask(),this.dispose&&await Promise.all(Array.from(this.dataStore,async([e,t])=>{try{await this.dispose?.(e,t)}catch(t){this.logger?.error({message:`Failed to dispose entry "${e}" during close`,category:`MemoryStore`,error:t,code:`MemoryStoreDisposeError`})}})),this.dataStore.clear(),this.expiryMap.clear(),this.hashStore.clear(),this.hashExpiryMap.clear(),this.groupMap.clear(),this.groupExpiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()).filter(t=>t.includes(e)),i=[],a=t?parseInt(t,10):0;for(let e=a;e<n+a;e++){let t=r[e];if(!t)break;let a=await this.getData(t);if(a&&i.push(a),i.length>=n)break}return{items:i,cursor:i.length<n?void 0:(a+n).toString()}}},EventClient=class{constructor(e,t,n){this.executorMethodStore=null,this.promiseStore=null,this.eventClientConfig=null,this.executorMethodStoreConfig=null,this.pendingPromiseStoreConfig=null,this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new MemoryStore(i),this.promiseStore=new MemoryStore(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/1e3;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return d(n)?n:(await this.setPendingEvent(e,t),this.getPendingEvent(e))}async getPendingEvent(e){return this.promiseStore?.getData(e)??null}async deleteEvent(e){return(await Promise.all([this.promiseStore?.delete(e),this.executorMethodStore?.delete(e)])).every(Boolean)}async resolveEvent(e,t){try{let n=await this.executorMethodStore?.getData(e);s(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??6e4),n=await this.executorMethodStore?.getData(e)),n?.resolve?.(t)}catch(t){t instanceof Error&&this.logger.error({message:`Error handling event for key ${e}: ${t.message}`,category:this.constructor.name,context:{eventKey:e},error:t,code:`EventClientResolveError`})}}async defaultExecutorMethodDispose(e,t){d(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):d(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return l(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[]}getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:(s(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,s(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await P.build(e,t,n)??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:`RedisClientError`,category:n??`buildRedisClientInstance`});return}};var P=class RedisClient{#e;#t;static async build({getRedisClient:e=m.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o},s,c){let l=new RedisClient;l.#t=s;try{l.#e=e({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:t,port:n,keepAlive:i,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,disableOfflineQueue:!0});let s=getDefaultRedisListeners(c??`RedisClient`,l.#t);return addRedisEventHandlers(l.#e,s),await l.#e.connect(),l}catch(e){let t=e;return l.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:c??`RedisClient`}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}async getData(e){if(!this.#i())return null;try{let t=await this.#e.get(e);if(!t)return null;let n=this.#n(t);return u(n)?t:n}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getDataKeysFromGroup(e){if(!this.#i())return null;try{return await this.#e.sMembers(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting data from group`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i}){if(!this.#i())return!1;try{let a=u(t)?t:JSON.stringify(t);if(await this.#e.set(e,a,{EX:n}),d(r)&&r.length>0)for(let t of r)await this.#e.sAdd(t,[e]),d(i)&&Number.isFinite(i)&&i>0&&await this.#e.expire(t,i);return!0}catch(e){let t=e;return this.#t?.error({message:`Error setting data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async setTTL(e,t){if(!this.#i())return!1;if(!Number.isFinite(t)||t<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;try{let n=await this.#e.expire(e,t);return n||this.#t?.debug({message:`No keys updated for ${e}`,category:RedisClient.name}),n}catch(e){let t=e;return this.#t?.error({message:`Error resetting data TTL`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async executeScript({sha1:e,keys:t,args:n}){if(!this.#i())return null;try{return await this.#e.evalSha(e,{keys:t,arguments:n})}catch(e){let t=e;throw this.#t?.error({message:`Error executing script`,error:t,code:`RedisClientScriptExecuteError`,category:RedisClient.name}),t}}async loadScript(e){if(!this.#i())return null;try{return await this.#e.scriptLoad(e)}catch(e){let t=e;return this.#t?.error({message:`Error loading script`,error:t,code:`RedisClientScriptLoadError`,category:RedisClient.name}),null}}async scriptExists(e){if(!this.#i())return e.map(()=>!1);try{return(await this.#e.scriptExists(e)).map(e=>!!e)}catch(t){let n=t;return this.#t?.error({message:`Error checking script existence`,error:n,code:`RedisClientScriptError`,category:RedisClient.name}),e.map(()=>!1)}}async#r(e,t,n){if(!this.#i())return null;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),null;try{let r=[{args:[e,t]},{args:[`expire`,t,n.toString()]}],i=(await this.#e.multiExecutor(r))?.[0];return typeof i==`number`?i:null}catch(t){let n=t;return this.#t?.error({message:`Error executing ${e} operation`,error:n,code:`RedisClientCommandError`,category:RedisClient.name}),null}}async increment(e,t){return this.#r(`incr`,e,t)}async decrement(e,t){return this.#r(`decr`,e,t)}async subscribe(e,t){if(!this.#i())return!1;try{return await this.#e.pSubscribe(e,t),!0}catch(t){let n=t;return this.#t?.error({message:`Error subscribing to ${e}`,error:n,code:`RedisClientSubscribeError`,category:RedisClient.name}),!1}}async unsubscribe(e){if(!this.#i())return!1;try{return await this.#e.pUnsubscribe(e),!0}catch(t){let n=t;return this.#t?.error({message:`Error unsubscribing from ${e}`,error:n,code:`RedisClientUnsubscribeError`,category:RedisClient.name}),!1}}async publish(e,t){if(!this.#i())return null;try{let n=await this.#e.publish(e,t);return n===0&&this.#t?.debug({message:`No subscribers found for channel ${e}`,category:RedisClient.name}),n}catch(t){let n=t;return this.#t?.error({message:`Error publishing to ${e}`,error:n,code:`RedisClientPublishError`,category:RedisClient.name}),null}}getClient(){return this.#i()?this.#e:null}isAvailable(){return this.#e.isReady&&this.#e.isOpen}async close(){try{this.#e.isOpen&&await this.#e.quit()}catch(e){try{await this.#e.disconnect()}catch{}this.#t?.error({message:`Error gracefully closing Redis client, forced disconnect`,error:e,code:`RedisClientError`,category:RedisClient.name})}}#i(){let e=this.isAvailable();return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:`RedisClientRedisNotReady`}),e}async listData({partialKey:e,limit:t,cursor:n}){try{let r=n?parseInt(n,10):0,i=await this.#e.sScan(e,r,{COUNT:t}),a=[];for(let e of i.members){let t=await this.getData(e);d(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(e){let t=e;return this.#t?.error({message:`Error listing data`,error:t,code:`RedisClientListError`,category:RedisClient.name}),{items:null}}}async deleteData(e,t){try{if(!this.#i())return!1;let n=await this.#e.del(e);return n===0&&this.#t?.debug({message:`No keys deleted for ${e}`,category:RedisClient.name}),d(t)&&t.length>0&&(await Promise.allSettled(t.map(t=>this.#e.sRem(t,e)))).forEach((e,n)=>{e.status===`rejected`&&this.#t?.error({message:`Error removing key from group set ${t[n]}`,error:e.reason,code:`RedisClientDeleteError`,category:RedisClient.name})}),n>0}catch(e){let t=e;return this.#t?.error({message:`Error deleting data`,error:t,code:`RedisClientDeleteError`,category:RedisClient.name}),!1}}async deleteDataKeyFromGroup(e,t){if(!this.#i())return!1;try{let n=await this.#e.sRem(e,t);return n===0&&this.#t?.debug({message:`No keys removed from group ${e}`,category:RedisClient.name}),n>0}catch(t){let n=t;return this.#t?.error({message:`Error removing key from group set ${e}`,error:n,code:`RedisClientDeleteError`,category:RedisClient.name}),!1}}async setHashData({key:e,entries:t,cacheTTL:n}){if(!this.#i())return!1;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;let r=Object.entries(t);if(r.length===0)return!1;try{let t=r.flatMap(([e,t])=>[e,u(t)?t:JSON.stringify(t)]);return await this.#e.multiExecutor([{args:[`hset`,e,...t]},{args:[`expire`,e,n.toString()]}]),!0}catch(e){let t=e;return this.#t?.error({message:`Error setting hash data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async getHashData(e,t){if(!this.#i())return null;try{let n=await this.#e.hGet(e,t);if(n!==``&&s(n))return null;let r=this.#n(n);return u(r)?n:r}catch(e){let t=e;return this.#t?.error({message:`Error getting hash data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getAllHashData(e){if(!this.#i())return null;try{let t=await this.#e.hGetAll(e);return Object.keys(t).length===0?null:Object.fromEntries(Object.entries(t).map(([e,t])=>{let n=this.#n(t);return[e,u(n)?t:n]}))}catch(e){let t=e;return this.#t?.error({message:`Error getting all hash data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async deleteHashData(e,t){if(!this.#i())return null;if(t.length===0)return 0;try{return await this.#e.hDel(e,t)}catch(e){let t=e;return this.#t?.error({message:`Error deleting hash data`,error:t,code:`RedisClientDeleteError`,category:RedisClient.name}),null}}};const addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:`RedisClientError`,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0}async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let o=t??await buildRedisClientInstance(e,i,this.name);if(s(o))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=o,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();d(e)&&(e.on(`ready`,async()=>{this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){if(d(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!(s(this.scripts)||Object.keys(this.scripts).length===0)){this.reloadInProgress=this.performReload();try{await this.reloadInProgress}finally{this.reloadInProgress=null}}}async performReload(){this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts),this.lastReloadTime=Date.now()}async loadScripts(e,t){if(d(t))for(let[e,n]of t)this.scriptMap.set(e,n);let n=Object.entries(e),r=n.map(([e])=>this.scriptMap.get(e)).filter(d),i=new Map;if(r.length>0&&d(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if(d(e)){r.forEach((t,n)=>{i.set(t,e[n]??!1)});let t=e.filter(Boolean).length;t>0&&this.logger?.info({message:`${t}/${r.length} scripts already exist in Redis; skipping load for existing scripts`,category:this.name})}}for(let[e,t]of n){let n=this.scriptMap.get(e);if(n&&i.get(n))continue;let r=await this.cacheClient?.loadScript?.(t);d(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:`ScriptManagerLoadingError`})}}async executeScript(e,n,r){if(!this.isRedisReady())return this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:n,args:r}}),null;let i=this.scriptMap?.get(e);if(s(i))throw this.logger?.error({message:`Script for ${e} not found in script map`,category:this.name,code:`ScriptManagerExecutionError`}),Error(`Script for ${e} not found`);try{return await this.cacheClient?.executeScript?.({sha1:i,keys:n,args:r})??null}catch(a){if(a instanceof Error&&a.message.includes(`NOSCRIPT`)){let a=Date.now()-this.lastReloadTime;if(a<1500){let n=1500-a;this.logger?.info({message:`Script ${e} not found, reload occurred ${a}ms ago. Waiting ${n}ms before reloading`,category:this.name}),await t(n)}if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),i=this.scriptMap?.get(e),s(i))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:i,keys:n,args:r})??null}throw a instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${a.message}`,category:this.name,context:{keys:n,args:r},error:a,code:`ScriptManagerExecutionError`}),a}}isRedisReady(){let e=this.cacheClient?.getClient?.();if(d(this.cacheClient)&&s(e))return this.logger?.warning({message:`Cache client exists but getClient() returned null - cannot verify Redis readiness`,category:this.name}),!1;let t=e?.isReady&&e?.isOpen;return this.isReady()&&d(this.cacheClient)&&(t??!1)}},SubscriptionManager=class{constructor(e){this.options={getCacheClient:buildRedisClientInstance},this.subscriptionMap=null,this.subscriptionClient=null,this.name=`SubscriptionManager`,this.options={...this.options,...e}}async initialize(e=this.options){let{config:t,getCacheClient:n,logger:r}=e;if(this.logger=r,this.subscriptionMap=new MemoryStore({instantiator:`${e?.instantiator}(${this.name})`,evictionFrequency:e?.subscriptionTTL,staleDataThreshold:e?.staleSubscriptionsThreshold,truncateThreshold:e?.truncateThreshold,truncationPercentage:e?.truncationPercentage,typeGuard:e=>typeof e==`string`,dispose:async e=>{await this.subscriptionClient?.unsubscribe?.(e)}}),d(t))this.subscriptionClient=await n?.(t,this.logger,e?.instantiator)??null,this.logger?.info({message:`${this.name} initialized for ${e.instantiator}.`,category:this.name});else throw Error(`SubscriptionManager requires a Redis client configuration.`)}async subscribe(e,t){this.isReady()||await this.initialize(this.options);let n=await this.subscriptionMap?.getData(e),r=i(t.toString());return await this.subscriptionMap?.setData({key:e,value:r}),n===r?!0:await this.subscriptionClient?.subscribe?.(e,t)??!1}async unsubscribe(e){return this.isReady()||await this.initialize(this.options),this.subscriptionClient?.unsubscribe?.(e)??!1}isReady(){return d(this.subscriptionClient)&&d(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionClient?.close?.(),this.subscriptionMap=null,this.subscriptionClient=null}};const F=15e3,I=15e3,L=1e4;var QueueManager=class extends ScriptManager{constructor(...e){super(...e),this.subscriptionManager=null,this.eventClient=null,this.name=`QueueManager`}async additionalInitialization(){if(s(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:6e4,truncateThreshold:L,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:I,truncateThreshold:L,truncationPercentage:1},{instantiator:this.name,evictionFrequency:I,truncateThreshold:L,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=F,o){try{let s=`${e}:${t}`;await this.subscriptionManager?.subscribe(s,async(n,r)=>{if(r.includes(s)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let c=await this.executeScript(n?`lPush`:`rPush`,[e],[t,`60000`])===1,l=!i||!c?await this.waitForTurnOrAbort(s,a,o):o?.aborted===!0;return await this.eventClient?.deleteEvent(s),l||o?.aborted===!0?null:await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:`QueueManagerJoinAndWaitTurnError`,context:{queueName:e,value:t}}),n}}async waitForTurnOrAbort(e,t,n){if(d(n)&&n.aborted)return!0;let r=this.eventClient?.waitForEvent(e,t);return s(n)?(await r,!1):await new Promise((e,t)=>{let onAbort=()=>{n.removeEventListener(`abort`,onAbort),e(!0)};n.addEventListener(`abort`,onAbort,{once:!0}),n.aborted&&onAbort(),Promise.resolve(r).then(()=>{n.removeEventListener(`abort`,onAbort),e(!1)},e=>{n.removeEventListener(`abort`,onAbort),t(e)})})}async remove(e,t){try{return(await this.executeScript(`remove`,[e],[t])??0)>0}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error removing item from queue`,category:this.name,error:n,code:`QueueManagerRemoveError`,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(`lPop`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:`QueueManagerPopError`,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(`llen`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:`QueueManagerLengthError`,context:{queueName:e}}),t}}isReady(){return d(this.subscriptionManager)&&d(this.cacheClient)&&d(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const R=`__keyevent@0__:`,z=`${R}set`,ee=`${R}expire`,B=`${R}expired`,V=`${R}srem`,te=[z,ee,B],ne={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,re={tryConcurrency:`
2
2
  local requestId = KEYS[1]
3
3
  local targetKey = KEYS[2]
4
4
  local queueKey = KEYS[3]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/transport",
3
- "version": "2.28.2",
3
+ "version": "2.29.0",
4
4
  "description": "",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",