@nathapp/nestjs-queue 4.0.2 → 4.0.3

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.
Files changed (32) hide show
  1. package/README.md +79 -0
  2. package/dist/decorator/processor.decorator.js.map +1 -1
  3. package/dist/explorer/processor.explorer.d.ts +1 -1
  4. package/dist/provider/bullmq/bullmq.provider.d.ts +2 -0
  5. package/dist/provider/bullmq/bullmq.provider.js +108 -58
  6. package/dist/provider/bullmq/bullmq.provider.js.map +1 -1
  7. package/dist/provider/kafka/kafka.provider.d.ts +11 -4
  8. package/dist/provider/kafka/kafka.provider.js +529 -293
  9. package/dist/provider/kafka/kafka.provider.js.map +1 -1
  10. package/dist/provider/rabbitmq/rabbitmq.provider.d.ts +18 -3
  11. package/dist/provider/rabbitmq/rabbitmq.provider.js +440 -252
  12. package/dist/provider/rabbitmq/rabbitmq.provider.js.map +1 -1
  13. package/dist/service/queue.service.d.ts +1 -1
  14. package/dist/utils/batch-result.d.ts +3 -0
  15. package/dist/utils/batch-result.js +42 -0
  16. package/dist/utils/batch-result.js.map +1 -0
  17. package/dist/utils/delayed-scheduler.d.ts +4 -1
  18. package/dist/utils/delayed-scheduler.js +46 -24
  19. package/dist/utils/delayed-scheduler.js.map +1 -1
  20. package/dist/utils/errors.d.ts +3 -3
  21. package/dist/utils/named-processor-registry.d.ts +10 -0
  22. package/dist/utils/named-processor-registry.js +45 -0
  23. package/dist/utils/named-processor-registry.js.map +1 -0
  24. package/dist/utils/redis-idempotency-store.d.ts +2 -0
  25. package/dist/utils/redis-idempotency-store.js +36 -3
  26. package/dist/utils/redis-idempotency-store.js.map +1 -1
  27. package/dist/utils/sanitize.js +21 -9
  28. package/dist/utils/sanitize.js.map +1 -1
  29. package/dist/utils/validation.js +0 -2
  30. package/dist/utils/validation.js.map +1 -1
  31. package/package.json +5 -4
  32. package/tsconfig.test.json +16 -0
@@ -11,20 +11,16 @@ const sanitize_1 = require("../../utils/sanitize");
11
11
  const delayed_scheduler_1 = require("../../utils/delayed-scheduler");
12
12
  const lock_renewal_1 = require("../../utils/lock-renewal");
13
13
  const uuid_1 = require("uuid");
14
+ const batch_result_1 = require("../../utils/batch-result");
15
+ const validation_1 = require("../../utils/validation");
16
+ const named_processor_registry_1 = require("../../utils/named-processor-registry");
14
17
  let _amqpConnectionManager = null;
15
- let _amqplib = null;
16
18
  async function getAmqpConnectionManager() {
17
19
  if (!_amqpConnectionManager) {
18
20
  _amqpConnectionManager = await Promise.resolve().then(() => require('amqp-connection-manager'));
19
21
  }
20
22
  return _amqpConnectionManager;
21
23
  }
22
- async function getAmqplib() {
23
- if (!_amqplib) {
24
- _amqplib = await Promise.resolve().then(() => require('amqplib'));
25
- }
26
- return _amqplib;
27
- }
28
24
  class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
29
25
  constructor(options) {
30
26
  var _a;
@@ -35,9 +31,15 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
35
31
  this.channels = new Map();
36
32
  this.consumerTags = new Map();
37
33
  this.eventListeners = new Map();
34
+ this.registry = new named_processor_registry_1.NamedProcessorRegistry();
35
+ this.consumerConcurrency = new Map();
38
36
  this.isShuttingDown = false;
39
37
  this.batchAccumulators = new Map();
40
38
  this.batchTimers = new Map();
39
+ this.delayedDeliveries = new Map();
40
+ this.channelGenerations = new Map();
41
+ this.channelGenerationCounter = 0;
42
+ this.hasWarnedLowPrefetchRetention = false;
41
43
  this.type = provider_enum_1.QueueProviderType.RABBITMQ;
42
44
  this.metrics = options.metrics;
43
45
  if (!((_a = options.idempotency) === null || _a === void 0 ? void 0 : _a.store)) {
@@ -63,19 +65,30 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
63
65
  heartbeatIntervalInSeconds: 5,
64
66
  reconnectTimeInSeconds: reconnectOptions.initialDelay ? reconnectOptions.initialDelay / 1000 : 5,
65
67
  });
66
- this.connection.on('connect', () => {
67
- this.logger.log('RabbitMQ connected');
68
- });
69
- this.connection.on('disconnect', (params) => {
70
- var _a;
71
- this.logger.warn(`RabbitMQ disconnected: ${((_a = params.err) === null || _a === void 0 ? void 0 : _a.message) || 'unknown'}`);
72
- });
73
- this.connection.on('connectFailed', (params) => {
74
- var _a;
75
- this.logger.error(`RabbitMQ connection failed: ${((_a = params.err) === null || _a === void 0 ? void 0 : _a.message) || 'unknown'}`);
76
- });
68
+ this.registerConnectionHandlers(this.connection);
77
69
  }
78
- catch (error) {
70
+ catch (_error) {
71
+ }
72
+ }
73
+ registerConnectionHandlers(connection) {
74
+ connection.on('connect', () => {
75
+ this.logger.log('RabbitMQ connected');
76
+ });
77
+ connection.on('disconnect', (params) => {
78
+ var _a;
79
+ this.logger.warn(`RabbitMQ disconnected: ${((_a = params.err) === null || _a === void 0 ? void 0 : _a.message) || 'unknown'}`);
80
+ this.invalidateChannelGenerations();
81
+ this.delayedDeliveries.clear();
82
+ });
83
+ connection.on('connectFailed', (params) => {
84
+ var _a;
85
+ this.logger.error(`RabbitMQ connection failed: ${((_a = params.err) === null || _a === void 0 ? void 0 : _a.message) || 'unknown'}`);
86
+ });
87
+ }
88
+ invalidateChannelGenerations() {
89
+ this.channelGenerationCounter += 1;
90
+ for (const [name] of this.channels) {
91
+ this.channelGenerations.set(name, this.channelGenerationCounter);
79
92
  }
80
93
  }
