@autofleet/rabbit 5.9.0-beta-d063edda.2 → 5.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{env as e}from"node:process";import{setImmediate as t}from"node:timers/promises";import{EventEmitter as n,addAbortListener as r,once as i}from"node:events";import a from"moment";import o from"redis-lock";import{connect as s}from"amqp-connection-manager";import{backOff as c}from"exponential-backoff";import l,{runWithLoggerContext as u}from"@autofleet/logger";import{CONTEXTS_IDS_HEADER as d,INTERNAL_REQUEST_PATHS_HEADER as f,createOrSetRabbitTrace as p,getUser as m,newTrace as h,outbreak as g,traceTypes as _}from"@autofleet/zehut";import{randomUUID as v}from"node:crypto";import{createClient as y}from"redis";var b=l(),x=class extends Error{constructor(e){super(e),this.name=`RabbitError`}},S=e=>y({socket:e});const C=1e3*5,w=`x-retry-count`,T=`x-trace-id`,E=`x-af-user-id`,D=`x-af-automation-id`,O=`x-total-processing-duration-ms`,k=`x-redelivered-count`,A={limit:1,retries:1,deadMessageTtl:432e5,lockTimeout:C,useConsumeWithLock:!1,auditContext:null,enableRabbitTrace:!1,callNackOnAbort:!1},j={startingDelay:500,timeMultiple:4,numOfAttempts:5},M={startingDelay:1,timeMultiple:1,numOfAttempts:5},N={arguments:{"ha-promote-on-failure":`always`,"ha-promote-on-shutdown":`always`}},P={CONSUMER:`consumer`,PUBLISHER:`publisher`},{PROJECT_ID:F}=process.env,I=async(e,t)=>e.assertExchange(t,`fanout`),L=()=>Math.floor(Math.random()*1e5),R=()=>{if(Promise.withResolvers)return Promise.withResolvers();let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},z=()=>[`af-experiment-manager`,`dev1-experiment-manager`].includes(F||``),B=()=>z()?j:M,V={host:process.env.RABBITMQ_SERVICE_HOST||`localhost`,username:process.env.RABBITMQ_USERNAME||`guest`,password:process.env.RABBITMQ_PASSWORD||`guest`};async function H(e,{taskName:t,queueName:n}){let r=`http://${V.host}:15672/api/exchanges/%2f/amq.default/publish`,i={task:t,id:v(),args:[e]},a={properties:{delivery_mode:2,content_type:`application/json`},routing_key:n,payload:JSON.stringify(i),payload_encoding:`string`};try{let e=await fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Basic ${Buffer.from(`${V.username}:${V.password}`).toString(`base64`)}`},body:JSON.stringify(a)});if(e.ok){let t=await e.json();b.info(`Successfully published message:`,t)}else b.error(`Failed to publish message. Status code: ${e.status}`),b.error(`Response: ${await e.text()}`)}catch(e){throw b.error(`Error sending request:`,e instanceof Error?e.message:String(e)),e}}const{DISABLE_QUORUM_QUEUES_CONSUME:U,DISABLE_QUORUM_QUEUES_PUBLISH:W,MY_POD_NAME:G}=e;var K=class e{static parseMsg(e){let t=e.content.toString();try{t=JSON.parse(t)}catch{}return{...e,content:t}}static validateName(e,t){if(!t||t===``)throw new x(`error while using ${e} with no name`)}static getPublishOptions(e={}){let t=m(),n=g.getCurrentContextTraceId();return{timestamp:a().unix(),timeout:1e4,headers:{creationTimestamp:a().valueOf(),...e,...t?.id===void 0?{}:{[E]:t.id},...t?.contextIds===void 0?{}:{[d]:t.contextIds},...t?.requestedContextPaths===void 0?{}:{[f]:t.requestedContextPaths},...n===void 0?{}:{[T]:n}}}}#e=new Set;#t;constructor(t={},r){this.options=t,this.redisConfig=r,this.DISCONNECT_MSG=`rabbit: connection disconnect`,this.RECONNECT_MSG=`rabbit: connection disconnect - reconnecting`,this.publishChannel=null,this.publishChannelSetupPromise=null,this.publishConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`publishConnectionCreated`,connectionFailedEventName:`publishConnectionFailed`,blockReconnect:!1,connectionRole:P.PUBLISHER},this.consumeConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`consumeConnectionCreated`,connectionFailedEventName:`consumeConnectionFailed`,blockReconnect:!1,connectionRole:P.CONSUMER},this.em=new n,this.exchanges={},this.queues={},this.queueSetupPromises={},this.assertExchangePromises={},this.consumersTags=new Map,this.consumersToRegister=[],this.pendingConsumers=[],this.doesVHostExist=!1,this.vhost=`quorum-vhost`,this.gracefulShutdownStarted=!1,this.activeCallbackCount=0,this.shutdownAbortController=new AbortController,this.oldPublishChannel=null,this.oldPublishChannelSetupPromise=null,this.oldPublishConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`oldPublishConnectionCreated`,connectionFailedEventName:`oldPublishConnectionFailed`,blockReconnect:!1,connectionRole:P.PUBLISHER},this.oldConsumeConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`oldConsumeConnectionCreated`,connectionFailedEventName:`oldConsumeConnectionFailed`,blockReconnect:!1,connectionRole:P.CONSUMER},this.oldEm=new n,this.oldExchanges={},this.oldQueues={},this.oldQueueSetupPromises={},this.oldAssertExchangePromises={},this.oldConsumersTags=new Map,this.oldConsumersToRegister=[],this.assertVHost=async()=>{if(this.doesVHostExist)return;let e=process.env.RABBITMQ_USERNAME||`guest`,t=process.env.RABBITMQ_PASSWORD||`guest`,n={Authorization:`Basic ${Buffer.from(`${e}:${t}`).toString(`base64`)}`,"Content-Type":`application/json`},r=`${`http://${(this.options?.rabbitHost||process.env.RABBITMQ_SERVICE_HOST||`localhost`).split(`:`)[0]}:15672`}/api/vhosts/${encodeURIComponent(this.vhost)}`;try{let e=await fetch(r,{method:`GET`,headers:n});if(e.status===200){this.doesVHostExist=!0,this.#t.info(`Vhost exists`,{vhost:this.vhost});return}if(e.status!==404)throw this.#t.error(`Failed to check vhost`,{response:e}),new x(`Failed to check vhost`);let t=await fetch(r,{method:`PUT`,headers:n,body:JSON.stringify({default_queue_type:`quorum`})});if(!t.ok)throw this.#t.error(`Failed to create vhost`,{response:t}),new x(`Failed to create vhost`);this.doesVHostExist=!0,this.#t.info(`Vhost created`,{vhost:this.vhost})}catch(e){throw this.#t.error(`Failed to check or create vhost`,{error:e}),e}},this.shouldConsumeMessageByTimestamp=async e=>{if(!e)return!1;let{headers:t}=e.properties,n=t?.creationTimestamp;if(n&&t?.redisTimestampValidationKey&&this.redisClient){let e=this.getRedisKey(t.redisTimestampValidationKey),r=await this.redisClient.get(e);return!r||parseInt(r,10)<=parseInt(n,10)}return!0},this.ack=(e,t,n=!1,r=null)=>async i=>{if(!t)return;this.#t.debug(`rabbit acking message`,{deliveryTag:t.fields.deliveryTag}),e.ack(t);let{headers:a}=t.properties,o=a?.creationTimestamp;if(n&&o&&a?.redisTimestampValidationKey&&this.redisClient){let e=parseInt(o,10),t=this.getRedisKey(a.redisTimestampValidationKey);await this.redisClient.set(t,e,{EX:3600}),await this.unlockRedisIfNeeded(r)}},this.executeSafely=async(e,t)=>{try{await e()}catch(e){this.#t.error(`rabbit: error in ${t}`,{error:e})}},this.nack=(t,n,r,i,a,o)=>async(s,{skipRetry:c=!1,consumptionDuration:l,isAborted:u=!1,nackContext:d}={})=>{if(await this.unlockRedisIfNeeded(o),!t||!a){this.#t.error(`no channel or msg`,{msg:a});return}let f=this.getRetriesCount(a),p=this.getTotalConsumptionDuration(a)??0,m=this.getRedeliveredCount(a),h=p+(l??0),g=(c||f>=r.retries)&&!u;this.#t.info(`nack message`,{deliveryTag:a.fields.deliveryTag,currentRetryCount:f,updatedConsumptionDuration:h,sendToDeadQueue:g,isAborted:u}),r.onNack&&this.executeSafely(()=>r.onNack({msg:e.parseMsg(a),retryCount:f,remainingRetries:(r.retries??0)-f,sendToDeadQueue:g,nackContext:d}),`onNack callback`),await this.sendToQueue(`${n}${g?`-dead`:``}`,e.parseMsg(a).content,g?i:r,{...a.properties.headers,[w]:u?f:f+1,[O]:h,[k]:u?m+1:m},r.isQuorumQueue),this.#t.debug(`rabbit nacking message`,{deliveryTag:a.fields.deliveryTag}),t.ack(a)},this.maskURL=e=>{try{let t=new URL(e);return t.username=`***`,t.password=`***`,t.toString()}catch{return e}},this.#t=t?.logger??b,this.identifier=t?.identifier||G||v();let{redisClient:i,redisLock:a}=this.#n(t,r);this.redisClient=i,this.redisLock=a,this.options?.dontGracefulShutdown||(this.#t.info(`rabbit: [gracefully-shutdown] adding gracefully shutdown for process.pid ${process.pid}`),process.on(`SIGTERM`,async()=>{await this.gracefulShutdown(`SIGTERM`)}),process.on(`SIGINT`,async()=>{await this.gracefulShutdown(`SIGINT`)}))}#n(e,t){let n;return!t&&!e?.redisClient?(this.#t.info(`rabbit: No Redis config provided and no Redis client provided, disabling Redis features`),{redisClient:void 0,redisLock:void 0}):(e?.redisClient?(this.#t.info(`rabbit: Using provided redis client`),n=e.redisClient):(this.#t.info(`rabbit: No redis client provided, creating new redis client`),n=S(t).on(`error`,e=>{this.#t.error(`rabbit: Redis error`,{err:e,redisConfig:t})}),n.connect().catch(e=>{this.#t.error(`rabbit: Failed to connect to Redis`,{err:e,redisConfig:t})})),{redisClient:n,redisLock:o(n)})}getRedisKey(e){return`${this.redisConfig?.prefix||``}${e}`}getRetriesCount(e){let t=e.properties.headers?.[w];return Number.parseInt(t||`0`,10)||0}getRedeliveredCount(e){let t=e.properties.headers?.[k];return Number.parseInt(t||`0`,10)||0}getTotalConsumptionDuration(e){let t=e.properties.headers?.[O];return t?Number.parseInt(t,10):0}async getConnection(e){let{amqpConnection:t,creatingConnection:n,connectionCreatedEventName:r,connectionFailedEventName:a,blockReconnect:o,connectionRole:c}=e;if(o){this.#t.debug(`rabbit: block reconnect`);return}if(t!==null){if(this.options?.disableReconnect||t?.isConnected())return this.#t.debug(`rabbit: connection - is connected`),t;this.#t.debug(`rabbit: connection - reconnecting`)}if(n){this.#t.debug(`rabbit: creating connection emi`);let[e,t]=await Promise.race([r,a].map(e=>i(this.em,e).then(([t])=>[e,t])));if(e===r)return t;throw t}e.creatingConnection=!0;let l=!1,u=()=>{let e=process.env.RABBITMQ_USERNAME||`guest`,t=process.env.RABBITMQ_PASSWORD||`guest`,n=this.options?.rabbitHost||process.env.RABBITMQ_SERVICE_HOST||`localhost`;return this.#t.debug(`rabbit: creating connection`,{host:n,userName:e,HEARTBEAT:`60`}),[`amqp://${e}:${t}@${n}/${this.vhost}?heartbeat=60`]},d=s(u(),{findServers:u,connectionOptions:{clientProperties:{connection_name:`${this.identifier}:quorum:${c}`}}});e.amqpConnection=d;let{promise:f,reject:p,resolve:m}=R();return d.on(`error`,e=>{this.#t.error(`rabbit: connection error`,{err:e}),l||(l=!0,p(e),this.em.emit(a,e))}),d.on(`connectFailed`,e=>{this.consumersTags.clear(),typeof e.url==`string`&&(e.url=this.maskURL(e.url)),this.#t.error(`rabbit: connection connectFailed`,{err:e,advice:`Check if the vhost exist`,vhost:this.vhost}),l||(l=!0,p(e),this.em.emit(a,e))}),d.on(`disconnect`,({err:t})=>{this.consumersTags.clear(),this.#t.debug(`rabbit: connection closed`),this.options?.disableReconnect?(this.#t.error(`${this.DISCONNECT_MSG}${t&&` - ${t}`}`),e.blockReconnect=!0):this.#t.error(`${this.RECONNECT_MSG}${t&&` - ${t}`}`)}),d.once(`connect`,async()=>{this.#t.debug(`rabbit: connection established`),e.creatingConnection=!1,this.em.emit(r,d),l=!0,m(d)}),f}async getNewChannel({name:e=L().toString(),onClose:t=null,options:n={},connection:r}){let a;try{a=await this.getConnection(r)}catch(t){throw this.#t.error(`rabbit: error on get connection for new channel ${e} `,{e:t}),t}let o=a?.createChannel({...n,name:e});i(o,`close`).then(n=>{this.#t.error(`rabbit: channel ${e} closed`),t?.(n)});try{return await i(o,`connect`),this.#t.debug(`rabbit: channel ${e} CONNECTED`),o}catch(t){throw this.#t.error(`rabbit: channel error ${e} error`,{err:t}),t}}async assertChannel({force:e=!1,connection:t}){if(this.publishChannel&&!e)return this.publishChannel;if(this.publishChannelSetupPromise)return this.publishChannelSetupPromise;let{promise:n,resolve:r,reject:i}=R();this.publishChannelSetupPromise=n;try{let e=await this.getNewChannel({connection:t,...t.connectionRole===P.PUBLISHER&&{name:`publish:${this.identifier}:quorum`}});e.on(`error`,e=>{this.#t.error(`rabbit: channel error`,{err:e})}),this.publishConnection===t&&(this.publishChannel=e),r(e)}catch(e){i(e)}return n}async assertExchange(e,t){let n=await this.assertChannel({connection:t});return this.exchanges[e]?(delete this.assertExchangePromises[e],this.exchanges[e]):this.assertExchangePromises[e]?this.assertExchangePromises[e]:(this.assertExchangePromises[e]=I(n,e),this.exchanges[e]=await this.assertExchangePromises[e],this.exchanges[e])}async getQueueLength(t){e.validateName(`queue`,t);let{publishChannel:n}=this;if(!n)throw new x(`channel is not defined`);return this.#t.debug(`rabbit: getting queue length`,{queue:t,connected:this.publishConnection.amqpConnection?.isConnected()}),n?.checkQueue(t)}async deleteQueue(t,n){e.validateName(`queue`,t);let r=await this.assertChannel({connection:n});this.#t.info(`rabbit: deleting queue`,{queue:t});let i=await r.deleteQueue(t);return this.#t.debug(`queue deleted`,i),i}async bindQueue(e,t){let n=await this.assertChannel({connection:this.publishConnection});return await n.addSetup(n=>n.bindQueue(e,t,``)),n.bindQueue(e,t,``)}async setupQueue(e,t){let n,r=this.publishConnection,i={...t,durable:!0,arguments:{...t?.arguments,"x-consumer-timeout":1e3*60*60*24,"x-queue-type":`quorum`}};try{let t=await this.assertChannel({connection:r});this.#t.debug(`assertQueue->channel.addSetup`,{queueName:e}),await t.addSetup(async t=>{await t.assertQueue(e,i)}),this.#t.debug(`assertQueue->channel.assertQueue`,{queueName:e}),n=await t.assertQueue(e,i)}catch(a){if(this.#t.error(`rabbit: assertQueue error`,{queueName:e,options:t,error:a}),this.options?.dontRetryAssert)throw a;{this.#t.debug(`retrying assertQueue`,{queueName:e});let t=await this.assertChannel({force:!0,connection:r});await this.deleteQueue(e,r),this.#t.debug(`retrying assertQueue->channel.addSetup`,{queueName:e}),await t.addSetup(t=>t.assertQueue(e,i)),this.#t.debug(`retrying assertQueue->channel.assertQueue`,{queueName:e}),n=await t.assertQueue(e,i)}}return this.queues[e]=n,n}static shouldUseQuorum(e){let t=process.env.QUORUM_QUEUES_WHITELIST;return t===`*`?!0:t?t.split(`,`).includes(e):!1}async assertQueue(t,n){return e.validateName(`queue`,t),this.queues[t]?(delete this.queueSetupPromises[t],this.queues[t]):(this.queueSetupPromises[t]??=this.setupQueue(t,n),this.queueSetupPromises[t])}saveConsumer(e,t,n){this.consumersToRegister.some(t=>t.queue===e)||(this.#t.info(`rabbit: consumer: ${e} saved in consumer array`),this.consumersToRegister.push({queue:e,callback:t,options:n}))}async consume(e,t,n){let r=async()=>{this.saveConsumerOld(e,t,n),n?.isQuorumQueue!==!1&&U!==`true`&&(this.saveConsumer(e,t,n),await c(()=>this.assertVHost(),B()),await this.consumeNew(e,t,n)),await this.consumeOld(e,t,n)};this.options.autoStartConsumers===!1?this.pendingConsumers.push(r):await r()}async consumeNew(e,t,n){await this.consumeFromRabbit(e,t,n)}async consumeOld(e,t,n){await this.consumeFromRabbitOld(e,t,n)}async lockRedisIfNeeded(e,t){let{properties:{headers:n}}=e,r=n?.creationTimestamp,i=null;return t.useConsumeWithLock&&r&&n?.redisTimestampValidationKey&&this.redisLock&&(i=await this.redisLock(n.redisTimestampValidationKey,t?.lockTimeout||C)),i}async unlockRedisIfNeeded(e){this.redisLock&&e&&await e()}async consumeFromRabbit(t,n,i){let a={...A,...i};e.validateName(`queue`,t);let o=v(),{limit:s,deadMessageTtl:c,useConsumeWithLock:l,lockTimeout:m,auditContext:g,enableRabbitTrace:y}=a;if(l){if(!this.redisLock)throw new x(`Usage of consumeWithLock requires RedisInstance`);this.#t.info(`rabbit: Consuming with lock from queue ${t} with lockTimeout: ${m}ms`)}return(await this.getNewChannel({connection:this.consumeConnection,name:`consume:${this.identifier}:${t}:quorum`})).addSetup(async l=>{await this.assertQueue(t,a),await l.prefetch(s,!1);let{consumerTag:m}=await l.consume(t,async s=>s?u(async()=>{let u=Date.now(),m=()=>Date.now()-u,{[T]:v,[E]:b,[D]:x,[d]:S,[f]:C}=s.properties.headers??{};this.#t.addToContext({userId:b});let w=e.parseMsg(s),O=await this.lockRedisIfNeeded(w,a),k=h(_.RABBIT);if(b&&y)try{await p(k,b,S,C)}catch(e){return this.#t.error(`rabbit: failed to setRabbitTrace`,{userId:b,e}),this.nack(l,t,a,{messageTtl:c},s,O)(s)}if(v&&k.context?.set(T,v),g&&await g(t,{userId:b,automationId:x}),!await this.shouldConsumeMessageByTimestamp(w))return await this.unlockRedisIfNeeded(O),this.ack(l,s)(s);let A=!1,j=async()=>{A||(A=!0,await this.ack(l,s,!0,O)(s))},M=async(e,n={})=>{if(A)return;this.#t.debug(`rabbit localNack`,{messageAcked:A,uniqueId:o,deliveryTag:s.fields.deliveryTag}),A=!0;let r=m();await this.nack(l,t,a,{messageTtl:c},s,O)(s,{...n,consumptionDuration:r})};this.activeCallbackCount++;let N=null;try{return i?.callNackOnAbort&&(N=r(this.shutdownAbortController.signal,()=>{this.#t.warn(`rabbit: callback aborted`,{uniqueId:o,deliveryTag:s.fields.deliveryTag});let e=M(s,{isAborted:!0});this.#e.add(e),e.finally(()=>{this.#e.delete(e)})})),await n(w,j,M,this.shutdownAbortController.signal)}catch{return await M(s)}finally{this.activeCallbackCount--,N&&N[Symbol.dispose]()}}):null,{...N,consumerTag:`${this.identifier}:${t}:quorum`});m?(this.#t.info(`rabbit: adding tag ${m} to the array.`),this.consumersTags.set(t,{channel:l,consumerTag:m})):this.#t.error(`rabbit: failed to consume from queue ${t}`)})}async consumeFromExchange(t,n,r,i){let a={...A,...i};e.validateName(`exchange`,n),e.validateName(`queue`,t);let{limit:o}=a,s=async()=>{i?.isQuorumQueue!==!1&&U!==`true`&&(this.saveConsumer(t,r,i),await c(()=>this.assertVHost(),B()),await(await this.getNewChannel({name:`consume-from-exchange:${this.identifier}:${n}:${t}:quorum`,connection:this.consumeConnection})).addSetup(async e=>{let a=await I(e,n);return await e.assertQueue(t),this.exchanges[n]=a,await e.prefetch(o,!1),Promise.all([e.bindQueue(t,n,``),this.consumeNew(t,r,i)])})),this.saveConsumerOld(t,r,i),await(await this.getNewChannelOld({name:`consume-from-exchange:${this.identifier}:${n}:${t}`,connection:this.oldConsumeConnection})).addSetup(async e=>{let a=await I(e,n);return await e.assertQueue(t),this.oldExchanges[n]=a,await e.prefetch(o,!1),Promise.all([e.bindQueue(t,n,``),this.consumeOld(t,r,i)])})};this.options.autoStartConsumers===!1?this.pendingConsumers.push(s):await s()}async startConsume(){await Promise.all(this.pendingConsumers.map(e=>e())),this.pendingConsumers.length=0}async publish(n,r,i,a=!0){if(await t(),a&&W!==`true`){await this.assertVHost(),e.validateName(`exchange`,n);let t=await this.assertChannel({connection:this.publishConnection});await this.assertExchange(n,this.publishConnection),await t.publish(n,``,Buffer.from(JSON.stringify(r)),e.getPublishOptions(i));return}e.validateName(`exchange`,n);let o=await this.assertChannelOld({connection:this.oldPublishConnection});await this.assertExchangeOld(n,this.oldPublishConnection),await o.publish(n,``,Buffer.from(JSON.stringify(r)),e.getPublishOptions(i))}async sendToQueue(t,n,r,i,a=!0){if(a&&W!==`true`){try{await this.assertVHost(),await this.assertChannel({connection:this.publishConnection})}catch(e){throw this.#t.error(`rabbit sendToQueue: failed to send assert channel when sending to queue ${t}`,{e}),e}try{e.validateName(`queue`,t),await this.assertQueue(t,r)}catch(e){throw this.#t.error(`rabbit sendToQueue: failed to assert queue ${t}`,{e}),e}try{let r=await this.publishChannel?.sendToQueue(t,Buffer.from(JSON.stringify(n)),e.getPublishOptions(i));return this.#t.debug(`rabbit: sending to queue ${t}`,{res:r}),r}catch(e){let n=await this.isConnected();throw this.#t.error(`rabbit sendToQueue: failed to send to queue ${t}, isConnected: ${n}`,{e}),e}}else{try{await this.assertChannelOld({connection:this.oldPublishConnection})}catch(e){throw this.#t.error(`rabbit sendToQueue: failed to send assert channel when sending to queue ${t}`,{e}),e}try{e.validateName(`queue`,t),await this.assertQueueOld(t,r)}catch(e){throw this.#t.error(`rabbit sendToQueue: failed to assert queue ${t}`,{e}),e}try{let r=await this.oldPublishChannel?.sendToQueue(t,Buffer.from(JSON.stringify(n)),e.getPublishOptions(i));return this.#t.debug(`rabbit: sending to queue ${t}`,{res:r}),r}catch(e){let n=await this.isConnectedOld();throw this.#t.error(`rabbit sendToQueue: failed to send to queue ${t}, isConnected: ${n}`,{e}),e}}}async isConnected(){let e=!0;if(!this.gracefulShutdownStarted){if(U!==`true`||W!==`true`){this.#t.debug(`rabbit: start is connected`);let[t,n]=await Promise.all([this.getConnection(this.consumeConnection),this.getConnection(this.publishConnection)]);if(e=t.isConnected()&&n.isConnected(),!e)return this.#t.error(`rabbit: isConnected - false`),!1;try{let e=this.consumersToRegister.filter(e=>!this.consumersTags.get(e.queue));if(e.length>0){let t=e.map(e=>e.queue);throw this.#t.error(`rabbit: found unregistered consumers for queues`,{count:t.length,queues:t}),new x(`Found unregistered consumers`)}let t=await this.assertChannel({connection:this.publishConnection});await t.waitForConnect(),await Promise.all(this.consumersToRegister.map(e=>t.checkQueue(e.queue)))}catch(e){return this.#t.error(`rabbit: isConnected - false`,{msg:e.message}),!1}}e=await this.isConnectedOld()}return this.#t.debug(`rabbit: isConnected - ${e}`),e}async stopAcceptingWork(){this.#t.info(`rabbit: stop accepting work - canceling all tags`);let e=[...this.consumersTags].map(([,{channel:e,consumerTag:t}])=>e.cancel(t)),t=[...this.oldConsumersTags].map(([,{channel:e,consumerTag:t}])=>e.cancel(t));this.consumersTags.clear(),this.oldConsumersTags.clear();let n=(await Promise.allSettled([...e,...t])).filter(e=>e.status===`rejected`);n.length>0?this.#t.warn(`rabbit: stop accepting work - failed to cancel #${n.length} tags: ${n}`):this.#t.info(`rabbit: stop accepting work - all tags successfully canceled.`)}async drain(e=1e4,t=!0){let n=Date.now(),r=this.activeCallbackCount;if(this.#t.info(`rabbit: [drain] waiting for active callbacks`,{activeCallbackCount:r,timeoutMs:e}),r===0){this.#t.info(`rabbit: [drain] no active callbacks to drain`);return}let i=this.publishChannel?.queueLength()??0;for(i>0&&this.#t.warn(`rabbit: [drain] there are still published messages waiting in the channel buffer`,{publishedMessagesWaiting:i});this.activeCallbackCount>0;){let r=Date.now()-n;if(r>=e){let n=this.activeCallbackCount;if(this.#t.warn(`rabbit: [drain] timeout waiting for callbacks`,{duration:r,remainingCallbacks:n,timeoutMs:e}),this.shutdownAbortController.abort(Error(`Graceful shutdown initiated by drain timeout after ${r}ms with ${n} callbacks still active`)),await Promise.allSettled([...this.#e]),t)throw Error(`Drain timeout after ${e}ms - ${n} callbacks still active`);return}await new Promise(e=>setTimeout(e,50))}let a=Date.now()-n;this.#t.info(`rabbit: [drain] all callbacks completed`,{duration:a,callbackCount:r})}async closeConnections(){if(this.activeCallbackCount>0){this.#t.warn(`rabbit: closing connections received with active callbacks. not performing the close`,{activeCallbackCount:this.activeCallbackCount});return}this.#t.info(`rabbit: closing connections`);let e=[this.consumeConnection,this.publishConnection,this.oldConsumeConnection,this.oldPublishConnection];await Promise.allSettled(e.map(async e=>{if(e.amqpConnection)try{await e.amqpConnection.close(),this.#t.info(`rabbit: connection closed successfully`)}catch(e){this.#t.error(`rabbit: error closing connection`,{e})}}))}async gracefulShutdown(e){this.gracefulShutdownStarted=!0;let t=this.consumersTags.size+this.oldConsumersTags.size;this.#t.info(`rabbit: [gracefully-shutdown] received ${e}! canceling #${t} tags...`),await this.stopAcceptingWork(),this.shutdownAbortController.abort(Error(`Graceful shutdown initiated by signal: ${e}`))}async consumeFromRabbitOld(t,n,i){let a={...A,...i};e.validateName(`queue`,t);let o=v(),{limit:s,deadMessageTtl:c,useConsumeWithLock:l,lockTimeout:m,auditContext:g,enableRabbitTrace:y,callNackOnAbort:b}=a;if(l){if(!this.redisLock)throw new x(`Usage of consumeWithLock requires RedisInstance`);this.#t.info(`rabbit: Consuming with lock from queue ${t} with lockTimeout: ${m}ms`)}return(await this.getNewChannelOld({connection:this.oldConsumeConnection,name:`consume:${this.identifier}:${t}`})).addSetup(async i=>{await this.assertQueueOld(t,a),await i.prefetch(s,!1);let{consumerTag:l}=await i.consume(t,async s=>s?u(async()=>{let l=Date.now(),u=()=>Date.now()-l,{[T]:m,[E]:v,[D]:x,[d]:S,[f]:C}=s.properties.headers??{};this.#t.addToContext({userId:v});let w=e.parseMsg(s),O=await this.lockRedisIfNeeded(w,a),k=h(_.RABBIT);if(v&&y)try{await p(k,v,S,C)}catch(e){return this.#t.error(`rabbit: failed to setRabbitTrace`,{userId:v,e}),this.nack(i,t,a,{messageTtl:c},s,O)(s)}if(m&&k.context?.set(T,m),g&&await g(t,{userId:v,automationId:x}),!await this.shouldConsumeMessageByTimestamp(w))return await this.unlockRedisIfNeeded(O),this.ack(i,s)(s);let A=!1,j=async()=>{A||(A=!0,await this.ack(i,s,!0,O)(s))},M=async(e,n={})=>{if(A)return;this.#t.debug(`rabbit localNack`,{messageAcked:A,uniqueId:o,deliveryTag:s.fields.deliveryTag}),A=!0;let r=u();await this.nack(i,t,a,{messageTtl:c},s,O)(s,{...n,consumptionDuration:r})};this.activeCallbackCount++;let N=null;try{return b&&(N=r(this.shutdownAbortController.signal,()=>{this.#t.info(`rabbit: shutdown signal received, calling localNack for in-flight message`,{uniqueId:o,deliveryTag:s.fields.deliveryTag});let e=M(s,{isAborted:!0});this.#e.add(e),e.finally(()=>{this.#e.delete(e)})})),await n(w,j,M,this.shutdownAbortController.signal)}catch{return await M(s)}finally{this.activeCallbackCount--,N&&N?.[Symbol.dispose]()}}):null,{...N,consumerTag:`${this.identifier}:${t}`});l?(this.#t.info(`rabbit: adding tag ${l} to the array old`),this.oldConsumersTags.set(t,{channel:i,consumerTag:l})):this.#t.error(`rabbit: failed to consume from queue ${t} old`)})}async getNewChannelOld({name:e=L().toString(),onClose:t=null,options:n={},connection:r}){let a;try{a=await this.getConnectionOld(r)}catch(t){throw this.#t.error(`rabbit: error on get connection for new channel ${e} `,{e:t}),t}if(!a)throw Error(`rabbit: couldnt get connection for new channel ${e}`);let o=a?.createChannel({...n,name:e});i(o,`close`).then(n=>{this.#t.error(`rabbit: channel ${e} closed`),t?.(n)});try{return await i(o,`connect`),this.#t.debug(`rabbit: channel ${e} CONNECTED`),o}catch(t){throw this.#t.error(`rabbit: channel error ${e} error`,{err:t}),t}}async getConnectionOld(e){let{amqpConnection:t,creatingConnection:n,connectionCreatedEventName:r,connectionFailedEventName:a,blockReconnect:o,connectionRole:c}=e;if(o){this.#t.debug(`rabbit: block reconnect`);return}if(t!==null){if(this.options?.disableReconnect||t?.isConnected())return this.#t.debug(`rabbit: connection - is connected`),t;this.#t.debug(`rabbit: connection - reconnecting`)}if(n){let[e,t]=await Promise.race([r,a].map(e=>i(this.oldEm,e).then(([t])=>[e,t])));if(e===r)return t;throw t}e.creatingConnection=!0;let l=!1,u=()=>{let e=process.env.RABBITMQ_USERNAME||`guest`,t=process.env.RABBITMQ_PASSWORD||`guest`,n=this.options?.rabbitHost||process.env.RABBITMQ_SERVICE_HOST||`localhost`;return this.#t.debug(`rabbit: creating connection`,{host:n,userName:e,HEARTBEAT:`60`}),[`amqp://${e}:${t}@${n}?heartbeat=60`]},d=s(u(),{findServers:u,connectionOptions:{clientProperties:{connection_name:`${this.identifier}:${c}`}}});e.amqpConnection=d;let{promise:f,reject:p,resolve:m}=R();return d.on(`error`,e=>{this.#t.error(`rabbit: connection error`,{err:e}),l||(l=!0,p(e),this.oldEm.emit(a,e))}),d.on(`connectFailed`,e=>{this.oldConsumersTags.clear(),typeof e.url==`string`&&(e.url=this.maskURL(e.url)),this.#t.error(`rabbit: connection connectFailed`,{err:e}),l||(l=!0,p(e),this.oldEm.emit(a,e))}),d.on(`disconnect`,({err:t})=>{this.oldConsumersTags.clear(),this.#t.debug(`rabbit: connection closed`),this.options?.disableReconnect?(this.#t.error(`${this.DISCONNECT_MSG}${t&&` - ${t}`}`),e.blockReconnect=!0):this.#t.error(`${this.RECONNECT_MSG}${t&&` - ${t}`}`)}),d.once(`connect`,async()=>{this.#t.debug(`rabbit: connection established`),e.creatingConnection=!1,this.oldEm.emit(r,d),l=!0,m(d)}),f}saveConsumerOld(e,t,n){this.oldConsumersToRegister.some(t=>t.queue===e)||(this.#t.info(`rabbit: consumer: ${e} saved in consumer array`),this.oldConsumersToRegister.push({queue:e,callback:t,options:n}))}async assertQueueOld(t,n){return e.validateName(`queue`,t),this.oldQueues[t]?(delete this.oldQueueSetupPromises[t],this.oldQueues[t]):(this.oldQueueSetupPromises[t]??=this.setupQueueOld(t,n),this.oldQueueSetupPromises[t])}async setupQueueOld(t,n){let r,i=this.oldPublishConnection,a=e.shouldUseQuorum(t),o={...n,durable:!0,arguments:{...n?.arguments,"x-consumer-timeout":1e3*60*60*24,"x-queue-type":a?`quorum`:`classic`}};try{let e=await this.assertChannelOld({connection:i});this.#t.debug(`assertQueue->channel.addSetup`,{queueName:t}),await e.addSetup(e=>e.assertQueue(t,o)),this.#t.debug(`assertQueue->channel.assertQueue`,{queueName:t}),r=await e.assertQueue(t,o)}catch(e){if(this.#t.error(`rabbit: assertQueue error`,{queueName:t,options:n,error:e}),this.options?.dontRetryAssert)throw e;{this.#t.debug(`retrying assertQueue`,{queueName:t});let e=await this.assertChannelOld({force:!0,connection:i});await this.deleteQueueOld(t,i),this.#t.debug(`retrying assertQueue->channel.addSetup`,{queueName:t}),await e.addSetup(e=>e.assertQueue(t,o)),this.#t.debug(`retrying assertQueue->channel.assertQueue`,{queueName:t}),r=await e.assertQueue(t,o)}}return this.oldQueues[t]=r,r}async assertChannelOld({force:e=!1,connection:t}){if(this.oldPublishChannel&&!e)return this.oldPublishChannel;if(this.oldPublishChannelSetupPromise)return this.oldPublishChannelSetupPromise;let{promise:n,resolve:r,reject:i}=R();this.oldPublishChannelSetupPromise=n;try{let e=await this.getNewChannelOld({connection:t,...t.connectionRole===P.PUBLISHER&&{name:`publish:${this.identifier}`}});e.on(`error`,e=>{this.#t.error(`rabbit: channel error`,{err:e})}),this.oldPublishConnection===t&&(this.oldPublishChannel=e),r(e)}catch(e){i(e)}return n}async deleteQueueOld(t,n){e.validateName(`queue`,t);let r=await this.assertChannelOld({connection:n});this.#t.info(`rabbit: deleting queue`,{queue:t});let i=await r.deleteQueue(t);return this.#t.debug(`queue deleted`,i),i}async assertExchangeOld(e,t){let n=await this.assertChannelOld({connection:t});return this.oldExchanges[e]?(delete this.oldAssertExchangePromises[e],this.oldExchanges[e]):this.oldAssertExchangePromises[e]?this.oldAssertExchangePromises[e]:(this.oldAssertExchangePromises[e]=I(n,e),this.oldExchanges[e]=await this.oldAssertExchangePromises[e],this.oldExchanges[e])}async isConnectedOld(){if(this.gracefulShutdownStarted)return!0;this.#t.debug(`rabbit: start is connected old`);let[e,t]=await Promise.all([this.getConnectionOld(this.oldConsumeConnection),this.getConnectionOld(this.oldPublishConnection)]);if(!(e.isConnected()&&t.isConnected()))return this.#t.error(`rabbit: isConnected old - false`),!1;try{let e=this.oldConsumersToRegister.filter(e=>!this.oldConsumersTags.get(e.queue));if(e.length>0){let t=e.map(e=>e.queue);throw this.#t.error(`rabbit: found unregistered consumers for queues old`,{count:t.length,queues:t}),new x(`Found unregistered consumers old`)}let t=await this.assertChannelOld({connection:this.oldPublishConnection});return await t.waitForConnect(),await Promise.all(this.oldConsumersToRegister.map(e=>t.checkQueue(e.queue))),!0}catch(e){return this.#t.error(`rabbit: isConnected - false old`,{msg:e.message}),!1}}};export{K as default,H as sendCeleryTaskViaHttp};
1
+ import{env as e}from"node:process";import{setImmediate as t}from"node:timers/promises";import{EventEmitter as n,addAbortListener as r,once as i}from"node:events";import a from"moment";import o from"redis-lock";import{connect as s}from"amqp-connection-manager";import{backOff as c}from"exponential-backoff";import l,{runWithLoggerContext as u}from"@autofleet/logger";import{CONTEXTS_IDS_HEADER as d,INTERNAL_REQUEST_PATHS_HEADER as f,createOrSetRabbitTrace as p,getUser as m,newTrace as h,outbreak as g,traceTypes as _}from"@autofleet/zehut";import{randomUUID as v}from"node:crypto";import{createClient as y}from"redis";var b=l(),x=class extends Error{constructor(e){super(e),this.name=`RabbitError`}},S=e=>y({socket:e});const C=1e3*5,w=`x-retry-count`,T=`x-trace-id`,E=`x-af-user-id`,D=`x-af-automation-id`,O=`x-total-processing-duration-ms`,k=`x-redelivered-count`,A={limit:1,retries:1,deadMessageTtl:432e5,lockTimeout:C,useConsumeWithLock:!1,auditContext:null,enableRabbitTrace:!1,callNackOnAbort:!1},j={startingDelay:500,timeMultiple:4,numOfAttempts:5},M={startingDelay:1,timeMultiple:1,numOfAttempts:5},N={arguments:{"ha-promote-on-failure":`always`,"ha-promote-on-shutdown":`always`}},P={CONSUMER:`consumer`,PUBLISHER:`publisher`},{PROJECT_ID:F}=process.env,I=async(e,t)=>e.assertExchange(t,`fanout`),L=()=>Math.floor(Math.random()*1e5),R=()=>{if(Promise.withResolvers)return Promise.withResolvers();let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},z=()=>[`af-experiment-manager`,`dev1-experiment-manager`].includes(F||``),B=()=>z()?j:M,V={host:process.env.RABBITMQ_SERVICE_HOST||`localhost`,username:process.env.RABBITMQ_USERNAME||`guest`,password:process.env.RABBITMQ_PASSWORD||`guest`};async function H(e,{taskName:t,queueName:n}){let r=`http://${V.host}:15672/api/exchanges/%2f/amq.default/publish`,i={task:t,id:v(),args:[e]},a={properties:{delivery_mode:2,content_type:`application/json`},routing_key:n,payload:JSON.stringify(i),payload_encoding:`string`};try{let e=await fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Basic ${Buffer.from(`${V.username}:${V.password}`).toString(`base64`)}`},body:JSON.stringify(a)});if(e.ok){let t=await e.json();b.info(`Successfully published message:`,t)}else b.error(`Failed to publish message. Status code: ${e.status}`),b.error(`Response: ${await e.text()}`)}catch(e){throw b.error(`Error sending request:`,e instanceof Error?e.message:String(e)),e}}const{DISABLE_QUORUM_QUEUES_CONSUME:U,DISABLE_QUORUM_QUEUES_PUBLISH:W,MY_POD_NAME:G}=e;var K=class e{static parseMsg(e){let t=e.content.toString();try{t=JSON.parse(t)}catch{}return{...e,content:t}}static validateName(e,t){if(!t||t===``)throw new x(`error while using ${e} with no name`)}static getPublishOptions(e={}){let t=m(),n=g.getCurrentContextTraceId();return{timestamp:a().unix(),timeout:1e4,headers:{creationTimestamp:a().valueOf(),...e,...t?.id===void 0?{}:{[E]:t.id},...t?.contextIds===void 0?{}:{[d]:t.contextIds},...t?.requestedContextPaths===void 0?{}:{[f]:t.requestedContextPaths},...n===void 0?{}:{[T]:n}}}}#e=new Set;#t;constructor(t={},r){this.options=t,this.redisConfig=r,this.DISCONNECT_MSG=`rabbit: connection disconnect`,this.RECONNECT_MSG=`rabbit: connection disconnect - reconnecting`,this.publishChannel=null,this.publishChannelSetupPromise=null,this.publishConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`publishConnectionCreated`,connectionFailedEventName:`publishConnectionFailed`,blockReconnect:!1,connectionRole:P.PUBLISHER},this.consumeConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`consumeConnectionCreated`,connectionFailedEventName:`consumeConnectionFailed`,blockReconnect:!1,connectionRole:P.CONSUMER},this.em=new n,this.exchanges={},this.queues={},this.queueSetupPromises={},this.assertExchangePromises={},this.consumersTags=new Map,this.consumersToRegister=[],this.pendingConsumers=[],this.doesVHostExist=!1,this.vhost=`quorum-vhost`,this.gracefulShutdownStarted=!1,this.activeCallbackCount=0,this.shutdownAbortController=new AbortController,this.oldPublishChannel=null,this.oldPublishChannelSetupPromise=null,this.oldPublishConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`oldPublishConnectionCreated`,connectionFailedEventName:`oldPublishConnectionFailed`,blockReconnect:!1,connectionRole:P.PUBLISHER},this.oldConsumeConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`oldConsumeConnectionCreated`,connectionFailedEventName:`oldConsumeConnectionFailed`,blockReconnect:!1,connectionRole:P.CONSUMER},this.oldEm=new n,this.oldExchanges={},this.oldQueues={},this.oldQueueSetupPromises={},this.oldAssertExchangePromises={},this.oldConsumersTags=new Map,this.oldConsumersToRegister=[],this.assertVHost=async()=>{if(this.doesVHostExist)return;let e=process.env.RABBITMQ_USERNAME||`guest`,t=process.env.RABBITMQ_PASSWORD||`guest`,n={Authorization:`Basic ${Buffer.from(`${e}:${t}`).toString(`base64`)}`,"Content-Type":`application/json`},r=`${`http://${(this.options?.rabbitHost||process.env.RABBITMQ_SERVICE_HOST||`localhost`).split(`:`)[0]}:15672`}/api/vhosts/${encodeURIComponent(this.vhost)}`;try{let e=await fetch(r,{method:`GET`,headers:n});if(e.status===200){this.doesVHostExist=!0,this.#t.info(`Vhost exists`,{vhost:this.vhost});return}if(e.status!==404)throw this.#t.error(`Failed to check vhost`,{response:e}),new x(`Failed to check vhost`);let t=await fetch(r,{method:`PUT`,headers:n,body:JSON.stringify({default_queue_type:`quorum`})});if(!t.ok)throw this.#t.error(`Failed to create vhost`,{response:t}),new x(`Failed to create vhost`);this.doesVHostExist=!0,this.#t.info(`Vhost created`,{vhost:this.vhost})}catch(e){throw this.#t.error(`Failed to check or create vhost`,{error:e}),e}},this.shouldConsumeMessageByTimestamp=async e=>{if(!e)return!1;let{headers:t}=e.properties,n=t?.creationTimestamp;if(n&&t?.redisTimestampValidationKey&&this.redisClient){let e=this.getRedisKey(t.redisTimestampValidationKey),r=await this.redisClient.get(e);return!r||parseInt(r,10)<=parseInt(n,10)}return!0},this.ack=(e,t,n=!1,r=null)=>async i=>{if(!t)return;this.#t.debug(`rabbit acking message`,{deliveryTag:t.fields.deliveryTag}),e.ack(t);let{headers:a}=t.properties,o=a?.creationTimestamp;if(n&&o&&a?.redisTimestampValidationKey&&this.redisClient){let e=parseInt(o,10),t=this.getRedisKey(a.redisTimestampValidationKey);await this.redisClient.set(t,e,{EX:3600}),await this.unlockRedisIfNeeded(r)}},this.executeSafely=async(e,t)=>{try{await e()}catch(e){this.#t.error(`rabbit: error in ${t}`,{error:e})}},this.nack=(t,n,r,i,a,o)=>async(s,{skipRetry:c=!1,consumptionDuration:l,isAborted:u=!1,nackContext:d,error:f}={})=>{if(await this.unlockRedisIfNeeded(o),!t||!a){this.#t.error(`no channel or msg`,{msg:a});return}let p=this.getRetriesCount(a),m=this.getTotalConsumptionDuration(a)??0,h=this.getRedeliveredCount(a),g=m+(l??0),_=(c||p>=r.retries)&&!u,v={deliveryTag:a.fields.deliveryTag,currentRetryCount:p,maxRetries:r.retries,updatedConsumptionDuration:g,sendToDeadQueue:_,isAborted:u,error:f};_?this.#t.error(`nack message - sent to dead-letter queue`,v):u?this.#t.info(`nack message - requeued after shutdown abort`,v):this.#t.warn(`nack message - requeued for retry`,v),r.onNack&&this.executeSafely(()=>r.onNack({msg:e.parseMsg(a),retryCount:p,remainingRetries:(r.retries??0)-p,sendToDeadQueue:_,nackContext:d}),`onNack callback`),await this.sendToQueue(`${n}${_?`-dead`:``}`,e.parseMsg(a).content,_?i:r,{...a.properties.headers,[w]:u?p:p+1,[O]:g,[k]:u?h+1:h},r.isQuorumQueue),this.#t.debug(`rabbit nacking message`,{deliveryTag:a.fields.deliveryTag}),t.ack(a)},this.maskURL=e=>{try{let t=new URL(e);return t.username=`***`,t.password=`***`,t.toString()}catch{return e}},this.#t=t?.logger??b,this.identifier=t?.identifier||G||v();let{redisClient:i,redisLock:a}=this.#n(t,r);this.redisClient=i,this.redisLock=a,this.options?.dontGracefulShutdown||(this.#t.info(`rabbit: [gracefully-shutdown] adding gracefully shutdown for process.pid ${process.pid}`),process.on(`SIGTERM`,async()=>{await this.gracefulShutdown(`SIGTERM`)}),process.on(`SIGINT`,async()=>{await this.gracefulShutdown(`SIGINT`)}))}#n(e,t){let n;return!t&&!e?.redisClient?(this.#t.info(`rabbit: No Redis config provided and no Redis client provided, disabling Redis features`),{redisClient:void 0,redisLock:void 0}):(e?.redisClient?(this.#t.info(`rabbit: Using provided redis client`),n=e.redisClient):(this.#t.info(`rabbit: No redis client provided, creating new redis client`),n=S(t).on(`error`,e=>{this.#t.error(`rabbit: Redis error`,{err:e,redisConfig:t})}),n.connect().catch(e=>{this.#t.error(`rabbit: Failed to connect to Redis`,{err:e,redisConfig:t})})),{redisClient:n,redisLock:o(n)})}getRedisKey(e){return`${this.redisConfig?.prefix||``}${e}`}getRetriesCount(e){let t=e.properties.headers?.[w];return Number.parseInt(t||`0`,10)||0}getRedeliveredCount(e){let t=e.properties.headers?.[k];return Number.parseInt(t||`0`,10)||0}getTotalConsumptionDuration(e){let t=e.properties.headers?.[O];return t?Number.parseInt(t,10):0}async getConnection(e){let{amqpConnection:t,creatingConnection:n,connectionCreatedEventName:r,connectionFailedEventName:a,blockReconnect:o,connectionRole:c}=e;if(o){this.#t.debug(`rabbit: block reconnect`);return}if(t!==null){if(this.options?.disableReconnect||t?.isConnected())return this.#t.debug(`rabbit: connection - is connected`),t;this.#t.debug(`rabbit: connection - reconnecting`)}if(n){this.#t.debug(`rabbit: creating connection emi`);let[e,t]=await Promise.race([r,a].map(e=>i(this.em,e).then(([t])=>[e,t])));if(e===r)return t;throw t}e.creatingConnection=!0;let l=!1,u=()=>{let e=process.env.RABBITMQ_USERNAME||`guest`,t=process.env.RABBITMQ_PASSWORD||`guest`,n=this.options?.rabbitHost||process.env.RABBITMQ_SERVICE_HOST||`localhost`;return this.#t.debug(`rabbit: creating connection`,{host:n,userName:e,HEARTBEAT:`60`}),[`amqp://${e}:${t}@${n}/${this.vhost}?heartbeat=60`]},d=s(u(),{findServers:u,connectionOptions:{clientProperties:{connection_name:`${this.identifier}:quorum:${c}`}}});e.amqpConnection=d;let{promise:f,reject:p,resolve:m}=R();return d.on(`error`,e=>{this.#t.error(`rabbit: connection error`,{err:e}),l||(l=!0,p(e),this.em.emit(a,e))}),d.on(`connectFailed`,e=>{this.consumersTags.clear(),typeof e.url==`string`&&(e.url=this.maskURL(e.url)),this.#t.error(`rabbit: connection connectFailed`,{err:e,advice:`Check if the vhost exist`,vhost:this.vhost}),l||(l=!0,p(e),this.em.emit(a,e))}),d.on(`disconnect`,({err:t})=>{this.consumersTags.clear(),this.#t.debug(`rabbit: connection closed`),this.options?.disableReconnect?(this.#t.error(`${this.DISCONNECT_MSG}${t&&` - ${t}`}`),e.blockReconnect=!0):this.#t.error(`${this.RECONNECT_MSG}${t&&` - ${t}`}`)}),d.once(`connect`,async()=>{this.#t.debug(`rabbit: connection established`),e.creatingConnection=!1,this.em.emit(r,d),l=!0,m(d)}),f}async getNewChannel({name:e=L().toString(),onClose:t=null,options:n={},connection:r}){let a;try{a=await this.getConnection(r)}catch(t){throw this.#t.error(`rabbit: error on get connection for new channel ${e} `,{e:t}),t}let o=a?.createChannel({...n,name:e});i(o,`close`).then(n=>{this.#t.error(`rabbit: channel ${e} closed`),t?.(n)});try{return await i(o,`connect`),this.#t.debug(`rabbit: channel ${e} CONNECTED`),o}catch(t){throw this.#t.error(`rabbit: channel error ${e} error`,{err:t}),t}}async assertChannel({force:e=!1,connection:t}){if(this.publishChannel&&!e)return this.publishChannel;if(this.publishChannelSetupPromise)return this.publishChannelSetupPromise;let{promise:n,resolve:r,reject:i}=R();this.publishChannelSetupPromise=n;try{let e=await this.getNewChannel({connection:t,...t.connectionRole===P.PUBLISHER&&{name:`publish:${this.identifier}:quorum`}});e.on(`error`,e=>{this.#t.error(`rabbit: channel error`,{err:e})}),this.publishConnection===t&&(this.publishChannel=e),r(e)}catch(e){i(e)}return n}async assertExchange(e,t){let n=await this.assertChannel({connection:t});return this.exchanges[e]?(delete this.assertExchangePromises[e],this.exchanges[e]):this.assertExchangePromises[e]?this.assertExchangePromises[e]:(this.assertExchangePromises[e]=I(n,e),this.exchanges[e]=await this.assertExchangePromises[e],this.exchanges[e])}async getQueueLength(t){e.validateName(`queue`,t);let{publishChannel:n}=this;if(!n)throw new x(`channel is not defined`);return this.#t.debug(`rabbit: getting queue length`,{queue:t,connected:this.publishConnection.amqpConnection?.isConnected()}),n?.checkQueue(t)}async deleteQueue(t,n){e.validateName(`queue`,t);let r=await this.assertChannel({connection:n});this.#t.info(`rabbit: deleting queue`,{queue:t});let i=await r.deleteQueue(t);return this.#t.debug(`queue deleted`,i),i}async bindQueue(e,t){let n=await this.assertChannel({connection:this.publishConnection});return await n.addSetup(n=>n.bindQueue(e,t,``)),n.bindQueue(e,t,``)}async setupQueue(e,t){let n,r=this.publishConnection,i={...t,durable:!0,arguments:{...t?.arguments,"x-consumer-timeout":1e3*60*60*24,"x-queue-type":`quorum`}};try{let t=await this.assertChannel({connection:r});this.#t.debug(`assertQueue->channel.addSetup`,{queueName:e}),await t.addSetup(async t=>{await t.assertQueue(e,i)}),this.#t.debug(`assertQueue->channel.assertQueue`,{queueName:e}),n=await t.assertQueue(e,i)}catch(a){if(this.#t.error(`rabbit: assertQueue error`,{queueName:e,options:t,error:a}),this.options?.dontRetryAssert)throw a;{this.#t.debug(`retrying assertQueue`,{queueName:e});let t=await this.assertChannel({force:!0,connection:r});await this.deleteQueue(e,r),this.#t.debug(`retrying assertQueue->channel.addSetup`,{queueName:e}),await t.addSetup(t=>t.assertQueue(e,i)),this.#t.debug(`retrying assertQueue->channel.assertQueue`,{queueName:e}),n=await t.assertQueue(e,i)}}return this.queues[e]=n,n}static shouldUseQuorum(e){let t=process.env.QUORUM_QUEUES_WHITELIST;return t===`*`?!0:t?t.split(`,`).includes(e):!1}async assertQueue(t,n){return e.validateName(`queue`,t),this.queues[t]?(delete this.queueSetupPromises[t],this.queues[t]):(this.queueSetupPromises[t]??=this.setupQueue(t,n),this.queueSetupPromises[t])}saveConsumer(e,t,n){this.consumersToRegister.some(t=>t.queue===e)||(this.#t.info(`rabbit: consumer: ${e} saved in consumer array`),this.consumersToRegister.push({queue:e,callback:t,options:n}))}async consume(e,t,n){let r=async()=>{this.saveConsumerOld(e,t,n),n?.isQuorumQueue!==!1&&U!==`true`&&(this.saveConsumer(e,t,n),await c(()=>this.assertVHost(),B()),await this.consumeNew(e,t,n)),await this.consumeOld(e,t,n)};this.options.autoStartConsumers===!1?this.pendingConsumers.push(r):await r()}async consumeNew(e,t,n){await this.consumeFromRabbit(e,t,n)}async consumeOld(e,t,n){await this.consumeFromRabbitOld(e,t,n)}async lockRedisIfNeeded(e,t){let{properties:{headers:n}}=e,r=n?.creationTimestamp,i=null;return t.useConsumeWithLock&&r&&n?.redisTimestampValidationKey&&this.redisLock&&(i=await this.redisLock(n.redisTimestampValidationKey,t?.lockTimeout||C)),i}async unlockRedisIfNeeded(e){this.redisLock&&e&&await e()}async consumeFromRabbit(t,n,i){let a={...A,...i};e.validateName(`queue`,t);let o=v(),{limit:s,deadMessageTtl:c,useConsumeWithLock:l,lockTimeout:m,auditContext:g,enableRabbitTrace:y}=a;if(l){if(!this.redisLock)throw new x(`Usage of consumeWithLock requires RedisInstance`);this.#t.info(`rabbit: Consuming with lock from queue ${t} with lockTimeout: ${m}ms`)}return(await this.getNewChannel({connection:this.consumeConnection,name:`consume:${this.identifier}:${t}:quorum`})).addSetup(async l=>{await this.assertQueue(t,a),await l.prefetch(s,!1);let{consumerTag:m}=await l.consume(t,s=>s?(this.activeCallbackCount++,u(async()=>{let u=Date.now(),m=()=>Date.now()-u,{[T]:v,[E]:b,[D]:x,[d]:S,[f]:C}=s.properties.headers??{};this.#t.addToContext({userId:b});let w=e.parseMsg(s),O=await this.lockRedisIfNeeded(w,a),k=h(_.RABBIT);if(b&&y)try{await p(k,b,S,C)}catch(e){return this.#t.error(`rabbit: failed to setRabbitTrace`,{userId:b,e}),this.nack(l,t,a,{messageTtl:c},s,O)(s)}if(v&&k.context?.set(T,v),g&&await g(t,{userId:b,automationId:x}),!await this.shouldConsumeMessageByTimestamp(w))return await this.unlockRedisIfNeeded(O),this.ack(l,s)(s);let A=!1,j=async()=>{A||(A=!0,await this.ack(l,s,!0,O)(s))},M=async(e,n={})=>{if(A)return;this.#t.debug(`rabbit localNack`,{messageAcked:A,uniqueId:o,deliveryTag:s.fields.deliveryTag}),A=!0;let r=m();await this.nack(l,t,a,{messageTtl:c},s,O)(s,{...n,consumptionDuration:r})},N=null;try{return i?.callNackOnAbort&&(N=r(this.shutdownAbortController.signal,()=>{this.#t.warn(`rabbit: callback aborted`,{uniqueId:o,deliveryTag:s.fields.deliveryTag});let e=M(s,{isAborted:!0});this.#e.add(e),e.finally(()=>{this.#e.delete(e)})})),await n(w,j,M,this.shutdownAbortController.signal)}catch(e){return await M(s,{error:e})}finally{N&&N[Symbol.dispose]()}}).finally(()=>{this.activeCallbackCount--})):null,{...N,consumerTag:`${this.identifier}:${t}:quorum`});m?(this.#t.info(`rabbit: adding tag ${m} to the array.`),this.consumersTags.set(t,{channel:l,consumerTag:m})):this.#t.error(`rabbit: failed to consume from queue ${t}`)})}async consumeFromExchange(t,n,r,i){let a={...A,...i};e.validateName(`exchange`,n),e.validateName(`queue`,t);let{limit:o}=a,s=async()=>{i?.isQuorumQueue!==!1&&U!==`true`&&(this.saveConsumer(t,r,i),await c(()=>this.assertVHost(),B()),await(await this.getNewChannel({name:`consume-from-exchange:${this.identifier}:${n}:${t}:quorum`,connection:this.consumeConnection})).addSetup(async e=>{let a=await I(e,n);return await e.assertQueue(t),this.exchanges[n]=a,await e.prefetch(o,!1),Promise.all([e.bindQueue(t,n,``),this.consumeNew(t,r,i)])})),this.saveConsumerOld(t,r,i),await(await this.getNewChannelOld({name:`consume-from-exchange:${this.identifier}:${n}:${t}`,connection:this.oldConsumeConnection})).addSetup(async e=>{let a=await I(e,n);return await e.assertQueue(t),this.oldExchanges[n]=a,await e.prefetch(o,!1),Promise.all([e.bindQueue(t,n,``),this.consumeOld(t,r,i)])})};this.options.autoStartConsumers===!1?this.pendingConsumers.push(s):await s()}async startConsume(){await Promise.all(this.pendingConsumers.map(e=>e())),this.pendingConsumers.length=0}async publish(n,r,i,a=!0){if(await t(),a&&W!==`true`){await this.assertVHost(),e.validateName(`exchange`,n);let t=await this.assertChannel({connection:this.publishConnection});await this.assertExchange(n,this.publishConnection),await t.publish(n,``,Buffer.from(JSON.stringify(r)),e.getPublishOptions(i));return}e.validateName(`exchange`,n);let o=await this.assertChannelOld({connection:this.oldPublishConnection});await this.assertExchangeOld(n,this.oldPublishConnection),await o.publish(n,``,Buffer.from(JSON.stringify(r)),e.getPublishOptions(i))}async sendToQueue(t,n,r,i,a=!0){if(a&&W!==`true`){try{await this.assertVHost(),await this.assertChannel({connection:this.publishConnection})}catch(e){throw this.#t.error(`rabbit sendToQueue: failed to send assert channel when sending to queue ${t}`,{e}),e}try{e.validateName(`queue`,t),await this.assertQueue(t,r)}catch(e){throw this.#t.error(`rabbit sendToQueue: failed to assert queue ${t}`,{e}),e}try{let r=await this.publishChannel?.sendToQueue(t,Buffer.from(JSON.stringify(n)),e.getPublishOptions(i));return this.#t.debug(`rabbit: sending to queue ${t}`,{res:r}),r}catch(e){let n=await this.isConnected();throw this.#t.error(`rabbit sendToQueue: failed to send to queue ${t}, isConnected: ${n}`,{e}),e}}else{try{await this.assertChannelOld({connection:this.oldPublishConnection})}catch(e){throw this.#t.error(`rabbit sendToQueue: failed to send assert channel when sending to queue ${t}`,{e}),e}try{e.validateName(`queue`,t),await this.assertQueueOld(t,r)}catch(e){throw this.#t.error(`rabbit sendToQueue: failed to assert queue ${t}`,{e}),e}try{let r=await this.oldPublishChannel?.sendToQueue(t,Buffer.from(JSON.stringify(n)),e.getPublishOptions(i));return this.#t.debug(`rabbit: sending to queue ${t}`,{res:r}),r}catch(e){let n=await this.isConnectedOld();throw this.#t.error(`rabbit sendToQueue: failed to send to queue ${t}, isConnected: ${n}`,{e}),e}}}async isConnected(){let e=!0;if(!this.gracefulShutdownStarted){if(U!==`true`||W!==`true`){this.#t.debug(`rabbit: start is connected`);let[t,n]=await Promise.all([this.getConnection(this.consumeConnection),this.getConnection(this.publishConnection)]);if(e=t.isConnected()&&n.isConnected(),!e)return this.#t.error(`rabbit: isConnected - false`),!1;try{let e=this.consumersToRegister.filter(e=>!this.consumersTags.get(e.queue));if(e.length>0){let t=e.map(e=>e.queue);throw this.#t.error(`rabbit: found unregistered consumers for queues`,{count:t.length,queues:t}),new x(`Found unregistered consumers`)}let t=await this.assertChannel({connection:this.publishConnection});await t.waitForConnect(),await Promise.all(this.consumersToRegister.map(e=>t.checkQueue(e.queue)))}catch(e){return this.#t.error(`rabbit: isConnected - false`,{msg:e.message}),!1}}e=await this.isConnectedOld()}return this.#t.debug(`rabbit: isConnected - ${e}`),e}async stopAcceptingWork(){this.#t.info(`rabbit: stop accepting work - canceling all tags`);let e=[...this.consumersTags].map(([,{channel:e,consumerTag:t}])=>e.cancel(t)),t=[...this.oldConsumersTags].map(([,{channel:e,consumerTag:t}])=>e.cancel(t));this.consumersTags.clear(),this.oldConsumersTags.clear();let n=(await Promise.allSettled([...e,...t])).filter(e=>e.status===`rejected`);n.length>0?this.#t.warn(`rabbit: stop accepting work - failed to cancel #${n.length} tags: ${n}`):this.#t.info(`rabbit: stop accepting work - all tags successfully canceled.`)}async drain(e=1e4,t=!0){let n=Date.now(),r=this.activeCallbackCount;if(this.#t.info(`rabbit: [drain] waiting for active callbacks`,{activeCallbackCount:r,timeoutMs:e}),r===0){this.#t.info(`rabbit: [drain] no active callbacks to drain`);return}let i=this.publishChannel?.queueLength()??0;for(i>0&&this.#t.warn(`rabbit: [drain] there are still published messages waiting in the channel buffer`,{publishedMessagesWaiting:i});this.activeCallbackCount>0;){let r=Date.now()-n;if(r>=e){let n=this.activeCallbackCount;if(this.#t.warn(`rabbit: [drain] timeout waiting for callbacks`,{duration:r,remainingCallbacks:n,timeoutMs:e}),this.shutdownAbortController.abort(Error(`Graceful shutdown initiated by drain timeout after ${r}ms with ${n} callbacks still active`)),await Promise.allSettled([...this.#e]),t)throw Error(`Drain timeout after ${e}ms - ${n} callbacks still active`);return}await new Promise(e=>setTimeout(e,50))}let a=Date.now()-n;this.#t.info(`rabbit: [drain] all callbacks completed`,{duration:a,callbackCount:r})}async closeConnections(){if(this.activeCallbackCount>0){this.#t.warn(`rabbit: closing connections received with active callbacks. not performing the close`,{activeCallbackCount:this.activeCallbackCount});return}this.#t.info(`rabbit: closing connections`);let e=[this.consumeConnection,this.publishConnection,this.oldConsumeConnection,this.oldPublishConnection];await Promise.allSettled(e.map(async e=>{if(e.amqpConnection)try{await e.amqpConnection.close(),this.#t.info(`rabbit: connection closed successfully`)}catch(e){this.#t.error(`rabbit: error closing connection`,{e})}}))}async gracefulShutdown(e){this.gracefulShutdownStarted=!0;let t=this.consumersTags.size+this.oldConsumersTags.size;this.#t.info(`rabbit: [gracefully-shutdown] received ${e}! canceling #${t} tags...`),await this.stopAcceptingWork(),this.shutdownAbortController.abort(Error(`Graceful shutdown initiated by signal: ${e}`))}async consumeFromRabbitOld(t,n,i){let a={...A,...i};e.validateName(`queue`,t);let o=v(),{limit:s,deadMessageTtl:c,useConsumeWithLock:l,lockTimeout:m,auditContext:g,enableRabbitTrace:y,callNackOnAbort:b}=a;if(l){if(!this.redisLock)throw new x(`Usage of consumeWithLock requires RedisInstance`);this.#t.info(`rabbit: Consuming with lock from queue ${t} with lockTimeout: ${m}ms`)}return(await this.getNewChannelOld({connection:this.oldConsumeConnection,name:`consume:${this.identifier}:${t}`})).addSetup(async i=>{await this.assertQueueOld(t,a),await i.prefetch(s,!1);let{consumerTag:l}=await i.consume(t,s=>s?(this.activeCallbackCount++,u(async()=>{let l=Date.now(),u=()=>Date.now()-l,{[T]:m,[E]:v,[D]:x,[d]:S,[f]:C}=s.properties.headers??{};this.#t.addToContext({userId:v});let w=e.parseMsg(s),O=await this.lockRedisIfNeeded(w,a),k=h(_.RABBIT);if(v&&y)try{await p(k,v,S,C)}catch(e){return this.#t.error(`rabbit: failed to setRabbitTrace`,{userId:v,e}),this.nack(i,t,a,{messageTtl:c},s,O)(s)}if(m&&k.context?.set(T,m),g&&await g(t,{userId:v,automationId:x}),!await this.shouldConsumeMessageByTimestamp(w))return await this.unlockRedisIfNeeded(O),this.ack(i,s)(s);let A=!1,j=async()=>{A||(A=!0,await this.ack(i,s,!0,O)(s))},M=async(e,n={})=>{if(A)return;this.#t.debug(`rabbit localNack`,{messageAcked:A,uniqueId:o,deliveryTag:s.fields.deliveryTag}),A=!0;let r=u();await this.nack(i,t,a,{messageTtl:c},s,O)(s,{...n,consumptionDuration:r})},N=null;try{return b&&(N=r(this.shutdownAbortController.signal,()=>{this.#t.info(`rabbit: shutdown signal received, calling localNack for in-flight message`,{uniqueId:o,deliveryTag:s.fields.deliveryTag});let e=M(s,{isAborted:!0});this.#e.add(e),e.finally(()=>{this.#e.delete(e)})})),await n(w,j,M,this.shutdownAbortController.signal)}catch(e){return await M(s,{error:e})}finally{N&&N?.[Symbol.dispose]()}}).finally(()=>{this.activeCallbackCount--})):null,{...N,consumerTag:`${this.identifier}:${t}`});l?(this.#t.info(`rabbit: adding tag ${l} to the array old`),this.oldConsumersTags.set(t,{channel:i,consumerTag:l})):this.#t.error(`rabbit: failed to consume from queue ${t} old`)})}async getNewChannelOld({name:e=L().toString(),onClose:t=null,options:n={},connection:r}){let a;try{a=await this.getConnectionOld(r)}catch(t){throw this.#t.error(`rabbit: error on get connection for new channel ${e} `,{e:t}),t}if(!a)throw Error(`rabbit: couldnt get connection for new channel ${e}`);let o=a?.createChannel({...n,name:e});i(o,`close`).then(n=>{this.#t.error(`rabbit: channel ${e} closed`),t?.(n)});try{return await i(o,`connect`),this.#t.debug(`rabbit: channel ${e} CONNECTED`),o}catch(t){throw this.#t.error(`rabbit: channel error ${e} error`,{err:t}),t}}async getConnectionOld(e){let{amqpConnection:t,creatingConnection:n,connectionCreatedEventName:r,connectionFailedEventName:a,blockReconnect:o,connectionRole:c}=e;if(o){this.#t.debug(`rabbit: block reconnect`);return}if(t!==null){if(this.options?.disableReconnect||t?.isConnected())return this.#t.debug(`rabbit: connection - is connected`),t;this.#t.debug(`rabbit: connection - reconnecting`)}if(n){let[e,t]=await Promise.race([r,a].map(e=>i(this.oldEm,e).then(([t])=>[e,t])));if(e===r)return t;throw t}e.creatingConnection=!0;let l=!1,u=()=>{let e=process.env.RABBITMQ_USERNAME||`guest`,t=process.env.RABBITMQ_PASSWORD||`guest`,n=this.options?.rabbitHost||process.env.RABBITMQ_SERVICE_HOST||`localhost`;return this.#t.debug(`rabbit: creating connection`,{host:n,userName:e,HEARTBEAT:`60`}),[`amqp://${e}:${t}@${n}?heartbeat=60`]},d=s(u(),{findServers:u,connectionOptions:{clientProperties:{connection_name:`${this.identifier}:${c}`}}});e.amqpConnection=d;let{promise:f,reject:p,resolve:m}=R();return d.on(`error`,e=>{this.#t.error(`rabbit: connection error`,{err:e}),l||(l=!0,p(e),this.oldEm.emit(a,e))}),d.on(`connectFailed`,e=>{this.oldConsumersTags.clear(),typeof e.url==`string`&&(e.url=this.maskURL(e.url)),this.#t.error(`rabbit: connection connectFailed`,{err:e}),l||(l=!0,p(e),this.oldEm.emit(a,e))}),d.on(`disconnect`,({err:t})=>{this.oldConsumersTags.clear(),this.#t.debug(`rabbit: connection closed`),this.options?.disableReconnect?(this.#t.error(`${this.DISCONNECT_MSG}${t&&` - ${t}`}`),e.blockReconnect=!0):this.#t.error(`${this.RECONNECT_MSG}${t&&` - ${t}`}`)}),d.once(`connect`,async()=>{this.#t.debug(`rabbit: connection established`),e.creatingConnection=!1,this.oldEm.emit(r,d),l=!0,m(d)}),f}saveConsumerOld(e,t,n){this.oldConsumersToRegister.some(t=>t.queue===e)||(this.#t.info(`rabbit: consumer: ${e} saved in consumer array`),this.oldConsumersToRegister.push({queue:e,callback:t,options:n}))}async assertQueueOld(t,n){return e.validateName(`queue`,t),this.oldQueues[t]?(delete this.oldQueueSetupPromises[t],this.oldQueues[t]):(this.oldQueueSetupPromises[t]??=this.setupQueueOld(t,n),this.oldQueueSetupPromises[t])}async setupQueueOld(t,n){let r,i=this.oldPublishConnection,a=e.shouldUseQuorum(t),o={...n,durable:!0,arguments:{...n?.arguments,"x-consumer-timeout":1e3*60*60*24,"x-queue-type":a?`quorum`:`classic`}};try{let e=await this.assertChannelOld({connection:i});this.#t.debug(`assertQueue->channel.addSetup`,{queueName:t}),await e.addSetup(e=>e.assertQueue(t,o)),this.#t.debug(`assertQueue->channel.assertQueue`,{queueName:t}),r=await e.assertQueue(t,o)}catch(e){if(this.#t.error(`rabbit: assertQueue error`,{queueName:t,options:n,error:e}),this.options?.dontRetryAssert)throw e;{this.#t.debug(`retrying assertQueue`,{queueName:t});let e=await this.assertChannelOld({force:!0,connection:i});await this.deleteQueueOld(t,i),this.#t.debug(`retrying assertQueue->channel.addSetup`,{queueName:t}),await e.addSetup(e=>e.assertQueue(t,o)),this.#t.debug(`retrying assertQueue->channel.assertQueue`,{queueName:t}),r=await e.assertQueue(t,o)}}return this.oldQueues[t]=r,r}async assertChannelOld({force:e=!1,connection:t}){if(this.oldPublishChannel&&!e)return this.oldPublishChannel;if(this.oldPublishChannelSetupPromise)return this.oldPublishChannelSetupPromise;let{promise:n,resolve:r,reject:i}=R();this.oldPublishChannelSetupPromise=n;try{let e=await this.getNewChannelOld({connection:t,...t.connectionRole===P.PUBLISHER&&{name:`publish:${this.identifier}`}});e.on(`error`,e=>{this.#t.error(`rabbit: channel error`,{err:e})}),this.oldPublishConnection===t&&(this.oldPublishChannel=e),r(e)}catch(e){i(e)}return n}async deleteQueueOld(t,n){e.validateName(`queue`,t);let r=await this.assertChannelOld({connection:n});this.#t.info(`rabbit: deleting queue`,{queue:t});let i=await r.deleteQueue(t);return this.#t.debug(`queue deleted`,i),i}async assertExchangeOld(e,t){let n=await this.assertChannelOld({connection:t});return this.oldExchanges[e]?(delete this.oldAssertExchangePromises[e],this.oldExchanges[e]):this.oldAssertExchangePromises[e]?this.oldAssertExchangePromises[e]:(this.oldAssertExchangePromises[e]=I(n,e),this.oldExchanges[e]=await this.oldAssertExchangePromises[e],this.oldExchanges[e])}async isConnectedOld(){if(this.gracefulShutdownStarted)return!0;this.#t.debug(`rabbit: start is connected old`);let[e,t]=await Promise.all([this.getConnectionOld(this.oldConsumeConnection),this.getConnectionOld(this.oldPublishConnection)]);if(!(e.isConnected()&&t.isConnected()))return this.#t.error(`rabbit: isConnected old - false`),!1;try{let e=this.oldConsumersToRegister.filter(e=>!this.oldConsumersTags.get(e.queue));if(e.length>0){let t=e.map(e=>e.queue);throw this.#t.error(`rabbit: found unregistered consumers for queues old`,{count:t.length,queues:t}),new x(`Found unregistered consumers old`)}let t=await this.assertChannelOld({connection:this.oldPublishConnection});return await t.waitForConnect(),await Promise.all(this.oldConsumersToRegister.map(e=>t.checkQueue(e.queue))),!0}catch(e){return this.#t.error(`rabbit: isConnected - false old`,{msg:e.message}),!1}}};export{K as default,H as sendCeleryTaskViaHttp};
2
2
  //# sourceMappingURL=index.js.map