@autofleet/rabbit 5.6.0-beta.0 → 5.6.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/README.md CHANGED
@@ -5,4 +5,32 @@ The required version of zehut is now `^4.0.0`.
5
5
 
6
6
  This was moved to being a peer-dependency in order to ensure that the version of `zehut` used here is the same as used in the MS, and not risk the package using v4 while the service is using v3, which would cause `zehut` to have multiple traces, which will not all hold the correct data.
7
7
 
8
- Additionally, the minimum node version is now 18, due to the minimum version of node defined in `zehut`.
8
+ Additionally, the minimum node version is now 18, due to the minimum version of node defined in `zehut`.
9
+
10
+ ## `onNack` hook
11
+
12
+ Called whenever a message is nacked — whether it's retried or sent to the dead-letter queue.
13
+
14
+ ```ts
15
+ rabbit.consume('my-queue', async (msg, ack, nack) => {
16
+ try {
17
+ await processMessage(msg);
18
+ await ack();
19
+ } catch (error) {
20
+ await nack(msg, { nackContext: { error: error.message, orderId: msg.content.id } });
21
+ }
22
+ }, {
23
+ retries: 3,
24
+ onNack: ({ msg, retryCount, remainingRetries, sendToDeadQueue, nackContext }) => {
25
+ logger.warn('message nacked', { retryCount, remainingRetries, sendToDeadQueue, nackContext });
26
+ },
27
+ });
28
+ ```
29
+
30
+ | Param | Type | Description |
31
+ |---|---|---|
32
+ | `msg` | `Message` | The parsed message |
33
+ | `retryCount` | `number` | Current retry attempt number |
34
+ | `remainingRetries` | `number` | Retries left before dead-letter |
35
+ | `sendToDeadQueue` | `boolean` | `true` if the message is going to the dead-letter queue |
36
+ | `nackContext` | `Record<string, unknown>` | Optional context passed from the consumer callback via `nack()` |
@@ -40,9 +40,17 @@ interface ConsumeOptions {
40
40
  enableRabbitTrace?: boolean;
41
41
  isQuorumQueue?: boolean;
42
42
  callNackOnAbort?: boolean;
43
+ onNack?: (params: {
44
+ msg: Message;
45
+ retryCount: number;
46
+ remainingRetries: number;
47
+ sendToDeadQueue: boolean;
48
+ nackContext?: Record<string, unknown>;
49
+ }) => void | Promise<void>;
43
50
  }
44
51
  interface NackOptions {
45
52
  skipRetry?: boolean;
53
+ nackContext?: Record<string, unknown>;
46
54
  }
