@autofleet/rabbit 5.2.1 → 5.3.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.
@@ -33,6 +33,7 @@ interface ConsumeOptions {
33
33
  auditContext?: any;
34
34
  enableRabbitTrace?: boolean;
35
35
  isQuorumQueue?: boolean;
36
+ callNackOnAbort?: boolean;
36
37
  }
37
38
  interface NackOptions {
38
39
  skipRetry?: boolean;
@@ -71,6 +72,10 @@ interface IAfRabbitMq {
71
72
  consumeFromExchange(queue: string, exchange: string, callback: CallbackFunction, options?: ConsumeOptions): Promise<void>;
72
73
  publish(exchange: string, content: any, customHeaders?: PublishOptions["headers"]): Promise<void>;
73
74
  sendToQueue(queue: string, content: any, options?: Options.AssertQueue | null, customHeaders?: PublishOptions["headers"]): Promise<boolean | undefined>;
75
+ getRetriesCount(msg: ConsumeMessage): number;
76
+ getTotalConsumptionDuration(msg: ConsumeMessage): number;
77
+ stopAcceptingWork(): Promise<void>;
78
+ drain(timeoutMs?: number, throwOnTimeout?: boolean): Promise<void>;
74
79
  redisClient?: ReturnType<typeof getRedisInstance>;
75
80
  }
76
81
  interface AfRabbitOptions {
@@ -88,6 +93,7 @@ interface AfRabbitOptions {
88
93
  rabbitHost?: string;
89
94
  vhost?: string;
90
95
  logger?: LoggerInstanceManager;
96
+ closeConnectionOnGracefulShutdown?: boolean;
91
97
  }
92
98
  interface newChannelOpts {
93
99
  name?: string;
@@ -129,6 +135,8 @@ declare class RabbitMq implements IAfRabbitMq {
129
135
  private doesVHostExist;
130
136
  private readonly vhost;
131
137
  private gracefulShutdownStarted;
138
+ /** Count of active callbacks (more memory efficient than storing promises) */
139
+ private activeCallbackCount;
132
140
  shutdownAbortController: AbortController;
133
141
  oldPublishChannel: ChannelWrapper | null;
134
142
  oldPublishChannelSetupPromise: Promise<ChannelWrapper> | null;
@@ -148,10 +156,18 @@ declare class RabbitMq implements IAfRabbitMq {
148
156
  private getRedisKey;
149
157
  private assertVHost;
150
158
  private shouldConsumeMessageByTimestamp;
159
+ getRetriesCount(msg: ConsumeMessage): number;
160
+ getRedeliveredCount(msg: ConsumeMessage): number;
161
+ getTotalConsumptionDuration(msg: ConsumeMessage): number;
151
162
  ack: (channel: ConfirmChannel, msg: ConsumeMessageOrNull, shouldUpdateRedisTimestamp?: boolean, releaseLock?: (() => Promise<void>) | null) => (userMsg: ConsumeMessage) => Promise<void>;
152
163
  nack: (channel: ConfirmChannel, queue: string, options: ConsumeOptions, deadQueueOptions: Options.AssertQueue, msg: ConsumeMessageOrNull, releaseLock?: (() => Promise<void>) | null) => (userMsg: ConsumeMessageOrNull, {
153
- skipRetry
154
- }?: NackOptions) => Promise<void>;
164
+ skipRetry,
165
+ consumptionDuration,
166
+ isAborted
167
+ }?: NackOptions & {
168
+ isAborted?: boolean;
169
+ consumptionDuration?: number;
170
+ }) => Promise<void>;
155
171
  getConnection(connection: ConnectionData): Promise<AmqpConnectionManager>;
156
172
  getNewChannel({
157
173
  name,
@@ -181,6 +197,17 @@ declare class RabbitMq implements IAfRabbitMq {
181
197
  publish(exchange: string, content: any, customHeaders?: PublishOptions["headers"], isQuorumQueue?: boolean): Promise<void>;
182
198
  sendToQueue(queue: string, content: any, options?: Options.AssertQueue, customHeaders?: PublishOptions["headers"], isQuorumQueue?: boolean): Promise<boolean | undefined>;
183
199
  isConnected(): Promise<boolean>;
200
+ stopAcceptingWork(): Promise<void>;
201
+ /**
202
+ * Waits for all in-flight consumer callbacks to complete.
203
+ *
204
+ * @param timeoutMs - Maximum time to wait in milliseconds (default: 10000 = 10s)
205
+ * @param throwOnTimeout - Whether to throw error on timeout (default: true)
206
+ * @returns Promise that resolves when all callbacks complete or timeout occurs
207
+ * @throws Error if timeout occurs and throwOnTimeout is true
208
+ */
209
+ drain(timeoutMs?: number, throwOnTimeout?: boolean): Promise<void>;
210
+ closeConnections(): Promise<void>;
184
211
  gracefulShutdown(signal: string): Promise<void>;
185
212
  private consumeFromRabbitOld;
186
213
  getNewChannelOld({
@@ -205,4 +232,4 @@ declare class RabbitMq implements IAfRabbitMq {
205
232
  type ConsumerCallbackFunction = CallbackFunction;
206
233
  //#endregion
207
234
  export { sendCeleryTaskViaHttp as a, RabbitMq as i, ConsumerCallbackFunction as n, IAfRabbitMq as r, AfRabbitOptions as t };
208
- //# sourceMappingURL=index-DG_7Rl-n.d.ts.map
235
+ //# sourceMappingURL=index-ezrXlCuE.d.ts.map
@@ -33,6 +33,7 @@ interface ConsumeOptions {
33
33
  auditContext?: any;
34
34
  enableRabbitTrace?: boolean;
35
35
  isQuorumQueue?: boolean;
36
+ callNackOnAbort?: boolean;
36
37
  }
37
38
  interface NackOptions {
38
39
  skipRetry?: boolean;
@@ -71,6 +72,10 @@ interface IAfRabbitMq {
71
72
  consumeFromExchange(queue: string, exchange: string, callback: CallbackFunction, options?: ConsumeOptions): Promise<void>;
72
73
  publish(exchange: string, content: any, customHeaders?: PublishOptions["headers"]): Promise<void>;
73
74
  sendToQueue(queue: string, content: any, options?: Options.AssertQueue | null, customHeaders?: PublishOptions["headers"]): Promise<boolean | undefined>;
75
+ getRetriesCount(msg: ConsumeMessage): number;
76
+ getTotalConsumptionDuration(msg: ConsumeMessage): number;
77
+ stopAcceptingWork(): Promise<void>;
78
+ drain(timeoutMs?: number, throwOnTimeout?: boolean): Promise<void>;
74
79
  redisClient?: ReturnType<typeof getRedisInstance>;
75
80
  }
76
81
  interface AfRabbitOptions {
@@ -88,6 +93,7 @@ interface AfRabbitOptions {
88
93
  rabbitHost?: string;
89
94
  vhost?: string;
90
95
  logger?: LoggerInstanceManager;
96
+ closeConnectionOnGracefulShutdown?: boolean;
91
97
  }
92
98
  interface newChannelOpts {
93
99
  name?: string;
@@ -129,6 +135,8 @@ declare class RabbitMq implements IAfRabbitMq {
129
135
  private doesVHostExist;
130
136
  private readonly vhost;
131
137
  private gracefulShutdownStarted;
138
+ /** Count of active callbacks (more memory efficient than storing promises) */
139
+ private activeCallbackCount;
132
140
  shutdownAbortController: AbortController;
133
141
  oldPublishChannel: ChannelWrapper | null;
134
142
  oldPublishChannelSetupPromise: Promise<ChannelWrapper> | null;
@@ -148,10 +156,18 @@ declare class RabbitMq implements IAfRabbitMq {
148
156
  private getRedisKey;
149
157
  private assertVHost;
150
158
  private shouldConsumeMessageByTimestamp;
159
+ getRetriesCount(msg: ConsumeMessage): number;
160
+ getRedeliveredCount(msg: ConsumeMessage): number;
161
+ getTotalConsumptionDuration(msg: ConsumeMessage): number;
151
162
  ack: (channel: ConfirmChannel, msg: ConsumeMessageOrNull, shouldUpdateRedisTimestamp?: boolean, releaseLock?: (() => Promise<void>) | null) => (userMsg: ConsumeMessage) => Promise<void>;
152
163
  nack: (channel: ConfirmChannel, queue: string, options: ConsumeOptions, deadQueueOptions: Options.AssertQueue, msg: ConsumeMessageOrNull, releaseLock?: (() => Promise<void>) | null) => (userMsg: ConsumeMessageOrNull, {
153
- skipRetry
154
- }?: NackOptions) => Promise<void>;
164
+ skipRetry,
165
+ consumptionDuration,
166
+ isAborted
167
+ }?: NackOptions & {
168
+ isAborted?: boolean;
169
+ consumptionDuration?: number;
170
+ }) => Promise<void>;
155
171
  getConnection(connection: ConnectionData): Promise<AmqpConnectionManager>;
156
172
  getNewChannel({
157
173
  name,
@@ -181,6 +197,17 @@ declare class RabbitMq implements IAfRabbitMq {
181
197
  publish(exchange: string, content: any, customHeaders?: PublishOptions["headers"], isQuorumQueue?: boolean): Promise<void>;
182
198
  sendToQueue(queue: string, content: any, options?: Options.AssertQueue, customHeaders?: PublishOptions["headers"], isQuorumQueue?: boolean): Promise<boolean | undefined>;
183
199
  isConnected(): Promise<boolean>;
200
+ stopAcceptingWork(): Promise<void>;
201
+ /**
202
+ * Waits for all in-flight consumer callbacks to complete.
203
+ *
204
+ * @param timeoutMs - Maximum time to wait in milliseconds (default: 10000 = 10s)
205
+ * @param throwOnTimeout - Whether to throw error on timeout (default: true)
206
+ * @returns Promise that resolves when all callbacks complete or timeout occurs
207
+ * @throws Error if timeout occurs and throwOnTimeout is true
208
+ */
209
+ drain(timeoutMs?: number, throwOnTimeout?: boolean): Promise<void>;
210
+ closeConnections(): Promise<void>;
184
211
  gracefulShutdown(signal: string): Promise<void>;
185
212
  private consumeFromRabbitOld;
186
213
  getNewChannelOld({
@@ -205,4 +232,4 @@ declare class RabbitMq implements IAfRabbitMq {
205
232
  type ConsumerCallbackFunction = CallbackFunction;
206
233
  //#endregion
207
234
  export { sendCeleryTaskViaHttp as a, RabbitMq as i, ConsumerCallbackFunction as n, IAfRabbitMq as r, AfRabbitOptions as t };
208
- //# sourceMappingURL=index-DYLqlA6K.d.cts.map
235
+ //# sourceMappingURL=index-fdDN8Zdi.d.cts.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/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=!1,j={limit:1,retries:1,deadMessageTtl:432e5,lockTimeout:T,useConsumeWithLock:!1,auditContext:null,enableRabbitTrace:!1},M={startingDelay:500,timeMultiple:4,numOfAttempts:5},N={startingDelay:1,timeMultiple:1,numOfAttempts:5},{PROJECT_ID:P}=process.env,F=async(e,t)=>e.assertExchange(t,`fanout`),I=()=>Math.floor(Math.random()*1e5),L=()=>{if(Promise.withResolvers)return Promise.withResolvers();let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},R=()=>[`af-experiment-manager`,`dev1-experiment-manager`].includes(P||``),z=()=>R()?M:N,B=`ha-promote-on-failure`,V=`ha-promote-on-shutdown`,H={arguments:{"ha-promote-on-failure":`always`,"ha-promote-on-shutdown":`always`}},U={host:process.env.RABBITMQ_SERVICE_HOST||`localhost`,username:process.env.RABBITMQ_USERNAME||`guest`,password:process.env.RABBITMQ_PASSWORD||`guest`};async function W(e,{taskName:t,queueName:n}){let r=`http://${U.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(`${U.username}:${U.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 G=1e3*10,{DISABLE_QUORUM_QUEUES_CONSUME:K,DISABLE_QUORUM_QUEUES_PUBLISH:q}=c.env,J=`60`;var Y=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,[O]:t?.id,[h.CONTEXTS_IDS_HEADER]:t?.contextIds,[D]:n}}}#e;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},this.consumeConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`consumeConnectionCreated`,connectionFailedEventName:`consumeConnectionFailed`,blockReconnect:!1},this.em=new u.EventEmitter,this.exchanges={},this.queues={},this.queueSetupPromises={},this.assertExchangePromises={},this.consumersTags=new Map,this.consumersToRegister=[],this.doesVHostExist=!1,this.vhost=`quorum-vhost`,this.gracefulShutdownStarted=!1,this.shutdownAbortController=new AbortController,this.oldPublishChannel=null,this.oldPublishChannelSetupPromise=null,this.oldPublishConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`oldPublishConnectionCreated`,connectionFailedEventName:`oldPublishConnectionFailed`,blockReconnect:!1},this.oldConsumeConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`oldConsumeConnectionCreated`,connectionFailedEventName:`oldConsumeConnectionFailed`,blockReconnect:!1},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.#e.info(`Vhost exists`,{vhost:this.vhost});return}if(e.status!==404)throw this.#e.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.#e.error(`Failed to create vhost`,{response:t}),new x(`Failed to create vhost`);this.doesVHostExist=!0,this.#e.info(`Vhost created`,{vhost:this.vhost})}catch(e){throw this.#e.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.#e.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}={})=>{if(await this.unlockRedisIfNeeded(o),!t||!a){this.#e.error(`no channel or msg`,{msg:a});return}let l=Number.parseInt(a.properties.headers?.[E]||`0`,10)||0,u=c||l>=r.retries;await this.sendToQueue(`${n}${u?`-dead`:``}`,e.parseMsg(a).content,u?i:r,{...a.properties.headers,[E]:l+1}),this.#e.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.#e=t?.logger??b,n&&(this.redisClient=C(n).on(`error`,e=>{this.#e.error(`rabbit: Redis error`,{err:e,redisConfig:n})}),this.redisClient.connect().catch(e=>{this.#e.error(`rabbit: Failed to connect to Redis`,{err:e,redisConfig:n})}),this.redisLock=(0,f.default)(this.redisClient)),this.#e.info(`rabbit: [gracefully-shutdown] adding gracefully shutdown for process.pid ${process.pid}`),this.options?.dontGracefulShutdown||(process.on(`SIGTERM`,async()=>{await this.gracefulShutdown(`SIGTERM`)}),process.on(`SIGINT`,async()=>{await this.gracefulShutdown(`SIGINT`)}))}getRedisKey(e){return`${this.redisConfig?.prefix||``}${e}`}async getConnection(e){let{amqpConnection:t,creatingConnection:n,connectionCreatedEventName:r,connectionFailedEventName:i,blockReconnect:a}=e;if(a){this.#e.debug(`rabbit: block reconnect`);return}if(t!==null){if(this.options?.disableReconnect||t?.isConnected())return this.#e.debug(`rabbit: connection - is connected`),t;this.#e.debug(`rabbit: connection - reconnecting`)}if(n){this.#e.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 o=!1,s=()=>{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.#e.debug(`rabbit: creating connection`,{host:n,userName:e,HEARTBEAT:`60`}),[`amqp://${e}:${t}@${n}/${this.vhost}?heartbeat=60`]},c=(0,p.connect)(s(),{findServers:s});e.amqpConnection=c;let{promise:l,reject:d,resolve:f}=L();return c.on(`error`,e=>{this.#e.error(`rabbit: connection error`,{err:e}),o||(o=!0,d(e),this.em.emit(i,e))}),c.on(`connectFailed`,e=>{this.consumersTags.clear(),typeof e.url==`string`&&(e.url=this.maskURL(e.url)),this.#e.error(`rabbit: connection connectFailed`,{err:e,advice:`Check if the vhost exist`,vhost:this.vhost}),o||(o=!0,d(e),this.em.emit(i,e))}),c.on(`disconnect`,({err:t})=>{this.consumersTags.clear(),this.#e.debug(`rabbit: connection closed`),this.options?.disableReconnect?(this.#e.error(`${this.DISCONNECT_MSG}${t&&` - ${t}`}`),e.blockReconnect=!0):this.#e.error(`${this.RECONNECT_MSG}${t&&` - ${t}`}`)}),c.once(`connect`,async()=>{this.#e.debug(`rabbit: connection established`),e.creatingConnection=!1,this.em.emit(r,c),o=!0,f(c)}),l}async getNewChannel({name:e=I().toString(),onClose:t=null,options:n={},connection:r}){let i;try{i=await this.getConnection(r)}catch(t){throw this.#e.error(`rabbit: error on get connection for new channel ${e} `,{e:t}),t}let a=i?.createChannel({...n});(0,u.once)(a,`close`).then(n=>{this.#e.error(`rabbit: channel ${e} closed`),t?.(n)});try{return await(0,u.once)(a,`connect`),this.#e.debug(`rabbit: channel ${e} CONNECTED`),a}catch(t){throw this.#e.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}=L();this.publishChannelSetupPromise=n;try{let e=await this.getNewChannel({connection:t});e.on(`error`,e=>{this.#e.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]=F(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.#e.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.#e.info(`rabbit: deleting queue`,{queue:t});let i=await r.deleteQueue(t);return this.#e.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.#e.debug(`assertQueue->channel.addSetup`,{queueName:e}),await t.addSetup(async t=>{await t.assertQueue(e,i)}),this.#e.debug(`assertQueue->channel.assertQueue`,{queueName:e}),n=await t.assertQueue(e,i)}catch(a){if(this.#e.error(`rabbit: assertQueue error`,{queueName:e,options:t,error:a}),this.options?.dontRetryAssert)throw a;{this.#e.debug(`retrying assertQueue`,{queueName:e});let t=await this.assertChannel({force:!0,connection:r});await this.deleteQueue(e,r),this.#e.debug(`retrying assertQueue->channel.addSetup`,{queueName:e}),await t.addSetup(t=>t.assertQueue(e,i)),this.#e.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.#e.info(`rabbit: consumer: ${e} saved in consumer array`),this.consumersToRegister.push({queue:e,callback:t,options:n}))}async consume(e,t,n){this.saveConsumerOld(e,t,n),n?.isQuorumQueue!==!1&&K!==`true`&&(this.saveConsumer(e,t,n),await(0,m.backOff)(()=>this.assertVHost(),z()),await this.consumeNew(e,t,n)),await this.consumeOld(e,t,n)}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={...j,...r};e.validateName(`queue`,t);let a=(0,g.randomUUID)(),{limit:o,deadMessageTtl:s,useConsumeWithLock:c,lockTimeout:l,auditContext:u,enableRabbitTrace:d}=i;if(c){if(!this.redisLock)throw new x(`Usage of consumeWithLock requires RedisInstance`);this.#e.info(`rabbit: Consuming with lock from queue ${t} with lockTimeout: ${l}ms`)}return(await this.getNewChannel({connection:this.consumeConnection})).addSetup(async r=>{await this.assertQueue(t,i),await r.prefetch(o,!1);let{consumerTag:c}=await r.consume(t,async o=>{if(!o)return null;let{[D]:c,[O]:l,[k]:f,[h.CONTEXTS_IDS_HEADER]:p}=o.properties.headers??{},m=e.parseMsg(o),g=await this.lockRedisIfNeeded(m,i),_=(0,h.newTrace)(h.traceTypes.RABBIT);if(l&&d)try{await(0,h.createOrSetRabbitTrace)(_,l,p)}catch(e){return this.#e.error(`rabbit: failed to setRabbitTrace`,{userId:l,e}),this.nack(r,t,i,{messageTtl:s},o,g)(o)}if(c&&_.context?.set(D,c),u&&await u(t,{userId:l,automationId:f}),!await this.shouldConsumeMessageByTimestamp(m))return await this.unlockRedisIfNeeded(g),this.ack(r,o)(o);let v=!1,y=async()=>{v||(v=!0,await this.ack(r,o,!0,g)(o))},b=async(e,n={})=>{v||(this.#e.debug(`rabbit localNack`,{messageAcked:v,uniqueId:a,deliveryTag:o.fields.deliveryTag}),v=!0,await this.nack(r,t,i,{messageTtl:s},o,g)(o,n))};try{return await n(m,y,b,this.shutdownAbortController.signal)}catch{return b(o)}},H);c?(this.#e.info(`rabbit: adding tag ${c} to the array.`),this.consumersTags.set(t,{channel:r,consumerTag:c})):this.#e.error(`rabbit: failed to consume from queue ${t}`)})}async consumeFromExchange(t,n,r,i){let a={...j,...i};e.validateName(`exchange`,n),e.validateName(`queue`,t);let{limit:o}=a;i?.isQuorumQueue!==!1&&K!==`true`&&(await this.saveConsumer(t,r,i),await(0,m.backOff)(()=>this.assertVHost(),z()),await(await this.getNewChannel({name:`consume-exchange-${n}-queue-${t}`,connection:this.consumeConnection})).addSetup(async e=>{let a=await F(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-exchange-${n}-queue-${t}-old`,connection:this.oldConsumeConnection})).addSetup(async e=>{let a=await F(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)])})}async publish(t,n,r,i=!0){if(await(0,l.setImmediate)(),i&&q!==`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&&q!==`true`){try{await this.assertVHost(),await this.assertChannel({connection:this.publishConnection})}catch(e){throw this.#e.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.#e.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.#e.debug(`rabbit: sending to queue ${t}`,{res:r}),r}catch(e){let n=await this.isConnected();throw this.#e.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.#e.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.#e.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.#e.debug(`rabbit: sending to queue ${t}`,{res:r}),r}catch(e){let n=await this.isConnectedOld();throw this.#e.error(`rabbit sendToQueue: failed to send to queue ${t}, isConnected: ${n}`,{e}),e}}}async isConnected(){let e=!0;if(!this.gracefulShutdownStarted){if(K!==`true`||q!==`true`){this.#e.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.#e.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.#e.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.#e.error(`rabbit: isConnected - false`,{msg:e.message}),!1}}e=await this.isConnectedOld()}return this.#e.debug(`rabbit: isConnected - ${e}`),e}async gracefulShutdown(e){this.shutdownAbortController.abort(Error(`Graceful shutdown initiated by signal: ${e}`)),this.gracefulShutdownStarted=!0;let t=this.consumersTags.size+this.oldConsumersTags.size;this.#e.info(`rabbit: [gracefully-shutdown] received ${e}! canceling #${t} tags...`);let n=[...this.consumersTags].map(([,{channel:e,consumerTag:t}])=>e.cancel(t)),r=[...this.oldConsumersTags].map(([,{channel:e,consumerTag:t}])=>e.cancel(t));this.consumersTags.clear(),this.oldConsumersTags.clear();let i=(await Promise.allSettled([...n,...r])).filter(e=>e.status===`rejected`);i.length>0?this.#e.warn(`rabbit: [gracefully-shutdown] #${i.length}/${t} tags failed to cancel: ${i}`):this.#e.info(`rabbit: [gracefully-shutdown] all tags successfully canceled.`)}async consumeFromRabbitOld(t,n,r){let i={...j,...r};e.validateName(`queue`,t);let a=(0,g.randomUUID)(),{limit:o,deadMessageTtl:s,useConsumeWithLock:c,lockTimeout:l,auditContext:u,enableRabbitTrace:d}=i;if(c){if(!this.redisLock)throw new x(`Usage of consumeWithLock requires RedisInstance`);this.#e.info(`rabbit: Consuming with lock from queue ${t} with lockTimeout: ${l}ms`)}return(await this.getNewChannelOld({connection:this.oldConsumeConnection})).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{[D]:c,[O]:l,[k]:f,[h.CONTEXTS_IDS_HEADER]:p}=o.properties.headers??{},m=e.parseMsg(o),g=await this.lockRedisIfNeeded(m,i),_=(0,h.newTrace)(h.traceTypes.RABBIT);if(l&&d)try{await(0,h.createOrSetRabbitTrace)(_,l,p)}catch(e){return this.#e.error(`rabbit: failed to setRabbitTrace`,{userId:l,e}),this.nack(r,t,i,{messageTtl:s},o,g)(o)}if(c&&_.context?.set(D,c),u&&await u(t,{userId:l,automationId:f}),!await this.shouldConsumeMessageByTimestamp(m))return await this.unlockRedisIfNeeded(g),this.ack(r,o)(o);let v=!1,y=async()=>{v||(v=!0,await this.ack(r,o,!0,g)(o))},b=async(e,n={})=>{v||(this.#e.debug(`rabbit localNack`,{messageAcked:v,uniqueId:a,deliveryTag:o.fields.deliveryTag}),v=!0,await this.nack(r,t,i,{messageTtl:s},o,g)(o,n))};try{return await n(m,y,b,this.shutdownAbortController.signal)}catch{return b(o)}},H);c?(this.#e.info(`rabbit: adding tag ${c} to the array old`),this.oldConsumersTags.set(t,{channel:r,consumerTag:c})):this.#e.error(`rabbit: failed to consume from queue ${t} old`)})}async getNewChannelOld({name:e=I().toString(),onClose:t=null,options:n={},connection:r}){let i;try{i=await this.getConnectionOld(r)}catch(t){throw this.#e.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});(0,u.once)(a,`close`).then(n=>{this.#e.error(`rabbit: channel ${e} closed`),t?.(n)});try{return await(0,u.once)(a,`connect`),this.#e.debug(`rabbit: channel ${e} CONNECTED`),a}catch(t){throw this.#e.error(`rabbit: channel error ${e} error`,{err:t}),t}}async getConnectionOld(e){let{amqpConnection:t,creatingConnection:n,connectionCreatedEventName:r,connectionFailedEventName:i,blockReconnect:a}=e;if(a){this.#e.debug(`rabbit: block reconnect`);return}if(t!==null){if(this.options?.disableReconnect||t?.isConnected())return this.#e.debug(`rabbit: connection - is connected`),t;this.#e.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 o=!1,s=()=>{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.#e.debug(`rabbit: creating connection`,{host:n,userName:e,HEARTBEAT:`60`}),[`amqp://${e}:${t}@${n}?heartbeat=60`]},c=await(0,p.connect)(s(),{findServers:s});e.amqpConnection=c;let{promise:l,reject:d,resolve:f}=L();return c.on(`error`,e=>{this.#e.error(`rabbit: connection error`,{err:e}),o||(o=!0,d(e),this.oldEm.emit(i,e))}),c.on(`connectFailed`,e=>{this.oldConsumersTags.clear(),typeof e.url==`string`&&(e.url=this.maskURL(e.url)),this.#e.error(`rabbit: connection connectFailed`,{err:e}),o||(o=!0,d(e),this.oldEm.emit(i,e))}),c.on(`disconnect`,({err:t})=>{this.oldConsumersTags.clear(),this.#e.debug(`rabbit: connection closed`),this.options?.disableReconnect?(this.#e.error(`${this.DISCONNECT_MSG}${t&&` - ${t}`}`),e.blockReconnect=!0):this.#e.error(`${this.RECONNECT_MSG}${t&&` - ${t}`}`)}),c.once(`connect`,async()=>{this.#e.debug(`rabbit: connection established`),e.creatingConnection=!1,this.oldEm.emit(r,c),o=!0,f(c)}),l}saveConsumerOld(e,t,n){this.oldConsumersToRegister.some(t=>t.queue===e)||(this.#e.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.#e.debug(`assertQueue->channel.addSetup`,{queueName:t}),await e.addSetup(e=>e.assertQueue(t,o)),this.#e.debug(`assertQueue->channel.assertQueue`,{queueName:t}),r=await e.assertQueue(t,o)}catch(e){if(this.#e.error(`rabbit: assertQueue error`,{queueName:t,options:n,error:e}),this.options?.dontRetryAssert)throw e;{this.#e.debug(`retrying assertQueue`,{queueName:t});let e=await this.assertChannelOld({force:!0,connection:i});await this.deleteQueueOld(t,i),this.#e.debug(`retrying assertQueue->channel.addSetup`,{queueName:t}),await e.addSetup(e=>e.assertQueue(t,o)),this.#e.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}=L();this.oldPublishChannelSetupPromise=n;try{let e=await this.getNewChannelOld({connection:t});e.on(`error`,e=>{this.#e.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.#e.info(`rabbit: deleting queue`,{queue:t});let i=await r.deleteQueue(t);return this.#e.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]=F(n,e),this.oldExchanges[e]=await this.oldAssertExchangePromises[e],this.oldExchanges[e])}async isConnectedOld(){if(this.gracefulShutdownStarted)return!0;this.#e.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.#e.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.#e.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.#e.error(`rabbit: isConnected - false old`,{msg:e.message}),!1}}},X=Y;exports.default=X,exports.sendCeleryTaskViaHttp=W,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},{PROJECT_ID:I}=process.env,L=async(e,t)=>e.assertExchange(t,`fanout`),R=()=>Math.floor(Math.random()*1e5),z=()=>{if(Promise.withResolvers)return Promise.withResolvers();let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},B=()=>[`af-experiment-manager`,`dev1-experiment-manager`].includes(I||``),V=()=>B()?P:F,H=`ha-promote-on-failure`,U=`ha-promote-on-shutdown`,W={arguments:{"ha-promote-on-failure":`always`,"ha-promote-on-shutdown":`always`}},G={host:process.env.RABBITMQ_SERVICE_HOST||`localhost`,username:process.env.RABBITMQ_USERNAME||`guest`,password:process.env.RABBITMQ_PASSWORD||`guest`};async function K(e,{taskName:t,queueName:n}){let r=`http://${G.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(`${G.username}:${G.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 q=1e3*10,{DISABLE_QUORUM_QUEUES_CONSUME:J,DISABLE_QUORUM_QUEUES_PUBLISH:Y}=c.env,X=`60`;var Z=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,[O]:t?.id,[h.CONTEXTS_IDS_HEADER]:t?.contextIds,[D]:n}}}#e;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},this.consumeConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`consumeConnectionCreated`,connectionFailedEventName:`consumeConnectionFailed`,blockReconnect:!1},this.em=new u.EventEmitter,this.exchanges={},this.queues={},this.queueSetupPromises={},this.assertExchangePromises={},this.consumersTags=new Map,this.consumersToRegister=[],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},this.oldConsumeConnection={amqpConnection:null,creatingConnection:!1,connectionCreatedEventName:`oldConsumeConnectionCreated`,connectionFailedEventName:`oldConsumeConnectionFailed`,blockReconnect:!1},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.#e.info(`Vhost exists`,{vhost:this.vhost});return}if(e.status!==404)throw this.#e.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.#e.error(`Failed to create vhost`,{response:t}),new x(`Failed to create vhost`);this.doesVHostExist=!0,this.#e.info(`Vhost created`,{vhost:this.vhost})}catch(e){throw this.#e.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.#e.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.#e.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.#e.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.#e.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.#e=t?.logger??b,n&&(this.redisClient=C(n).on(`error`,e=>{this.#e.error(`rabbit: Redis error`,{err:e,redisConfig:n})}),this.redisClient.connect().catch(e=>{this.#e.error(`rabbit: Failed to connect to Redis`,{err:e,redisConfig:n})}),this.redisLock=(0,f.default)(this.redisClient)),this.#e.info(`rabbit: [gracefully-shutdown] adding gracefully shutdown for process.pid ${process.pid}`),this.options?.dontGracefulShutdown||(process.on(`SIGTERM`,async()=>{await this.gracefulShutdown(`SIGTERM`)}),process.on(`SIGINT`,async()=>{await this.gracefulShutdown(`SIGINT`)}))}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}=e;if(a){this.#e.debug(`rabbit: block reconnect`);return}if(t!==null){if(this.options?.disableReconnect||t?.isConnected())return this.#e.debug(`rabbit: connection - is connected`),t;this.#e.debug(`rabbit: connection - reconnecting`)}if(n){this.#e.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 o=!1,s=()=>{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.#e.debug(`rabbit: creating connection`,{host:n,userName:e,HEARTBEAT:`60`}),[`amqp://${e}:${t}@${n}/${this.vhost}?heartbeat=60`]},c=(0,p.connect)(s(),{findServers:s});e.amqpConnection=c;let{promise:l,reject:d,resolve:f}=z();return c.on(`error`,e=>{this.#e.error(`rabbit: connection error`,{err:e}),o||(o=!0,d(e),this.em.emit(i,e))}),c.on(`connectFailed`,e=>{this.consumersTags.clear(),typeof e.url==`string`&&(e.url=this.maskURL(e.url)),this.#e.error(`rabbit: connection connectFailed`,{err:e,advice:`Check if the vhost exist`,vhost:this.vhost}),o||(o=!0,d(e),this.em.emit(i,e))}),c.on(`disconnect`,({err:t})=>{this.consumersTags.clear(),this.#e.debug(`rabbit: connection closed`),this.options?.disableReconnect?(this.#e.error(`${this.DISCONNECT_MSG}${t&&` - ${t}`}`),e.blockReconnect=!0):this.#e.error(`${this.RECONNECT_MSG}${t&&` - ${t}`}`)}),c.once(`connect`,async()=>{this.#e.debug(`rabbit: connection established`),e.creatingConnection=!1,this.em.emit(r,c),o=!0,f(c)}),l}async getNewChannel({name:e=R().toString(),onClose:t=null,options:n={},connection:r}){let i;try{i=await this.getConnection(r)}catch(t){throw this.#e.error(`rabbit: error on get connection for new channel ${e} `,{e:t}),t}let a=i?.createChannel({...n});(0,u.once)(a,`close`).then(n=>{this.#e.error(`rabbit: channel ${e} closed`),t?.(n)});try{return await(0,u.once)(a,`connect`),this.#e.debug(`rabbit: channel ${e} CONNECTED`),a}catch(t){throw this.#e.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}=z();this.publishChannelSetupPromise=n;try{let e=await this.getNewChannel({connection:t});e.on(`error`,e=>{this.#e.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]=L(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.#e.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.#e.info(`rabbit: deleting queue`,{queue:t});let i=await r.deleteQueue(t);return this.#e.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.#e.debug(`assertQueue->channel.addSetup`,{queueName:e}),await t.addSetup(async t=>{await t.assertQueue(e,i)}),this.#e.debug(`assertQueue->channel.assertQueue`,{queueName:e}),n=await t.assertQueue(e,i)}catch(a){if(this.#e.error(`rabbit: assertQueue error`,{queueName:e,options:t,error:a}),this.options?.dontRetryAssert)throw a;{this.#e.debug(`retrying assertQueue`,{queueName:e});let t=await this.assertChannel({force:!0,connection:r});await this.deleteQueue(e,r),this.#e.debug(`retrying assertQueue->channel.addSetup`,{queueName:e}),await t.addSetup(t=>t.assertQueue(e,i)),this.#e.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.#e.info(`rabbit: consumer: ${e} saved in consumer array`),this.consumersToRegister.push({queue:e,callback:t,options:n}))}async consume(e,t,n){this.saveConsumerOld(e,t,n),n?.isQuorumQueue!==!1&&J!==`true`&&(this.saveConsumer(e,t,n),await(0,m.backOff)(()=>this.assertVHost(),V()),await this.consumeNew(e,t,n)),await this.consumeOld(e,t,n)}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.#e.info(`rabbit: Consuming with lock from queue ${t} with lockTimeout: ${l}ms`)}return(await this.getNewChannel({connection:this.consumeConnection})).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.#e.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.#e.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,async()=>{this.#e.warn(`rabbit: callback aborted`,{uniqueId:a,deliveryTag:o.fields.deliveryTag}),await w(o,{isAborted:!0})})),await n(y,C,w,this.shutdownAbortController.signal)}catch{return w(o)}finally{this.activeCallbackCount--,T&&T[Symbol.dispose]()}},W);l?(this.#e.info(`rabbit: adding tag ${l} to the array.`),this.consumersTags.set(t,{channel:c,consumerTag:l})):this.#e.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;i?.isQuorumQueue!==!1&&J!==`true`&&(await this.saveConsumer(t,r,i),await(0,m.backOff)(()=>this.assertVHost(),V()),await(await this.getNewChannel({name:`consume-exchange-${n}-queue-${t}`,connection:this.consumeConnection})).addSetup(async e=>{let a=await L(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-exchange-${n}-queue-${t}-old`,connection:this.oldConsumeConnection})).addSetup(async e=>{let a=await L(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)])})}async publish(t,n,r,i=!0){if(await(0,l.setImmediate)(),i&&Y!==`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&&Y!==`true`){try{await this.assertVHost(),await this.assertChannel({connection:this.publishConnection})}catch(e){throw this.#e.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.#e.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.#e.debug(`rabbit: sending to queue ${t}`,{res:r}),r}catch(e){let n=await this.isConnected();throw this.#e.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.#e.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.#e.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.#e.debug(`rabbit: sending to queue ${t}`,{res:r}),r}catch(e){let n=await this.isConnectedOld();throw this.#e.error(`rabbit sendToQueue: failed to send to queue ${t}, isConnected: ${n}`,{e}),e}}}async isConnected(){let e=!0;if(!this.gracefulShutdownStarted){if(J!==`true`||Y!==`true`){this.#e.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.#e.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.#e.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.#e.error(`rabbit: isConnected - false`,{msg:e.message}),!1}}e=await this.isConnectedOld()}return this.#e.debug(`rabbit: isConnected - ${e}`),e}async stopAcceptingWork(){this.#e.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.#e.warn(`rabbit: stop accepting work - failed to cancel #${n.length} tags: ${n}`):this.#e.info(`rabbit: stop accepting work - all tags successfully canceled.`)}async drain(e=1e4,t=!0){let n=Date.now(),r=this.activeCallbackCount;if(this.#e.info(`rabbit: [drain] waiting for active callbacks`,{activeCallbackCount:r,timeoutMs:e}),r===0){this.#e.info(`rabbit: [drain] no active callbacks to drain`);return}let i=this.publishChannel?.queueLength()??0;for(i>0&&this.#e.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.#e.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`)),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.#e.info(`rabbit: [drain] all callbacks completed`,{duration:a,callbackCount:r})}async closeConnections(){if(this.activeCallbackCount>0){this.#e.warn(`rabbit: closing connections received with active callbacks. not performing the close`,{activeCallbackCount:this.activeCallbackCount});return}this.#e.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.#e.info(`rabbit: connection closed successfully`)}catch(e){this.#e.error(`rabbit: error closing connection`,{e})}}))}async gracefulShutdown(e){this.gracefulShutdownStarted=!0;let t=this.consumersTags.size+this.oldConsumersTags.size;this.#e.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.#e.info(`rabbit: Consuming with lock from queue ${t} with lockTimeout: ${l}ms`)}return(await this.getNewChannelOld({connection:this.oldConsumeConnection})).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.#e.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.#e.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.#e.info(`rabbit: shutdown signal received, calling localNack for in-flight message`,{uniqueId:a,deliveryTag:o.fields.deliveryTag}),w(o,{isAborted:!0})})),await n(y,C,w,this.shutdownAbortController.signal)}catch{return w(o)}finally{this.activeCallbackCount--,T&&T?.[Symbol.dispose]()}},W);c?(this.#e.info(`rabbit: adding tag ${c} to the array old`),this.oldConsumersTags.set(t,{channel:r,consumerTag:c})):this.#e.error(`rabbit: failed to consume from queue ${t} old`)})}async getNewChannelOld({name:e=R().toString(),onClose:t=null,options:n={},connection:r}){let i;try{i=await this.getConnectionOld(r)}catch(t){throw this.#e.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});(0,u.once)(a,`close`).then(n=>{this.#e.error(`rabbit: channel ${e} closed`),t?.(n)});try{return await(0,u.once)(a,`connect`),this.#e.debug(`rabbit: channel ${e} CONNECTED`),a}catch(t){throw this.#e.error(`rabbit: channel error ${e} error`,{err:t}),t}}async getConnectionOld(e){let{amqpConnection:t,creatingConnection:n,connectionCreatedEventName:r,connectionFailedEventName:i,blockReconnect:a}=e;if(a){this.#e.debug(`rabbit: block reconnect`);return}if(t!==null){if(this.options?.disableReconnect||t?.isConnected())return this.#e.debug(`rabbit: connection - is connected`),t;this.#e.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 o=!1,s=()=>{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.#e.debug(`rabbit: creating connection`,{host:n,userName:e,HEARTBEAT:`60`}),[`amqp://${e}:${t}@${n}?heartbeat=60`]},c=await(0,p.connect)(s(),{findServers:s});e.amqpConnection=c;let{promise:l,reject:d,resolve:f}=z();return c.on(`error`,e=>{this.#e.error(`rabbit: connection error`,{err:e}),o||(o=!0,d(e),this.oldEm.emit(i,e))}),c.on(`connectFailed`,e=>{this.oldConsumersTags.clear(),typeof e.url==`string`&&(e.url=this.maskURL(e.url)),this.#e.error(`rabbit: connection connectFailed`,{err:e}),o||(o=!0,d(e),this.oldEm.emit(i,e))}),c.on(`disconnect`,({err:t})=>{this.oldConsumersTags.clear(),this.#e.debug(`rabbit: connection closed`),this.options?.disableReconnect?(this.#e.error(`${this.DISCONNECT_MSG}${t&&` - ${t}`}`),e.blockReconnect=!0):this.#e.error(`${this.RECONNECT_MSG}${t&&` - ${t}`}`)}),c.once(`connect`,async()=>{this.#e.debug(`rabbit: connection established`),e.creatingConnection=!1,this.oldEm.emit(r,c),o=!0,f(c)}),l}saveConsumerOld(e,t,n){this.oldConsumersToRegister.some(t=>t.queue===e)||(this.#e.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.#e.debug(`assertQueue->channel.addSetup`,{queueName:t}),await e.addSetup(e=>e.assertQueue(t,o)),this.#e.debug(`assertQueue->channel.assertQueue`,{queueName:t}),r=await e.assertQueue(t,o)}catch(e){if(this.#e.error(`rabbit: assertQueue error`,{queueName:t,options:n,error:e}),this.options?.dontRetryAssert)throw e;{this.#e.debug(`retrying assertQueue`,{queueName:t});let e=await this.assertChannelOld({force:!0,connection:i});await this.deleteQueueOld(t,i),this.#e.debug(`retrying assertQueue->channel.addSetup`,{queueName:t}),await e.addSetup(e=>e.assertQueue(t,o)),this.#e.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}=z();this.oldPublishChannelSetupPromise=n;try{let e=await this.getNewChannelOld({connection:t});e.on(`error`,e=>{this.#e.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.#e.info(`rabbit: deleting queue`,{queue:t});let i=await r.deleteQueue(t);return this.#e.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]=L(n,e),this.oldExchanges[e]=await this.oldAssertExchangePromises[e],this.oldExchanges[e])}async isConnectedOld(){if(this.gracefulShutdownStarted)return!0;this.#e.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.#e.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.#e.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.#e.error(`rabbit: isConnected - false old`,{msg:e.message}),!1}}},Q=Z;exports.default=Q,exports.sendCeleryTaskViaHttp=K,exports.t=s;
2
2
  //# sourceMappingURL=index.cjs.map