@stackone/transport 2.19.1 → 2.20.1
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 +2 -2
- package/dist/index.d.cts +9 -1
- package/dist/index.d.mts +9 -1
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
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,__commonJSMin=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),__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(`jsonpath-plus`),m=require(`@stackone/redaction`),h=require(`qs`);h=__toESM(h);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 g=1e3,_=100,v=60,y=6e4,b=60,x=y,S=y*10,C=100,w=10;let T=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async getDataKeysFromGroup(e){this.isReady()||this.initialize(),this.updateLastAccessedAt();let t=this.groupExpiryMap.get(e);return(0,o.notMissing)(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),[]):Array.from(this.groupMap.get(e)??[])}async setData({key:e,value:t,cacheTTL:n=60,groupKeys:r,groupKeyTTL:i}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),(0,o.notMissing)(this.typeGuard)&&!this.typeGuard(t))return!1;let a=n*g,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*g: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.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=0;return this.dataStore.forEach(async(e,i)=>{let a=Date.now(),o=this.expiryMap.get(i)??0,s=this.truncateThreshold*this.truncationPercentage/100;(o<=a||t&&r>=0&&r<=s)&&n.push(this.lockManager.withLock(i,async()=>(this.dispose&&await this.dispose(i,e),this.dataStore.delete(i)))),r++}),await Promise.all(n),{dataStoreSize:e,prunedDataStoreSize:this.dataStore.size}}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`}),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:T.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)}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*g;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n)}),!0}close(){this.stopEvictionTask(),this.dataStore.clear(),this.expiryMap.clear(),this.groupMap.clear(),this.groupExpiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()).filter(t=>t.includes(e)),i=[],a=t?parseInt(t,10):0;for(let e=a;e<n+a;e++){let t=r[e];if(!t)break;let a=await this.getData(t);if(a&&i.push(a),i.length>=n)break}return{items:i,cursor:i.length<n?void 0:(a+n).toString()}}};const E=1e3,ee=6e4;let D=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var EventClient=class{constructor(e,t,n){this.executorMethodStore=null,this.promiseStore=null,this.eventClientConfig=null,this.executorMethodStoreConfig=null,this.pendingPromiseStoreConfig=null,this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new MemoryStore(i),this.promiseStore=new MemoryStore(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/1e3;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return(0,o.notMissing)(n)?n:(await this.setPendingEvent(e,t),this.getPendingEvent(e))}async getPendingEvent(e){return this.promiseStore?.getData(e)??null}async deleteEvent(e){return(await Promise.all([this.promiseStore?.delete(e),this.executorMethodStore?.delete(e)])).every(Boolean)}async resolveEvent(e,t){try{let n=await this.executorMethodStore?.getData(e);(0,o.isMissing)(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??6e4),n=await this.executorMethodStore?.getData(e)),n?.resolve?.(t)}catch(t){t instanceof Error&&this.logger.error({message:`Error handling event for key ${e}: ${t.message}`,category:this.constructor.name,context:{eventKey:e},error:t,code:D.EventClientResolveError})}}async defaultExecutorMethodDispose(e,t){(0,o.notMissing)(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):(0,o.notMissing)(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return(0,o.isObject)(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[]}getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:((0,o.isMissing)(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,(0,o.isMissing)(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}};let O=function(e){return e.RedisClientError=`RedisClientError`,e.RedisClientCommandError=`RedisClientCommandError`,e.RedisClientDeleteError=`RedisClientDeleteError`,e.RedisClientInvalidTTL=`RedisClientInvalidTTL`,e.RedisClientListError=`RedisClientListError`,e.RedisClientNotInitialized=`RedisClientNotInitialized`,e.RedisClientPublishError=`RedisClientPublishError`,e.RedisClientReadError=`RedisClientReadError`,e.RedisClientRedisNotReady=`RedisClientRedisNotReady`,e.RedisClientScriptError=`RedisClientScriptError`,e.RedisClientScriptExecuteError=`RedisClientScriptExecuteError`,e.RedisClientScriptLoadError=`RedisClientScriptLoadError`,e.RedisClientSubscribeError=`RedisClientSubscribeError`,e.RedisClientUnsubscribeError=`RedisClientUnsubscribeError`,e.RedisClientWriteError=`RedisClientWriteError`,e}({});const buildRedisClientInstance=async(e,t,n)=>{try{return await te.build(e,t,n)??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:O.RedisClientError,category:n??`buildRedisClientInstance`});return}};var te=class RedisClient{#e;#t;static async build({getRedisClient:e=s.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o},c,l){let u=new RedisClient;u.#t=c;try{u.#e=e({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:t,port:n,tls:r,keepAlive:i},database:o,disableOfflineQueue:!0});let s=getDefaultRedisListeners(l??`RedisClient`,u.#t);return addRedisEventHandlers(u.#e,s),await u.#e.connect(),u}catch(e){let t=e;return u.#t?.error({message:`Error building Cache Manager.`,error:t,code:O.RedisClientError,category:l??`RedisClient`}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}async getData(e){if(!this.#i())return null;try{let t=await this.#e.get(e);if(!t)return null;let n=this.#n(t);return(0,o.isString)(n)?t:n}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:O.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:O.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:O.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:O.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:O.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:O.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:O.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:O.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:O.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:O.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:O.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:O.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:O.RedisClientPublishError,category:RedisClient.name}),null}}getClient(){return this.#i()?this.#e:null}#i(){let e=this.#e.isReady&&this.#e.isOpen;return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:O.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:O.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:O.RedisClientDeleteError,category:RedisClient.name})}),n>0}catch(e){let t=e;return this.#t?.error({message:`Error deleting data`,error:t,code:O.RedisClientDeleteError,category:RedisClient.name}),!1}}};const addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:O.RedisClientError,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];let ne=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});const re=1500;var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0}async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let s=t??await buildRedisClientInstance(e,i,this.name);if((0,o.isMissing)(s))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=s,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();(0,o.notMissing)(e)&&(e.on(`ready`,async()=>{this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){if((0,o.notMissing)(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!((0,o.isMissing)(this.scripts)||Object.keys(this.scripts).length===0)){this.reloadInProgress=this.performReload();try{await this.reloadInProgress}finally{this.reloadInProgress=null}}}async performReload(){this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts),this.lastReloadTime=Date.now()}async loadScripts(e,t){if((0,o.notMissing)(t))for(let[e,n]of t)this.scriptMap.set(e,n);let n=Object.entries(e),r=n.map(([e])=>this.scriptMap.get(e)).filter(o.notMissing),i=new Map;if(r.length>0&&(0,o.notMissing)(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if((0,o.notMissing)(e)){r.forEach((t,n)=>{i.set(t,e[n]??!1)});let t=e.filter(Boolean).length;t>0&&this.logger?.info({message:`${t}/${r.length} scripts already exist in Redis; skipping load for existing scripts`,category:this.name})}}for(let[e,t]of n){let n=this.scriptMap.get(e);if(n&&i.get(n))continue;let r=await this.cacheClient?.loadScript?.(t);(0,o.notMissing)(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:ne.ScriptManagerLoadingError})}}async executeScript(e,t,n){if(!this.isRedisReady())return this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:t,args:n}}),null;let r=this.scriptMap?.get(e);if((0,o.isMissing)(r))throw this.logger?.error({message:`Script for ${e} not found in script map`,category:this.name,code:ne.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<re){let t=re-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:ne.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.subscriptionMap=null,this.subscriptionClient=null}};const ie=6e4,ae=15e3,oe=!1,se=6e4,ce=15e3,le=1e4,ue=1;let k=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),A=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});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:le,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:ce,truncateThreshold:le,truncationPercentage:1},{instantiator:this.name,evictionFrequency:ce,truncateThreshold:le,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0){try{let a=`${e}:${t}`;await this.subscriptionManager?.subscribe(a,async(n,r)=>{if(r.includes(a)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let o=await this.executeScript(n?A.lPush:A.rPush,[e],[t,`60000`])===1;return(!i||!o)&&await this.eventClient?.waitForEvent(a,15e3),await this.eventClient?.deleteEvent(a),await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:k.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(A.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:k.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(A.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:k.QueueManagerLengthError,context:{queueName:e}}),t}}isReady(){return(0,o.notMissing)(this.subscriptionManager)&&(0,o.notMissing)(this.cacheClient)&&(0,o.notMissing)(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const de=5,fe=12e4,pe=1e4,me=1,he=60,ge=90,j=`__keyevent@0__:`,_e=`${j}set`,ve=`${j}expire`,M=`${j}expired`,ye=`${j}srem`,be=`config_check_test_key`,xe=[_e,ve,M],Se=1,Ce=2e4,we={mainMaxConcurrency:30};let N=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e.ConcurrencyManagerPublishNextItemFailed=`ConcurrencyManagerPublishNextItemFailed`,e.ConcurrencyManagerReleaseRequestFailed=`ConcurrencyManagerReleaseRequestFailed`,e}({}),P=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const Te={[P.tryConcurrency]:`
|
|
1
|
+
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,__commonJSMin=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),__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(`jsonpath-plus`),m=require(`@stackone/redaction`),h=require(`qs`);h=__toESM(h);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 g=1e3,_=100,v=60,y=6e4,b=60,x=y,S=y*10,C=100,w=10;let T=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async getDataKeysFromGroup(e){this.isReady()||this.initialize(),this.updateLastAccessedAt();let t=this.groupExpiryMap.get(e);return(0,o.notMissing)(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),[]):Array.from(this.groupMap.get(e)??[])}async setData({key:e,value:t,cacheTTL:n=60,groupKeys:r,groupKeyTTL:i}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),(0,o.notMissing)(this.typeGuard)&&!this.typeGuard(t))return!1;let a=n*g,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*g: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.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=0;return this.dataStore.forEach(async(e,i)=>{let a=Date.now(),o=this.expiryMap.get(i)??0,s=this.truncateThreshold*this.truncationPercentage/100;(o<=a||t&&r>=0&&r<=s)&&n.push(this.lockManager.withLock(i,async()=>(this.dispose&&await this.dispose(i,e),this.dataStore.delete(i)))),r++}),await Promise.all(n),{dataStoreSize:e,prunedDataStoreSize:this.dataStore.size}}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`}),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:T.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*g;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n)}),!0}close(){this.stopEvictionTask(),this.dataStore.clear(),this.expiryMap.clear(),this.groupMap.clear(),this.groupExpiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()).filter(t=>t.includes(e)),i=[],a=t?parseInt(t,10):0;for(let e=a;e<n+a;e++){let t=r[e];if(!t)break;let a=await this.getData(t);if(a&&i.push(a),i.length>=n)break}return{items:i,cursor:i.length<n?void 0:(a+n).toString()}}};const E=1e3,ee=6e4;let D=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var EventClient=class{constructor(e,t,n){this.executorMethodStore=null,this.promiseStore=null,this.eventClientConfig=null,this.executorMethodStoreConfig=null,this.pendingPromiseStoreConfig=null,this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new MemoryStore(i),this.promiseStore=new MemoryStore(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/1e3;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return(0,o.notMissing)(n)?n:(await this.setPendingEvent(e,t),this.getPendingEvent(e))}async getPendingEvent(e){return this.promiseStore?.getData(e)??null}async deleteEvent(e){return(await Promise.all([this.promiseStore?.delete(e),this.executorMethodStore?.delete(e)])).every(Boolean)}async resolveEvent(e,t){try{let n=await this.executorMethodStore?.getData(e);(0,o.isMissing)(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??6e4),n=await this.executorMethodStore?.getData(e)),n?.resolve?.(t)}catch(t){t instanceof Error&&this.logger.error({message:`Error handling event for key ${e}: ${t.message}`,category:this.constructor.name,context:{eventKey:e},error:t,code:D.EventClientResolveError})}}async defaultExecutorMethodDispose(e,t){(0,o.notMissing)(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):(0,o.notMissing)(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return(0,o.isObject)(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[]}getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:((0,o.isMissing)(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,(0,o.isMissing)(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}};let O=function(e){return e.RedisClientError=`RedisClientError`,e.RedisClientCommandError=`RedisClientCommandError`,e.RedisClientDeleteError=`RedisClientDeleteError`,e.RedisClientInvalidTTL=`RedisClientInvalidTTL`,e.RedisClientListError=`RedisClientListError`,e.RedisClientNotInitialized=`RedisClientNotInitialized`,e.RedisClientPublishError=`RedisClientPublishError`,e.RedisClientReadError=`RedisClientReadError`,e.RedisClientRedisNotReady=`RedisClientRedisNotReady`,e.RedisClientScriptError=`RedisClientScriptError`,e.RedisClientScriptExecuteError=`RedisClientScriptExecuteError`,e.RedisClientScriptLoadError=`RedisClientScriptLoadError`,e.RedisClientSubscribeError=`RedisClientSubscribeError`,e.RedisClientUnsubscribeError=`RedisClientUnsubscribeError`,e.RedisClientWriteError=`RedisClientWriteError`,e}({});const buildRedisClientInstance=async(e,t,n)=>{try{return await te.build(e,t,n)??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:O.RedisClientError,category:n??`buildRedisClientInstance`});return}};var te=class RedisClient{#e;#t;static async build({getRedisClient:e=s.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o},c,l){let u=new RedisClient;u.#t=c;try{u.#e=e({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:t,port:n,tls:r,keepAlive:i},database:o,disableOfflineQueue:!0});let s=getDefaultRedisListeners(l??`RedisClient`,u.#t);return addRedisEventHandlers(u.#e,s),await u.#e.connect(),u}catch(e){let t=e;return u.#t?.error({message:`Error building Cache Manager.`,error:t,code:O.RedisClientError,category:l??`RedisClient`}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}async getData(e){if(!this.#i())return null;try{let t=await this.#e.get(e);if(!t)return null;let n=this.#n(t);return(0,o.isString)(n)?t:n}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:O.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:O.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:O.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:O.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:O.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:O.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:O.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:O.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:O.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:O.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:O.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:O.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:O.RedisClientPublishError,category:RedisClient.name}),null}}getClient(){return this.#i()?this.#e:null}isAvailable(){return this.#e.isReady&&this.#e.isOpen}#i(){let e=this.isAvailable();return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:O.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:O.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:O.RedisClientDeleteError,category:RedisClient.name})}),n>0}catch(e){let t=e;return this.#t?.error({message:`Error deleting data`,error:t,code:O.RedisClientDeleteError,category:RedisClient.name}),!1}}};const addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:O.RedisClientError,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];let ne=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});const re=1500;var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0}async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let s=t??await buildRedisClientInstance(e,i,this.name);if((0,o.isMissing)(s))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=s,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();(0,o.notMissing)(e)&&(e.on(`ready`,async()=>{this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){if((0,o.notMissing)(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!((0,o.isMissing)(this.scripts)||Object.keys(this.scripts).length===0)){this.reloadInProgress=this.performReload();try{await this.reloadInProgress}finally{this.reloadInProgress=null}}}async performReload(){this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts),this.lastReloadTime=Date.now()}async loadScripts(e,t){if((0,o.notMissing)(t))for(let[e,n]of t)this.scriptMap.set(e,n);let n=Object.entries(e),r=n.map(([e])=>this.scriptMap.get(e)).filter(o.notMissing),i=new Map;if(r.length>0&&(0,o.notMissing)(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if((0,o.notMissing)(e)){r.forEach((t,n)=>{i.set(t,e[n]??!1)});let t=e.filter(Boolean).length;t>0&&this.logger?.info({message:`${t}/${r.length} scripts already exist in Redis; skipping load for existing scripts`,category:this.name})}}for(let[e,t]of n){let n=this.scriptMap.get(e);if(n&&i.get(n))continue;let r=await this.cacheClient?.loadScript?.(t);(0,o.notMissing)(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:ne.ScriptManagerLoadingError})}}async executeScript(e,t,n){if(!this.isRedisReady())return this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:t,args:n}}),null;let r=this.scriptMap?.get(e);if((0,o.isMissing)(r))throw this.logger?.error({message:`Script for ${e} not found in script map`,category:this.name,code:ne.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<re){let t=re-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:ne.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.subscriptionMap=null,this.subscriptionClient=null}};const ie=6e4,ae=15e3,oe=!1,se=6e4,ce=15e3,le=1e4,ue=1;let k=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),A=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});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:le,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:ce,truncateThreshold:le,truncationPercentage:1},{instantiator:this.name,evictionFrequency:ce,truncateThreshold:le,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0){try{let a=`${e}:${t}`;await this.subscriptionManager?.subscribe(a,async(n,r)=>{if(r.includes(a)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let o=await this.executeScript(n?A.lPush:A.rPush,[e],[t,`60000`])===1;return(!i||!o)&&await this.eventClient?.waitForEvent(a,15e3),await this.eventClient?.deleteEvent(a),await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:k.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(A.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:k.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(A.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:k.QueueManagerLengthError,context:{queueName:e}}),t}}isReady(){return(0,o.notMissing)(this.subscriptionManager)&&(0,o.notMissing)(this.cacheClient)&&(0,o.notMissing)(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const de=5,fe=12e4,pe=1e4,me=1,he=60,ge=90,j=`__keyevent@0__:`,_e=`${j}set`,ve=`${j}expire`,M=`${j}expired`,ye=`${j}srem`,be=`config_check_test_key`,xe=[_e,ve,M],Se=1,Ce=2e4,we={mainMaxConcurrency:30};let N=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e.ConcurrencyManagerPublishNextItemFailed=`ConcurrencyManagerPublishNextItemFailed`,e.ConcurrencyManagerReleaseRequestFailed=`ConcurrencyManagerReleaseRequestFailed`,e}({}),P=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const Te={[P.tryConcurrency]:`
|
|
2
2
|
local requestId = KEYS[1]
|
|
3
3
|
local targetKey = KEYS[2]
|
|
4
4
|
local queueKey = KEYS[3]
|
|
@@ -94,7 +94,7 @@ var e=Object.create,t=Object.defineProperty,__name=(e,n)=>t(e,`name`,{value:n,co
|
|
|
94
94
|
|
|
95
95
|
redis.call('publish', nextItemKey, nextItem)
|
|
96
96
|
end
|
|
97
|
-
`};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??o.generateRequestId,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.info({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if((0,o.isMissing)(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return(0,o.isMissing)(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(_e)&&n.includes(ve)&&n.includes(M)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(xe.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:N.ConcurrencyManagerRedisEventsEmitError}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return await this.subscriptionManager?.subscribe(M,async(n,r)=>{if(r===M&&n.includes(t)&&n.includes(e))try{await this.releaseRequest(e,t)}catch(n){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:{requestId:e,targetConcurrencyKey:t},error:n,code:N.ConcurrencyManagerReleaseRequestFailed})}})??!1}async subscribeToSetRemoval(e,t){return await this.subscriptionManager?.subscribe(ye,async(n,r)=>{if(r===ye&&n.includes(e))try{await this.executeScript(P.publishNextItem,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:N.ConcurrencyManagerPublishNextItemFailed})}})??!1}async registerRequest(e,t,n,r){let i=`concurrency:${e}`,a=`queue:${e}`,s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(r??``):r?.includes(e.urlPattern))?.subPoolKey,c=(0,o.notMissing)(s)?`${i}-${s}`:i,{mainMaxConcurrency:l,subPools:u}=t,d=[{key:i,maxConcurrency:l},...u?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${i}-${t}`,maxConcurrency:n}})??[]],f=d.map(e=>e.key),p=d.map(e=>e.maxConcurrency),[m,h]=await Promise.all([this.subscribeToLeaseExpiry(n,c),this.subscribeToSetRemoval(c,a)]),g={requestId:n,targetConcurrencyKey:c,leaseSubscription:m,setRemovalSubscription:h,queueKey:a},_=await this.executeScript(P.tryConcurrency,[n,c,a,...f],[`60`,l.toString(),`90`,...p.map(String)]);if((0,o.notMissing)(_)&&_[0])return{...g,joinCondition:`optimistic`,failureReason:_[1]};let v=0,y=[];for(;v<5;){let e=v>1,t=await this.queueManager?.joinAndWaitTurn(a,n,e,async(e,t)=>await this.executeScript(P.tryConcurrency,[n,c,a,...f],[`60`,l.toString(),`90`,...p.map(String)]),!1),r=(0,o.notMissing)(t)?t[0]:!1,i=(0,o.notMissing)(t)?t[1]:``;if((0,o.notMissing)(i)&&i!==``&&y.push(i),v++,r)return v>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${v} attempts.`,context:{...g,registerAttempts:v,joinCondition:`attempts`,failureMessages:y}}),{...g,joinCondition:`attempts`};await(0,o.delay)((0,o.exponentialBackoffInMS)(v,100))}return this.logger?.error({category:this.name,message:`Failed to register request after ${v} attempts.`,context:{...g,registerAttempts:v,joinCondition:`failed`,failureMessages:y},code:N.ConcurrencyManagerRegistrationFailed}),{...g,joinCondition:`failed`}}async releaseRequest(e,t){return(0,o.isString)(t)&&(0,o.isString)(e)?!!await this.executeScript(P.removeFromSet,[t],[e]):!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}close(){this.subscriptionManager?.close(),this.queueManager?.close(),this.scriptMap?.clear(),this.hasValidRedisConfig=!1}};const Ee={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t)=>{if((0,o.isMissing)(t)||t?.length===0||(0,o.isMissing)(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let n=t?.filter(t=>t.receivedStatus===e.status);if(n?.length)for(let t of n){let n=t.condition,r=(0,c.safeEvaluate)(n,e)===!0;if((0,o.isMissing)(n)||r)return{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:t?.message??Ee[t.targetStatus]??`Unknown error`}}return e},De=(0,o.zStrictObject)({receivedStatus:o.z.number(),targetStatus:o.z.number(),message:o.z.string().optional(),condition:o.z.string().optional()});var F=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let n=e.map(e=>safeSerialize(e,t));return t.delete(e),n}let n=e,r={};t.add(n);for(let[e,i]of Object.entries(n))r[e]=safeSerialize(i,t);return t.delete(n),r},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new u.default.Agent(n),d=l.default.create({...t,httpsAgent:c});if(e){let t={axiosInstance:d,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(d,e,t)}return d}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return(0,o.notMissing)(e)&&(0,o.isFunction)(e)&&typeof e(t)==`function`?e(t):e??null}};const Oe=300;var ke=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e){this.dataStore=null,this.initialize(e)}static getInstance(e){return(0,o.isMissing)(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(e){this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,typeGuard:e=>(0,o.notMissing)(e)}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:(0,o.notMissing)(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return(0,o.notMissing)(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const Ae=ke.getInstance(),abortErrorInterceptor=()=>__name(e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)},`abortErrorInterceptor`),je=7.5,Me={mainRatelimit:25};let Ne=function(e){return e.incr=`incr`,e}({}),I=function(e){return e.RateLimiterReleaseRequestFailed=`RateLimiterReleaseRequestFailed`,e.RateLimitOrConcurrencyManagerNotInitialized=`RateLimitOrConcurrencyManagerNotInitialized`,e.InterceptorContextNotPresent=`InterceptorContextNotPresent`,e.InterceptorMaxWaitTimeExceeded=`InterceptorMaxWaitTimeExceeded`,e}({});const createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&(0,f.clearTimeout)(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},Pe=`checkConcurrencyInterceptor`,checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>__name(async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:Pe,...a,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(t),hasConfig:(0,o.notMissing)(a)},code:I.InterceptorContextNotPresent});else if((0,o.isMissing)(i)||(0,o.isMissing)(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:Pe,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:(0,o.notMissing)(i),concurrencyManagerInitialized:(0,o.notMissing)(r)},code:I.RateLimitOrConcurrencyManagerNotInitialized});else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let o=(0,d.randomUUID)(),{provider:s,accountSecureId:c}=t,l=n?.rateLimits??Me,u=n?.concurrency??we,f=await i.getDynamicMaxWaitTime(l,u,a.url),register=async()=>r.registerRequest(`${c}-${s}`,u,o,a.url),p,m=0;for(;m<=f;){let n=Math.floor(Date.now()/1e3),r=await i.getWaitTime(`${c}-${s}`,l,a.url)??0,o=Math.max(r-n,0);if(r===0){p=await register();break}if(await abortableDelay(o*1e3,a),m+=o,m>=f){p=await register(),e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${s} - Account: ${c}`,context:{...t,interceptor:Pe,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:f},code:I.InterceptorMaxWaitTimeExceeded});break}}return{...a,requestMetadata:p}}return a},`checkConcurrencyInterceptor`),Fe=1,Ie=10,Le=5,Re=3250368e4,L=1e3,ze=/^\d+(\.\d+)?$/,Be=1e3,adjustUnixTimestamp=e=>e<3250368e4?e*L:e;var Ve=__commonJSMin(((e,t)=>{function _extends(){return t.exports=_extends=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},t.exports.__esModule=!0,t.exports.default=t.exports,_extends.apply(null,arguments)}t.exports=_extends,t.exports.__esModule=!0,t.exports.default=t.exports})),He={epsilon:1e-12,matrix:`Matrix`,number:`number`,precision:64,predictable:!1,randomSeed:null};function isNumber$1(e){return typeof e==`number`}__name(isNumber$1,`isNumber`);function isBigNumber(e){return!e||typeof e!=`object`||typeof e.constructor!=`function`?!1:e.isBigNumber===!0&&typeof e.constructor.prototype==`object`&&e.constructor.prototype.isBigNumber===!0||typeof e.constructor.isDecimal==`function`&&e.constructor.isDecimal(e)===!0}function isComplex(e){return e&&typeof e==`object`&&Object.getPrototypeOf(e).isComplex===!0||!1}function isFraction(e){return e&&typeof e==`object`&&Object.getPrototypeOf(e).isFraction===!0||!1}function isUnit(e){return e&&e.constructor.prototype.isUnit===!0||!1}function isString$1(e){return typeof e==`string`}__name(isString$1,`isString`);var R=Array.isArray;function isMatrix(e){return e&&e.constructor.prototype.isMatrix===!0||!1}function isCollection(e){return Array.isArray(e)||isMatrix(e)}function isDenseMatrix(e){return e&&e.isDenseMatrix&&e.constructor.prototype.isMatrix===!0||!1}function isSparseMatrix(e){return e&&e.isSparseMatrix&&e.constructor.prototype.isMatrix===!0||!1}function isRange(e){return e&&e.constructor.prototype.isRange===!0||!1}function isIndex(e){return e&&e.constructor.prototype.isIndex===!0||!1}function isBoolean(e){return typeof e==`boolean`}function isResultSet(e){return e&&e.constructor.prototype.isResultSet===!0||!1}function isHelp(e){return e&&e.constructor.prototype.isHelp===!0||!1}function isFunction(e){return typeof e==`function`}function isDate(e){return e instanceof Date}function isRegExp(e){return e instanceof RegExp}function isObject$2(e){return!!(e&&typeof e==`object`&&e.constructor===Object&&!isComplex(e)&&!isFraction(e))}__name(isObject$2,`isObject`);function isNull(e){return e===null}function isUndefined(e){return e===void 0}function isAccessorNode(e){return e&&e.isAccessorNode===!0&&e.constructor.prototype.isNode===!0||!1}function isArrayNode(e){return e&&e.isArrayNode===!0&&e.constructor.prototype.isNode===!0||!1}function isAssignmentNode(e){return e&&e.isAssignmentNode===!0&&e.constructor.prototype.isNode===!0||!1}function isBlockNode(e){return e&&e.isBlockNode===!0&&e.constructor.prototype.isNode===!0||!1}function isConditionalNode(e){return e&&e.isConditionalNode===!0&&e.constructor.prototype.isNode===!0||!1}function isConstantNode(e){return e&&e.isConstantNode===!0&&e.constructor.prototype.isNode===!0||!1}function isFunctionAssignmentNode(e){return e&&e.isFunctionAssignmentNode===!0&&e.constructor.prototype.isNode===!0||!1}function isFunctionNode(e){return e&&e.isFunctionNode===!0&&e.constructor.prototype.isNode===!0||!1}function isIndexNode(e){return e&&e.isIndexNode===!0&&e.constructor.prototype.isNode===!0||!1}function isNode(e){return e&&e.isNode===!0&&e.constructor.prototype.isNode===!0||!1}function isObjectNode(e){return e&&e.isObjectNode===!0&&e.constructor.prototype.isNode===!0||!1}function isOperatorNode(e){return e&&e.isOperatorNode===!0&&e.constructor.prototype.isNode===!0||!1}function isParenthesisNode(e){return e&&e.isParenthesisNode===!0&&e.constructor.prototype.isNode===!0||!1}function isRangeNode(e){return e&&e.isRangeNode===!0&&e.constructor.prototype.isNode===!0||!1}function isRelationalNode(e){return e&&e.isRelationalNode===!0&&e.constructor.prototype.isNode===!0||!1}function isSymbolNode(e){return e&&e.isSymbolNode===!0&&e.constructor.prototype.isNode===!0||!1}function isChain(e){return e&&e.constructor.prototype.isChain===!0||!1}function typeOf(e){var t=typeof e;return t===`object`?e===null?`null`:isBigNumber(e)?`BigNumber`:e.constructor&&e.constructor.name?e.constructor.name:`Object`:t}function clone$2(e){var t=typeof e;if(t===`number`||t===`string`||t===`boolean`||e==null)return e;if(typeof e.clone==`function`)return e.clone();if(Array.isArray(e))return e.map(function(e){return clone$2(e)});if(e instanceof Date)return new Date(e.valueOf());if(isBigNumber(e))return e;if(isObject$2(e))return mapObject(e,clone$2);throw TypeError(`Cannot clone: unknown type of value (value: ${e})`)}__name(clone$2,`clone`);function mapObject(e,t){var n={};for(var r in e)hasOwnProperty(e,r)&&(n[r]=t(e[r]));return n}function deepStrictEqual(e,t){var n,r,i;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(r=0,i=e.length;r<i;r++)if(!deepStrictEqual(e[r],t[r]))return!1;return!0}else if(typeof e==`function`)return e===t;else if(e instanceof Object){if(Array.isArray(t)||!(t instanceof Object))return!1;for(n in e)if(!(n in t)||!deepStrictEqual(e[n],t[n]))return!1;for(n in t)if(!(n in e))return!1;return!0}else return e===t}function hasOwnProperty(e,t){return e&&Object.hasOwnProperty.call(e,t)}function pickShallow(e,t){for(var n={},r=0;r<t.length;r++){var i=t[r],a=e[i];a!==void 0&&(n[i]=a)}return n}var Ue=[`Matrix`,`Array`],We=[`number`,`BigNumber`,`Fraction`],Ge=__toESM(Ve(),1),Ke=__name(function config$2(e){if(e)throw Error(`The global config is readonly.
|
|
97
|
+
`};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??o.generateRequestId,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.info({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if((0,o.isMissing)(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return(0,o.isMissing)(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(_e)&&n.includes(ve)&&n.includes(M)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(xe.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:N.ConcurrencyManagerRedisEventsEmitError}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return await this.subscriptionManager?.subscribe(M,async(n,r)=>{if(r===M&&n.includes(t)&&n.includes(e))try{await this.releaseRequest(e,t)}catch(n){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:{requestId:e,targetConcurrencyKey:t},error:n,code:N.ConcurrencyManagerReleaseRequestFailed})}})??!1}async subscribeToSetRemoval(e,t){return await this.subscriptionManager?.subscribe(ye,async(n,r)=>{if(r===ye&&n.includes(e))try{await this.executeScript(P.publishNextItem,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:N.ConcurrencyManagerPublishNextItemFailed})}})??!1}async registerRequest(e,t,n,r){let i=`concurrency:${e}`,a=`queue:${e}`,s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(r??``):r?.includes(e.urlPattern))?.subPoolKey,c=(0,o.notMissing)(s)?`${i}-${s}`:i,{mainMaxConcurrency:l,subPools:u}=t,d=[{key:i,maxConcurrency:l},...u?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${i}-${t}`,maxConcurrency:n}})??[]],f=d.map(e=>e.key),p=d.map(e=>e.maxConcurrency),[m,h]=await Promise.all([this.subscribeToLeaseExpiry(n,c),this.subscribeToSetRemoval(c,a)]),g={requestId:n,targetConcurrencyKey:c,leaseSubscription:m,setRemovalSubscription:h,queueKey:a},_=await this.executeScript(P.tryConcurrency,[n,c,a,...f],[`60`,l.toString(),`90`,...p.map(String)]);if((0,o.notMissing)(_)&&_[0])return{...g,joinCondition:`optimistic`,failureReason:_[1]};let v=0,y=[];for(;v<5;){let e=v>1,t=await this.queueManager?.joinAndWaitTurn(a,n,e,async(e,t)=>await this.executeScript(P.tryConcurrency,[n,c,a,...f],[`60`,l.toString(),`90`,...p.map(String)]),!1),r=(0,o.notMissing)(t)?t[0]:!1,i=(0,o.notMissing)(t)?t[1]:``;if((0,o.notMissing)(i)&&i!==``&&y.push(i),v++,r)return v>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${v} attempts.`,context:{...g,registerAttempts:v,joinCondition:`attempts`,failureMessages:y}}),{...g,joinCondition:`attempts`};await(0,o.delay)((0,o.exponentialBackoffInMS)(v,100))}return this.logger?.error({category:this.name,message:`Failed to register request after ${v} attempts.`,context:{...g,registerAttempts:v,joinCondition:`failed`,failureMessages:y},code:N.ConcurrencyManagerRegistrationFailed}),{...g,joinCondition:`failed`}}async releaseRequest(e,t){return(0,o.isString)(t)&&(0,o.isString)(e)?!!await this.executeScript(P.removeFromSet,[t],[e]):!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}close(){this.subscriptionManager?.close(),this.queueManager?.close(),this.scriptMap?.clear(),this.hasValidRedisConfig=!1}};const Ee={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t)=>{if((0,o.isMissing)(t)||t?.length===0||(0,o.isMissing)(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let n=t?.filter(t=>t.receivedStatus===e.status);if(n?.length)for(let t of n){let n=t.condition,r=(0,c.safeEvaluate)(n,e)===!0;if((0,o.isMissing)(n)||r)return{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:t?.message??Ee[t.targetStatus]??`Unknown error`}}return e},De=(0,o.zStrictObject)({receivedStatus:o.z.number(),targetStatus:o.z.number(),message:o.z.string().optional(),condition:o.z.string().optional()});var F=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let n=e.map(e=>safeSerialize(e,t));return t.delete(e),n}let n=e,r={};t.add(n);for(let[e,i]of Object.entries(n))r[e]=safeSerialize(i,t);return t.delete(n),r},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new u.default.Agent(n),d=l.default.create({...t,httpsAgent:c});if(e){let t={axiosInstance:d,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(d,e,t)}return d}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return(0,o.notMissing)(e)&&(0,o.isFunction)(e)&&typeof e(t)==`function`?e(t):e??null}};const Oe=300;var ke=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return(0,o.isMissing)(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,typeGuard:e=>(0,o.notMissing)(e)}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:(0,o.notMissing)(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return(0,o.notMissing)(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const Ae=ke.getInstance(),abortErrorInterceptor=()=>__name(e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)},`abortErrorInterceptor`),je=7.5,Me={mainRatelimit:25};let Ne=function(e){return e.incr=`incr`,e}({}),I=function(e){return e.RateLimiterReleaseRequestFailed=`RateLimiterReleaseRequestFailed`,e.RateLimitOrConcurrencyManagerNotInitialized=`RateLimitOrConcurrencyManagerNotInitialized`,e.InterceptorContextNotPresent=`InterceptorContextNotPresent`,e.InterceptorMaxWaitTimeExceeded=`InterceptorMaxWaitTimeExceeded`,e}({});const createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&(0,f.clearTimeout)(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},Pe=`checkConcurrencyInterceptor`,checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>__name(async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:Pe,...a,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(t),hasConfig:(0,o.notMissing)(a)},code:I.InterceptorContextNotPresent});else if((0,o.isMissing)(i)||(0,o.isMissing)(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:Pe,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:(0,o.notMissing)(i),concurrencyManagerInitialized:(0,o.notMissing)(r)},code:I.RateLimitOrConcurrencyManagerNotInitialized});else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let o=(0,d.randomUUID)(),{provider:s,accountSecureId:c}=t,l=n?.rateLimits??Me,u=n?.concurrency??we,f=await i.getDynamicMaxWaitTime(l,u,a.url),register=async()=>r.registerRequest(`${c}-${s}`,u,o,a.url),p,m=0;for(;m<=f;){let n=Math.floor(Date.now()/1e3),r=await i.getWaitTime(`${c}-${s}`,l,a.url)??0,o=Math.max(r-n,0);if(r===0){p=await register();break}if(await abortableDelay(o*1e3,a),m+=o,m>=f){p=await register(),e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${s} - Account: ${c}`,context:{...t,interceptor:Pe,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:f},code:I.InterceptorMaxWaitTimeExceeded});break}}return{...a,requestMetadata:p}}return a},`checkConcurrencyInterceptor`),Fe=1,Ie=10,Le=5,Re=3250368e4,L=1e3,ze=/^\d+(\.\d+)?$/,Be=1e3,adjustUnixTimestamp=e=>e<3250368e4?e*L:e;var Ve=__commonJSMin(((e,t)=>{function _extends(){return t.exports=_extends=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},t.exports.__esModule=!0,t.exports.default=t.exports,_extends.apply(null,arguments)}t.exports=_extends,t.exports.__esModule=!0,t.exports.default=t.exports})),He={epsilon:1e-12,matrix:`Matrix`,number:`number`,precision:64,predictable:!1,randomSeed:null};function isNumber$1(e){return typeof e==`number`}__name(isNumber$1,`isNumber`);function isBigNumber(e){return!e||typeof e!=`object`||typeof e.constructor!=`function`?!1:e.isBigNumber===!0&&typeof e.constructor.prototype==`object`&&e.constructor.prototype.isBigNumber===!0||typeof e.constructor.isDecimal==`function`&&e.constructor.isDecimal(e)===!0}function isComplex(e){return e&&typeof e==`object`&&Object.getPrototypeOf(e).isComplex===!0||!1}function isFraction(e){return e&&typeof e==`object`&&Object.getPrototypeOf(e).isFraction===!0||!1}function isUnit(e){return e&&e.constructor.prototype.isUnit===!0||!1}function isString$1(e){return typeof e==`string`}__name(isString$1,`isString`);var R=Array.isArray;function isMatrix(e){return e&&e.constructor.prototype.isMatrix===!0||!1}function isCollection(e){return Array.isArray(e)||isMatrix(e)}function isDenseMatrix(e){return e&&e.isDenseMatrix&&e.constructor.prototype.isMatrix===!0||!1}function isSparseMatrix(e){return e&&e.isSparseMatrix&&e.constructor.prototype.isMatrix===!0||!1}function isRange(e){return e&&e.constructor.prototype.isRange===!0||!1}function isIndex(e){return e&&e.constructor.prototype.isIndex===!0||!1}function isBoolean(e){return typeof e==`boolean`}function isResultSet(e){return e&&e.constructor.prototype.isResultSet===!0||!1}function isHelp(e){return e&&e.constructor.prototype.isHelp===!0||!1}function isFunction(e){return typeof e==`function`}function isDate(e){return e instanceof Date}function isRegExp(e){return e instanceof RegExp}function isObject$2(e){return!!(e&&typeof e==`object`&&e.constructor===Object&&!isComplex(e)&&!isFraction(e))}__name(isObject$2,`isObject`);function isNull(e){return e===null}function isUndefined(e){return e===void 0}function isAccessorNode(e){return e&&e.isAccessorNode===!0&&e.constructor.prototype.isNode===!0||!1}function isArrayNode(e){return e&&e.isArrayNode===!0&&e.constructor.prototype.isNode===!0||!1}function isAssignmentNode(e){return e&&e.isAssignmentNode===!0&&e.constructor.prototype.isNode===!0||!1}function isBlockNode(e){return e&&e.isBlockNode===!0&&e.constructor.prototype.isNode===!0||!1}function isConditionalNode(e){return e&&e.isConditionalNode===!0&&e.constructor.prototype.isNode===!0||!1}function isConstantNode(e){return e&&e.isConstantNode===!0&&e.constructor.prototype.isNode===!0||!1}function isFunctionAssignmentNode(e){return e&&e.isFunctionAssignmentNode===!0&&e.constructor.prototype.isNode===!0||!1}function isFunctionNode(e){return e&&e.isFunctionNode===!0&&e.constructor.prototype.isNode===!0||!1}function isIndexNode(e){return e&&e.isIndexNode===!0&&e.constructor.prototype.isNode===!0||!1}function isNode(e){return e&&e.isNode===!0&&e.constructor.prototype.isNode===!0||!1}function isObjectNode(e){return e&&e.isObjectNode===!0&&e.constructor.prototype.isNode===!0||!1}function isOperatorNode(e){return e&&e.isOperatorNode===!0&&e.constructor.prototype.isNode===!0||!1}function isParenthesisNode(e){return e&&e.isParenthesisNode===!0&&e.constructor.prototype.isNode===!0||!1}function isRangeNode(e){return e&&e.isRangeNode===!0&&e.constructor.prototype.isNode===!0||!1}function isRelationalNode(e){return e&&e.isRelationalNode===!0&&e.constructor.prototype.isNode===!0||!1}function isSymbolNode(e){return e&&e.isSymbolNode===!0&&e.constructor.prototype.isNode===!0||!1}function isChain(e){return e&&e.constructor.prototype.isChain===!0||!1}function typeOf(e){var t=typeof e;return t===`object`?e===null?`null`:isBigNumber(e)?`BigNumber`:e.constructor&&e.constructor.name?e.constructor.name:`Object`:t}function clone$2(e){var t=typeof e;if(t===`number`||t===`string`||t===`boolean`||e==null)return e;if(typeof e.clone==`function`)return e.clone();if(Array.isArray(e))return e.map(function(e){return clone$2(e)});if(e instanceof Date)return new Date(e.valueOf());if(isBigNumber(e))return e;if(isObject$2(e))return mapObject(e,clone$2);throw TypeError(`Cannot clone: unknown type of value (value: ${e})`)}__name(clone$2,`clone`);function mapObject(e,t){var n={};for(var r in e)hasOwnProperty(e,r)&&(n[r]=t(e[r]));return n}function deepStrictEqual(e,t){var n,r,i;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(r=0,i=e.length;r<i;r++)if(!deepStrictEqual(e[r],t[r]))return!1;return!0}else if(typeof e==`function`)return e===t;else if(e instanceof Object){if(Array.isArray(t)||!(t instanceof Object))return!1;for(n in e)if(!(n in t)||!deepStrictEqual(e[n],t[n]))return!1;for(n in t)if(!(n in e))return!1;return!0}else return e===t}function hasOwnProperty(e,t){return e&&Object.hasOwnProperty.call(e,t)}function pickShallow(e,t){for(var n={},r=0;r<t.length;r++){var i=t[r],a=e[i];a!==void 0&&(n[i]=a)}return n}var Ue=[`Matrix`,`Array`],We=[`number`,`BigNumber`,`Fraction`],Ge=__toESM(Ve(),1),Ke=__name(function config$2(e){if(e)throw Error(`The global config is readonly.
|
|
98
98
|
Please create a mathjs instance if you want to change the default configuration.
|
|
99
99
|
Example:
|
|
100
100
|
|
package/dist/index.d.cts
CHANGED
|
@@ -116,6 +116,7 @@ declare abstract class AsyncSingleton<T, O> {
|
|
|
116
116
|
//#endregion
|
|
117
117
|
//#region src/cacheClient/types.d.ts
|
|
118
118
|
interface ICacheClient<ClientType = unknown> {
|
|
119
|
+
isAvailable(): boolean;
|
|
119
120
|
getData<T>(key: string): Promise<T | null>;
|
|
120
121
|
getDataKeysFromGroup(groupKey: string): Promise<string[] | null>;
|
|
121
122
|
listData<T>({
|
|
@@ -225,6 +226,7 @@ declare class RedisClient implements ICacheClient<RedisClientType> {
|
|
|
225
226
|
unsubscribe(pattern: string): Promise<boolean>;
|
|
226
227
|
publish(channel: string, message: string): Promise<number | null>;
|
|
227
228
|
getClient(): RedisClientType | null;
|
|
229
|
+
isAvailable(): boolean;
|
|
228
230
|
listData<T>({
|
|
229
231
|
partialKey,
|
|
230
232
|
limit,
|
|
@@ -929,8 +931,13 @@ declare class InstanceManager {
|
|
|
929
931
|
private static instance;
|
|
930
932
|
private static logger;
|
|
931
933
|
private dataStore;
|
|
934
|
+
private options;
|
|
932
935
|
private constructor();
|
|
933
|
-
static getInstance(
|
|
936
|
+
static getInstance(options?: {
|
|
937
|
+
logger?: ILogger;
|
|
938
|
+
staleDataThreshold?: number;
|
|
939
|
+
truncateThreshold?: number;
|
|
940
|
+
}): InstanceManager;
|
|
934
941
|
private initialize;
|
|
935
942
|
get<T>(key: string): Promise<T | null>;
|
|
936
943
|
set<T>(key: string, value: T, cacheTTL?: number): Promise<boolean>;
|
|
@@ -987,6 +994,7 @@ declare class MemoryStore<T> implements ICacheClient {
|
|
|
987
994
|
private stopEvictionTask;
|
|
988
995
|
private updateLastAccessedAt;
|
|
989
996
|
isReady(): boolean;
|
|
997
|
+
isAvailable(): boolean;
|
|
990
998
|
setTTL(key: string, cacheTTL: number): Promise<boolean>;
|
|
991
999
|
close(): void;
|
|
992
1000
|
listData<T>({
|
package/dist/index.d.mts
CHANGED
|
@@ -115,6 +115,7 @@ declare abstract class AsyncSingleton<T, O> {
|
|
|
115
115
|
//#endregion
|
|
116
116
|
//#region src/cacheClient/types.d.ts
|
|
117
117
|
interface ICacheClient<ClientType = unknown> {
|
|
118
|
+
isAvailable(): boolean;
|
|
118
119
|
getData<T>(key: string): Promise<T | null>;
|
|
119
120
|
getDataKeysFromGroup(groupKey: string): Promise<string[] | null>;
|
|
120
121
|
listData<T>({
|
|
@@ -224,6 +225,7 @@ declare class RedisClient implements ICacheClient<RedisClientType> {
|
|
|
224
225
|
unsubscribe(pattern: string): Promise<boolean>;
|
|
225
226
|
publish(channel: string, message: string): Promise<number | null>;
|
|
226
227
|
getClient(): RedisClientType | null;
|
|
228
|
+
isAvailable(): boolean;
|
|
227
229
|
listData<T>({
|
|
228
230
|
partialKey,
|
|
229
231
|
limit,
|
|
@@ -928,8 +930,13 @@ declare class InstanceManager {
|
|
|
928
930
|
private static instance;
|
|
929
931
|
private static logger;
|
|
930
932
|
private dataStore;
|
|
933
|
+
private options;
|
|
931
934
|
private constructor();
|
|
932
|
-
static getInstance(
|
|
935
|
+
static getInstance(options?: {
|
|
936
|
+
logger?: ILogger;
|
|
937
|
+
staleDataThreshold?: number;
|
|
938
|
+
truncateThreshold?: number;
|
|
939
|
+
}): InstanceManager;
|
|
933
940
|
private initialize;
|
|
934
941
|
get<T>(key: string): Promise<T | null>;
|
|
935
942
|
set<T>(key: string, value: T, cacheTTL?: number): Promise<boolean>;
|
|
@@ -986,6 +993,7 @@ declare class MemoryStore<T> implements ICacheClient {
|
|
|
986
993
|
private stopEvictionTask;
|
|
987
994
|
private updateLastAccessedAt;
|
|
988
995
|
isReady(): boolean;
|
|
996
|
+
isAvailable(): boolean;
|
|
989
997
|
setTTL(key: string, cacheTTL: number): Promise<boolean>;
|
|
990
998
|
close(): void;
|
|
991
999
|
listData<T>({
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e,r as t,t as n}from"./chunk-hhuvQGXm.mjs";import{delay as r,exponentialBackoffInMS as i,generateRequestId as a,getContentHash as o,isFunction as s,isFutureUnixTimestamp as c,isMissing as l,isNumber as u,isObject as d,isString as f,notMissing as p,z as m,zStrictObject as h}from"@stackone/utils";import*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{randomUUID as S}from"crypto";import{clearTimeout as C}from"node:timers";import{JSONPath as w}from"jsonpath-plus";import{redactUrl as T}from"@stackone/redaction";import E from"qs";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 D=1e3;let O=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async getDataKeysFromGroup(e){this.isReady()||this.initialize(),this.updateLastAccessedAt();let t=this.groupExpiryMap.get(e);return p(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),[]):Array.from(this.groupMap.get(e)??[])}async setData({key:e,value:t,cacheTTL:n=60,groupKeys:r,groupKeyTTL:i}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),p(this.typeGuard)&&!this.typeGuard(t))return!1;let a=n*D,o=Date.now()+a;if(await this.lockManager.withLock(e,async()=>{(p(this.typeGuard)&&this.typeGuard(t)||l(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,o)}),p(r)&&r.length>0){let t=p(i)&&Number.isFinite(i)&&i>0?i*D:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,new Set),this.groupMap.get(n)?.add(e),p(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(p(t)&&t.length>0)for(let n of t)this.groupMap.get(n)?.delete(e);return this.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=0;return this.dataStore.forEach(async(e,i)=>{let a=Date.now(),o=this.expiryMap.get(i)??0,s=this.truncateThreshold*this.truncationPercentage/100;(o<=a||t&&r>=0&&r<=s)&&n.push(this.lockManager.withLock(i,async()=>(this.dispose&&await this.dispose(i,e),this.dataStore.delete(i)))),r++}),await Promise.all(n),{dataStoreSize:e,prunedDataStoreSize:this.dataStore.size}}startEvictionTask(){if(p(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`}),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:O.MemoryStorePruneError}),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}finally{if(p(e?.dataStoreSize)&&p(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 p(this.evictionInterval)&&p(this.dataStore)&&p(this.expiryMap)&&p(this.lockManager)}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*D;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n)}),!0}close(){this.stopEvictionTask(),this.dataStore.clear(),this.expiryMap.clear(),this.groupMap.clear(),this.groupExpiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()).filter(t=>t.includes(e)),i=[],a=t?parseInt(t,10):0;for(let e=a;e<n+a;e++){let t=r[e];if(!t)break;let a=await this.getData(t);if(a&&i.push(a),i.length>=n)break}return{items:i,cursor:i.length<n?void 0:(a+n).toString()}}};let k=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var EventClient=class{constructor(e,t,n){this.executorMethodStore=null,this.promiseStore=null,this.eventClientConfig=null,this.executorMethodStoreConfig=null,this.pendingPromiseStoreConfig=null,this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new MemoryStore(i),this.promiseStore=new MemoryStore(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/1e3;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return p(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);l(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:k.EventClientResolveError})}}async defaultExecutorMethodDispose(e,t){p(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):p(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return d(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[]}getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:(l(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,l(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}};let A=function(e){return e.RedisClientError=`RedisClientError`,e.RedisClientCommandError=`RedisClientCommandError`,e.RedisClientDeleteError=`RedisClientDeleteError`,e.RedisClientInvalidTTL=`RedisClientInvalidTTL`,e.RedisClientListError=`RedisClientListError`,e.RedisClientNotInitialized=`RedisClientNotInitialized`,e.RedisClientPublishError=`RedisClientPublishError`,e.RedisClientReadError=`RedisClientReadError`,e.RedisClientRedisNotReady=`RedisClientRedisNotReady`,e.RedisClientScriptError=`RedisClientScriptError`,e.RedisClientScriptExecuteError=`RedisClientScriptExecuteError`,e.RedisClientScriptLoadError=`RedisClientScriptLoadError`,e.RedisClientSubscribeError=`RedisClientSubscribeError`,e.RedisClientUnsubscribeError=`RedisClientUnsubscribeError`,e.RedisClientWriteError=`RedisClientWriteError`,e}({});const buildRedisClientInstance=async(e,t,n)=>{try{return await ee.build(e,t,n)??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:A.RedisClientError,category:n??`buildRedisClientInstance`});return}};var ee=class RedisClient{#e;#t;static async build({getRedisClient:e=g.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o},s,c){let l=new RedisClient;l.#t=s;try{l.#e=e({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:t,port:n,tls:r,keepAlive:i},database:o,disableOfflineQueue:!0});let s=getDefaultRedisListeners(c??`RedisClient`,l.#t);return addRedisEventHandlers(l.#e,s),await l.#e.connect(),l}catch(e){let t=e;return l.#t?.error({message:`Error building Cache Manager.`,error:t,code:A.RedisClientError,category:c??`RedisClient`}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}async getData(e){if(!this.#i())return null;try{let t=await this.#e.get(e);if(!t)return null;let n=this.#n(t);return f(n)?t:n}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:A.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:A.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=f(t)?t:JSON.stringify(t);if(await this.#e.set(e,a,{EX:n}),p(r)&&r.length>0)for(let t of r)await this.#e.sAdd(t,[e]),p(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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.RedisClientPublishError,category:RedisClient.name}),null}}getClient(){return this.#i()?this.#e:null}#i(){let e=this.#e.isReady&&this.#e.isOpen;return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:A.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);p(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:A.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}),p(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:A.RedisClientDeleteError,category:RedisClient.name})}),n>0}catch(e){let t=e;return this.#t?.error({message:`Error deleting data`,error:t,code:A.RedisClientDeleteError,category:RedisClient.name}),!1}}};const addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:A.RedisClientError,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];let te=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});const ne=1500;var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0}async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let o=t??await buildRedisClientInstance(e,i,this.name);if(l(o))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=o,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();p(e)&&(e.on(`ready`,async()=>{this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){if(p(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!(l(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(p(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(p),i=new Map;if(r.length>0&&p(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if(p(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);p(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:te.ScriptManagerLoadingError})}}async executeScript(e,t,n){if(!this.isRedisReady())return this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:t,args:n}}),null;let i=this.scriptMap?.get(e);if(l(i))throw this.logger?.error({message:`Script for ${e} not found in script map`,category:this.name,code:te.ScriptManagerExecutionError}),Error(`Script for ${e} not found`);try{return await this.cacheClient?.executeScript?.({sha1:i,keys:t,args:n})??null}catch(a){if(a instanceof Error&&a.message.includes(`NOSCRIPT`)){let a=Date.now()-this.lastReloadTime;if(a<ne){let t=ne-a;this.logger?.info({message:`Script ${e} not found, reload occurred ${a}ms ago. Waiting ${t}ms before reloading`,category:this.name}),await r(t)}if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),i=this.scriptMap?.get(e),l(i))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:i,keys:t,args:n})??null}throw a instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${a.message}`,category:this.name,context:{keys:t,args:n},error:a,code:te.ScriptManagerExecutionError}),a}}isRedisReady(){let e=this.cacheClient?.getClient?.();if(p(this.cacheClient)&&l(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()&&p(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)}}),p(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=o(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 p(this.subscriptionClient)&&p(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionMap=null,this.subscriptionClient=null}};const re=15e3,ie=1e4;let ae=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),j=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});var QueueManager=class extends ScriptManager{constructor(...e){super(...e),this.subscriptionManager=null,this.eventClient=null,this.name=`QueueManager`}async additionalInitialization(){if(l(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:ie,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:re,truncateThreshold:ie,truncationPercentage:1},{instantiator:this.name,evictionFrequency:re,truncateThreshold:ie,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0){try{let a=`${e}:${t}`;await this.subscriptionManager?.subscribe(a,async(n,r)=>{if(r.includes(a)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let o=await this.executeScript(n?j.lPush:j.rPush,[e],[t,`60000`])===1;return(!i||!o)&&await this.eventClient?.waitForEvent(a,15e3),await this.eventClient?.deleteEvent(a),await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:ae.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(j.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:ae.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(j.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:ae.QueueManagerLengthError,context:{queueName:e}}),t}}isReady(){return p(this.subscriptionManager)&&p(this.cacheClient)&&p(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const M=`__keyevent@0__:`,oe=`${M}set`,se=`${M}expire`,N=`${M}expired`,ce=`${M}srem`,le=[oe,se,N],ue={mainMaxConcurrency:30};let P=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e.ConcurrencyManagerPublishNextItemFailed=`ConcurrencyManagerPublishNextItemFailed`,e.ConcurrencyManagerReleaseRequestFailed=`ConcurrencyManagerReleaseRequestFailed`,e}({}),F=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const de={[F.tryConcurrency]:`
|
|
1
|
+
import{n as e,r as t,t as n}from"./chunk-hhuvQGXm.mjs";import{delay as r,exponentialBackoffInMS as i,generateRequestId as a,getContentHash as o,isFunction as s,isFutureUnixTimestamp as c,isMissing as l,isNumber as u,isObject as d,isString as f,notMissing as p,z as m,zStrictObject as h}from"@stackone/utils";import*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{randomUUID as S}from"crypto";import{clearTimeout as C}from"node:timers";import{JSONPath as w}from"jsonpath-plus";import{redactUrl as T}from"@stackone/redaction";import E from"qs";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 D=1e3;let O=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async getDataKeysFromGroup(e){this.isReady()||this.initialize(),this.updateLastAccessedAt();let t=this.groupExpiryMap.get(e);return p(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),[]):Array.from(this.groupMap.get(e)??[])}async setData({key:e,value:t,cacheTTL:n=60,groupKeys:r,groupKeyTTL:i}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),p(this.typeGuard)&&!this.typeGuard(t))return!1;let a=n*D,o=Date.now()+a;if(await this.lockManager.withLock(e,async()=>{(p(this.typeGuard)&&this.typeGuard(t)||l(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,o)}),p(r)&&r.length>0){let t=p(i)&&Number.isFinite(i)&&i>0?i*D:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,new Set),this.groupMap.get(n)?.add(e),p(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(p(t)&&t.length>0)for(let n of t)this.groupMap.get(n)?.delete(e);return this.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=0;return this.dataStore.forEach(async(e,i)=>{let a=Date.now(),o=this.expiryMap.get(i)??0,s=this.truncateThreshold*this.truncationPercentage/100;(o<=a||t&&r>=0&&r<=s)&&n.push(this.lockManager.withLock(i,async()=>(this.dispose&&await this.dispose(i,e),this.dataStore.delete(i)))),r++}),await Promise.all(n),{dataStoreSize:e,prunedDataStoreSize:this.dataStore.size}}startEvictionTask(){if(p(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`}),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:O.MemoryStorePruneError}),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}finally{if(p(e?.dataStoreSize)&&p(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 p(this.evictionInterval)&&p(this.dataStore)&&p(this.expiryMap)&&p(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*D;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n)}),!0}close(){this.stopEvictionTask(),this.dataStore.clear(),this.expiryMap.clear(),this.groupMap.clear(),this.groupExpiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()).filter(t=>t.includes(e)),i=[],a=t?parseInt(t,10):0;for(let e=a;e<n+a;e++){let t=r[e];if(!t)break;let a=await this.getData(t);if(a&&i.push(a),i.length>=n)break}return{items:i,cursor:i.length<n?void 0:(a+n).toString()}}};let k=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var EventClient=class{constructor(e,t,n){this.executorMethodStore=null,this.promiseStore=null,this.eventClientConfig=null,this.executorMethodStoreConfig=null,this.pendingPromiseStoreConfig=null,this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new MemoryStore(i),this.promiseStore=new MemoryStore(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/1e3;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return p(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);l(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:k.EventClientResolveError})}}async defaultExecutorMethodDispose(e,t){p(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):p(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return d(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[]}getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:(l(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,l(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}};let A=function(e){return e.RedisClientError=`RedisClientError`,e.RedisClientCommandError=`RedisClientCommandError`,e.RedisClientDeleteError=`RedisClientDeleteError`,e.RedisClientInvalidTTL=`RedisClientInvalidTTL`,e.RedisClientListError=`RedisClientListError`,e.RedisClientNotInitialized=`RedisClientNotInitialized`,e.RedisClientPublishError=`RedisClientPublishError`,e.RedisClientReadError=`RedisClientReadError`,e.RedisClientRedisNotReady=`RedisClientRedisNotReady`,e.RedisClientScriptError=`RedisClientScriptError`,e.RedisClientScriptExecuteError=`RedisClientScriptExecuteError`,e.RedisClientScriptLoadError=`RedisClientScriptLoadError`,e.RedisClientSubscribeError=`RedisClientSubscribeError`,e.RedisClientUnsubscribeError=`RedisClientUnsubscribeError`,e.RedisClientWriteError=`RedisClientWriteError`,e}({});const buildRedisClientInstance=async(e,t,n)=>{try{return await ee.build(e,t,n)??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:A.RedisClientError,category:n??`buildRedisClientInstance`});return}};var ee=class RedisClient{#e;#t;static async build({getRedisClient:e=g.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o},s,c){let l=new RedisClient;l.#t=s;try{l.#e=e({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:t,port:n,tls:r,keepAlive:i},database:o,disableOfflineQueue:!0});let s=getDefaultRedisListeners(c??`RedisClient`,l.#t);return addRedisEventHandlers(l.#e,s),await l.#e.connect(),l}catch(e){let t=e;return l.#t?.error({message:`Error building Cache Manager.`,error:t,code:A.RedisClientError,category:c??`RedisClient`}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}async getData(e){if(!this.#i())return null;try{let t=await this.#e.get(e);if(!t)return null;let n=this.#n(t);return f(n)?t:n}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:A.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:A.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=f(t)?t:JSON.stringify(t);if(await this.#e.set(e,a,{EX:n}),p(r)&&r.length>0)for(let t of r)await this.#e.sAdd(t,[e]),p(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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.RedisClientPublishError,category:RedisClient.name}),null}}getClient(){return this.#i()?this.#e:null}isAvailable(){return this.#e.isReady&&this.#e.isOpen}#i(){let e=this.isAvailable();return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:A.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);p(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:A.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}),p(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:A.RedisClientDeleteError,category:RedisClient.name})}),n>0}catch(e){let t=e;return this.#t?.error({message:`Error deleting data`,error:t,code:A.RedisClientDeleteError,category:RedisClient.name}),!1}}};const addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:A.RedisClientError,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];let te=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});const ne=1500;var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0}async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let o=t??await buildRedisClientInstance(e,i,this.name);if(l(o))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=o,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();p(e)&&(e.on(`ready`,async()=>{this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){if(p(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!(l(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(p(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(p),i=new Map;if(r.length>0&&p(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if(p(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);p(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:te.ScriptManagerLoadingError})}}async executeScript(e,t,n){if(!this.isRedisReady())return this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:t,args:n}}),null;let i=this.scriptMap?.get(e);if(l(i))throw this.logger?.error({message:`Script for ${e} not found in script map`,category:this.name,code:te.ScriptManagerExecutionError}),Error(`Script for ${e} not found`);try{return await this.cacheClient?.executeScript?.({sha1:i,keys:t,args:n})??null}catch(a){if(a instanceof Error&&a.message.includes(`NOSCRIPT`)){let a=Date.now()-this.lastReloadTime;if(a<ne){let t=ne-a;this.logger?.info({message:`Script ${e} not found, reload occurred ${a}ms ago. Waiting ${t}ms before reloading`,category:this.name}),await r(t)}if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),i=this.scriptMap?.get(e),l(i))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:i,keys:t,args:n})??null}throw a instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${a.message}`,category:this.name,context:{keys:t,args:n},error:a,code:te.ScriptManagerExecutionError}),a}}isRedisReady(){let e=this.cacheClient?.getClient?.();if(p(this.cacheClient)&&l(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()&&p(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)}}),p(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=o(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 p(this.subscriptionClient)&&p(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionMap=null,this.subscriptionClient=null}};const re=15e3,ie=1e4;let ae=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),j=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});var QueueManager=class extends ScriptManager{constructor(...e){super(...e),this.subscriptionManager=null,this.eventClient=null,this.name=`QueueManager`}async additionalInitialization(){if(l(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:ie,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:re,truncateThreshold:ie,truncationPercentage:1},{instantiator:this.name,evictionFrequency:re,truncateThreshold:ie,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0){try{let a=`${e}:${t}`;await this.subscriptionManager?.subscribe(a,async(n,r)=>{if(r.includes(a)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let o=await this.executeScript(n?j.lPush:j.rPush,[e],[t,`60000`])===1;return(!i||!o)&&await this.eventClient?.waitForEvent(a,15e3),await this.eventClient?.deleteEvent(a),await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:ae.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(j.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:ae.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(j.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:ae.QueueManagerLengthError,context:{queueName:e}}),t}}isReady(){return p(this.subscriptionManager)&&p(this.cacheClient)&&p(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const M=`__keyevent@0__:`,oe=`${M}set`,se=`${M}expire`,N=`${M}expired`,ce=`${M}srem`,le=[oe,se,N],ue={mainMaxConcurrency:30};let P=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e.ConcurrencyManagerPublishNextItemFailed=`ConcurrencyManagerPublishNextItemFailed`,e.ConcurrencyManagerReleaseRequestFailed=`ConcurrencyManagerReleaseRequestFailed`,e}({}),F=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const de={[F.tryConcurrency]:`
|
|
2
2
|
local requestId = KEYS[1]
|
|
3
3
|
local targetKey = KEYS[2]
|
|
4
4
|
local queueKey = KEYS[3]
|
|
@@ -94,7 +94,7 @@ import{n as e,r as t,t as n}from"./chunk-hhuvQGXm.mjs";import{delay as r,exponen
|
|
|
94
94
|
|
|
95
95
|
redis.call('publish', nextItemKey, nextItem)
|
|
96
96
|
end
|
|
97
|
-
`};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??a,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.info({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if(l(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return l(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(oe)&&n.includes(se)&&n.includes(N)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(le.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:P.ConcurrencyManagerRedisEventsEmitError}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return await this.subscriptionManager?.subscribe(N,async(n,r)=>{if(r===N&&n.includes(t)&&n.includes(e))try{await this.releaseRequest(e,t)}catch(n){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:{requestId:e,targetConcurrencyKey:t},error:n,code:P.ConcurrencyManagerReleaseRequestFailed})}})??!1}async subscribeToSetRemoval(e,t){return await this.subscriptionManager?.subscribe(ce,async(n,r)=>{if(r===ce&&n.includes(e))try{await this.executeScript(F.publishNextItem,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:P.ConcurrencyManagerPublishNextItemFailed})}})??!1}async registerRequest(e,t,n,a){let o=`concurrency:${e}`,s=`queue:${e}`,c=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(a??``):a?.includes(e.urlPattern))?.subPoolKey,l=p(c)?`${o}-${c}`:o,{mainMaxConcurrency:u,subPools:d}=t,f=[{key:o,maxConcurrency:u},...d?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${o}-${t}`,maxConcurrency:n}})??[]],m=f.map(e=>e.key),h=f.map(e=>e.maxConcurrency),[g,_]=await Promise.all([this.subscribeToLeaseExpiry(n,l),this.subscribeToSetRemoval(l,s)]),v={requestId:n,targetConcurrencyKey:l,leaseSubscription:g,setRemovalSubscription:_,queueKey:s},y=await this.executeScript(F.tryConcurrency,[n,l,s,...m],[`60`,u.toString(),`90`,...h.map(String)]);if(p(y)&&y[0])return{...v,joinCondition:`optimistic`,failureReason:y[1]};let b=0,x=[];for(;b<5;){let e=b>1,t=await this.queueManager?.joinAndWaitTurn(s,n,e,async(e,t)=>await this.executeScript(F.tryConcurrency,[n,l,s,...m],[`60`,u.toString(),`90`,...h.map(String)]),!1),a=p(t)?t[0]:!1,o=p(t)?t[1]:``;if(p(o)&&o!==``&&x.push(o),b++,a)return b>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${b} attempts.`,context:{...v,registerAttempts:b,joinCondition:`attempts`,failureMessages:x}}),{...v,joinCondition:`attempts`};await r(i(b,100))}return this.logger?.error({category:this.name,message:`Failed to register request after ${b} attempts.`,context:{...v,registerAttempts:b,joinCondition:`failed`,failureMessages:x},code:P.ConcurrencyManagerRegistrationFailed}),{...v,joinCondition:`failed`}}async releaseRequest(e,t){return f(t)&&f(e)?!!await this.executeScript(F.removeFromSet,[t],[e]):!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}close(){this.subscriptionManager?.close(),this.queueManager?.close(),this.scriptMap?.clear(),this.hasValidRedisConfig=!1}};const fe={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t)=>{if(l(t)||t?.length===0||l(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let n=t?.filter(t=>t.receivedStatus===e.status);if(n?.length)for(let t of n){let n=t.condition,r=v(n,e)===!0;if(l(n)||r)return{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:t?.message??fe[t.targetStatus]??`Unknown error`}}return e},pe=h({receivedStatus:m.number(),targetStatus:m.number(),message:m.string().optional(),condition:m.string().optional()});var me=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let n=e.map(e=>safeSerialize(e,t));return t.delete(e),n}let n=e,r={};t.add(n);for(let[e,i]of Object.entries(n))r[e]=safeSerialize(i,t);return t.delete(n),r},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new x.Agent(n),l=y.create({...t,httpsAgent:c});if(e){let t={axiosInstance:l,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(l,e,t)}return l}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return p(e)&&s(e)&&typeof e(t)==`function`?e(t):e??null}},he=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e){this.dataStore=null,this.initialize(e)}static getInstance(e){return l(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(e){this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,typeGuard:e=>p(e)}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:p(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return p(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const ge=he.getInstance(),abortErrorInterceptor=()=>e(e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)},`abortErrorInterceptor`),_e={mainRatelimit:25};let ve=function(e){return e.incr=`incr`,e}({}),I=function(e){return e.RateLimiterReleaseRequestFailed=`RateLimiterReleaseRequestFailed`,e.RateLimitOrConcurrencyManagerNotInitialized=`RateLimitOrConcurrencyManagerNotInitialized`,e.InterceptorContextNotPresent=`InterceptorContextNotPresent`,e.InterceptorMaxWaitTimeExceeded=`InterceptorMaxWaitTimeExceeded`,e}({});const createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&C(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},ye=`checkConcurrencyInterceptor`,checkConcurrencyInterceptor=({logger:t,context:n,requestConfig:r,concurrencyManager:i,rateLimitManager:a})=>e(async e=>{if(e.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,e,`ERR_CANCELED`));if(l(n))t?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:ye,...e,httpsAgent:void 0,headers:void 0,hasContext:p(n),hasConfig:p(e)},code:I.InterceptorContextNotPresent});else if(l(a)||l(i))t?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:ye,...e,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:p(a),concurrencyManagerInitialized:p(i)},code:I.RateLimitOrConcurrencyManagerNotInitialized});else if(p(n.provider)&&p(n.accountSecureId)){let o=S(),{provider:s,accountSecureId:c}=n,l=r?.rateLimits??_e,u=r?.concurrency??ue,d=await a.getDynamicMaxWaitTime(l,u,e.url),register=async()=>i.registerRequest(`${c}-${s}`,u,o,e.url),f,p=0;for(;p<=d;){let r=Math.floor(Date.now()/1e3),i=await a.getWaitTime(`${c}-${s}`,l,e.url)??0,o=Math.max(i-r,0);if(i===0){f=await register();break}if(await abortableDelay(o*1e3,e),p+=o,p>=d){f=await register(),t?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${s} - Account: ${c}`,context:{...n,interceptor:ye,...e,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:d},code:I.InterceptorMaxWaitTimeExceeded});break}}return{...e,requestMetadata:f}}return e},`checkConcurrencyInterceptor`),L=1e3,be=/^\d+(\.\d+)?$/,adjustUnixTimestamp=e=>e<3250368e4?e*L:e;var xe=n(((e,t)=>{function _extends(){return t.exports=_extends=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},t.exports.__esModule=!0,t.exports.default=t.exports,_extends.apply(null,arguments)}t.exports=_extends,t.exports.__esModule=!0,t.exports.default=t.exports})),Se={epsilon:1e-12,matrix:`Matrix`,number:`number`,precision:64,predictable:!1,randomSeed:null};function isNumber$1(e){return typeof e==`number`}e(isNumber$1,`isNumber`);function isBigNumber(e){return!e||typeof e!=`object`||typeof e.constructor!=`function`?!1:e.isBigNumber===!0&&typeof e.constructor.prototype==`object`&&e.constructor.prototype.isBigNumber===!0||typeof e.constructor.isDecimal==`function`&&e.constructor.isDecimal(e)===!0}function isComplex(e){return e&&typeof e==`object`&&Object.getPrototypeOf(e).isComplex===!0||!1}function isFraction(e){return e&&typeof e==`object`&&Object.getPrototypeOf(e).isFraction===!0||!1}function isUnit(e){return e&&e.constructor.prototype.isUnit===!0||!1}function isString$1(e){return typeof e==`string`}e(isString$1,`isString`);var R=Array.isArray;function isMatrix(e){return e&&e.constructor.prototype.isMatrix===!0||!1}function isCollection(e){return Array.isArray(e)||isMatrix(e)}function isDenseMatrix(e){return e&&e.isDenseMatrix&&e.constructor.prototype.isMatrix===!0||!1}function isSparseMatrix(e){return e&&e.isSparseMatrix&&e.constructor.prototype.isMatrix===!0||!1}function isRange(e){return e&&e.constructor.prototype.isRange===!0||!1}function isIndex(e){return e&&e.constructor.prototype.isIndex===!0||!1}function isBoolean(e){return typeof e==`boolean`}function isResultSet(e){return e&&e.constructor.prototype.isResultSet===!0||!1}function isHelp(e){return e&&e.constructor.prototype.isHelp===!0||!1}function isFunction$1(e){return typeof e==`function`}e(isFunction$1,`isFunction`);function isDate(e){return e instanceof Date}function isRegExp(e){return e instanceof RegExp}function isObject$1(e){return!!(e&&typeof e==`object`&&e.constructor===Object&&!isComplex(e)&&!isFraction(e))}e(isObject$1,`isObject`);function isNull(e){return e===null}function isUndefined(e){return e===void 0}function isAccessorNode(e){return e&&e.isAccessorNode===!0&&e.constructor.prototype.isNode===!0||!1}function isArrayNode(e){return e&&e.isArrayNode===!0&&e.constructor.prototype.isNode===!0||!1}function isAssignmentNode(e){return e&&e.isAssignmentNode===!0&&e.constructor.prototype.isNode===!0||!1}function isBlockNode(e){return e&&e.isBlockNode===!0&&e.constructor.prototype.isNode===!0||!1}function isConditionalNode(e){return e&&e.isConditionalNode===!0&&e.constructor.prototype.isNode===!0||!1}function isConstantNode(e){return e&&e.isConstantNode===!0&&e.constructor.prototype.isNode===!0||!1}function isFunctionAssignmentNode(e){return e&&e.isFunctionAssignmentNode===!0&&e.constructor.prototype.isNode===!0||!1}function isFunctionNode(e){return e&&e.isFunctionNode===!0&&e.constructor.prototype.isNode===!0||!1}function isIndexNode(e){return e&&e.isIndexNode===!0&&e.constructor.prototype.isNode===!0||!1}function isNode(e){return e&&e.isNode===!0&&e.constructor.prototype.isNode===!0||!1}function isObjectNode(e){return e&&e.isObjectNode===!0&&e.constructor.prototype.isNode===!0||!1}function isOperatorNode(e){return e&&e.isOperatorNode===!0&&e.constructor.prototype.isNode===!0||!1}function isParenthesisNode(e){return e&&e.isParenthesisNode===!0&&e.constructor.prototype.isNode===!0||!1}function isRangeNode(e){return e&&e.isRangeNode===!0&&e.constructor.prototype.isNode===!0||!1}function isRelationalNode(e){return e&&e.isRelationalNode===!0&&e.constructor.prototype.isNode===!0||!1}function isSymbolNode(e){return e&&e.isSymbolNode===!0&&e.constructor.prototype.isNode===!0||!1}function isChain(e){return e&&e.constructor.prototype.isChain===!0||!1}function typeOf(e){var t=typeof e;return t===`object`?e===null?`null`:isBigNumber(e)?`BigNumber`:e.constructor&&e.constructor.name?e.constructor.name:`Object`:t}function clone$2(e){var t=typeof e;if(t===`number`||t===`string`||t===`boolean`||e==null)return e;if(typeof e.clone==`function`)return e.clone();if(Array.isArray(e))return e.map(function(e){return clone$2(e)});if(e instanceof Date)return new Date(e.valueOf());if(isBigNumber(e))return e;if(isObject$1(e))return mapObject(e,clone$2);throw TypeError(`Cannot clone: unknown type of value (value: ${e})`)}e(clone$2,`clone`);function mapObject(e,t){var n={};for(var r in e)hasOwnProperty(e,r)&&(n[r]=t(e[r]));return n}function deepStrictEqual(e,t){var n,r,i;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(r=0,i=e.length;r<i;r++)if(!deepStrictEqual(e[r],t[r]))return!1;return!0}else if(typeof e==`function`)return e===t;else if(e instanceof Object){if(Array.isArray(t)||!(t instanceof Object))return!1;for(n in e)if(!(n in t)||!deepStrictEqual(e[n],t[n]))return!1;for(n in t)if(!(n in e))return!1;return!0}else return e===t}function hasOwnProperty(e,t){return e&&Object.hasOwnProperty.call(e,t)}function pickShallow(e,t){for(var n={},r=0;r<t.length;r++){var i=t[r],a=e[i];a!==void 0&&(n[i]=a)}return n}var Ce=[`Matrix`,`Array`],we=[`number`,`BigNumber`,`Fraction`],Te=t(xe(),1),Ee=e(function config$2(e){if(e)throw Error(`The global config is readonly.
|
|
97
|
+
`};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??a,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.info({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if(l(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return l(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(oe)&&n.includes(se)&&n.includes(N)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(le.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:P.ConcurrencyManagerRedisEventsEmitError}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return await this.subscriptionManager?.subscribe(N,async(n,r)=>{if(r===N&&n.includes(t)&&n.includes(e))try{await this.releaseRequest(e,t)}catch(n){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:{requestId:e,targetConcurrencyKey:t},error:n,code:P.ConcurrencyManagerReleaseRequestFailed})}})??!1}async subscribeToSetRemoval(e,t){return await this.subscriptionManager?.subscribe(ce,async(n,r)=>{if(r===ce&&n.includes(e))try{await this.executeScript(F.publishNextItem,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:P.ConcurrencyManagerPublishNextItemFailed})}})??!1}async registerRequest(e,t,n,a){let o=`concurrency:${e}`,s=`queue:${e}`,c=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(a??``):a?.includes(e.urlPattern))?.subPoolKey,l=p(c)?`${o}-${c}`:o,{mainMaxConcurrency:u,subPools:d}=t,f=[{key:o,maxConcurrency:u},...d?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${o}-${t}`,maxConcurrency:n}})??[]],m=f.map(e=>e.key),h=f.map(e=>e.maxConcurrency),[g,_]=await Promise.all([this.subscribeToLeaseExpiry(n,l),this.subscribeToSetRemoval(l,s)]),v={requestId:n,targetConcurrencyKey:l,leaseSubscription:g,setRemovalSubscription:_,queueKey:s},y=await this.executeScript(F.tryConcurrency,[n,l,s,...m],[`60`,u.toString(),`90`,...h.map(String)]);if(p(y)&&y[0])return{...v,joinCondition:`optimistic`,failureReason:y[1]};let b=0,x=[];for(;b<5;){let e=b>1,t=await this.queueManager?.joinAndWaitTurn(s,n,e,async(e,t)=>await this.executeScript(F.tryConcurrency,[n,l,s,...m],[`60`,u.toString(),`90`,...h.map(String)]),!1),a=p(t)?t[0]:!1,o=p(t)?t[1]:``;if(p(o)&&o!==``&&x.push(o),b++,a)return b>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${b} attempts.`,context:{...v,registerAttempts:b,joinCondition:`attempts`,failureMessages:x}}),{...v,joinCondition:`attempts`};await r(i(b,100))}return this.logger?.error({category:this.name,message:`Failed to register request after ${b} attempts.`,context:{...v,registerAttempts:b,joinCondition:`failed`,failureMessages:x},code:P.ConcurrencyManagerRegistrationFailed}),{...v,joinCondition:`failed`}}async releaseRequest(e,t){return f(t)&&f(e)?!!await this.executeScript(F.removeFromSet,[t],[e]):!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}close(){this.subscriptionManager?.close(),this.queueManager?.close(),this.scriptMap?.clear(),this.hasValidRedisConfig=!1}};const fe={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t)=>{if(l(t)||t?.length===0||l(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let n=t?.filter(t=>t.receivedStatus===e.status);if(n?.length)for(let t of n){let n=t.condition,r=v(n,e)===!0;if(l(n)||r)return{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:t?.message??fe[t.targetStatus]??`Unknown error`}}return e},pe=h({receivedStatus:m.number(),targetStatus:m.number(),message:m.string().optional(),condition:m.string().optional()});var me=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let n=e.map(e=>safeSerialize(e,t));return t.delete(e),n}let n=e,r={};t.add(n);for(let[e,i]of Object.entries(n))r[e]=safeSerialize(i,t);return t.delete(n),r},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new x.Agent(n),l=y.create({...t,httpsAgent:c});if(e){let t={axiosInstance:l,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(l,e,t)}return l}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return p(e)&&s(e)&&typeof e(t)==`function`?e(t):e??null}},he=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return l(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,typeGuard:e=>p(e)}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:p(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return p(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const ge=he.getInstance(),abortErrorInterceptor=()=>e(e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)},`abortErrorInterceptor`),_e={mainRatelimit:25};let ve=function(e){return e.incr=`incr`,e}({}),I=function(e){return e.RateLimiterReleaseRequestFailed=`RateLimiterReleaseRequestFailed`,e.RateLimitOrConcurrencyManagerNotInitialized=`RateLimitOrConcurrencyManagerNotInitialized`,e.InterceptorContextNotPresent=`InterceptorContextNotPresent`,e.InterceptorMaxWaitTimeExceeded=`InterceptorMaxWaitTimeExceeded`,e}({});const createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&C(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},ye=`checkConcurrencyInterceptor`,checkConcurrencyInterceptor=({logger:t,context:n,requestConfig:r,concurrencyManager:i,rateLimitManager:a})=>e(async e=>{if(e.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,e,`ERR_CANCELED`));if(l(n))t?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:ye,...e,httpsAgent:void 0,headers:void 0,hasContext:p(n),hasConfig:p(e)},code:I.InterceptorContextNotPresent});else if(l(a)||l(i))t?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:ye,...e,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:p(a),concurrencyManagerInitialized:p(i)},code:I.RateLimitOrConcurrencyManagerNotInitialized});else if(p(n.provider)&&p(n.accountSecureId)){let o=S(),{provider:s,accountSecureId:c}=n,l=r?.rateLimits??_e,u=r?.concurrency??ue,d=await a.getDynamicMaxWaitTime(l,u,e.url),register=async()=>i.registerRequest(`${c}-${s}`,u,o,e.url),f,p=0;for(;p<=d;){let r=Math.floor(Date.now()/1e3),i=await a.getWaitTime(`${c}-${s}`,l,e.url)??0,o=Math.max(i-r,0);if(i===0){f=await register();break}if(await abortableDelay(o*1e3,e),p+=o,p>=d){f=await register(),t?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${s} - Account: ${c}`,context:{...n,interceptor:ye,...e,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:d},code:I.InterceptorMaxWaitTimeExceeded});break}}return{...e,requestMetadata:f}}return e},`checkConcurrencyInterceptor`),L=1e3,be=/^\d+(\.\d+)?$/,adjustUnixTimestamp=e=>e<3250368e4?e*L:e;var xe=n(((e,t)=>{function _extends(){return t.exports=_extends=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},t.exports.__esModule=!0,t.exports.default=t.exports,_extends.apply(null,arguments)}t.exports=_extends,t.exports.__esModule=!0,t.exports.default=t.exports})),Se={epsilon:1e-12,matrix:`Matrix`,number:`number`,precision:64,predictable:!1,randomSeed:null};function isNumber$1(e){return typeof e==`number`}e(isNumber$1,`isNumber`);function isBigNumber(e){return!e||typeof e!=`object`||typeof e.constructor!=`function`?!1:e.isBigNumber===!0&&typeof e.constructor.prototype==`object`&&e.constructor.prototype.isBigNumber===!0||typeof e.constructor.isDecimal==`function`&&e.constructor.isDecimal(e)===!0}function isComplex(e){return e&&typeof e==`object`&&Object.getPrototypeOf(e).isComplex===!0||!1}function isFraction(e){return e&&typeof e==`object`&&Object.getPrototypeOf(e).isFraction===!0||!1}function isUnit(e){return e&&e.constructor.prototype.isUnit===!0||!1}function isString$1(e){return typeof e==`string`}e(isString$1,`isString`);var R=Array.isArray;function isMatrix(e){return e&&e.constructor.prototype.isMatrix===!0||!1}function isCollection(e){return Array.isArray(e)||isMatrix(e)}function isDenseMatrix(e){return e&&e.isDenseMatrix&&e.constructor.prototype.isMatrix===!0||!1}function isSparseMatrix(e){return e&&e.isSparseMatrix&&e.constructor.prototype.isMatrix===!0||!1}function isRange(e){return e&&e.constructor.prototype.isRange===!0||!1}function isIndex(e){return e&&e.constructor.prototype.isIndex===!0||!1}function isBoolean(e){return typeof e==`boolean`}function isResultSet(e){return e&&e.constructor.prototype.isResultSet===!0||!1}function isHelp(e){return e&&e.constructor.prototype.isHelp===!0||!1}function isFunction$1(e){return typeof e==`function`}e(isFunction$1,`isFunction`);function isDate(e){return e instanceof Date}function isRegExp(e){return e instanceof RegExp}function isObject$1(e){return!!(e&&typeof e==`object`&&e.constructor===Object&&!isComplex(e)&&!isFraction(e))}e(isObject$1,`isObject`);function isNull(e){return e===null}function isUndefined(e){return e===void 0}function isAccessorNode(e){return e&&e.isAccessorNode===!0&&e.constructor.prototype.isNode===!0||!1}function isArrayNode(e){return e&&e.isArrayNode===!0&&e.constructor.prototype.isNode===!0||!1}function isAssignmentNode(e){return e&&e.isAssignmentNode===!0&&e.constructor.prototype.isNode===!0||!1}function isBlockNode(e){return e&&e.isBlockNode===!0&&e.constructor.prototype.isNode===!0||!1}function isConditionalNode(e){return e&&e.isConditionalNode===!0&&e.constructor.prototype.isNode===!0||!1}function isConstantNode(e){return e&&e.isConstantNode===!0&&e.constructor.prototype.isNode===!0||!1}function isFunctionAssignmentNode(e){return e&&e.isFunctionAssignmentNode===!0&&e.constructor.prototype.isNode===!0||!1}function isFunctionNode(e){return e&&e.isFunctionNode===!0&&e.constructor.prototype.isNode===!0||!1}function isIndexNode(e){return e&&e.isIndexNode===!0&&e.constructor.prototype.isNode===!0||!1}function isNode(e){return e&&e.isNode===!0&&e.constructor.prototype.isNode===!0||!1}function isObjectNode(e){return e&&e.isObjectNode===!0&&e.constructor.prototype.isNode===!0||!1}function isOperatorNode(e){return e&&e.isOperatorNode===!0&&e.constructor.prototype.isNode===!0||!1}function isParenthesisNode(e){return e&&e.isParenthesisNode===!0&&e.constructor.prototype.isNode===!0||!1}function isRangeNode(e){return e&&e.isRangeNode===!0&&e.constructor.prototype.isNode===!0||!1}function isRelationalNode(e){return e&&e.isRelationalNode===!0&&e.constructor.prototype.isNode===!0||!1}function isSymbolNode(e){return e&&e.isSymbolNode===!0&&e.constructor.prototype.isNode===!0||!1}function isChain(e){return e&&e.constructor.prototype.isChain===!0||!1}function typeOf(e){var t=typeof e;return t===`object`?e===null?`null`:isBigNumber(e)?`BigNumber`:e.constructor&&e.constructor.name?e.constructor.name:`Object`:t}function clone$2(e){var t=typeof e;if(t===`number`||t===`string`||t===`boolean`||e==null)return e;if(typeof e.clone==`function`)return e.clone();if(Array.isArray(e))return e.map(function(e){return clone$2(e)});if(e instanceof Date)return new Date(e.valueOf());if(isBigNumber(e))return e;if(isObject$1(e))return mapObject(e,clone$2);throw TypeError(`Cannot clone: unknown type of value (value: ${e})`)}e(clone$2,`clone`);function mapObject(e,t){var n={};for(var r in e)hasOwnProperty(e,r)&&(n[r]=t(e[r]));return n}function deepStrictEqual(e,t){var n,r,i;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(r=0,i=e.length;r<i;r++)if(!deepStrictEqual(e[r],t[r]))return!1;return!0}else if(typeof e==`function`)return e===t;else if(e instanceof Object){if(Array.isArray(t)||!(t instanceof Object))return!1;for(n in e)if(!(n in t)||!deepStrictEqual(e[n],t[n]))return!1;for(n in t)if(!(n in e))return!1;return!0}else return e===t}function hasOwnProperty(e,t){return e&&Object.hasOwnProperty.call(e,t)}function pickShallow(e,t){for(var n={},r=0;r<t.length;r++){var i=t[r],a=e[i];a!==void 0&&(n[i]=a)}return n}var Ce=[`Matrix`,`Array`],we=[`number`,`BigNumber`,`Fraction`],Te=t(xe(),1),Ee=e(function config$2(e){if(e)throw Error(`The global config is readonly.
|
|
98
98
|
Please create a mathjs instance if you want to change the default configuration.
|
|
99
99
|
Example:
|
|
100
100
|
|