47
55
  type Message = Omit<ConsumeMessage, "content"> & {
48
56
  content: any;
@@ -187,10 +195,12 @@ declare class RabbitMq implements IAfRabbitMq {
187
195
  getRedeliveredCount(msg: ConsumeMessage): number;
188
196
  getTotalConsumptionDuration(msg: ConsumeMessage): number;
189
197
  ack: (channel: ConfirmChannel, msg: ConsumeMessageOrNull, shouldUpdateRedisTimestamp?: boolean, releaseLock?: (() => Promise<void>) | null) => (userMsg: ConsumeMessage) => Promise<void>;
198
+ private executeSafely;
190
199
  nack: (channel: ConfirmChannel, queue: string, options: ConsumeOptions, deadQueueOptions: Options.AssertQueue, msg: ConsumeMessageOrNull, releaseLock?: (() => Promise<void>) | null) => (userMsg: ConsumeMessageOrNull, {
191
200
  skipRetry,
192
201
  consumptionDuration,
193
- isAborted
202
+ isAborted,
203
+ nackContext
194
204
  }?: NackOptions & {
195
205
  isAborted?: boolean;
196
206
  consumptionDuration?: number;
@@ -260,4 +270,4 @@ declare class RabbitMq implements IAfRabbitMq {
260
270
  type ConsumerCallbackFunction = CallbackFunction;
261
271
  //#endregion
262
272
  export { sendCeleryTaskViaHttp as a, RabbitMq as i, ConsumerCallbackFunction as n, IAfRabbitMq as r, AfRabbitOptions as t };
263
- //# sourceMappingURL=index-COhISXIE.d.cts.map
273
+ //# sourceMappingURL=index-8E2dTXAY.d.cts.map
@@ -41,9 +41,17 @@ interface ConsumeOptions {
41
41
  enableRabbitTrace?: boolean;
42
42
  isQuorumQueue?: boolean;
43
43
  callNackOnAbort?: boolean;
44
+ onNack?: (params: {
45
+ msg: Message;
46
+ retryCount: number;
47
+ remainingRetries: number;
48
+ sendToDeadQueue: boolean;
49
+ nackContext?: Record<string, unknown>;
50
+ }) => void | Promise<void>;
44
51
  }
45
52
  interface NackOptions {
46
53
  skipRetry?: boolean;
54
+ nackContext?: Record<string, unknown>;
47
55
  }
48
56
  type Message = Omit<ConsumeMessage, "content"> & {
49
57
  content: any;
@@ -188,10 +196,12 @@ declare class RabbitMq implements IAfRabbitMq {
188
196
  getRedeliveredCount(msg: ConsumeMessage): number;
189
197
  getTotalConsumptionDuration(msg: ConsumeMessage): number;
190
198
  ack: (channel: ConfirmChannel, msg: ConsumeMessageOrNull, shouldUpdateRedisTimestamp?: boolean, releaseLock?: (() => Promise<void>) | null) => (userMsg: ConsumeMessage) => Promise<void>;
199
+ private executeSafely;
191
200
  nack: (channel: ConfirmChannel, queue: string, options: ConsumeOptions, deadQueueOptions: Options.AssertQueue, msg: ConsumeMessageOrNull, releaseLock?: (() => Promise<void>) | null) => (userMsg: ConsumeMessageOrNull, {
192
201
  skipRetry,
193
202
  consumptionDuration,
194
- isAborted
203
+ isAborted,
204
+ nackContext
195
205
  }?: NackOptions & {
196
206
  isAborted?: boolean;
197
207
  consumptionDuration?: number;
@@ -261,4 +271,4 @@ declare class RabbitMq implements IAfRabbitMq {
261
271
  type ConsumerCallbackFunction = CallbackFunction;
262
272
  //#endregion
263
273
  export { sendCeleryTaskViaHttp as a, RabbitMq as i, ConsumerCallbackFunction as n, IAfRabbitMq as r, AfRabbitOptions as t };
264
- //# sourceMappingURL=index-B5CP99aq.d.ts.map
274
+ //# sourceMappingURL=index-_hV-HaYU.d.ts.map
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,`__esModule`,{value:!0});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(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},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`node:process`),l=require(`node:timers/promises`),u=require(`node:events`),d=require(`moment`);d=s(d);let f=require(`redis-lock`);f=s(f);let p=require(`amqp-connection-manager`),m=require(`exponential-backoff`),h=require(`@autofleet/logger`);h=s(h);let g=require(`@autofleet/zehut`),_=require(`node:crypto`),v=require(`redis`);const y=(0,h.default)();var b=y,x=class extends Error{constructor(e){super(e),this.name=`RabbitError`}};const S=e=>(0,v.createClient)({socket:e});var C=S;const w=6e4*60*12,T=1e3*5,E=`x-retry-count`,D=`x-trace-id`,O=`x-af-user-id`,k=`x-af-automation-id`,A=`x-total-processing-duration-ms`,j=`x-redelivered-count`,M=!1,N={limit:1,retries:1,deadMessageTtl:432e5,lockTimeout:T,useConsumeWithLock:!1,auditContext:null,enableRabbitTrace:!1,callNackOnAbort:!1},P={startingDelay:500,timeMultiple:4,numOfAttempts:5},F={startingDelay:1,timeMultiple:1,numOfAttempts:5},I=`ha-promote-on-failure`,L=`ha-promote-on-shutdown`,R={arguments:{"ha-promote-on-failure":`always`,"ha-promote-on-shutdown":`always`}},z={CONSUMER:`consumer`,PUBLISHER:`publisher`},{PROJECT_ID:B}=process.env,V=async(e,t)=>e.assertExchange(t,`fanout`),H=()=>Math.floor(Math.random()*1e5),U=()=>{if(Promise.withResolvers)return Promise.withResolvers();let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},W=()=>[`af-experiment-manager`,`dev1-experiment-manager`].includes(B||``),G=()=>W()?P:F,K={host:process.env.RABBITMQ_SERVICE_HOST||`localhost`,username:process.env.RABBITMQ_USERNAME||`guest`,password:process.env.RABBITMQ_PASSWORD||`guest`};async function q(e,{taskName:t,queueName:n}){let r=`http://${K.host}:15672/api/exchanges/%2f/amq.default/publish`,i={task:t,id:(0,_.randomUUID)(),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(`${K.username}:${K.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 J=1e3*10,{DISABLE_QUORUM_QUEUES_CONSUME:Y,DISABLE_QUORUM_QUEUES_PUBLISH:X,MY_POD_NAME:Z}=c.env,ee=`60`;var Q=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=(0,g.getUser)(),n=g.outbreak.getCurrentContextTraceId();return{timestamp:(0,d.default)().unix(),timeout:1e4,headers:{creationTimestamp:(0,d.default)().valueOf(),...e,...t?.id===void 0?{}:{[O]:t.id},...t?.contextIds===void 0?{}:{[g.CONTEXTS_IDS_HEADER]:t.contextIds},...n===void 0?{}:{[D]:n}}}}#e=new Set;#t;constructor(t={},n){this.options=t,this.redisConfig=n,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:z.PUBLISHER},this.consumeConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`consumeConnectionCreated`,connectionFailedEventName:`consumeConnectionFailed`,blockReconnect:!1,connectionRole:z.CONSUMER},this.em=new u.EventEmitter,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:z.PUBLISHER},this.oldConsumeConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`oldConsumeConnectionCreated`,connectionFailedEventName:`oldConsumeConnectionFailed`,blockReconnect:!1,connectionRole:z.CONSUMER},this.oldEm=new u.EventEmitter,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}),await 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.nack=(t,n,r,i,a,o)=>async(s,{skipRetry:c=!1,consumptionDuration:l,isAborted:u=!1}={})=>{if(await this.unlockRedisIfNeeded(o),!t||!a){this.#t.error(`no channel or msg`,{msg:a});return}let d=this.getRetriesCount(a),f=this.getTotalConsumptionDuration(a)??0,p=this.getRedeliveredCount(a),m=f+(l??0),h=(c||d>=r.retries)&&!u;this.#t.info(`nack message`,{deliveryTag:a.fields.deliveryTag,currentRetryCount:d,updatedConsumptionDuration:m,sendToDeadQueue:h,isAborted:u}),await this.sendToQueue(`${n}${h?`-dead`:``}`,e.parseMsg(a).content,h?i:r,{...a.properties.headers,[E]:u?d:d+1,[A]:m,[j]:u?p+1:p},r.isQuorumQueue),this.#t.debug(`rabbit nacking message`,{deliveryTag:a.fields.deliveryTag}),await 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||Z||(0,_.randomUUID)();let{redisClient:r,redisLock:i}=this.#n(t,n);this.redisClient=r,this.redisLock=i,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=C(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:(0,f.default)(n)})}getRedisKey(e){return`${this.redisConfig?.prefix||``}${e}`}getRetriesCount(e){let t=e.properties.headers?.[E];return Number.parseInt(t||`0`,10)||0}getRedeliveredCount(e){let t=e.properties.headers?.[j];return Number.parseInt(t||`0`,10)||0}getTotalConsumptionDuration(e){let t=e.properties.headers?.[A];return t?Number.parseInt(t,10):0}async getConnection(e){let{amqpConnection:t,creatingConnection:n,connectionCreatedEventName:r,connectionFailedEventName:i,blockReconnect:a,connectionRole:o}=e;if(a){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,i].map(e=>(0,u.once)(this.em,e).then(([t])=>[e,t])));if(e===r)return t;throw t}e.creatingConnection=!0;let s=!1,c=()=>{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`]},l=(0,p.connect)(c(),{findServers:c,connectionOptions:{clientProperties:{connection_name:`${this.identifier}:quorum:${o}`}}});e.amqpConnection=l;let{promise:d,reject:f,resolve:m}=U();return l.on(`error`,e=>{this.#t.error(`rabbit: connection error`,{err:e}),s||(s=!0,f(e),this.em.emit(i,e))}),l.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}),s||(s=!0,f(e),this.em.emit(i,e))}),l.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}`}`)}),l.once(`connect`,async()=>{this.#t.debug(`rabbit: connection established`),e.creatingConnection=!1,this.em.emit(r,l),s=!0,m(l)}),d}async getNewChannel({name:e=H().toString(),onClose:t=null,options:n={},connection:r}){let i;try{i=await this.getConnection(r)}catch(t){throw this.#t.error(`rabbit: error on get connection for new channel ${e} `,{e:t}),t}let a=i?.createChannel({...n,name:e});(0,u.once)(a,`close`).then(n=>{this.#t.error(`rabbit: channel ${e} closed`),t?.(n)});try{return await(0,u.once)(a,`connect`),this.#t.debug(`rabbit: channel ${e} CONNECTED`),a}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}=U();this.publishChannelSetupPromise=n;try{let e=await this.getNewChannel({connection:t,...t.connectionRole===z.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]=V(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&&Y!==`true`&&(this.saveConsumer(e,t,n),await(0,m.backOff)(()=>this.assertVHost(),G()),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||T)),i}async unlockRedisIfNeeded(e){this.redisLock&&e&&await e()}async consumeFromRabbit(t,n,r){let i={...N,...r};e.validateName(`queue`,t);let a=(0,_.randomUUID)(),{limit:o,deadMessageTtl:s,useConsumeWithLock:c,lockTimeout:l,auditContext:d,enableRabbitTrace:f}=i;if(c){if(!this.redisLock)throw new x(`Usage of consumeWithLock requires RedisInstance`);this.#t.info(`rabbit: Consuming with lock from queue ${t} with lockTimeout: ${l}ms`)}return(await this.getNewChannel({connection:this.consumeConnection,name:`consume:${this.identifier}:${t}:quorum`})).addSetup(async c=>{await this.assertQueue(t,i),await c.prefetch(o,!1);let{consumerTag:l}=await c.consume(t,async o=>o?(0,h.runWithLoggerContext)(async()=>{let l=Date.now(),p=()=>Date.now()-l,{[D]:m,[O]:h,[k]:_,[g.CONTEXTS_IDS_HEADER]:v}=o.properties.headers??{};this.#t.addToContext({userId:h});let y=e.parseMsg(o),b=await this.lockRedisIfNeeded(y,i),x=(0,g.newTrace)(g.traceTypes.RABBIT);if(h&&f)try{await(0,g.createOrSetRabbitTrace)(x,h,v)}catch(e){return this.#t.error(`rabbit: failed to setRabbitTrace`,{userId:h,e}),this.nack(c,t,i,{messageTtl:s},o,b)(o)}if(m&&x.context?.set(D,m),d&&await d(t,{userId:h,automationId:_}),!await this.shouldConsumeMessageByTimestamp(y))return await this.unlockRedisIfNeeded(b),this.ack(c,o)(o);let S=!1,C=async()=>{S||(S=!0,await this.ack(c,o,!0,b)(o))},w=async(e,n={})=>{if(S)return;this.#t.debug(`rabbit localNack`,{messageAcked:S,uniqueId:a,deliveryTag:o.fields.deliveryTag}),S=!0;let r=p();await this.nack(c,t,i,{messageTtl:s},o,b)(o,{...n,consumptionDuration:r})};this.activeCallbackCount++;let T=null;try{return r?.callNackOnAbort&&(T=(0,u.addAbortListener)(this.shutdownAbortController.signal,()=>{this.#t.warn(`rabbit: callback aborted`,{uniqueId:a,deliveryTag:o.fields.deliveryTag});let e=w(o,{isAborted:!0});this.#e.add(e),e.finally(()=>{this.#e.delete(e)})})),await n(y,C,w,this.shutdownAbortController.signal)}catch{return await w(o)}finally{this.activeCallbackCount--,T&&T[Symbol.dispose]()}}):null,{...R,consumerTag:`${this.identifier}:${t}:quorum`});l?(this.#t.info(`rabbit: adding tag ${l} to the array.`),this.consumersTags.set(t,{channel:c,consumerTag:l})):this.#t.error(`rabbit: failed to consume from queue ${t}`)})}async consumeFromExchange(t,n,r,i){let a={...N,...i};e.validateName(`exchange`,n),e.validateName(`queue`,t);let{limit:o}=a,s=async()=>{i?.isQuorumQueue!==!1&&Y!==`true`&&(await this.saveConsumer(t,r,i),await(0,m.backOff)(()=>this.assertVHost(),G()),await(await this.getNewChannel({name:`consume-from-exchange:${this.identifier}:${n}:${t}:quorum`,connection:this.consumeConnection})).addSetup(async e=>{let a=await V(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)])})),await 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 V(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(t,n,r,i=!0){if(await(0,l.setImmediate)(),i&&X!==`true`){await this.assertVHost(),e.validateName(`exchange`,t);let i=await this.assertChannel({connection:this.publishConnection});await this.assertExchange(t,this.publishConnection),await i.publish(t,``,Buffer.from(JSON.stringify(n)),e.getPublishOptions(r));return}e.validateName(`exchange`,t);let a=await this.assertChannelOld({connection:this.oldPublishConnection});await this.assertExchangeOld(t,this.oldPublishConnection),await a.publish(t,``,Buffer.from(JSON.stringify(n)),e.getPublishOptions(r))}async sendToQueue(t,n,r,i,a=!0){if(a&&X!==`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(Y!==`true`||X!==`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,r){let i={...N,...r};e.validateName(`queue`,t);let a=(0,_.randomUUID)(),{limit:o,deadMessageTtl:s,useConsumeWithLock:c,lockTimeout:l,auditContext:d,enableRabbitTrace:f,callNackOnAbort:p}=i;if(c){if(!this.redisLock)throw new x(`Usage of consumeWithLock requires RedisInstance`);this.#t.info(`rabbit: Consuming with lock from queue ${t} with lockTimeout: ${l}ms`)}return(await this.getNewChannelOld({connection:this.oldConsumeConnection,name:`consume:${this.identifier}:${t}`})).addSetup(async r=>{await this.assertQueueOld(t,i),await r.prefetch(o,!1);let{consumerTag:c}=await r.consume(t,async o=>o?(0,h.runWithLoggerContext)(async()=>{let c=Date.now(),l=()=>Date.now()-c,{[D]:m,[O]:h,[k]:_,[g.CONTEXTS_IDS_HEADER]:v}=o.properties.headers??{};this.#t.addToContext({userId:h});let y=e.parseMsg(o),b=await this.lockRedisIfNeeded(y,i),x=(0,g.newTrace)(g.traceTypes.RABBIT);if(h&&f)try{await(0,g.createOrSetRabbitTrace)(x,h,v)}catch(e){return this.#t.error(`rabbit: failed to setRabbitTrace`,{userId:h,e}),this.nack(r,t,i,{messageTtl:s},o,b)(o)}if(m&&x.context?.set(D,m),d&&await d(t,{userId:h,automationId:_}),!await this.shouldConsumeMessageByTimestamp(y))return await this.unlockRedisIfNeeded(b),this.ack(r,o)(o);let S=!1,C=async()=>{S||(S=!0,await this.ack(r,o,!0,b)(o))},w=async(e,n={})=>{if(S)return;this.#t.debug(`rabbit localNack`,{messageAcked:S,uniqueId:a,deliveryTag:o.fields.deliveryTag}),S=!0;let c=l();await this.nack(r,t,i,{messageTtl:s},o,b)(o,{...n,consumptionDuration:c})};this.activeCallbackCount++;let T=null;try{return p&&(T=(0,u.addAbortListener)(this.shutdownAbortController.signal,()=>{this.#t.info(`rabbit: shutdown signal received, calling localNack for in-flight message`,{uniqueId:a,deliveryTag:o.fields.deliveryTag});let e=w(o,{isAborted:!0});this.#e.add(e),e.finally(()=>{this.#e.delete(e)})})),await n(y,C,w,this.shutdownAbortController.signal)}catch{return await w(o)}finally{this.activeCallbackCount--,T&&T?.[Symbol.dispose]()}}):null,{...R,consumerTag:`${this.identifier}:${t}`});c?(this.#t.info(`rabbit: adding tag ${c} to the array old`),this.oldConsumersTags.set(t,{channel:r,consumerTag:c})):this.#t.error(`rabbit: failed to consume from queue ${t} old`)})}async getNewChannelOld({name:e=H().toString(),onClose:t=null,options:n={},connection:r}){let i;try{i=await this.getConnectionOld(r)}catch(t){throw this.#t.error(`rabbit: error on get connection for new channel ${e} `,{e:t}),t}if(!i)throw Error(`rabbit: couldnt get connection for new channel ${e}`);let a=i?.createChannel({...n,name:e});(0,u.once)(a,`close`).then(n=>{this.#t.error(`rabbit: channel ${e} closed`),t?.(n)});try{return await(0,u.once)(a,`connect`),this.#t.debug(`rabbit: channel ${e} CONNECTED`),a}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:i,blockReconnect:a,connectionRole:o}=e;if(a){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,i].map(e=>(0,u.once)(this.oldEm,e).then(([t])=>[e,t])));if(e===r)return t;throw t}e.creatingConnection=!0;let s=!1,c=()=>{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`]},l=await(0,p.connect)(c(),{findServers:c,connectionOptions:{clientProperties:{connection_name:`${this.identifier}:${o}`}}});e.amqpConnection=l;let{promise:d,reject:f,resolve:m}=U();return l.on(`error`,e=>{this.#t.error(`rabbit: connection error`,{err:e}),s||(s=!0,f(e),this.oldEm.emit(i,e))}),l.on(`connectFailed`,e=>{this.oldConsumersTags.clear(),typeof e.url==`string`&&(e.url=this.maskURL(e.url)),this.#t.error(`rabbit: connection connectFailed`,{err:e}),s||(s=!0,f(e),this.oldEm.emit(i,e))}),l.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}`}`)}),l.once(`connect`,async()=>{this.#t.debug(`rabbit: connection established`),e.creatingConnection=!1,this.oldEm.emit(r,l),s=!0,m(l)}),d}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}=U();this.oldPublishChannelSetupPromise=n;try{let e=await this.getNewChannelOld({connection:t,...t.connectionRole===z.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]=V(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}}},$=Q;exports.default=$,exports.sendCeleryTaskViaHttp=q,exports.t=s;
1
+ Object.defineProperty(exports,`__esModule`,{value:!0});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(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},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`node:process`),l=require(`node:timers/promises`),u=require(`node:events`),d=require(`moment`);d=s(d);let f=require(`redis-lock`);f=s(f);let p=require(`amqp-connection-manager`),m=require(`exponential-backoff`),h=require(`@autofleet/zehut`),g=require(`node:crypto`),_=require(`@autofleet/logger`);_=s(_);let v=require(`redis`);const y=(0,_.default)();var b=y,x=class extends Error{constructor(e){super(e),this.name=`RabbitError`}};const S=e=>(0,v.createClient)({socket:e});var C=S;const w=6e4*60*12,T=1e3*5,E=`x-retry-count`,D=`x-trace-id`,O=`x-af-user-id`,k=`x-af-automation-id`,A=`x-total-processing-duration-ms`,j=`x-redelivered-count`,M=!1,N={limit:1,retries:1,deadMessageTtl:432e5,lockTimeout:T,useConsumeWithLock:!1,auditContext:null,enableRabbitTrace:!1,callNackOnAbort:!1},P={startingDelay:500,timeMultiple:4,numOfAttempts:5},F={startingDelay:1,timeMultiple:1,numOfAttempts:5},I=`ha-promote-on-failure`,L=`ha-promote-on-shutdown`,R={arguments:{"ha-promote-on-failure":`always`,"ha-promote-on-shutdown":`always`}},z={CONSUMER:`consumer`,PUBLISHER:`publisher`},{PROJECT_ID:B}=process.env,V=async(e,t)=>e.assertExchange(t,`fanout`),H=()=>Math.floor(Math.random()*1e5),U=()=>{if(Promise.withResolvers)return Promise.withResolvers();let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},W=()=>[`af-experiment-manager`,`dev1-experiment-manager`].includes(B||``),G=()=>W()?P:F,K={host:process.env.RABBITMQ_SERVICE_HOST||`localhost`,username:process.env.RABBITMQ_USERNAME||`guest`,password:process.env.RABBITMQ_PASSWORD||`guest`};async function q(e,{taskName:t,queueName:n}){let r=`http://${K.host}:15672/api/exchanges/%2f/amq.default/publish`,i={task:t,id:(0,g.randomUUID)(),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(`${K.username}:${K.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 J=1e3*10,{DISABLE_QUORUM_QUEUES_CONSUME:Y,DISABLE_QUORUM_QUEUES_PUBLISH:X,MY_POD_NAME:Z}=c.env,ee=`60`;var Q=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=(0,h.getUser)(),n=h.outbreak.getCurrentContextTraceId();return{timestamp:(0,d.default)().unix(),timeout:1e4,headers:{creationTimestamp:(0,d.default)().valueOf(),...e,...t?.id===void 0?{}:{[O]:t.id},...t?.contextIds===void 0?{}:{[h.CONTEXTS_IDS_HEADER]:t.contextIds},...n===void 0?{}:{[D]:n}}}}#e=new Set;#t;constructor(t={},n){this.options=t,this.redisConfig=n,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:z.PUBLISHER},this.consumeConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`consumeConnectionCreated`,connectionFailedEventName:`consumeConnectionFailed`,blockReconnect:!1,connectionRole:z.CONSUMER},this.em=new u.EventEmitter,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:z.PUBLISHER},this.oldConsumeConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`oldConsumeConnectionCreated`,connectionFailedEventName:`oldConsumeConnectionFailed`,blockReconnect:!1,connectionRole:z.CONSUMER},this.oldEm=new u.EventEmitter,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}),await 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,[E]:u?f:f+1,[A]:h,[j]:u?m+1:m},r.isQuorumQueue),this.#t.debug(`rabbit nacking message`,{deliveryTag:a.fields.deliveryTag}),await 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||Z||(0,g.randomUUID)();let{redisClient:r,redisLock:i}=this.#n(t,n);this.redisClient=r,this.redisLock=i,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=C(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:(0,f.default)(n)})}getRedisKey(e){return`${this.redisConfig?.prefix||``}${e}`}getRetriesCount(e){let t=e.properties.headers?.[E];return Number.parseInt(t||`0`,10)||0}getRedeliveredCount(e){let t=e.properties.headers?.[j];return Number.parseInt(t||`0`,10)||0}getTotalConsumptionDuration(e){let t=e.properties.headers?.[A];return t?Number.parseInt(t,10):0}async getConnection(e){let{amqpConnection:t,creatingConnection:n,connectionCreatedEventName:r,connectionFailedEventName:i,blockReconnect:a,connectionRole:o}=e;if(a){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,i].map(e=>(0,u.once)(this.em,e).then(([t])=>[e,t])));if(e===r)return t;throw t}e.creatingConnection=!0;let s=!1,c=()=>{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`]},l=(0,p.connect)(c(),{findServers:c,connectionOptions:{clientProperties:{connection_name:`${this.identifier}:quorum:${o}`}}});e.amqpConnection=l;let{promise:d,reject:f,resolve:m}=U();return l.on(`error`,e=>{this.#t.error(`rabbit: connection error`,{err:e}),s||(s=!0,f(e),this.em.emit(i,e))}),l.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}),s||(s=!0,f(e),this.em.emit(i,e))}),l.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}`}`)}),l.once(`connect`,async()=>{this.#t.debug(`rabbit: connection established`),e.creatingConnection=!1,this.em.emit(r,l),s=!0,m(l)}),d}async getNewChannel({name:e=H().toString(),onClose:t=null,options:n={},connection:r}){let i;try{i=await this.getConnection(r)}catch(t){throw this.#t.error(`rabbit: error on get connection for new channel ${e} `,{e:t}),t}let a=i?.createChannel({...n,name:e});(0,u.once)(a,`close`).then(n=>{this.#t.error(`rabbit: channel ${e} closed`),t?.(n)});try{return await(0,u.once)(a,`connect`),this.#t.debug(`rabbit: channel ${e} CONNECTED`),a}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}=U();this.publishChannelSetupPromise=n;try{let e=await this.getNewChannel({connection:t,...t.connectionRole===z.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]=V(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&&Y!==`true`&&(this.saveConsumer(e,t,n),await(0,m.backOff)(()=>this.assertVHost(),G()),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||T)),i}async unlockRedisIfNeeded(e){this.redisLock&&e&&await e()}async consumeFromRabbit(t,n,r){let i={...N,...r};e.validateName(`queue`,t);let a=(0,g.randomUUID)(),{limit:o,deadMessageTtl:s,useConsumeWithLock:c,lockTimeout:l,auditContext:d,enableRabbitTrace:f}=i;if(c){if(!this.redisLock)throw new x(`Usage of consumeWithLock requires RedisInstance`);this.#t.info(`rabbit: Consuming with lock from queue ${t} with lockTimeout: ${l}ms`)}return(await this.getNewChannel({connection:this.consumeConnection,name:`consume:${this.identifier}:${t}:quorum`})).addSetup(async c=>{await this.assertQueue(t,i),await c.prefetch(o,!1);let{consumerTag:l}=await c.consume(t,async o=>{if(!o)return null;let l=Date.now(),p=()=>Date.now()-l,{[D]:m,[O]:g,[k]:_,[h.CONTEXTS_IDS_HEADER]:v}=o.properties.headers??{},y=e.parseMsg(o),b=await this.lockRedisIfNeeded(y,i),x=(0,h.newTrace)(h.traceTypes.RABBIT);if(g&&f)try{await(0,h.createOrSetRabbitTrace)(x,g,v)}catch(e){return this.#t.error(`rabbit: failed to setRabbitTrace`,{userId:g,e}),this.nack(c,t,i,{messageTtl:s},o,b)(o)}if(m&&x.context?.set(D,m),d&&await d(t,{userId:g,automationId:_}),!await this.shouldConsumeMessageByTimestamp(y))return await this.unlockRedisIfNeeded(b),this.ack(c,o)(o);let S=!1,C=async()=>{S||(S=!0,await this.ack(c,o,!0,b)(o))},w=async(e,n={})=>{if(S)return;this.#t.debug(`rabbit localNack`,{messageAcked:S,uniqueId:a,deliveryTag:o.fields.deliveryTag}),S=!0;let r=p();await this.nack(c,t,i,{messageTtl:s},o,b)(o,{...n,consumptionDuration:r})};this.activeCallbackCount++;let T=null;try{return r?.callNackOnAbort&&(T=(0,u.addAbortListener)(this.shutdownAbortController.signal,()=>{this.#t.warn(`rabbit: callback aborted`,{uniqueId:a,deliveryTag:o.fields.deliveryTag});let e=w(o,{isAborted:!0});this.#e.add(e),e.finally(()=>{this.#e.delete(e)})})),await n(y,C,w,this.shutdownAbortController.signal)}catch{return await w(o)}finally{this.activeCallbackCount--,T&&T[Symbol.dispose]()}},{...R,consumerTag:`${this.identifier}:${t}:quorum`});l?(this.#t.info(`rabbit: adding tag ${l} to the array.`),this.consumersTags.set(t,{channel:c,consumerTag:l})):this.#t.error(`rabbit: failed to consume from queue ${t}`)})}async consumeFromExchange(t,n,r,i){let a={...N,...i};e.validateName(`exchange`,n),e.validateName(`queue`,t);let{limit:o}=a,s=async()=>{i?.isQuorumQueue!==!1&&Y!==`true`&&(await this.saveConsumer(t,r,i),await(0,m.backOff)(()=>this.assertVHost(),G()),await(await this.getNewChannel({name:`consume-from-exchange:${this.identifier}:${n}:${t}:quorum`,connection:this.consumeConnection})).addSetup(async e=>{let a=await V(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)])})),await 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 V(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(t,n,r,i=!0){if(await(0,l.setImmediate)(),i&&X!==`true`){await this.assertVHost(),e.validateName(`exchange`,t);let i=await this.assertChannel({connection:this.publishConnection});await this.assertExchange(t,this.publishConnection),await i.publish(t,``,Buffer.from(JSON.stringify(n)),e.getPublishOptions(r));return}e.validateName(`exchange`,t);let a=await this.assertChannelOld({connection:this.oldPublishConnection});await this.assertExchangeOld(t,this.oldPublishConnection),await a.publish(t,``,Buffer.from(JSON.stringify(n)),e.getPublishOptions(r))}async sendToQueue(t,n,r,i,a=!0){if(a&&X!==`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(Y!==`true`||X!==`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,r){let i={...N,...r};e.validateName(`queue`,t);let a=(0,g.randomUUID)(),{limit:o,deadMessageTtl:s,useConsumeWithLock:c,lockTimeout:l,auditContext:d,enableRabbitTrace:f,callNackOnAbort:p}=i;if(c){if(!this.redisLock)throw new x(`Usage of consumeWithLock requires RedisInstance`);this.#t.info(`rabbit: Consuming with lock from queue ${t} with lockTimeout: ${l}ms`)}return(await this.getNewChannelOld({connection:this.oldConsumeConnection,name:`consume:${this.identifier}:${t}`})).addSetup(async r=>{await this.assertQueueOld(t,i),await r.prefetch(o,!1);let{consumerTag:c}=await r.consume(t,async o=>{if(!o)return null;let c=Date.now(),l=()=>Date.now()-c,{[D]:m,[O]:g,[k]:_,[h.CONTEXTS_IDS_HEADER]:v}=o.properties.headers??{},y=e.parseMsg(o),b=await this.lockRedisIfNeeded(y,i),x=(0,h.newTrace)(h.traceTypes.RABBIT);if(g&&f)try{await(0,h.createOrSetRabbitTrace)(x,g,v)}catch(e){return this.#t.error(`rabbit: failed to setRabbitTrace`,{userId:g,e}),this.nack(r,t,i,{messageTtl:s},o,b)(o)}if(m&&x.context?.set(D,m),d&&await d(t,{userId:g,automationId:_}),!await this.shouldConsumeMessageByTimestamp(y))return await this.unlockRedisIfNeeded(b),this.ack(r,o)(o);let S=!1,C=async()=>{S||(S=!0,await this.ack(r,o,!0,b)(o))},w=async(e,n={})=>{if(S)return;this.#t.debug(`rabbit localNack`,{messageAcked:S,uniqueId:a,deliveryTag:o.fields.deliveryTag}),S=!0;let c=l();await this.nack(r,t,i,{messageTtl:s},o,b)(o,{...n,consumptionDuration:c})};this.activeCallbackCount++;let T=null;try{return p&&(T=(0,u.addAbortListener)(this.shutdownAbortController.signal,()=>{this.#t.info(`rabbit: shutdown signal received, calling localNack for in-flight message`,{uniqueId:a,deliveryTag:o.fields.deliveryTag});let e=w(o,{isAborted:!0});this.#e.add(e),e.finally(()=>{this.#e.delete(e)})})),await n(y,C,w,this.shutdownAbortController.signal)}catch{return await w(o)}finally{this.activeCallbackCount--,T&&T?.[Symbol.dispose]()}},{...R,consumerTag:`${this.identifier}:${t}`});c?(this.#t.info(`rabbit: adding tag ${c} to the array old`),this.oldConsumersTags.set(t,{channel:r,consumerTag:c})):this.#t.error(`rabbit: failed to consume from queue ${t} old`)})}async getNewChannelOld({name:e=H().toString(),onClose:t=null,options:n={},connection:r}){let i;try{i=await this.getConnectionOld(r)}catch(t){throw this.#t.error(`rabbit: error on get connection for new channel ${e} `,{e:t}),t}if(!i)throw Error(`rabbit: couldnt get connection for new channel ${e}`);let a=i?.createChannel({...n,name:e});(0,u.once)(a,`close`).then(n=>{this.#t.error(`rabbit: channel ${e} closed`),t?.(n)});try{return await(0,u.once)(a,`connect`),this.#t.debug(`rabbit: channel ${e} CONNECTED`),a}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:i,blockReconnect:a,connectionRole:o}=e;if(a){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,i].map(e=>(0,u.once)(this.oldEm,e).then(([t])=>[e,t])));if(e===r)return t;throw t}e.creatingConnection=!0;let s=!1,c=()=>{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`]},l=await(0,p.connect)(c(),{findServers:c,connectionOptions:{clientProperties:{connection_name:`${this.identifier}:${o}`}}});e.amqpConnection=l;let{promise:d,reject:f,resolve:m}=U();return l.on(`error`,e=>{this.#t.error(`rabbit: connection error`,{err:e}),s||(s=!0,f(e),this.oldEm.emit(i,e))}),l.on(`connectFailed`,e=>{this.oldConsumersTags.clear(),typeof e.url==`string`&&(e.url=this.maskURL(e.url)),this.#t.error(`rabbit: connection connectFailed`,{err:e}),s||(s=!0,f(e),this.oldEm.emit(i,e))}),l.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}`}`)}),l.once(`connect`,async()=>{this.#t.debug(`rabbit: connection established`),e.creatingConnection=!1,this.oldEm.emit(r,l),s=!0,m(l)}),d}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}=U();this.oldPublishChannelSetupPromise=n;try{let e=await this.getNewChannelOld({connection:t,...t.connectionRole===z.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]=V(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}}},$=Q;exports.default=$,exports.sendCeleryTaskViaHttp=q,exports.t=s;
2
2
  //# sourceMappingURL=index.cjs.map