81
94
  async getConnection() {
@@ -86,17 +99,7 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
86
99
  heartbeatIntervalInSeconds: 5,
87
100
  reconnectTimeInSeconds: reconnectOptions.initialDelay ? reconnectOptions.initialDelay / 1000 : 5,
88
101
  });
89
- this.connection.on('connect', () => {
90
- this.logger.log('RabbitMQ connected');
91
- });
92
- this.connection.on('disconnect', (params) => {
93
- var _a;
94
- this.logger.warn(`RabbitMQ disconnected: ${((_a = params.err) === null || _a === void 0 ? void 0 : _a.message) || 'unknown'}`);
95
- });
96
- this.connection.on('connectFailed', (params) => {
97
- var _a;
98
- this.logger.error(`RabbitMQ connection failed: ${((_a = params.err) === null || _a === void 0 ? void 0 : _a.message) || 'unknown'}`);
99
- });
102
+ this.registerConnectionHandlers(this.connection);
100
103
  }
101
104
  return this.connection;
102
105
  }
@@ -107,6 +110,100 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
107
110
  const originalId = headers['x-original-job-id'];
108
111
  return originalId ? String(originalId) : job.id;
109
112
  }
113
+ getDeliveryGroupKey(queueName, jobId) {
114
+ return `${queueName}\u0000${jobId}`;
115
+ }
116
+ warnIfLowPrefetchRetention() {
117
+ if (this.hasWarnedLowPrefetchRetention) {
118
+ return;
119
+ }
120
+ const effectivePrefetch = this.options.prefetchCount || 1;
121
+ if (effectivePrefetch > 1) {
122
+ return;
123
+ }
124
+ this.hasWarnedLowPrefetchRetention = true;
125
+ this.logger.warn(`Delayed delivery retained with prefetchCount=${effectivePrefetch}. ` +
126
+ 'Each retained (unacknowledged) delivery holds a prefetch slot, so this queue can be ' +
127
+ 'head-of-line blocked until the delay elapses. Use a dedicated queue for delayed jobs, ' +
128
+ 'raise prefetchCount, or use the broker-native delayed message exchange for long delays.');
129
+ }
130
+ isCurrentChannel(queueName, channel, channelGeneration) {
131
+ return (this.channels.get(queueName) === channel &&
132
+ this.channelGenerations.get(queueName) === channelGeneration);
133
+ }
134
+ buildRepublishHeaders(job, headers, idempotencyKey) {
135
+ var _a, _b, _c, _d, _e, _f, _g;
136
+ const { 'x-process-after': _processAfter, 'x-delay': _delay, ...sourceHeaders } = headers;
137
+ return {
138
+ ...(_a = job.opts) === null || _a === void 0 ? void 0 : _a.headers,
139
+ ...sourceHeaders,
140
+ 'x-original-job-id': idempotencyKey,
141
+ 'x-attempts': String((_c = (_b = headers['x-attempts']) !== null && _b !== void 0 ? _b : job.attemptsMade) !== null && _c !== void 0 ? _c : 0),
142
+ 'x-max-attempts': String((_f = (_d = headers['x-max-attempts']) !== null && _d !== void 0 ? _d : (_e = job.opts) === null || _e === void 0 ? void 0 : _e.attempts) !== null && _f !== void 0 ? _f : 1),
143
+ 'x-correlation-id': job.correlationId
144
+ ? String(job.correlationId)
145
+ : String((_g = headers['x-correlation-id']) !== null && _g !== void 0 ? _g : job.id),
146
+ };
147
+ }
148
+ scheduleDelayedDelivery(queueName, job, delay, msg, headers, channel, channelGeneration) {
149
+ var _a, _b;
150
+ const groupKey = this.getDeliveryGroupKey(queueName, job.id);
151
+ const retained = { msg, channel, channelGeneration };
152
+ this.warnIfLowPrefetchRetention();
153
+ const existing = this.delayedDeliveries.get(groupKey);
154
+ if (existing) {
155
+ existing.deliveries.push(retained);
156
+ this.logger.debug(`Delayed job ${job.id} already scheduled; retained duplicate delivery`);
157
+ return 'scheduled';
158
+ }
159
+ const idempotencyKey = this.getIdempotencyKey(job, headers);
160
+ const republishOpts = {
161
+ ...job.opts,
162
+ jobId: job.id,
163
+ delay: 0,
164
+ correlationId: (_a = job.correlationId) !== null && _a !== void 0 ? _a : (_b = job.opts) === null || _b === void 0 ? void 0 : _b.correlationId,
165
+ headers: this.buildRepublishHeaders(job, headers, idempotencyKey),
166
+ };
167
+ const scheduledJob = { ...job, opts: republishOpts };
168
+ this.delayedDeliveries.set(groupKey, {
169
+ queueName,
170
+ jobId: job.id,
171
+ settled: false,
172
+ deliveries: [retained],
173
+ });
174
+ const scheduled = this.delayedScheduler.schedule(queueName, scheduledJob, delay, (error) => this.settleDelayedDeliveryGroup(groupKey, error), groupKey);
175
+ if (scheduled) {
176
+ return 'scheduled';
177
+ }
178
+ this.delayedDeliveries.delete(groupKey);
179
+ return this.delayedScheduler.shuttingDown ? 'requeue' : 'process';
180
+ }
181
+ settleDelayedDeliveryGroup(groupKey, error) {
182
+ var _a;
183
+ const group = this.delayedDeliveries.get(groupKey);
184
+ if (!group || group.settled) {
185
+ return;
186
+ }
187
+ group.settled = true;
188
+ this.delayedDeliveries.delete(groupKey);
189
+ for (const delivery of group.deliveries) {
190
+ if (!this.isCurrentChannel(group.queueName, delivery.channel, delivery.channelGeneration)) {
191
+ this.logger.warn(`Skipping settlement of retained delayed job ${group.jobId}: original channel is no longer current`);
192
+ continue;
193
+ }
194
+ try {
195
+ if (error) {
196
+ delivery.channel.nack(delivery.msg, false, true);
197
+ }
198
+ else {
199
+ delivery.channel.ack(delivery.msg);
200
+ }
201
+ }
202
+ catch (settleError) {
203
+ this.logger.error(`Failed to settle retained delayed job ${group.jobId}: ${(_a = settleError === null || settleError === void 0 ? void 0 : settleError.message) !== null && _a !== void 0 ? _a : String(settleError)}`);
204
+ }
205
+ }
206
+ }
110
207
  calculateBackoff(job) {
111
208
  const opts = job.opts;
112
209
  if (!(opts === null || opts === void 0 ? void 0 : opts.backoff)) {
@@ -140,7 +237,6 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
140
237
  async getChannel(queueName) {
141
238
  if (!this.channels.has(queueName)) {
142
239
  const connection = await this.getConnection();
143
- const amqp = await getAmqplib();
144
240
  const queueOpts = this.options.queueOptions || {};
145
241
  const dlqName = `${queueName}-dlq`;
146
242
  const channel = connection.createChannel({
@@ -165,11 +261,16 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
165
261
  },
166
262
  });
167
263
  this.channels.set(queueName, channel);
264
+ this.channelGenerationCounter += 1;
265
+ this.channelGenerations.set(queueName, this.channelGenerationCounter);
168
266
  }
169
267
  return this.channels.get(queueName);
170
268
  }
171
269
  async add(queueName, jobName, data, opts) {
172
- var _a, _b;
270
+ var _a;
271
+ (0, validation_1.validateJobData)(data);
272
+ if (opts === null || opts === void 0 ? void 0 : opts.jobId)
273
+ (0, validation_1.validateJobId)(opts.jobId);
173
274
  const channel = await this.getChannel(queueName);
174
275
  const sanitizedCorrelationId = (0, errors_1.sanitizeCorrelationId)(opts === null || opts === void 0 ? void 0 : opts.correlationId);
175
276
  const job = {
@@ -181,43 +282,22 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
181
282
  attemptsMade: 0,
182
283
  correlationId: sanitizedCorrelationId,
183
284
  };
184
- const messageOptions = {
185
- persistent: true,
186
- messageId: job.id,
187
- correlationId: sanitizedCorrelationId,
188
- contentType: 'application/json',
189
- headers: {
190
- 'x-job-name': jobName,
191
- 'x-job-id': job.id,
192
- 'x-correlation-id': sanitizedCorrelationId || job.id,
193
- 'x-original-job-id': ((_a = opts === null || opts === void 0 ? void 0 : opts.headers) === null || _a === void 0 ? void 0 : _a['x-original-job-id']) || (opts === null || opts === void 0 ? void 0 : opts.jobId) || job.id,
194
- 'x-attempts': job.attemptsMade || 0,
195
- 'x-max-attempts': (opts === null || opts === void 0 ? void 0 : opts.attempts) || 1,
196
- 'x-timestamp': job.timestamp,
197
- ...opts === null || opts === void 0 ? void 0 : opts.headers,
198
- },
199
- };
200
- if ((opts === null || opts === void 0 ? void 0 : opts.priority) !== undefined) {
201
- messageOptions.priority = opts.priority;
202
- }
203
- if (opts === null || opts === void 0 ? void 0 : opts.delay) {
204
- if (this.options.useDelayedMessagePlugin) {
205
- messageOptions.headers['x-delay'] = opts.delay;
206
- }
207
- else {
208
- messageOptions.headers['x-process-after'] = Date.now() + opts.delay;
209
- this.logger.warn('Delayed messages without plugin may not be accurate. Consider installing rabbitmq_delayed_message_exchange plugin.');
210
- }
211
- }
285
+ const messageOptions = this.buildPublishOptions(job);
212
286
  await channel.sendToQueue(queueName, Buffer.from(JSON.stringify(job)), messageOptions);
213
287
  this.logger.debug(`Job added: ${jobName} (${job.id}) to queue ${queueName}`);
214
- (_b = this.metrics) === null || _b === void 0 ? void 0 : _b.jobAdded(queueName, jobName, job.id, {
288
+ (_a = this.metrics) === null || _a === void 0 ? void 0 : _a.jobAdded(queueName, jobName, job.id, {
215
289
  delay: opts === null || opts === void 0 ? void 0 : opts.delay,
216
290
  priority: opts === null || opts === void 0 ? void 0 : opts.priority,
217
291
  });
218
292
  return job;
219
293
  }
220
294
  async addBulk(queueName, jobs) {
295
+ var _a;
296
+ for (const j of jobs) {
297
+ (0, validation_1.validateJobData)(j.data);
298
+ if ((_a = j.opts) === null || _a === void 0 ? void 0 : _a.jobId)
299
+ (0, validation_1.validateJobId)(j.opts.jobId);
300
+ }
221
301
  const channel = await this.getChannel(queueName);
222
302
  const createdJobs = jobs.map((j) => {
223
303
  var _a, _b;
@@ -232,35 +312,8 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
232
312
  correlationId: sanitizedCorrelationId,
233
313
  };
234
314
  });
235
- const publishPromises = createdJobs.map((job, idx) => {
236
- var _a, _b, _c, _d;
237
- const original = jobs[idx];
238
- const messageOptions = {
239
- persistent: true,
240
- messageId: job.id,
241
- correlationId: job.correlationId,
242
- contentType: 'application/json',
243
- headers: {
244
- 'x-job-name': job.name,
245
- 'x-job-id': job.id,
246
- 'x-correlation-id': job.correlationId || job.id,
247
- 'x-original-job-id': ((_a = original.opts) === null || _a === void 0 ? void 0 : _a.jobId) || job.id,
248
- 'x-attempts': 0,
249
- 'x-max-attempts': ((_b = original.opts) === null || _b === void 0 ? void 0 : _b.attempts) || 1,
250
- 'x-timestamp': job.timestamp,
251
- },
252
- };
253
- if (((_c = original.opts) === null || _c === void 0 ? void 0 : _c.priority) !== undefined) {
254
- messageOptions.priority = original.opts.priority;
255
- }
256
- if ((_d = original.opts) === null || _d === void 0 ? void 0 : _d.delay) {
257
- if (this.options.useDelayedMessagePlugin) {
258
- messageOptions.headers['x-delay'] = original.opts.delay;
259
- }
260
- else {
261
- messageOptions.headers['x-process-after'] = Date.now() + original.opts.delay;
262
- }
263
- }
315
+ const publishPromises = createdJobs.map((job) => {
316
+ const messageOptions = this.buildPublishOptions(job);
264
317
  return channel.sendToQueue(queueName, Buffer.from(JSON.stringify(job)), messageOptions);
265
318
  });
266
319
  await Promise.all(publishPromises);
@@ -275,140 +328,200 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
275
328
  this.logger.debug(`${createdJobs.length} jobs added in bulk to queue ${queueName}`);
276
329
  return createdJobs;
277
330
  }
331
+ buildPublishOptions(job) {
332
+ var _a;
333
+ const opts = job.opts;
334
+ const headers = {
335
+ 'x-job-name': job.name,
336
+ 'x-job-id': job.id,
337
+ 'x-correlation-id': job.correlationId || job.id,
338
+ 'x-original-job-id': ((_a = opts === null || opts === void 0 ? void 0 : opts.headers) === null || _a === void 0 ? void 0 : _a['x-original-job-id']) || (opts === null || opts === void 0 ? void 0 : opts.jobId) || job.id,
339
+ 'x-attempts': job.attemptsMade || 0,
340
+ 'x-max-attempts': (opts === null || opts === void 0 ? void 0 : opts.attempts) || 1,
341
+ 'x-timestamp': job.timestamp,
342
+ ...opts === null || opts === void 0 ? void 0 : opts.headers,
343
+ };
344
+ if (opts === null || opts === void 0 ? void 0 : opts.delay) {
345
+ if (this.options.useDelayedMessagePlugin) {
346
+ headers['x-delay'] = opts.delay;
347
+ }
348
+ else {
349
+ headers['x-process-after'] = Date.now() + opts.delay;
350
+ this.logger.warn('Delayed messages without plugin may not be accurate. Consider installing rabbitmq_delayed_message_exchange plugin.');
351
+ }
352
+ }
353
+ return {
354
+ persistent: true,
355
+ messageId: job.id,
356
+ correlationId: job.correlationId,
357
+ contentType: 'application/json',
358
+ headers,
359
+ ...((opts === null || opts === void 0 ? void 0 : opts.priority) !== undefined ? { priority: opts.priority } : {}),
360
+ };
361
+ }
278
362
  async process(queueName, processor, options) {
279
- var _a, _b, _c, _d, _e;
280
- const consumerKey = (options === null || options === void 0 ? void 0 : options.name) ? `${queueName}:${options.name}` : queueName;
281
- if (this.consumerTags.has(consumerKey)) {
363
+ var _a, _b, _c, _d, _e, _f;
364
+ const status = this.registry.register(queueName, options === null || options === void 0 ? void 0 : options.name, processor);
365
+ if (status === 'duplicate') {
366
+ const consumerKey = (options === null || options === void 0 ? void 0 : options.name) ? `${queueName}:${options.name}` : queueName;
282
367
  this.logger.warn(`Consumer already exists for ${consumerKey}`);
283
368
  return false;
284
369
  }
285
- const channel = await this.getChannel(queueName);
286
- const idempotencyStore = (_a = this.options.idempotency) === null || _a === void 0 ? void 0 : _a.store;
287
- const lockTtl = (_c = (_b = this.options.idempotency) === null || _b === void 0 ? void 0 : _b.lockTtl) !== null && _c !== void 0 ? _c : 60000;
288
- const completedTtl = (_e = (_d = this.options.idempotency) === null || _d === void 0 ? void 0 : _d.completedTtl) !== null && _e !== void 0 ? _e : 3600000;
289
- const { consumerTag } = await channel.consume(queueName, async (msg) => {
290
- var _a, _b, _c, _d, _e;
291
- if (!msg)
292
- return;
293
- let job;
294
- try {
295
- const parsed = JSON.parse(msg.content.toString());
296
- (0, errors_1.validateJobStructure)(parsed);
297
- job = parsed;
298
- }
299
- catch (error) {
300
- this.logger.error(`Failed to parse or validate job message: ${error.message}`);
301
- channel.ack(msg);
302
- return;
303
- }
304
- const headers = msg.properties.headers || {};
305
- const attempts = parseInt(String(headers['x-attempts'] || '0'));
306
- const maxAttempts = parseInt(String(headers['x-max-attempts'] || '1'));
307
- const rawCorrelationId = headers['x-correlation-id'] || msg.properties.correlationId;
308
- if (rawCorrelationId) {
370
+ if (status === 'added') {
371
+ const requestedConcurrency = (options === null || options === void 0 ? void 0 : options.concurrency) || 1;
372
+ const existingConcurrency = (_a = this.consumerConcurrency.get(queueName)) !== null && _a !== void 0 ? _a : 1;
373
+ if (requestedConcurrency !== existingConcurrency) {
374
+ this.logger.debug(`Consumer for queue ${queueName} already exists with concurrency ${existingConcurrency}; ` +
375
+ `ignoring requested concurrency ${requestedConcurrency} for named processor "${options === null || options === void 0 ? void 0 : options.name}".`);
376
+ }
377
+ return true;
378
+ }
379
+ const idempotencyStore = (_b = this.options.idempotency) === null || _b === void 0 ? void 0 : _b.store;
380
+ const lockTtl = (_d = (_c = this.options.idempotency) === null || _c === void 0 ? void 0 : _c.lockTtl) !== null && _d !== void 0 ? _d : 60000;
381
+ const completedTtl = (_f = (_e = this.options.idempotency) === null || _e === void 0 ? void 0 : _e.completedTtl) !== null && _f !== void 0 ? _f : 3600000;
382
+ if (this.options.noAck) {
383
+ this.logger.warn('QueueOptions.noAck is deprecated and ignored: manual acknowledgement is required for retry/DLQ correctness (M-13)');
384
+ }
385
+ let channel;
386
+ let consumerTag;
387
+ try {
388
+ channel = await this.getChannel(queueName);
389
+ ({ consumerTag } = await channel.consume(queueName, async (msg) => {
390
+ var _a, _b, _c, _d, _e, _f, _g;
391
+ if (!msg)
392
+ return;
393
+ let job;
309
394
  try {
310
- job.correlationId = (0, errors_1.sanitizeCorrelationId)(String(rawCorrelationId));
395
+ const parsed = JSON.parse(msg.content.toString());
396
+ (0, errors_1.validateJobStructure)(parsed);
397
+ job = parsed;
311
398
  }
312
399
  catch (error) {
313
- this.logger.warn(`Invalid correlationId in message: ${error.message}`);
314
- }
315
- }
316
- if ((options === null || options === void 0 ? void 0 : options.name) && job.name !== options.name) {
317
- channel.ack(msg);
318
- return;
319
- }
320
- const idempotencyKey = idempotencyStore ? this.getIdempotencyKey(job, headers) : job.id;
321
- if (idempotencyStore) {
322
- const canProcess = await idempotencyStore.markProcessing(idempotencyKey, lockTtl);
323
- if (!canProcess) {
400
+ this.logger.error(`Failed to parse or validate job message: ${error.message}`);
324
401
  channel.ack(msg);
325
- this.logger.debug(`Job ${job.id} skipped (idempotency check, original ID: ${idempotencyKey})`);
326
402
  return;
327
403
  }
328
- }
329
- const processAfter = headers['x-process-after'];
330
- if (processAfter && parseInt(String(processAfter)) > Date.now()) {
331
- const delay = parseInt(String(processAfter)) - Date.now();
332
- if (idempotencyStore) {
333
- await idempotencyStore.releaseLock(idempotencyKey);
404
+ const headers = msg.properties.headers || {};
405
+ const attempts = parseInt(String(headers['x-attempts'] || '0'));
406
+ const maxAttempts = parseInt(String(headers['x-max-attempts'] || '1'));
407
+ const rawCorrelationId = headers['x-correlation-id'] || msg.properties.correlationId;
408
+ if (rawCorrelationId) {
409
+ try {
410
+ job.correlationId = (0, errors_1.sanitizeCorrelationId)(String(rawCorrelationId));
411
+ }
412
+ catch (error) {
413
+ this.logger.warn(`Invalid correlationId in message: ${error.message}`);
414
+ }
334
415
  }
335
- const scheduled = this.delayedScheduler.schedule(queueName, job, delay);
336
- if (scheduled) {
416
+ const handler = this.registry.resolve(queueName, job.name);
417
+ if (!handler) {
418
+ this.logger.warn(`No handler for job "${job.name}" on queue "${queueName}"`);
337
419
  channel.ack(msg);
338
- this.logger.debug(`Delayed job scheduled locally: ${job.id}, delay: ${delay}ms`);
420
+ return;
339
421
  }
340
- else {
341
- channel.nack(msg, false, true);
422
+ const processAfter = headers['x-process-after'];
423
+ if (processAfter && parseInt(String(processAfter), 10) > Date.now()) {
424
+ const delay = parseInt(String(processAfter), 10) - Date.now();
425
+ const channelGeneration = (_a = this.channelGenerations.get(queueName)) !== null && _a !== void 0 ? _a : 0;
426
+ const outcome = this.scheduleDelayedDelivery(queueName, job, delay, msg, headers, channel, channelGeneration);
427
+ if (outcome === 'scheduled') {
428
+ this.logger.debug(`Delayed job scheduled locally: ${job.id}, delay: ${delay}ms`);
429
+ return;
430
+ }
431
+ if (outcome === 'requeue') {
432
+ try {
433
+ channel.nack(msg, false, true);
434
+ }
435
+ catch (nackError) {
436
+ this.logger.error(`Failed to requeue delayed job ${job.id} during shutdown: ${(_b = nackError === null || nackError === void 0 ? void 0 : nackError.message) !== null && _b !== void 0 ? _b : String(nackError)}`);
437
+ }
438
+ return;
439
+ }
342
440
  }
343
- return;
344
- }
345
- let lockRenewal;
346
- if (idempotencyStore) {
347
- lockRenewal = new lock_renewal_1.LockRenewal(idempotencyStore, idempotencyKey, lockTtl, Math.floor(lockTtl / 2));
348
- lockRenewal.start();
349
- }
350
- try {
351
- this.emitEvent(queueName, queue_event_enum_1.QueueEvent.ACTIVE, job);
352
- (_a = this.metrics) === null || _a === void 0 ? void 0 : _a.jobStarted(queueName, job.name, job.id);
353
- const startTime = Date.now();
354
- const result = await processor(job);
355
- job.returnvalue = result;
441
+ const idempotencyKey = idempotencyStore ? this.getIdempotencyKey(job, headers) : job.id;
356
442
  if (idempotencyStore) {
357
- await idempotencyStore.markComplete(idempotencyKey, completedTtl);
443
+ const canProcess = await idempotencyStore.markProcessing(idempotencyKey, lockTtl);
444
+ if (!canProcess) {
445
+ channel.ack(msg);
446
+ this.logger.debug(`Job ${job.id} skipped (idempotency check, original ID: ${idempotencyKey})`);
447
+ return;
448
+ }
358
449
  }
359
- const duration = Date.now() - startTime;
360
- (_b = this.metrics) === null || _b === void 0 ? void 0 : _b.jobCompleted(queueName, job.name, job.id, duration);
361
- channel.ack(msg);
362
- this.emitEvent(queueName, queue_event_enum_1.QueueEvent.COMPLETED, job, result);
363
- this.logger.debug(`Job completed: ${job.name} (${job.id})`);
364
- }
365
- catch (error) {
366
- job.attemptsMade = attempts + 1;
367
- job.failedReason = (0, sanitize_1.sanitizeErrorMessage)(error instanceof Error ? error.message : String(error));
368
- (_c = this.metrics) === null || _c === void 0 ? void 0 : _c.jobFailed(queueName, job.name, job.id, job.failedReason, job.attemptsMade);
450
+ let lockRenewal;
369
451
  if (idempotencyStore) {
370
- await idempotencyStore.releaseLock(idempotencyKey);
452
+ lockRenewal = new lock_renewal_1.LockRenewal(idempotencyStore, idempotencyKey, lockTtl, Math.floor(lockTtl / 2));
453
+ lockRenewal.start();
371
454
  }
372
- if (job.attemptsMade < maxAttempts) {
373
- const delay = this.calculateBackoff(job);
374
- (_d = this.metrics) === null || _d === void 0 ? void 0 : _d.jobRetried(queueName, job.name, job.id, job.attemptsMade + 1, delay);
375
- try {
376
- const retryJobOpts = {
377
- ...job.opts,
378
- jobId: `${idempotencyKey}-retry-${job.attemptsMade + 1}`,
379
- delay,
380
- correlationId: job.correlationId,
381
- headers: {
382
- ...(_e = job.opts) === null || _e === void 0 ? void 0 : _e.headers,
383
- 'x-original-job-id': idempotencyKey,
384
- 'x-retry-count': String(job.attemptsMade + 1),
385
- },
386
- };
387
- await this.add(queueName, job.name, job.data, retryJobOpts);
388
- channel.ack(msg);
389
- this.logger.debug(`Job retry scheduled: ${job.name} (${job.id}), attempt ${job.attemptsMade + 1}/${maxAttempts}, delay ${delay}ms`);
390
- }
391
- catch (retryError) {
392
- this.logger.error(`Failed to schedule retry for job ${job.id}: ${retryError.message}`);
393
- channel.nack(msg, false, true);
455
+ try {
456
+ this.emitEvent(queueName, queue_event_enum_1.QueueEvent.ACTIVE, job);
457
+ (_c = this.metrics) === null || _c === void 0 ? void 0 : _c.jobStarted(queueName, job.name, job.id);
458
+ const startTime = Date.now();
459
+ const result = await handler(job);
460
+ job.returnvalue = result;
461
+ if (idempotencyStore) {
462
+ await idempotencyStore.markComplete(idempotencyKey, completedTtl);
394
463
  }
464
+ const duration = Date.now() - startTime;
465
+ (_d = this.metrics) === null || _d === void 0 ? void 0 : _d.jobCompleted(queueName, job.name, job.id, duration);
466
+ channel.ack(msg);
467
+ this.emitEvent(queueName, queue_event_enum_1.QueueEvent.COMPLETED, job, result);
468
+ this.logger.debug(`Job completed: ${job.name} (${job.id})`);
395
469
  }
396
- else {
397
- channel.nack(msg, false, false);
398
- const sanitizedMessage = (0, sanitize_1.sanitizeErrorMessage)(error instanceof Error ? error.message : String(error));
399
- this.emitEvent(queueName, queue_event_enum_1.QueueEvent.FAILED, job, new Error(sanitizedMessage));
400
- this.logger.error(`Job failed permanently: ${job.name} (${job.id}): ${sanitizedMessage}`);
470
+ catch (error) {
471
+ job.attemptsMade = attempts + 1;
472
+ job.failedReason = (0, sanitize_1.sanitizeErrorMessage)(error instanceof Error ? error.message : String(error));
473
+ (_e = this.metrics) === null || _e === void 0 ? void 0 : _e.jobFailed(queueName, job.name, job.id, job.failedReason, job.attemptsMade);
474
+ if (idempotencyStore) {
475
+ await idempotencyStore.releaseLock(idempotencyKey);
476
+ }
477
+ if (job.attemptsMade < maxAttempts) {
478
+ const delay = this.calculateBackoff(job);
479
+ (_f = this.metrics) === null || _f === void 0 ? void 0 : _f.jobRetried(queueName, job.name, job.id, job.attemptsMade + 1, delay);
480
+ try {
481
+ const retryJobOpts = {
482
+ ...job.opts,
483
+ jobId: `${idempotencyKey}-retry-${job.attemptsMade + 1}`,
484
+ delay,
485
+ correlationId: job.correlationId,
486
+ headers: {
487
+ ...(_g = job.opts) === null || _g === void 0 ? void 0 : _g.headers,
488
+ 'x-original-job-id': idempotencyKey,
489
+ 'x-retry-count': String(job.attemptsMade + 1),
490
+ },
491
+ };
492
+ await this.add(queueName, job.name, job.data, retryJobOpts);
493
+ channel.ack(msg);
494
+ this.logger.debug(`Job retry scheduled: ${job.name} (${job.id}), attempt ${job.attemptsMade + 1}/${maxAttempts}, delay ${delay}ms`);
495
+ }
496
+ catch (retryError) {
497
+ this.logger.error(`Failed to schedule retry for job ${job.id}: ${retryError.message}`);
498
+ channel.nack(msg, false, true);
499
+ }
500
+ }
501
+ else {
502
+ channel.nack(msg, false, false);
503
+ const sanitizedMessage = (0, sanitize_1.sanitizeErrorMessage)(error instanceof Error ? error.message : String(error));
504
+ this.emitEvent(queueName, queue_event_enum_1.QueueEvent.FAILED, job, new Error(sanitizedMessage));
505
+ this.logger.error(`Job failed permanently: ${job.name} (${job.id}): ${sanitizedMessage}`);
506
+ }
401
507
  }
402
- }
403
- finally {
404
- if (lockRenewal) {
405
- lockRenewal.stop();
508
+ finally {
509
+ if (lockRenewal) {
510
+ lockRenewal.stop();
511
+ }
406
512
  }
407
- }
408
- }, {
409
- noAck: this.options.noAck || false,
410
- });
411
- this.consumerTags.set(consumerKey, consumerTag);
513
+ }, {
514
+ noAck: false,
515
+ }));
516
+ }
517
+ catch (error) {
518
+ this.consumerTags.delete(queueName);
519
+ this.consumerConcurrency.delete(queueName);
520
+ this.registry.removeQueue(queueName);
521
+ throw error;
522
+ }
523
+ this.consumerTags.set(queueName, consumerTag);
524
+ this.consumerConcurrency.set(queueName, (options === null || options === void 0 ? void 0 : options.concurrency) || 1);
412
525
  this.logger.log(`Consumer started for queue: ${queueName}${(options === null || options === void 0 ? void 0 : options.name) ? ` (${options.name})` : ''}`);
413
526
  return true;
414
527
  }
@@ -428,7 +541,61 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
428
541
  });
429
542
  const accumulatorKey = queueName;
430
543
  this.batchAccumulators.set(accumulatorKey, []);
544
+ const settleFailure = async (entry, error) => {
545
+ var _a, _b, _c, _d, _e, _f, _g, _h;
546
+ const { job, msg, headers, idempotencyKey } = entry;
547
+ const currentAttempts = (Number.parseInt(String((_b = (_a = headers['x-attempts']) !== null && _a !== void 0 ? _a : job.attemptsMade) !== null && _b !== void 0 ? _b : 0), 10) || 0) + 1;
548
+ const maxAttempts = Number.parseInt(String((_e = (_c = headers['x-max-attempts']) !== null && _c !== void 0 ? _c : (_d = job.opts) === null || _d === void 0 ? void 0 : _d.attempts) !== null && _e !== void 0 ? _e : 1), 10) || 1;
549
+ job.attemptsMade = currentAttempts;
550
+ job.failedReason = (0, sanitize_1.sanitizeErrorMessage)(error.message);
551
+ (_f = this.metrics) === null || _f === void 0 ? void 0 : _f.jobFailed(queueName, job.name, job.id, job.failedReason, currentAttempts);
552
+ try {
553
+ if (retryFailedIndividually && currentAttempts < maxAttempts) {
554
+ const delay = this.calculateBackoff(job);
555
+ (_g = this.metrics) === null || _g === void 0 ? void 0 : _g.jobRetried(queueName, job.name, job.id, currentAttempts, delay);
556
+ await this.add(queueName, job.name, job.data, {
557
+ ...job.opts,
558
+ attempts: maxAttempts,
559
+ delay,
560
+ jobId: `${idempotencyKey}-retry-${currentAttempts}`,
561
+ correlationId: job.correlationId,
562
+ headers: {
563
+ ...(_h = job.opts) === null || _h === void 0 ? void 0 : _h.headers,
564
+ ...headers,
565
+ 'x-original-job-id': idempotencyKey,
566
+ 'x-attempts': String(currentAttempts),
567
+ 'x-max-attempts': String(maxAttempts),
568
+ 'x-retry-count': String(currentAttempts),
569
+ },
570
+ });
571
+ if (idempotencyStore)
572
+ await idempotencyStore.releaseLock(idempotencyKey);
573
+ channel.ack(msg);
574
+ entry.settled = true;
575
+ return;
576
+ }
577
+ if (idempotencyStore)
578
+ await idempotencyStore.releaseLock(idempotencyKey);
579
+ channel.nack(msg, false, false);
580
+ entry.settled = true;
581
+ this.emitEvent(queueName, queue_event_enum_1.QueueEvent.FAILED, job, error);
582
+ }
583
+ catch (publishError) {
584
+ this.logger.error(`Failed to hand off batch job ${job.id}: ${publishError instanceof Error ? publishError.message : String(publishError)}`);
585
+ try {
586
+ if (idempotencyStore)
587
+ await idempotencyStore.releaseLock(idempotencyKey);
588
+ }
589
+ finally {
590
+ if (!entry.settled) {
591
+ channel.nack(msg, false, true);
592
+ entry.settled = true;
593
+ }
594
+ }
595
+ }
596
+ };
431
597
  const processBatchFn = async () => {
598
+ var _a;
432
599
  const timer = this.batchTimers.get(accumulatorKey);
433
600
  if (timer) {
434
601
  clearTimeout(timer);
@@ -442,36 +609,31 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
442
609
  const startTime = Date.now();
443
610
  try {
444
611
  const result = await processor(jobs, options || {});
612
+ const jobResults = (0, batch_result_1.validateBatchResults)(queueName, jobs, result);
445
613
  for (let i = 0; i < batch.length; i++) {
446
- const { msg } = batch[i];
447
- const jobResult = result.results[i];
448
- const job = jobs[i];
614
+ const entry = batch[i];
615
+ const jobResult = jobResults[i];
449
616
  if (jobResult.success) {
450
- channel.ack(msg);
451
- if (idempotencyStore) {
452
- const headers = msg.properties.headers || {};
453
- const idempotencyKey = this.getIdempotencyKey(job, headers);
454
- await idempotencyStore.markComplete(idempotencyKey, completedTtl);
455
- }
456
- }
457
- else if (retryFailedIndividually && jobResult.error) {
458
- channel.nack(msg, false, true);
459
- if (idempotencyStore) {
460
- const headers = msg.properties.headers || {};
461
- const idempotencyKey = this.getIdempotencyKey(job, headers);
462
- await idempotencyStore.releaseLock(idempotencyKey);
463
- }
464
- }
465
- else if (!continueOnError && jobResult.error) {
466
- channel.ack(msg);
467
- if (idempotencyStore) {
468
- const headers = msg.properties.headers || {};
469
- const idempotencyKey = this.getIdempotencyKey(job, headers);
470
- await idempotencyStore.releaseLock(idempotencyKey);
471
- }
617
+ if (idempotencyStore)
618
+ await idempotencyStore.markComplete(entry.idempotencyKey, completedTtl);
619
+ channel.ack(entry.msg);
620
+ entry.settled = true;
621
+ (_a = this.metrics) === null || _a === void 0 ? void 0 : _a.jobCompleted(queueName, entry.job.name, entry.job.id, Date.now() - startTime);
622
+ this.emitEvent(queueName, queue_event_enum_1.QueueEvent.COMPLETED, entry.job, jobResult.result);
472
623
  }
473
624
  else {
474
- channel.ack(msg);
625
+ await settleFailure(entry, jobResult.error);
626
+ if (!continueOnError) {
627
+ for (const remaining of batch.slice(i + 1)) {
628
+ if (remaining.settled)
629
+ continue;
630
+ if (idempotencyStore)
631
+ await idempotencyStore.releaseLock(remaining.idempotencyKey);
632
+ channel.nack(remaining.msg, false, true);
633
+ remaining.settled = true;
634
+ }
635
+ break;
636
+ }
475
637
  }
476
638
  }
477
639
  const duration = Date.now() - startTime;
@@ -479,12 +641,15 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
479
641
  }
480
642
  catch (error) {
481
643
  this.logger.error(`Batch processing failed: ${error.message}`);
482
- for (const { msg } of batch) {
483
- channel.nack(msg, false, true);
644
+ const failure = error instanceof Error ? error : new Error(String(error));
645
+ for (const entry of batch) {
646
+ if (!entry.settled)
647
+ await settleFailure(entry, failure);
484
648
  }
485
649
  }
486
650
  };
487
651
  const { consumerTag } = await channel.consume(queueName, async (msg) => {
652
+ var _a, _b, _c, _d;
488
653
  if (!msg)
489
654
  return;
490
655
  let job;
@@ -499,6 +664,7 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
499
664
  return;
500
665
  }
501
666
  const headers = msg.properties.headers || {};
667
+ job.attemptsMade = Number.parseInt(String((_b = (_a = headers['x-attempts']) !== null && _a !== void 0 ? _a : job.attemptsMade) !== null && _b !== void 0 ? _b : 0), 10) || 0;
502
668
  const rawCorrelationId = headers['x-correlation-id'] || msg.properties.correlationId;
503
669
  if (rawCorrelationId) {
504
670
  try {
@@ -508,31 +674,42 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
508
674
  this.logger.warn(`Invalid correlationId in message: ${error.message}`);
509
675
  }
510
676
  }
677
+ const processAfter = headers['x-process-after'];
678
+ if (processAfter && parseInt(String(processAfter), 10) > Date.now()) {
679
+ const delay = parseInt(String(processAfter), 10) - Date.now();
680
+ const channelGeneration = (_c = this.channelGenerations.get(queueName)) !== null && _c !== void 0 ? _c : 0;
681
+ const outcome = this.scheduleDelayedDelivery(queueName, job, delay, msg, headers, channel, channelGeneration);
682
+ if (outcome === 'scheduled') {
683
+ this.logger.debug(`Delayed batch job scheduled locally: ${job.id}, delay: ${delay}ms`);
684
+ return;
685
+ }
686
+ if (outcome === 'requeue') {
687
+ try {
688
+ channel.nack(msg, false, true);
689
+ }
690
+ catch (nackError) {
691
+ this.logger.error(`Failed to requeue delayed batch job ${job.id} during shutdown: ${(_d = nackError === null || nackError === void 0 ? void 0 : nackError.message) !== null && _d !== void 0 ? _d : String(nackError)}`);
692
+ }
693
+ return;
694
+ }
695
+ }
511
696
  if (idempotencyStore) {
512
697
  const idempotencyKey = this.getIdempotencyKey(job, headers);
513
698
  const canProcess = await idempotencyStore.markProcessing(idempotencyKey, lockTtl);
514
699
  if (!canProcess) {
515
- channel.ack(msg);
516
- this.logger.debug(`Job ${job.id} skipped (idempotency check)`);
517
- return;
518
- }
519
- }
520
- const processAfter = headers['x-process-after'];
521
- if (processAfter && parseInt(String(processAfter)) > Date.now()) {
522
- const delay = parseInt(String(processAfter)) - Date.now();
523
- const scheduled = this.delayedScheduler.schedule(queueName, job, delay);
524
- if (scheduled) {
525
- if (idempotencyStore) {
526
- const idempotencyKey = this.getIdempotencyKey(job, headers);
527
- await idempotencyStore.releaseLock(idempotencyKey);
700
+ if (await idempotencyStore.isProcessed(idempotencyKey)) {
701
+ channel.ack(msg);
702
+ this.logger.debug(`Completed duplicate ${job.id} acknowledged (idempotency key: ${idempotencyKey})`);
703
+ }
704
+ else {
705
+ channel.nack(msg, false, true);
706
+ this.logger.debug(`Active duplicate ${job.id} requeued (idempotency key: ${idempotencyKey})`);
528
707
  }
529
- channel.ack(msg);
530
- this.logger.debug(`Delayed batch job scheduled locally: ${job.id}, delay: ${delay}ms`);
531
708
  return;
532
709
  }
533
710
  }
534
711
  const currentAccumulator = this.batchAccumulators.get(accumulatorKey) || [];
535
- currentAccumulator.push({ job, msg });
712
+ currentAccumulator.push({ job, msg, headers, idempotencyKey: this.getIdempotencyKey(job, headers) });
536
713
  if (currentAccumulator.length >= batchSize) {
537
714
  await processBatchFn();
538
715
  }
@@ -551,6 +728,12 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
551
728
  this.logger.log(`Batch consumer started for queue: ${queueName} (batchSize: ${batchSize})`);
552
729
  }
553
730
  async addBatch(queueName, jobs, batchId) {
731
+ var _a;
732
+ for (const j of jobs) {
733
+ (0, validation_1.validateJobData)(j.data);
734
+ if ((_a = j.opts) === null || _a === void 0 ? void 0 : _a.jobId)
735
+ (0, validation_1.validateJobId)(j.opts.jobId);
736
+ }
554
737
  const channel = await this.getChannel(queueName);
555
738
  const createdJobs = jobs.map((j) => {
556
739
  var _a, _b;
@@ -591,15 +774,15 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
591
774
  this.logger.debug(`${createdJobs.length} jobs added to batch queue ${queueName}${batchId ? ` (batch: ${batchId})` : ''}`);
592
775
  return createdJobs;
593
776
  }
594
- async getJob(queueName, jobId) {
777
+ async getJob(_queueName, _jobId) {
595
778
  this.logger.warn('getJob is not efficiently supported in RabbitMQ. Consider using a separate state store.');
596
779
  return null;
597
780
  }
598
- async getJobs(queueName, status, start = 0, end = 100) {
781
+ async getJobs(queueName, status, _start = 0, _end = 100) {
599
782
  this.logger.warn('getJobs is not efficiently supported in RabbitMQ. Consider using a separate state store.');
600
783
  return [];
601
784
  }
602
- async removeJob(queueName, jobId) {
785
+ async removeJob(_queueName, _jobId) {
603
786
  this.logger.warn('removeJob is not supported in RabbitMQ. Messages cannot be selectively deleted.');
604
787
  }
605
788
  async pause(queueName) {
@@ -664,6 +847,7 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
664
847
  var _a, _b, _c, _d, _e, _f;
665
848
  const timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : 30000;
666
849
  const force = (_b = options.force) !== null && _b !== void 0 ? _b : false;
850
+ const deadline = Date.now() + timeout;
667
851
  this.isShuttingDown = true;
668
852
  this.logger.log(`Closing RabbitMQ connections (timeout: ${timeout}ms, force: ${force})...`);
669
853
  for (const timer of this.batchTimers.values()) {
@@ -672,19 +856,20 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
672
856
  this.batchTimers.clear();
673
857
  this.batchAccumulators.clear();
674
858
  try {
675
- await this.delayedScheduler.shutdown({ executeImmediately: !force });
859
+ await (0, errors_1.withTimeout)(this.delayedScheduler.shutdown({ executeImmediately: !force }), Math.max(1, deadline - Date.now()), 'Delayed scheduler shutdown');
676
860
  this.logger.debug('Delayed scheduler shutdown complete');
677
861
  }
678
862
  catch (error) {
679
863
  this.logger.warn(`Failed to shutdown delayed scheduler: ${error.message}`);
680
864
  }
865
+ this.delayedDeliveries.clear();
681
866
  for (const [name, channel] of this.channels) {
682
867
  try {
683
868
  if (force) {
684
869
  await channel.close();
685
870
  }
686
871
  else {
687
- await (0, errors_1.withTimeout)(channel.close(), timeout / 2, `Channel ${name} close`);
872
+ await (0, errors_1.withTimeout)(channel.close(), Math.max(1, (deadline - Date.now()) / 2), `Channel ${name} close`);
688
873
  }
689
874
  this.logger.debug(`Channel closed: ${name}`);
690
875
  }
@@ -693,7 +878,10 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
693
878
  }
694
879
  }
695
880
  this.channels.clear();
881
+ this.channelGenerations.clear();
696
882
  this.consumerTags.clear();
883
+ this.registry.clear();
884
+ this.consumerConcurrency.clear();
697
885
  this.eventListeners.clear();
698
886
  if (this.connection) {
699
887
  try {
@@ -701,7 +889,7 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
701
889
  await this.connection.close();
702
890
  }
703
891
  else {
704
- await (0, errors_1.withTimeout)(this.connection.close(), timeout / 2, 'Connection close');
892
+ await (0, errors_1.withTimeout)(this.connection.close(), Math.max(1, (deadline - Date.now()) / 2), 'Connection close');
705
893
  }
706
894
  this.logger.log('All RabbitMQ connections closed');
707
895
  }