@stackone/transport 2.30.2 → 2.31.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.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.defaultExecutorMethodDispose=async(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`))},this.defaultPendingPromiseDispose=async(e,t)=>{t instanceof Promise&&t?.finally(()=>{})},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 close(){let e=this.executorMethodStore,t=this.promiseStore;this.executorMethodStore=null,this.promiseStore=null,await e?.close(),await t?.close()}defaultExecutorMethodTypeGuard(e){return(0,o.isObject)(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}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}},LogThrottle=class{#e;#t;#n=new Map;#r=new Map;constructor(e,t=128){this.#e=e,this.#t=t}consume(e,t=Date.now()){let n=this.#n.get(e);if(n!==void 0&&t-n<this.#e)return this.#r.set(e,(this.#r.get(e)??0)+1),null;let r=this.#r.get(e)??0;return this.#r.delete(e),this.#n.delete(e),this.#n.set(e,t),this.#i(),{suppressed:r}}clear(){this.#n.clear(),this.#r.clear()}#i(){for(;this.#n.size>this.#t;){let e=this.#n.keys().next().value;if(e===void 0)return;this.#n.delete(e),this.#r.delete(e)}}};const y=1e4,b=6e4,x=new Set([`ECONNRESET`,`ECONNREFUSED`,`EPIPE`,`ETIMEDOUT`,`EHOSTUNREACH`,`ENETUNREACH`,`ENETRESET`,`EAI_AGAIN`]),isTransientError=e=>{if(e instanceof s.ConnectionTimeoutError||e instanceof s.SocketClosedUnexpectedlyError)return!0;let t=e.code;return t!==void 0&&x.has(t)};var RedisConnectionHealth=class{#e;#t=null;#n=null;#r=0;#i=!1;constructor(e){this.#e=e}recordAttemptStart(e=Date.now()){this.#t=e,this.#n??=e}recordReady(){this.#t=null,this.#n=null,this.#r=0,this.#i=!0}assess(e,t=Date.now()){this.#r+=1,this.#n??=t;let n=this.#t===null?null:t-this.#t,r=e instanceof s.ConnectionTimeoutError&&n!==null&&n>this.#e*2,i=this.#n===null?null:t-this.#n;return{severity:this.#a(e,r,i),isFreezeArtifact:r,consecutiveFailures:this.#r,unhealthyForMs:i,attemptElapsedMs:n}}isHealthy(){return this.#i&&this.#n===null}#a(e,t,n){return t?`transient`:!isTransientError(e)||this.#r>=5||n!==null&&n>=3e4?`sustained`:`degraded`}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await S.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 S=class RedisClient{#e;#t;static async build({getRedisClient:e=s.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:c,connectTimeout:l=y,initialConnectTimeout:u=15e3,pingInterval:d},f,p){let m=new RedisClient,h=p??`RedisClient`;m.#t=f;try{m.#e=e({socket:{reconnectStrategy:a?computeReconnectDelay:!1,host:t,port:n,keepAlive:i,connectTimeout:l,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:c,disableOfflineQueue:!0,...(0,o.notMissing)(d)?{pingInterval:d}:{}});let s=new RedisConnectionHealth(l),f=getDefaultRedisListeners(h,m.#t,s);return addRedisEventHandlers(m.#e,f),s.recordAttemptStart(),await connectWithinBudget(m.#e,u)?m:(m.#t?.error({message:`Redis client did not connect within ${u}ms, giving up so the caller can degrade`,code:`RedisClientConnectTimeout`,category:h}),await teardownUnusableClient(m.#e),null)}catch(e){let t=e;return m.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:h}),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 computeReconnectDelay=e=>{let t=Math.min(100*2**e,5e3);return Math.round(t-t*.5*Math.random())},connectWithinBudget=async(e,t)=>{let n=Promise.resolve(e.connect());n.catch(()=>void 0);let r,i=new Promise(e=>{r=setTimeout(()=>e(!1),t)});try{return await Promise.race([n.then(()=>!0),i])}finally{clearTimeout(r)}},teardownUnusableClient=async e=>{try{await e.disconnect()}catch{}e.removeAllListeners()},addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t,n=new RedisConnectionHealth(y))=>{let r=new LogThrottle(b);return[{eventName:`error`,listener:i=>{let a=i instanceof Error?i:Error(String(i)),s=n.assess(a),c={consecutiveFailures:s.consecutiveFailures,unhealthyForMs:s.unhealthyForMs,attemptElapsedMs:s.attemptElapsedMs,isFreezeArtifact:s.isFreezeArtifact};if(s.severity===`transient`){t?.debug({message:s.isFreezeArtifact?`Redis connect timeout reported after ${s.attemptElapsedMs}ms, far beyond its budget; runtime was suspended mid-handshake`:`Redis client error ${a.message}`,category:e,context:{...c,error:a.message}});return}let l=r.consume(`${e}:${s.severity}:${a.name}`);if((0,o.isMissing)(l))return;let u={message:`Redis client error ${a.message}`,error:a,code:`RedisClientError`,category:e,context:{...c,suppressedSinceLastLog:l.suppressed}};if(s.severity===`sustained`){t?.error(u);return}t?.warning(u)}},{eventName:`ready`,listener:()=>{n.recordReady(),r.clear(),t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.debug({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{n.recordAttemptStart(),t?.debug({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.debug({message:`Redis client disconnected`,category:e})}}]};var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0,this.ownsCacheClient=!1,this.unavailableLogThrottle=new LogThrottle(b)}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=(0,o.isMissing)(t),c=t??await buildRedisClientInstance(e,i,this.name);if((0,o.isMissing)(c))throw Error(`Failed to build Redis client`);this.redisClientConfig=e,this.logger=i,this.cacheClient=c,this.ownsCacheClient=this.ownsCacheClient||s,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[];try{await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[])}catch(e){throw this.releaseAdditionalResources(),s&&this.closeCacheClient(),e}return this}closeCacheClient(){if(!this.ownsCacheClient)return;let e=this.cacheClient;this.cacheClient=void 0,this.ownsCacheClient=!1,(async()=>{try{await e?.close?.()}catch(e){this.logger?.error({message:`Failed to close Redis client`,category:this.name,error:e,code:`ScriptManagerCloseError`})}})()}releaseAdditionalResources(){}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();(0,o.notMissing)(e)&&(e.setMaxListeners(20),e.on(`ready`,async()=>{this.unavailableLogThrottle.clear(),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()){let r=this.unavailableLogThrottle.consume(`${this.name}:${e}`);return(0,o.notMissing)(r)&&this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:t,args:n,suppressedSinceLastLog:r.suppressed}}),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 C=15e3,w=15e3,T=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:T,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:w,truncateThreshold:T,truncationPercentage:1},{instantiator:this.name,evictionFrequency:w,truncateThreshold:T,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=C,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}releaseAdditionalResources(){this.subscriptionManager?.close(),this.subscriptionManager=null;let e=this.eventClient;this.eventClient=null,e?.close().catch(e=>{this.logger?.error({message:`Failed to close the event client`,category:this.name,error:e,code:`QueueManagerCloseError`})})}close(){this.releaseAdditionalResources(),this.scriptMap?.clear(),this.closeCacheClient()}};const E=`__keyevent@0__:`,D=`${E}set`,O=`${E}expire`,k=`${E}expired`,A=`${E}srem`,ee=[D,O,k],j={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,M={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 getDataBatch(e){return e.length===0?[]:Promise.all(e.map(e=>this.getData(e)))}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.defaultExecutorMethodDispose=async(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`))},this.defaultPendingPromiseDispose=async(e,t)=>{t instanceof Promise&&t?.finally(()=>{})},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 close(){let e=this.executorMethodStore,t=this.promiseStore;this.executorMethodStore=null,this.promiseStore=null,await e?.close(),await t?.close()}defaultExecutorMethodTypeGuard(e){return(0,o.isObject)(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}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}},LogThrottle=class{#e;#t;#n=new Map;#r=new Map;constructor(e,t=128){this.#e=e,this.#t=t}consume(e,t=Date.now()){let n=this.#n.get(e);if(n!==void 0&&t-n<this.#e)return this.#r.set(e,(this.#r.get(e)??0)+1),null;let r=this.#r.get(e)??0;return this.#r.delete(e),this.#n.delete(e),this.#n.set(e,t),this.#i(),{suppressed:r}}clear(){this.#n.clear(),this.#r.clear()}#i(){for(;this.#n.size>this.#t;){let e=this.#n.keys().next().value;if(e===void 0)return;this.#n.delete(e),this.#r.delete(e)}}};const y=1e4,b=6e4,x=new Set([`ECONNRESET`,`ECONNREFUSED`,`EPIPE`,`ETIMEDOUT`,`EHOSTUNREACH`,`ENETUNREACH`,`ENETRESET`,`EAI_AGAIN`]),isTransientError=e=>{if(e instanceof s.ConnectionTimeoutError||e instanceof s.SocketClosedUnexpectedlyError)return!0;let t=e.code;return t!==void 0&&x.has(t)};var RedisConnectionHealth=class{#e;#t=null;#n=null;#r=0;#i=!1;constructor(e){this.#e=e}recordAttemptStart(e=Date.now()){this.#t=e,this.#n??=e}recordReady(){this.#t=null,this.#n=null,this.#r=0,this.#i=!0}assess(e,t=Date.now()){this.#r+=1,this.#n??=t;let n=this.#t===null?null:t-this.#t,r=e instanceof s.ConnectionTimeoutError&&n!==null&&n>this.#e*2,i=this.#n===null?null:t-this.#n;return{severity:this.#a(e,r,i),isFreezeArtifact:r,consecutiveFailures:this.#r,unhealthyForMs:i,attemptElapsedMs:n}}isHealthy(){return this.#i&&this.#n===null}#a(e,t,n){return t?`transient`:!isTransientError(e)||this.#r>=5||n!==null&&n>=3e4?`sustained`:`degraded`}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await S.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 S=class RedisClient{#e;#t;static async build({getRedisClient:e=s.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:c,connectTimeout:l=y,initialConnectTimeout:u=15e3,pingInterval:d},f,p){let m=new RedisClient,h=p??`RedisClient`;m.#t=f;try{m.#e=e({socket:{reconnectStrategy:a?computeReconnectDelay:!1,host:t,port:n,keepAlive:i,connectTimeout:l,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:c,disableOfflineQueue:!0,...(0,o.notMissing)(d)?{pingInterval:d}:{}});let s=new RedisConnectionHealth(l),f=getDefaultRedisListeners(h,m.#t,s);return addRedisEventHandlers(m.#e,f),s.recordAttemptStart(),await connectWithinBudget(m.#e,u)?m:(m.#t?.error({message:`Redis client did not connect within ${u}ms, giving up so the caller can degrade`,code:`RedisClientConnectTimeout`,category:h}),await teardownUnusableClient(m.#e),null)}catch(e){let t=e;return m.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:h}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}#r(e){let t=this.#n(e);return(0,o.isString)(t)?e:t}async getData(e){if(!this.#a())return null;try{let t=await this.#e.get(e);return(0,o.notMissing)(t)?this.#r(t):null}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getDataBatch(e){if(e.length===0)return[];if(!this.#a())return e.map(()=>null);try{return(await this.#e.mGet(e)).map(e=>(0,o.notMissing)(e)?this.#r(e):null)}catch(t){let n=t;return this.#t?.error({message:`Error getting batch data`,error:n,code:`RedisClientReadError`,category:RedisClient.name}),e.map(()=>null)}}async getDataKeysFromGroup(e){if(!this.#a())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.#a())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.#a())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.#a())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.#a())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.#a())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#i(e,t,n){if(!this.#a())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.#i(`incr`,e,t)}async decrement(e,t){return this.#i(`decr`,e,t)}async subscribe(e,t){if(!this.#a())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.#a())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.#a())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.#a()?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})}}#a(){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.#a())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.#a())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.#a())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.#a())return null;try{let n=await this.#e.hGet(e,t);return n!==``&&(0,o.isMissing)(n)?null:this.#r(n)}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.#a())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])=>[e,this.#r(t)]))}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.#a())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 computeReconnectDelay=e=>{let t=Math.min(100*2**e,5e3);return Math.round(t-t*.5*Math.random())},connectWithinBudget=async(e,t)=>{let n=Promise.resolve(e.connect());n.catch(()=>void 0);let r,i=new Promise(e=>{r=setTimeout(()=>e(!1),t)});try{return await Promise.race([n.then(()=>!0),i])}finally{clearTimeout(r)}},teardownUnusableClient=async e=>{try{await e.disconnect()}catch{}e.removeAllListeners()},addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t,n=new RedisConnectionHealth(y))=>{let r=new LogThrottle(b);return[{eventName:`error`,listener:i=>{let a=i instanceof Error?i:Error(String(i)),s=n.assess(a),c={consecutiveFailures:s.consecutiveFailures,unhealthyForMs:s.unhealthyForMs,attemptElapsedMs:s.attemptElapsedMs,isFreezeArtifact:s.isFreezeArtifact};if(s.severity===`transient`){t?.debug({message:s.isFreezeArtifact?`Redis connect timeout reported after ${s.attemptElapsedMs}ms, far beyond its budget; runtime was suspended mid-handshake`:`Redis client error ${a.message}`,category:e,context:{...c,error:a.message}});return}let l=r.consume(`${e}:${s.severity}:${a.name}`);if((0,o.isMissing)(l))return;let u={message:`Redis client error ${a.message}`,error:a,code:`RedisClientError`,category:e,context:{...c,suppressedSinceLastLog:l.suppressed}};if(s.severity===`sustained`){t?.error(u);return}t?.warning(u)}},{eventName:`ready`,listener:()=>{n.recordReady(),r.clear(),t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.debug({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{n.recordAttemptStart(),t?.debug({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.debug({message:`Redis client disconnected`,category:e})}}]};var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0,this.ownsCacheClient=!1,this.unavailableLogThrottle=new LogThrottle(b)}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=(0,o.isMissing)(t),c=t??await buildRedisClientInstance(e,i,this.name);if((0,o.isMissing)(c))throw Error(`Failed to build Redis client`);this.redisClientConfig=e,this.logger=i,this.cacheClient=c,this.ownsCacheClient=this.ownsCacheClient||s,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[];try{await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[])}catch(e){throw this.releaseAdditionalResources(),s&&this.closeCacheClient(),e}return this}closeCacheClient(){if(!this.ownsCacheClient)return;let e=this.cacheClient;this.cacheClient=void 0,this.ownsCacheClient=!1,(async()=>{try{await e?.close?.()}catch(e){this.logger?.error({message:`Failed to close Redis client`,category:this.name,error:e,code:`ScriptManagerCloseError`})}})()}releaseAdditionalResources(){}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();(0,o.notMissing)(e)&&(e.setMaxListeners(20),e.on(`ready`,async()=>{this.unavailableLogThrottle.clear(),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()){let r=this.unavailableLogThrottle.consume(`${this.name}:${e}`);return(0,o.notMissing)(r)&&this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:t,args:n,suppressedSinceLastLog:r.suppressed}}),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 C=15e3,w=15e3,T=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:T,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:w,truncateThreshold:T,truncationPercentage:1},{instantiator:this.name,evictionFrequency:w,truncateThreshold:T,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=C,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}releaseAdditionalResources(){this.subscriptionManager?.close(),this.subscriptionManager=null;let e=this.eventClient;this.eventClient=null,e?.close().catch(e=>{this.logger?.error({message:`Failed to close the event client`,category:this.name,error:e,code:`QueueManagerCloseError`})})}close(){this.releaseAdditionalResources(),this.scriptMap?.clear(),this.closeCacheClient()}};const E=`__keyevent@0__:`,D=`${E}set`,O=`${E}expire`,k=`${E}expired`,A=`${E}srem`,ee=[D,O,k],j={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,M={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
@@ -33,6 +33,7 @@ declare abstract class AsyncSingleton<T, O> {
33
33
  interface ICacheClient<ClientType = unknown> {
34
34
  isAvailable(): boolean;
35
35
  getData<T>(key: string): Promise<T | null>;
36
+ getDataBatch<T>(keys: string[]): Promise<(T | null)[]>;
36
37
  getDataKeysFromGroup(groupKey: string): Promise<string[] | null>;
37
38
  listData<T>({
38
39
  partialKey,
@@ -128,6 +129,7 @@ declare class RedisClient implements ICacheClient<RedisClientType> {
128
129
  pingInterval
129
130
  }: RedisClientConfig, logger?: ILogger, invoker?: string): Promise<ICacheClient<RedisClientType> | null>;
130
131
  getData<T>(key: string): Promise<T | null>;
132
+ getDataBatch<T>(keys: string[]): Promise<(T | null)[]>;
131
133
  getDataKeysFromGroup(groupKey: string): Promise<string[] | null>;
132
134
  setData<T>({
133
135
  key,
@@ -1022,6 +1024,7 @@ declare class MemoryStore<T> implements ICacheClient {
1022
1024
  constructor(config?: MemoryStoreConfig<T>);
1023
1025
  private initialize;
1024
1026
  getData<U = T>(key: string): Promise<U | null>;
1027
+ getDataBatch<U = T>(keys: string[]): Promise<(U | null)[]>;
1025
1028
  getDataKeysFromGroup(groupKey: string): Promise<string[]>;
1026
1029
  deleteDataKeyFromGroup(groupKey: string, key: string): Promise<boolean>;
1027
1030
  private getLiveGroup;
package/dist/index.d.mts CHANGED
@@ -32,6 +32,7 @@ declare abstract class AsyncSingleton<T, O> {
32
32
  interface ICacheClient<ClientType = unknown> {
33
33
  isAvailable(): boolean;
34
34
  getData<T>(key: string): Promise<T | null>;
35
+ getDataBatch<T>(keys: string[]): Promise<(T | null)[]>;
35
36
  getDataKeysFromGroup(groupKey: string): Promise<string[] | null>;
36
37
  listData<T>({
37
38
  partialKey,
@@ -127,6 +128,7 @@ declare class RedisClient implements ICacheClient<RedisClientType> {
127
128
  pingInterval
128
129
  }: RedisClientConfig, logger?: ILogger, invoker?: string): Promise<ICacheClient<RedisClientType> | null>;
129
130
  getData<T>(key: string): Promise<T | null>;
131
+ getDataBatch<T>(keys: string[]): Promise<(T | null)[]>;
130
132
  getDataKeysFromGroup(groupKey: string): Promise<string[] | null>;
131
133
  setData<T>({
132
134
  key,
@@ -1021,6 +1023,7 @@ declare class MemoryStore<T> implements ICacheClient {
1021
1023
  constructor(config?: MemoryStoreConfig<T>);
1022
1024
  private initialize;
1023
1025
  getData<U = T>(key: string): Promise<U | null>;
1026
+ getDataBatch<U = T>(keys: string[]): Promise<(U | null)[]>;
1024
1027
  getDataKeysFromGroup(groupKey: string): Promise<string[]>;
1025
1028
  deleteDataKeyFromGroup(groupKey: string, key: string): Promise<boolean>;
1026
1029
  private getLiveGroup;
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{ConnectionTimeoutError as h,SocketClosedUnexpectedlyError as g}from"redis";import{evaluate as _,safeEvaluate as v}from"@stackone/expressions";import y,{isAxiosError as b}from"axios";import x from"node:https";import{createHash as S,createHmac as C,randomUUID as w}from"crypto";import{clearTimeout as T}from"node:timers";import{hasNumericValue as ee,isString as E}from"mathjs";import{JSONPath as D}from"jsonpath-plus";import{redactFields as O,redactUrl as k}from"@stackone/redaction";import A from"qs";import{XMLBuilder as te,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.defaultExecutorMethodDispose=async(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`))},this.defaultPendingPromiseDispose=async(e,t)=>{t instanceof Promise&&t?.finally(()=>{})},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 close(){let e=this.executorMethodStore,t=this.promiseStore;this.executorMethodStore=null,this.promiseStore=null,await e?.close(),await t?.close()}defaultExecutorMethodTypeGuard(e){return l(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}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}},LogThrottle=class{#e;#t;#n=new Map;#r=new Map;constructor(e,t=128){this.#e=e,this.#t=t}consume(e,t=Date.now()){let n=this.#n.get(e);if(n!==void 0&&t-n<this.#e)return this.#r.set(e,(this.#r.get(e)??0)+1),null;let r=this.#r.get(e)??0;return this.#r.delete(e),this.#n.delete(e),this.#n.set(e,t),this.#i(),{suppressed:r}}clear(){this.#n.clear(),this.#r.clear()}#i(){for(;this.#n.size>this.#t;){let e=this.#n.keys().next().value;if(e===void 0)return;this.#n.delete(e),this.#r.delete(e)}}};const ne=1e4,P=6e4,re=new Set([`ECONNRESET`,`ECONNREFUSED`,`EPIPE`,`ETIMEDOUT`,`EHOSTUNREACH`,`ENETUNREACH`,`ENETRESET`,`EAI_AGAIN`]),isTransientError=e=>{if(e instanceof h||e instanceof g)return!0;let t=e.code;return t!==void 0&&re.has(t)};var RedisConnectionHealth=class{#e;#t=null;#n=null;#r=0;#i=!1;constructor(e){this.#e=e}recordAttemptStart(e=Date.now()){this.#t=e,this.#n??=e}recordReady(){this.#t=null,this.#n=null,this.#r=0,this.#i=!0}assess(e,t=Date.now()){this.#r+=1,this.#n??=t;let n=this.#t===null?null:t-this.#t,r=e instanceof h&&n!==null&&n>this.#e*2,i=this.#n===null?null:t-this.#n;return{severity:this.#a(e,r,i),isFreezeArtifact:r,consecutiveFailures:this.#r,unhealthyForMs:i,attemptElapsedMs:n}}isHealthy(){return this.#i&&this.#n===null}#a(e,t,n){return t?`transient`:!isTransientError(e)||this.#r>=5||n!==null&&n>=3e4?`sustained`:`degraded`}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await F.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 F=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,connectTimeout:s=ne,initialConnectTimeout:c=15e3,pingInterval:l},u,f){let p=new RedisClient,h=f??`RedisClient`;p.#t=u;try{p.#e=e({socket:{reconnectStrategy:a?computeReconnectDelay:!1,host:t,port:n,keepAlive:i,connectTimeout:s,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,disableOfflineQueue:!0,...d(l)?{pingInterval:l}:{}});let u=new RedisConnectionHealth(s),f=getDefaultRedisListeners(h,p.#t,u);return addRedisEventHandlers(p.#e,f),u.recordAttemptStart(),await connectWithinBudget(p.#e,c)?p:(p.#t?.error({message:`Redis client did not connect within ${c}ms, giving up so the caller can degrade`,code:`RedisClientConnectTimeout`,category:h}),await teardownUnusableClient(p.#e),null)}catch(e){let t=e;return p.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:h}),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 computeReconnectDelay=e=>{let t=Math.min(100*2**e,5e3);return Math.round(t-t*.5*Math.random())},connectWithinBudget=async(e,t)=>{let n=Promise.resolve(e.connect());n.catch(()=>void 0);let r,i=new Promise(e=>{r=setTimeout(()=>e(!1),t)});try{return await Promise.race([n.then(()=>!0),i])}finally{clearTimeout(r)}},teardownUnusableClient=async e=>{try{await e.disconnect()}catch{}e.removeAllListeners()},addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t,n=new RedisConnectionHealth(ne))=>{let r=new LogThrottle(P);return[{eventName:`error`,listener:i=>{let a=i instanceof Error?i:Error(String(i)),o=n.assess(a),c={consecutiveFailures:o.consecutiveFailures,unhealthyForMs:o.unhealthyForMs,attemptElapsedMs:o.attemptElapsedMs,isFreezeArtifact:o.isFreezeArtifact};if(o.severity===`transient`){t?.debug({message:o.isFreezeArtifact?`Redis connect timeout reported after ${o.attemptElapsedMs}ms, far beyond its budget; runtime was suspended mid-handshake`:`Redis client error ${a.message}`,category:e,context:{...c,error:a.message}});return}let l=r.consume(`${e}:${o.severity}:${a.name}`);if(s(l))return;let u={message:`Redis client error ${a.message}`,error:a,code:`RedisClientError`,category:e,context:{...c,suppressedSinceLastLog:l.suppressed}};if(o.severity===`sustained`){t?.error(u);return}t?.warning(u)}},{eventName:`ready`,listener:()=>{n.recordReady(),r.clear(),t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.debug({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{n.recordAttemptStart(),t?.debug({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.debug({message:`Redis client disconnected`,category:e})}}]};var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0,this.ownsCacheClient=!1,this.unavailableLogThrottle=new LogThrottle(P)}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=s(t),c=t??await buildRedisClientInstance(e,i,this.name);if(s(c))throw Error(`Failed to build Redis client`);this.redisClientConfig=e,this.logger=i,this.cacheClient=c,this.ownsCacheClient=this.ownsCacheClient||o,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[];try{await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[])}catch(e){throw this.releaseAdditionalResources(),o&&this.closeCacheClient(),e}return this}closeCacheClient(){if(!this.ownsCacheClient)return;let e=this.cacheClient;this.cacheClient=void 0,this.ownsCacheClient=!1,(async()=>{try{await e?.close?.()}catch(e){this.logger?.error({message:`Failed to close Redis client`,category:this.name,error:e,code:`ScriptManagerCloseError`})}})()}releaseAdditionalResources(){}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();d(e)&&(e.setMaxListeners(20),e.on(`ready`,async()=>{this.unavailableLogThrottle.clear(),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()){let t=this.unavailableLogThrottle.consume(`${this.name}:${e}`);return d(t)&&this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:n,args:r,suppressedSinceLastLog:t.suppressed}}),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 I=15e3,ie=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:ie,truncateThreshold:L,truncationPercentage:1},{instantiator:this.name,evictionFrequency:ie,truncateThreshold:L,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=I,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}releaseAdditionalResources(){this.subscriptionManager?.close(),this.subscriptionManager=null;let e=this.eventClient;this.eventClient=null,e?.close().catch(e=>{this.logger?.error({message:`Failed to close the event client`,category:this.name,error:e,code:`QueueManagerCloseError`})})}close(){this.releaseAdditionalResources(),this.scriptMap?.clear(),this.closeCacheClient()}};const R=`__keyevent@0__:`,ae=`${R}set`,oe=`${R}expire`,z=`${R}expired`,se=`${R}srem`,ce=[ae,oe,z],le={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,ue={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{ConnectionTimeoutError as h,SocketClosedUnexpectedlyError as g}from"redis";import{evaluate as _,safeEvaluate as v}from"@stackone/expressions";import y,{isAxiosError as b}from"axios";import x from"node:https";import{createHash as S,createHmac as C,randomUUID as w}from"crypto";import{clearTimeout as T}from"node:timers";import{hasNumericValue as ee,isString as E}from"mathjs";import{JSONPath as D}from"jsonpath-plus";import{redactFields as O,redactUrl as k}from"@stackone/redaction";import A from"qs";import{XMLBuilder as te,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 getDataBatch(e){return e.length===0?[]:Promise.all(e.map(e=>this.getData(e)))}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.defaultExecutorMethodDispose=async(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`))},this.defaultPendingPromiseDispose=async(e,t)=>{t instanceof Promise&&t?.finally(()=>{})},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 close(){let e=this.executorMethodStore,t=this.promiseStore;this.executorMethodStore=null,this.promiseStore=null,await e?.close(),await t?.close()}defaultExecutorMethodTypeGuard(e){return l(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}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}},LogThrottle=class{#e;#t;#n=new Map;#r=new Map;constructor(e,t=128){this.#e=e,this.#t=t}consume(e,t=Date.now()){let n=this.#n.get(e);if(n!==void 0&&t-n<this.#e)return this.#r.set(e,(this.#r.get(e)??0)+1),null;let r=this.#r.get(e)??0;return this.#r.delete(e),this.#n.delete(e),this.#n.set(e,t),this.#i(),{suppressed:r}}clear(){this.#n.clear(),this.#r.clear()}#i(){for(;this.#n.size>this.#t;){let e=this.#n.keys().next().value;if(e===void 0)return;this.#n.delete(e),this.#r.delete(e)}}};const ne=1e4,P=6e4,re=new Set([`ECONNRESET`,`ECONNREFUSED`,`EPIPE`,`ETIMEDOUT`,`EHOSTUNREACH`,`ENETUNREACH`,`ENETRESET`,`EAI_AGAIN`]),isTransientError=e=>{if(e instanceof h||e instanceof g)return!0;let t=e.code;return t!==void 0&&re.has(t)};var RedisConnectionHealth=class{#e;#t=null;#n=null;#r=0;#i=!1;constructor(e){this.#e=e}recordAttemptStart(e=Date.now()){this.#t=e,this.#n??=e}recordReady(){this.#t=null,this.#n=null,this.#r=0,this.#i=!0}assess(e,t=Date.now()){this.#r+=1,this.#n??=t;let n=this.#t===null?null:t-this.#t,r=e instanceof h&&n!==null&&n>this.#e*2,i=this.#n===null?null:t-this.#n;return{severity:this.#a(e,r,i),isFreezeArtifact:r,consecutiveFailures:this.#r,unhealthyForMs:i,attemptElapsedMs:n}}isHealthy(){return this.#i&&this.#n===null}#a(e,t,n){return t?`transient`:!isTransientError(e)||this.#r>=5||n!==null&&n>=3e4?`sustained`:`degraded`}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await F.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 F=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,connectTimeout:s=ne,initialConnectTimeout:c=15e3,pingInterval:l},u,f){let p=new RedisClient,h=f??`RedisClient`;p.#t=u;try{p.#e=e({socket:{reconnectStrategy:a?computeReconnectDelay:!1,host:t,port:n,keepAlive:i,connectTimeout:s,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,disableOfflineQueue:!0,...d(l)?{pingInterval:l}:{}});let u=new RedisConnectionHealth(s),f=getDefaultRedisListeners(h,p.#t,u);return addRedisEventHandlers(p.#e,f),u.recordAttemptStart(),await connectWithinBudget(p.#e,c)?p:(p.#t?.error({message:`Redis client did not connect within ${c}ms, giving up so the caller can degrade`,code:`RedisClientConnectTimeout`,category:h}),await teardownUnusableClient(p.#e),null)}catch(e){let t=e;return p.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:h}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}#r(e){let t=this.#n(e);return u(t)?e:t}async getData(e){if(!this.#a())return null;try{let t=await this.#e.get(e);return d(t)?this.#r(t):null}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getDataBatch(e){if(e.length===0)return[];if(!this.#a())return e.map(()=>null);try{return(await this.#e.mGet(e)).map(e=>d(e)?this.#r(e):null)}catch(t){let n=t;return this.#t?.error({message:`Error getting batch data`,error:n,code:`RedisClientReadError`,category:RedisClient.name}),e.map(()=>null)}}async getDataKeysFromGroup(e){if(!this.#a())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.#a())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.#a())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.#a())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.#a())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.#a())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#i(e,t,n){if(!this.#a())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.#i(`incr`,e,t)}async decrement(e,t){return this.#i(`decr`,e,t)}async subscribe(e,t){if(!this.#a())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.#a())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.#a())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.#a()?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})}}#a(){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.#a())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.#a())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.#a())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.#a())return null;try{let n=await this.#e.hGet(e,t);return n!==``&&s(n)?null:this.#r(n)}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.#a())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])=>[e,this.#r(t)]))}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.#a())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 computeReconnectDelay=e=>{let t=Math.min(100*2**e,5e3);return Math.round(t-t*.5*Math.random())},connectWithinBudget=async(e,t)=>{let n=Promise.resolve(e.connect());n.catch(()=>void 0);let r,i=new Promise(e=>{r=setTimeout(()=>e(!1),t)});try{return await Promise.race([n.then(()=>!0),i])}finally{clearTimeout(r)}},teardownUnusableClient=async e=>{try{await e.disconnect()}catch{}e.removeAllListeners()},addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t,n=new RedisConnectionHealth(ne))=>{let r=new LogThrottle(P);return[{eventName:`error`,listener:i=>{let a=i instanceof Error?i:Error(String(i)),o=n.assess(a),c={consecutiveFailures:o.consecutiveFailures,unhealthyForMs:o.unhealthyForMs,attemptElapsedMs:o.attemptElapsedMs,isFreezeArtifact:o.isFreezeArtifact};if(o.severity===`transient`){t?.debug({message:o.isFreezeArtifact?`Redis connect timeout reported after ${o.attemptElapsedMs}ms, far beyond its budget; runtime was suspended mid-handshake`:`Redis client error ${a.message}`,category:e,context:{...c,error:a.message}});return}let l=r.consume(`${e}:${o.severity}:${a.name}`);if(s(l))return;let u={message:`Redis client error ${a.message}`,error:a,code:`RedisClientError`,category:e,context:{...c,suppressedSinceLastLog:l.suppressed}};if(o.severity===`sustained`){t?.error(u);return}t?.warning(u)}},{eventName:`ready`,listener:()=>{n.recordReady(),r.clear(),t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.debug({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{n.recordAttemptStart(),t?.debug({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.debug({message:`Redis client disconnected`,category:e})}}]};var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0,this.ownsCacheClient=!1,this.unavailableLogThrottle=new LogThrottle(P)}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=s(t),c=t??await buildRedisClientInstance(e,i,this.name);if(s(c))throw Error(`Failed to build Redis client`);this.redisClientConfig=e,this.logger=i,this.cacheClient=c,this.ownsCacheClient=this.ownsCacheClient||o,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[];try{await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[])}catch(e){throw this.releaseAdditionalResources(),o&&this.closeCacheClient(),e}return this}closeCacheClient(){if(!this.ownsCacheClient)return;let e=this.cacheClient;this.cacheClient=void 0,this.ownsCacheClient=!1,(async()=>{try{await e?.close?.()}catch(e){this.logger?.error({message:`Failed to close Redis client`,category:this.name,error:e,code:`ScriptManagerCloseError`})}})()}releaseAdditionalResources(){}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();d(e)&&(e.setMaxListeners(20),e.on(`ready`,async()=>{this.unavailableLogThrottle.clear(),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()){let t=this.unavailableLogThrottle.consume(`${this.name}:${e}`);return d(t)&&this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:n,args:r,suppressedSinceLastLog:t.suppressed}}),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 I=15e3,ie=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:ie,truncateThreshold:L,truncationPercentage:1},{instantiator:this.name,evictionFrequency:ie,truncateThreshold:L,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=I,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}releaseAdditionalResources(){this.subscriptionManager?.close(),this.subscriptionManager=null;let e=this.eventClient;this.eventClient=null,e?.close().catch(e=>{this.logger?.error({message:`Failed to close the event client`,category:this.name,error:e,code:`QueueManagerCloseError`})})}close(){this.releaseAdditionalResources(),this.scriptMap?.clear(),this.closeCacheClient()}};const R=`__keyevent@0__:`,ae=`${R}set`,oe=`${R}expire`,z=`${R}expired`,se=`${R}srem`,ce=[ae,oe,z],le={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,ue={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.30.2",
3
+ "version": "2.31.0",
4
4
  "description": "",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",