@nathapp/nestjs-queue 4.0.1 → 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 (33) 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/interface/queue-options.interface.d.ts +1 -0
  5. package/dist/provider/bullmq/bullmq.provider.d.ts +2 -0
  6. package/dist/provider/bullmq/bullmq.provider.js +108 -58
  7. package/dist/provider/bullmq/bullmq.provider.js.map +1 -1
  8. package/dist/provider/kafka/kafka.provider.d.ts +14 -4
  9. package/dist/provider/kafka/kafka.provider.js +584 -251
  10. package/dist/provider/kafka/kafka.provider.js.map +1 -1
  11. package/dist/provider/rabbitmq/rabbitmq.provider.d.ts +18 -3
  12. package/dist/provider/rabbitmq/rabbitmq.provider.js +442 -251
  13. package/dist/provider/rabbitmq/rabbitmq.provider.js.map +1 -1
  14. package/dist/service/queue.service.d.ts +1 -1
  15. package/dist/utils/batch-result.d.ts +3 -0
  16. package/dist/utils/batch-result.js +42 -0
  17. package/dist/utils/batch-result.js.map +1 -0
  18. package/dist/utils/delayed-scheduler.d.ts +5 -1
  19. package/dist/utils/delayed-scheduler.js +49 -18
  20. package/dist/utils/delayed-scheduler.js.map +1 -1
  21. package/dist/utils/errors.d.ts +3 -3
  22. package/dist/utils/named-processor-registry.d.ts +10 -0
  23. package/dist/utils/named-processor-registry.js +45 -0
  24. package/dist/utils/named-processor-registry.js.map +1 -0
  25. package/dist/utils/redis-idempotency-store.d.ts +4 -0
  26. package/dist/utils/redis-idempotency-store.js +55 -9
  27. package/dist/utils/redis-idempotency-store.js.map +1 -1
  28. package/dist/utils/sanitize.js +21 -9
  29. package/dist/utils/sanitize.js.map +1 -1
  30. package/dist/utils/validation.js +0 -2
  31. package/dist/utils/validation.js.map +1 -1
  32. package/package.json +5 -4
  33. package/tsconfig.test.json +16 -0
@@ -10,6 +10,9 @@ const sanitize_1 = require("../../utils/sanitize");
10
10
  const delayed_scheduler_1 = require("../../utils/delayed-scheduler");
11
11
  const lock_renewal_1 = require("../../utils/lock-renewal");
12
12
  const uuid_1 = require("uuid");
13
+ const batch_result_1 = require("../../utils/batch-result");
14
+ const validation_1 = require("../../utils/validation");
15
+ const named_processor_registry_1 = require("../../utils/named-processor-registry");
13
16
  let _kafkajs = null;
14
17
  async function getKafkaJS() {
15
18
  if (!_kafkajs) {
@@ -28,12 +31,17 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
28
31
  this.admin = null;
29
32
  this.consumers = new Map();
30
33
  this.eventListeners = new Map();
34
+ this.registry = new named_processor_registry_1.NamedProcessorRegistry();
35
+ this.consumerConcurrency = new Map();
31
36
  this.isProducerConnected = false;
32
37
  this.isAdminConnected = false;
33
38
  this.verifiedTopics = new Set();
34
39
  this.processedDelayedJobs = new Map();
35
40
  this.DELAYED_JOB_TTL_MS = 3600000;
36
41
  this.cleanupTimer = null;
42
+ this.pendingDelayeds = new Map();
43
+ this.partitionOffsets = new Map();
44
+ this.activeLockTimers = new Map();
37
45
  this.isShuttingDown = false;
38
46
  this.type = provider_enum_1.QueueProviderType.KAFKA;
39
47
  this.metrics = options.metrics;
@@ -189,7 +197,10 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
189
197
  }
190
198
  }
191
199
  async add(queueName, jobName, data, opts) {
192
- var _a, _b;
200
+ var _a;
201
+ (0, validation_1.validateJobData)(data);
202
+ if (opts === null || opts === void 0 ? void 0 : opts.jobId)
203
+ (0, validation_1.validateJobId)(opts.jobId);
193
204
  await this.ensureTopicExists(queueName);
194
205
  const producer = await this.ensureProducer();
195
206
  const sanitizedCorrelationId = (0, errors_1.sanitizeCorrelationId)(opts === null || opts === void 0 ? void 0 : opts.correlationId);
@@ -202,26 +213,7 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
202
213
  attemptsMade: 0,
203
214
  correlationId: sanitizedCorrelationId,
204
215
  };
205
- const headers = {
206
- 'x-job-name': jobName,
207
- 'x-job-id': job.id,
208
- '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,
209
- 'x-attempts': '0',
210
- 'x-max-attempts': String((opts === null || opts === void 0 ? void 0 : opts.attempts) || 1),
211
- };
212
- if (sanitizedCorrelationId) {
213
- headers['x-correlation-id'] = sanitizedCorrelationId;
214
- }
215
- if (opts === null || opts === void 0 ? void 0 : opts.headers) {
216
- Object.assign(headers, opts.headers);
217
- }
218
- if (opts === null || opts === void 0 ? void 0 : opts.delay) {
219
- headers['x-delay'] = String(opts.delay);
220
- headers['x-process-after'] = String(Date.now() + opts.delay);
221
- }
222
- if ((opts === null || opts === void 0 ? void 0 : opts.priority) !== undefined) {
223
- headers['x-priority'] = String(opts.priority);
224
- }
216
+ const headers = this.buildMessageHeaders(job);
225
217
  await producer.send({
226
218
  topic: queueName,
227
219
  messages: [{
@@ -231,13 +223,19 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
231
223
  }],
232
224
  });
233
225
  this.logger.debug(`Job added: ${jobName} (${job.id}) to topic ${queueName}`);
234
- (_b = this.metrics) === null || _b === void 0 ? void 0 : _b.jobAdded(queueName, jobName, job.id, {
226
+ (_a = this.metrics) === null || _a === void 0 ? void 0 : _a.jobAdded(queueName, jobName, job.id, {
235
227
  delay: opts === null || opts === void 0 ? void 0 : opts.delay,
236
228
  priority: opts === null || opts === void 0 ? void 0 : opts.priority,
237
229
  });
238
230
  return job;
239
231
  }
240
232
  async addBulk(queueName, jobs) {
233
+ var _a;
234
+ for (const j of jobs) {
235
+ (0, validation_1.validateJobData)(j.data);
236
+ if ((_a = j.opts) === null || _a === void 0 ? void 0 : _a.jobId)
237
+ (0, validation_1.validateJobId)(j.opts.jobId);
238
+ }
241
239
  await this.ensureTopicExists(queueName);
242
240
  const producer = await this.ensureProducer();
243
241
  const createdJobs = jobs.map((j) => {
@@ -252,23 +250,11 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
252
250
  correlationId: (0, errors_1.sanitizeCorrelationId)((_b = j.opts) === null || _b === void 0 ? void 0 : _b.correlationId),
253
251
  });
254
252
  });
255
- const messages = createdJobs.map((job) => {
256
- var _a, _b;
257
- const headers = {
258
- 'x-job-name': job.name,
259
- 'x-job-id': job.id,
260
- 'x-attempts': '0',
261
- 'x-max-attempts': String(((_a = job.opts) === null || _a === void 0 ? void 0 : _a.attempts) || 1),
262
- };
263
- if ((_b = job.opts) === null || _b === void 0 ? void 0 : _b.correlationId) {
264
- headers['x-correlation-id'] = job.opts.correlationId;
265
- }
266
- return {
267
- key: job.id,
268
- value: JSON.stringify(job),
269
- headers,
270
- };
271
- });
253
+ const messages = createdJobs.map((job) => ({
254
+ key: job.id,
255
+ value: JSON.stringify(job),
256
+ headers: this.buildMessageHeaders(job),
257
+ }));
272
258
  await producer.send({
273
259
  topic: queueName,
274
260
  messages,
@@ -276,153 +262,200 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
276
262
  this.logger.debug(`${createdJobs.length} jobs added to topic ${queueName}`);
277
263
  return createdJobs;
278
264
  }
265
+ buildMessageHeaders(job) {
266
+ var _a, _b;
267
+ const opts = job.opts;
268
+ return {
269
+ 'x-job-name': job.name,
270
+ 'x-job-id': job.id,
271
+ '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,
272
+ 'x-attempts': '0',
273
+ 'x-max-attempts': String((opts === null || opts === void 0 ? void 0 : opts.attempts) || 1),
274
+ ...(job.correlationId ? { 'x-correlation-id': job.correlationId } : {}),
275
+ ...((_b = opts === null || opts === void 0 ? void 0 : opts.headers) !== null && _b !== void 0 ? _b : {}),
276
+ ...((opts === null || opts === void 0 ? void 0 : opts.delay)
277
+ ? { 'x-delay': String(opts.delay), 'x-process-after': String(Date.now() + opts.delay) }
278
+ : {}),
279
+ ...((opts === null || opts === void 0 ? void 0 : opts.priority) !== undefined ? { 'x-priority': String(opts.priority) } : {}),
280
+ };
281
+ }
279
282
  async process(queueName, processor, options) {
280
- var _a, _b, _c, _d, _e;
281
- const consumerKey = (options === null || options === void 0 ? void 0 : options.name) ? `${queueName}:${options.name}` : queueName;
282
- if (this.consumers.has(consumerKey)) {
283
+ var _a;
284
+ const status = this.registry.register(queueName, options === null || options === void 0 ? void 0 : options.name, processor);
285
+ if (status === 'duplicate') {
286
+ const consumerKey = (options === null || options === void 0 ? void 0 : options.name) ? `${queueName}:${options.name}` : queueName;
283
287
  this.logger.warn(`Consumer already exists for ${consumerKey}`);
284
288
  return false;
285
289
  }
286
- await this.ensureTopicExists(queueName);
287
- const kafka = await this.getKafka();
288
- const groupId = `${this.options.groupId}-${queueName}`;
289
- const consumer = kafka.consumer({
290
- groupId,
291
- sessionTimeout: this.options.sessionTimeout || 30000,
292
- heartbeatInterval: this.options.heartbeatInterval || 3000,
293
- maxWaitTimeInMs: 100,
294
- retry: { retries: 5 },
295
- });
296
- await consumer.connect();
297
- await consumer.subscribe({ topic: queueName, fromBeginning: false });
298
- const idempotencyStore = (_a = this.options.idempotency) === null || _a === void 0 ? void 0 : _a.store;
299
- const lockTtl = (_c = (_b = this.options.idempotency) === null || _b === void 0 ? void 0 : _b.lockTtl) !== null && _c !== void 0 ? _c : 60000;
300
- const completedTtl = (_e = (_d = this.options.idempotency) === null || _d === void 0 ? void 0 : _d.completedTtl) !== null && _e !== void 0 ? _e : 3600000;
301
- this.consumers.set(consumerKey, consumer);
302
- await consumer.run({
303
- partitionsConsumedConcurrently: (options === null || options === void 0 ? void 0 : options.concurrency) || 1,
304
- eachMessage: async ({ message, partition, heartbeat }) => {
305
- var _a, _b, _c, _d, _e, _f, _g;
306
- if (!message.value)
307
- return;
308
- let job;
309
- try {
310
- const parsed = JSON.parse(message.value.toString());
311
- (0, errors_1.validateJobStructure)(parsed);
312
- job = parsed;
313
- }
314
- catch (error) {
315
- this.logger.error(`Failed to parse or validate job message: ${error.message}`);
316
- return;
317
- }
318
- const headers = {};
319
- if (message.headers) {
320
- for (const [key, value] of Object.entries(message.headers)) {
321
- headers[key] = (value === null || value === void 0 ? void 0 : value.toString()) || '';
322
- }
323
- }
324
- const rawCorrelationId = headers['x-correlation-id'];
325
- if (rawCorrelationId) {
290
+ if (status === 'added') {
291
+ const requestedConcurrency = (options === null || options === void 0 ? void 0 : options.concurrency) || 1;
292
+ const existingConcurrency = (_a = this.consumerConcurrency.get(queueName)) !== null && _a !== void 0 ? _a : 1;
293
+ if (requestedConcurrency !== existingConcurrency) {
294
+ this.logger.debug(`Consumer for topic ${queueName} already exists with concurrency ${existingConcurrency}; ` +
295
+ `ignoring requested concurrency ${requestedConcurrency} for named processor "${options === null || options === void 0 ? void 0 : options.name}".`);
296
+ }
297
+ return true;
298
+ }
299
+ let consumer;
300
+ try {
301
+ await this.ensureTopicExists(queueName);
302
+ const kafka = await this.getKafka();
303
+ const groupId = `${this.options.groupId}-${queueName}`;
304
+ consumer = kafka.consumer({
305
+ groupId,
306
+ sessionTimeout: this.options.sessionTimeout || 30000,
307
+ heartbeatInterval: this.options.heartbeatInterval || 3000,
308
+ maxWaitTimeInMs: 100,
309
+ retry: { retries: 5 },
310
+ });
311
+ await consumer.connect();
312
+ await consumer.subscribe({ topic: queueName, fromBeginning: false });
313
+ this.consumers.set(queueName, consumer);
314
+ this.consumerConcurrency.set(queueName, (options === null || options === void 0 ? void 0 : options.concurrency) || 1);
315
+ await consumer.run({
316
+ partitionsConsumedConcurrently: (options === null || options === void 0 ? void 0 : options.concurrency) || 1,
317
+ eachMessage: async ({ message, partition, heartbeat }) => {
318
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
319
+ if (!message.value)
320
+ return;
321
+ let job;
326
322
  try {
327
- job.correlationId = (0, errors_1.sanitizeCorrelationId)(rawCorrelationId);
323
+ const parsed = JSON.parse(message.value.toString());
324
+ (0, errors_1.validateJobStructure)(parsed);
325
+ job = parsed;
328
326
  }
329
327
  catch (error) {
330
- this.logger.warn(`Invalid correlationId in message: ${error.message}`);
331
- }
332
- }
333
- if ((options === null || options === void 0 ? void 0 : options.name) && job.name !== options.name) {
334
- return;
335
- }
336
- const idempotencyKey = idempotencyStore ? this.getIdempotencyKey(job, headers) : job.id;
337
- if (idempotencyStore) {
338
- const canProcess = await idempotencyStore.markProcessing(idempotencyKey, lockTtl);
339
- if (!canProcess) {
340
- this.logger.debug(`Job ${job.id} skipped (idempotency check, original ID: ${idempotencyKey})`);
328
+ this.logger.error(`Failed to parse or validate job message: ${error.message}`);
341
329
  return;
342
330
  }
343
- }
344
- const processAfter = headers['x-process-after'];
345
- if (processAfter && parseInt(processAfter) > Date.now()) {
346
- const delay = parseInt(processAfter) - Date.now();
347
- if (idempotencyStore) {
348
- await idempotencyStore.releaseLock(idempotencyKey);
331
+ const headers = {};
332
+ if (message.headers) {
333
+ for (const [key, value] of Object.entries(message.headers)) {
334
+ headers[key] = (value === null || value === void 0 ? void 0 : value.toString()) || '';
335
+ }
349
336
  }
350
- const delayKey = `${queueName}-${partition}-${message.offset}`;
351
- if (this.processedDelayedJobs.has(delayKey)) {
352
- return;
337
+ const idempotencyStore = (_a = this.options.idempotency) === null || _a === void 0 ? void 0 : _a.store;
338
+ const lockTtl = (_c = (_b = this.options.idempotency) === null || _b === void 0 ? void 0 : _b.lockTtl) !== null && _c !== void 0 ? _c : 60000;
339
+ const completedTtl = (_e = (_d = this.options.idempotency) === null || _d === void 0 ? void 0 : _d.completedTtl) !== null && _e !== void 0 ? _e : 3600000;
340
+ const rawCorrelationId = headers['x-correlation-id'];
341
+ if (rawCorrelationId) {
342
+ try {
343
+ job.correlationId = (0, errors_1.sanitizeCorrelationId)(rawCorrelationId);
344
+ }
345
+ catch (error) {
346
+ this.logger.warn(`Invalid correlationId in message: ${error.message}`);
347
+ }
353
348
  }
354
- const scheduled = this.delayedScheduler.schedule(queueName, job, delay);
355
- if (scheduled) {
356
- this.processedDelayedJobs.set(delayKey, Date.now());
357
- this.logger.debug(`Delayed job scheduled locally: ${job.id}, delay: ${delay}ms`);
349
+ const handler = this.registry.resolve(queueName, job.name);
350
+ if (!handler) {
351
+ this.logger.warn(`No handler for job "${job.name}" on topic "${queueName}"`);
358
352
  return;
359
353
  }
360
- }
361
- const maxAttempts = parseInt(((_b = (_a = message.headers) === null || _a === void 0 ? void 0 : _a['x-max-attempts']) === null || _b === void 0 ? void 0 : _b.toString()) || '1');
362
- let lockRenewal;
363
- if (idempotencyStore) {
364
- lockRenewal = new lock_renewal_1.LockRenewal(idempotencyStore, idempotencyKey, lockTtl, Math.floor(lockTtl / 2));
365
- lockRenewal.start();
366
- }
367
- try {
368
- this.emitEvent(queueName, queue_event_enum_1.QueueEvent.ACTIVE, job);
369
- (_c = this.metrics) === null || _c === void 0 ? void 0 : _c.jobStarted(queueName, job.name, job.id);
370
- const startTime = Date.now();
371
- const result = await processor(job);
372
- job.returnvalue = result;
354
+ const idempotencyKey = idempotencyStore ? this.getIdempotencyKey(job, headers) : job.id;
373
355
  if (idempotencyStore) {
374
- await idempotencyStore.markComplete(idempotencyKey, completedTtl);
356
+ const canProcess = await idempotencyStore.markProcessing(idempotencyKey, lockTtl);
357
+ if (!canProcess) {
358
+ this.logger.debug(`Job ${job.id} skipped (idempotency check, original ID: ${idempotencyKey})`);
359
+ return;
360
+ }
375
361
  }
376
- const duration = Date.now() - startTime;
377
- (_d = this.metrics) === null || _d === void 0 ? void 0 : _d.jobCompleted(queueName, job.name, job.id, duration);
378
- this.emitEvent(queueName, queue_event_enum_1.QueueEvent.COMPLETED, job, result);
379
- this.logger.debug(`Job completed: ${job.name} (${job.id})`);
380
- }
381
- catch (error) {
382
- const currentAttempts = job.attemptsMade + 1;
383
- job.failedReason = (0, sanitize_1.sanitizeErrorMessage)(error instanceof Error ? error.message : String(error));
384
- (_e = this.metrics) === null || _e === void 0 ? void 0 : _e.jobFailed(queueName, job.name, job.id, job.failedReason, currentAttempts);
362
+ const processAfter = headers['x-process-after'];
363
+ if (processAfter && parseInt(processAfter) > Date.now()) {
364
+ const delay = parseInt(processAfter) - Date.now();
365
+ if (idempotencyStore) {
366
+ await idempotencyStore.releaseLock(idempotencyKey);
367
+ }
368
+ const delayKey = `${queueName}-${partition}-${message.offset}`;
369
+ if (this.processedDelayedJobs.has(delayKey)) {
370
+ return;
371
+ }
372
+ const scheduled = this.delayedScheduler.schedule(queueName, job, delay);
373
+ if (scheduled) {
374
+ this.processedDelayedJobs.set(delayKey, Date.now());
375
+ this.logger.debug(`Delayed job scheduled locally: ${job.id}, delay: ${delay}ms`);
376
+ return;
377
+ }
378
+ }
379
+ const maxAttempts = parseInt(((_g = (_f = message.headers) === null || _f === void 0 ? void 0 : _f['x-max-attempts']) === null || _g === void 0 ? void 0 : _g.toString()) || '1');
380
+ let lockRenewal;
385
381
  if (idempotencyStore) {
386
- await idempotencyStore.releaseLock(idempotencyKey);
382
+ lockRenewal = new lock_renewal_1.LockRenewal(idempotencyStore, idempotencyKey, lockTtl, Math.floor(lockTtl / 2));
383
+ lockRenewal.start();
387
384
  }
388
- if (currentAttempts < maxAttempts) {
389
- const delay = this.calculateBackoff(job);
390
- (_f = this.metrics) === null || _f === void 0 ? void 0 : _f.jobRetried(queueName, job.name, job.id, currentAttempts, delay);
391
- await this.add(queueName, job.name, job.data, {
392
- ...job.opts,
393
- delay,
394
- jobId: `${idempotencyKey}-retry-${currentAttempts}`,
395
- correlationId: job.correlationId,
396
- headers: {
397
- ...(_g = job.opts) === null || _g === void 0 ? void 0 : _g.headers,
398
- 'x-original-job-id': idempotencyKey,
399
- 'x-retry-count': String(currentAttempts),
400
- },
401
- });
402
- this.logger.debug(`Job retry scheduled: ${job.name} (${job.id}), attempt ${currentAttempts}/${maxAttempts}`);
385
+ try {
386
+ this.emitEvent(queueName, queue_event_enum_1.QueueEvent.ACTIVE, job);
387
+ (_h = this.metrics) === null || _h === void 0 ? void 0 : _h.jobStarted(queueName, job.name, job.id);
388
+ const startTime = Date.now();
389
+ const result = await handler(job);
390
+ job.returnvalue = result;
391
+ if (idempotencyStore) {
392
+ await idempotencyStore.markComplete(idempotencyKey, completedTtl);
393
+ }
394
+ const duration = Date.now() - startTime;
395
+ (_j = this.metrics) === null || _j === void 0 ? void 0 : _j.jobCompleted(queueName, job.name, job.id, duration);
396
+ this.emitEvent(queueName, queue_event_enum_1.QueueEvent.COMPLETED, job, result);
397
+ this.logger.debug(`Job completed: ${job.name} (${job.id})`);
403
398
  }
404
- else {
405
- if (this.options.enableDLQ) {
406
- await this.sendToDLQ(queueName, job, error);
399
+ catch (error) {
400
+ const currentAttempts = job.attemptsMade + 1;
401
+ job.failedReason = (0, sanitize_1.sanitizeErrorMessage)(error instanceof Error ? error.message : String(error));
402
+ (_k = this.metrics) === null || _k === void 0 ? void 0 : _k.jobFailed(queueName, job.name, job.id, job.failedReason, currentAttempts);
403
+ if (idempotencyStore) {
404
+ await idempotencyStore.releaseLock(idempotencyKey);
405
+ }
406
+ if (currentAttempts < maxAttempts) {
407
+ const delay = this.calculateBackoff(job);
408
+ (_l = this.metrics) === null || _l === void 0 ? void 0 : _l.jobRetried(queueName, job.name, job.id, currentAttempts, delay);
409
+ await this.add(queueName, job.name, job.data, {
410
+ ...job.opts,
411
+ delay,
412
+ jobId: `${idempotencyKey}-retry-${currentAttempts}`,
413
+ correlationId: job.correlationId,
414
+ headers: {
415
+ ...(_m = job.opts) === null || _m === void 0 ? void 0 : _m.headers,
416
+ 'x-original-job-id': idempotencyKey,
417
+ 'x-retry-count': String(currentAttempts),
418
+ },
419
+ });
420
+ this.logger.debug(`Job retry scheduled: ${job.name} (${job.id}), attempt ${currentAttempts}/${maxAttempts}`);
421
+ }
422
+ else {
423
+ if (this.options.enableDLQ) {
424
+ await this.sendToDLQ(queueName, job, error);
425
+ }
426
+ this.emitEvent(queueName, queue_event_enum_1.QueueEvent.FAILED, job, new Error(job.failedReason));
427
+ this.logger.error(`Job failed: ${job.name} (${job.id}): ${job.failedReason}`);
407
428
  }
408
- this.emitEvent(queueName, queue_event_enum_1.QueueEvent.FAILED, job, new Error(job.failedReason));
409
- this.logger.error(`Job failed: ${job.name} (${job.id}): ${job.failedReason}`);
410
429
  }
411
- }
412
- finally {
413
- if (lockRenewal) {
414
- lockRenewal.stop();
430
+ finally {
431
+ if (lockRenewal) {
432
+ lockRenewal.stop();
433
+ }
415
434
  }
435
+ await heartbeat();
436
+ },
437
+ });
438
+ this.logger.log(`Consumer started for topic: ${queueName}${(options === null || options === void 0 ? void 0 : options.name) ? ` (${options.name})` : ''} in group ${groupId}`);
439
+ return true;
440
+ }
441
+ catch (error) {
442
+ this.consumers.delete(queueName);
443
+ this.consumerConcurrency.delete(queueName);
444
+ this.registry.removeQueue(queueName);
445
+ if (consumer) {
446
+ try {
447
+ await consumer.disconnect();
416
448
  }
417
- await heartbeat();
418
- },
419
- });
420
- this.logger.log(`Consumer started for topic: ${queueName}${(options === null || options === void 0 ? void 0 : options.name) ? ` (${options.name})` : ''} in group ${groupId}`);
421
- return true;
449
+ catch (disconnectError) {
450
+ this.logger.warn(`Failed to disconnect consumer during registration rollback: ${disconnectError.message}`);
451
+ }
452
+ }
453
+ throw error;
454
+ }
422
455
  }
423
456
  async processBatch(queueName, processor, options) {
424
- var _a, _b, _c, _d, _e;
425
- const { batchSize = 10 } = options || {};
457
+ var _a;
458
+ const { batchSize = 10, continueOnError = true, retryFailedIndividually = false, } = options || {};
426
459
  const consumerKey = `${queueName}:batch`;
427
460
  if (this.consumers.has(consumerKey)) {
428
461
  throw new errors_1.QueueError(`Batch consumer already exists for ${queueName}. Cannot register duplicate batch processor.`, 'WORKER_EXISTS', queueName);
@@ -439,118 +472,402 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
439
472
  });
440
473
  await consumer.connect();
441
474
  await consumer.subscribe({ topic: queueName, fromBeginning: false });
442
- const idempotencyStore = (_a = this.options.idempotency) === null || _a === void 0 ? void 0 : _a.store;
443
- const lockTtl = (_c = (_b = this.options.idempotency) === null || _b === void 0 ? void 0 : _b.lockTtl) !== null && _c !== void 0 ? _c : 60000;
444
- const completedTtl = (_e = (_d = this.options.idempotency) === null || _d === void 0 ? void 0 : _d.completedTtl) !== null && _e !== void 0 ? _e : 3600000;
445
475
  this.consumers.set(consumerKey, consumer);
446
- await consumer.run({
447
- eachBatch: async ({ batch, resolveOffset, heartbeat, commitOffsetsIfNecessary, }) => {
476
+ const delayedCommitMode = (_a = this.options.delayedOffsetCommit) !== null && _a !== void 0 ? _a : 'onExecute';
477
+ const deferDelayedCommits = delayedCommitMode === 'onExecute';
478
+ const runOptions = {
479
+ eachBatch: async ({ batch, resolveOffset, heartbeat, commitOffsetsIfNecessary, isStale }) => {
480
+ var _a, _b;
448
481
  const partition = batch.partition;
449
- const jobs = [];
450
- const messages = [];
482
+ const partitionKey = `${queueName}-${partition}`;
483
+ const offsetEntries = this.partitionOffsets.get(partitionKey) || [];
484
+ this.partitionOffsets.set(partitionKey, offsetEntries);
485
+ const registerOffset = (offset) => {
486
+ let entry = offsetEntries.find((candidate) => candidate.offset === offset);
487
+ if (!entry) {
488
+ entry = {
489
+ topic: queueName,
490
+ partition,
491
+ offset,
492
+ settled: false,
493
+ resolved: false,
494
+ resolveOffset,
495
+ commitOffsetsIfNecessary,
496
+ isStale,
497
+ };
498
+ const insertAt = offsetEntries.findIndex((candidate) => BigInt(candidate.offset) > BigInt(offset));
499
+ if (insertAt < 0)
500
+ offsetEntries.push(entry);
501
+ else
502
+ offsetEntries.splice(insertAt, 0, entry);
503
+ }
504
+ else {
505
+ entry.resolveOffset = resolveOffset;
506
+ entry.commitOffsetsIfNecessary = commitOffsetsIfNecessary;
507
+ entry.isStale = isStale;
508
+ entry.resolved = false;
509
+ }
510
+ return entry;
511
+ };
512
+ let chunk = [];
513
+ let stopBatch = false;
514
+ const settleFailure = async (entry, error) => {
515
+ var _a, _b, _c, _d, _e, _f, _g, _h;
516
+ const { job, headers, idempotencyKey } = entry;
517
+ const attempts = (Number.parseInt(String((_b = (_a = headers['x-attempts']) !== null && _a !== void 0 ? _a : job.attemptsMade) !== null && _b !== void 0 ? _b : 0), 10) || 0) + 1;
518
+ 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;
519
+ job.attemptsMade = attempts;
520
+ job.failedReason = (0, sanitize_1.sanitizeErrorMessage)(error.message);
521
+ (_f = this.metrics) === null || _f === void 0 ? void 0 : _f.jobFailed(queueName, job.name, job.id, job.failedReason, attempts);
522
+ if (retryFailedIndividually && attempts < maxAttempts) {
523
+ const delay = this.calculateBackoff(job);
524
+ (_g = this.metrics) === null || _g === void 0 ? void 0 : _g.jobRetried(queueName, job.name, job.id, attempts, delay);
525
+ await this.add(queueName, job.name, job.data, {
526
+ ...job.opts,
527
+ attempts: maxAttempts,
528
+ delay,
529
+ jobId: `${idempotencyKey}-retry-${attempts}`,
530
+ correlationId: job.correlationId,
531
+ headers: {
532
+ ...(_h = job.opts) === null || _h === void 0 ? void 0 : _h.headers,
533
+ ...headers,
534
+ 'x-original-job-id': idempotencyKey,
535
+ 'x-attempts': String(attempts),
536
+ 'x-max-attempts': String(maxAttempts),
537
+ 'x-retry-count': String(attempts),
538
+ },
539
+ });
540
+ return true;
541
+ }
542
+ if (this.options.enableDLQ) {
543
+ await this.sendToDLQ(queueName, job, error);
544
+ this.emitEvent(queueName, queue_event_enum_1.QueueEvent.FAILED, job, error);
545
+ return true;
546
+ }
547
+ return false;
548
+ };
549
+ const flushChunk = async () => {
550
+ var _a, _b, _c, _d, _e, _f;
551
+ if (chunk.length === 0 || stopBatch)
552
+ return;
553
+ const pending = chunk;
554
+ chunk = [];
555
+ const eligible = [];
556
+ const idempotencyStoreForBatch = (_a = this.options.idempotency) === null || _a === void 0 ? void 0 : _a.store;
557
+ const lockTtlForBatch = (_c = (_b = this.options.idempotency) === null || _b === void 0 ? void 0 : _b.lockTtl) !== null && _c !== void 0 ? _c : 60000;
558
+ if (idempotencyStoreForBatch) {
559
+ for (const entry of pending) {
560
+ const canProcess = await idempotencyStoreForBatch.markProcessing(entry.idempotencyKey, lockTtlForBatch);
561
+ if (canProcess) {
562
+ eligible.push(entry);
563
+ }
564
+ else if (await idempotencyStoreForBatch.isProcessed(entry.idempotencyKey)) {
565
+ entry.offsetEntry.settled = true;
566
+ }
567
+ else {
568
+ this.logger.debug(`Job ${entry.job.id} is held by an active idempotency lock`);
569
+ this.scheduleActiveLockRevisit(consumer, queueName, partition, entry.offsetEntry.offset);
570
+ consumer.pause([{ topic: queueName, partitions: [partition] }]);
571
+ stopBatch = true;
572
+ break;
573
+ }
574
+ }
575
+ }
576
+ else {
577
+ eligible.push(...pending);
578
+ }
579
+ if (eligible.length > 0) {
580
+ let jobResults;
581
+ try {
582
+ const result = await processor(eligible.map((entry) => entry.job), options || {});
583
+ jobResults = (0, batch_result_1.validateBatchResults)(queueName, eligible.map((entry) => entry.job), result);
584
+ }
585
+ catch (error) {
586
+ const failure = error instanceof Error ? error : new Error(String(error));
587
+ for (const entry of eligible) {
588
+ try {
589
+ const handedOff = await settleFailure(entry, failure);
590
+ if (handedOff)
591
+ entry.offsetEntry.settled = true;
592
+ if (idempotencyStoreForBatch)
593
+ await idempotencyStoreForBatch.releaseLock(entry.idempotencyKey);
594
+ if (!handedOff) {
595
+ stopBatch = true;
596
+ break;
597
+ }
598
+ }
599
+ catch (settlementError) {
600
+ this.logger.error(`Failed to hand off batch job ${entry.job.id}: ${settlementError instanceof Error ? settlementError.message : String(settlementError)}`);
601
+ stopBatch = true;
602
+ break;
603
+ }
604
+ }
605
+ const firstUnsettled = eligible.find((entry) => !entry.offsetEntry.settled);
606
+ if (firstUnsettled) {
607
+ this.scheduleActiveLockRevisit(consumer, queueName, partition, firstUnsettled.offsetEntry.offset);
608
+ consumer.pause([{ topic: queueName, partitions: [partition] }]);
609
+ stopBatch = true;
610
+ }
611
+ this.logger.error(`Batch processor failed: ${failure.message}`);
612
+ }
613
+ if (jobResults) {
614
+ for (let index = 0; index < eligible.length; index += 1) {
615
+ const entry = eligible[index];
616
+ const result = jobResults[index];
617
+ try {
618
+ if (result.success) {
619
+ if (idempotencyStoreForBatch) {
620
+ await idempotencyStoreForBatch.markComplete(entry.idempotencyKey, (_e = (_d = this.options.idempotency) === null || _d === void 0 ? void 0 : _d.completedTtl) !== null && _e !== void 0 ? _e : 3600000);
621
+ }
622
+ entry.offsetEntry.settled = true;
623
+ (_f = this.metrics) === null || _f === void 0 ? void 0 : _f.jobCompleted(queueName, entry.job.name, entry.job.id, 0);
624
+ this.emitEvent(queueName, queue_event_enum_1.QueueEvent.COMPLETED, entry.job, result.result);
625
+ }
626
+ else {
627
+ const handedOff = await settleFailure(entry, result.error);
628
+ if (handedOff)
629
+ entry.offsetEntry.settled = true;
630
+ if (idempotencyStoreForBatch)
631
+ await idempotencyStoreForBatch.releaseLock(entry.idempotencyKey);
632
+ if (!handedOff) {
633
+ this.scheduleActiveLockRevisit(consumer, queueName, partition, entry.offsetEntry.offset);
634
+ consumer.pause([{ topic: queueName, partitions: [partition] }]);
635
+ stopBatch = true;
636
+ }
637
+ else if (!continueOnError) {
638
+ for (const remaining of eligible.slice(index + 1)) {
639
+ if (idempotencyStoreForBatch)
640
+ await idempotencyStoreForBatch.releaseLock(remaining.idempotencyKey);
641
+ }
642
+ const firstRemaining = eligible[index + 1];
643
+ if (firstRemaining) {
644
+ this.scheduleActiveLockRevisit(consumer, queueName, partition, firstRemaining.offsetEntry.offset);
645
+ consumer.pause([{ topic: queueName, partitions: [partition] }]);
646
+ }
647
+ stopBatch = true;
648
+ }
649
+ }
650
+ }
651
+ catch (error) {
652
+ const failure = error instanceof Error ? error : new Error(String(error));
653
+ if (idempotencyStoreForBatch) {
654
+ await idempotencyStoreForBatch.releaseLock(entry.idempotencyKey);
655
+ }
656
+ this.logger.error(`Failed to settle batch job ${entry.job.id}: ${failure.message}`);
657
+ this.scheduleActiveLockRevisit(consumer, queueName, partition, entry.offsetEntry.offset);
658
+ consumer.pause([{ topic: queueName, partitions: [partition] }]);
659
+ stopBatch = true;
660
+ }
661
+ if (stopBatch)
662
+ break;
663
+ }
664
+ }
665
+ }
666
+ await heartbeat();
667
+ };
451
668
  for (const message of batch.messages) {
452
- if (!message.value)
669
+ const offsetEntry = registerOffset(message.offset);
670
+ const delayKey = `${queueName}-${partition}-${message.offset}`;
671
+ if (deferDelayedCommits && this.pendingDelayeds.has(delayKey)) {
672
+ consumer.pause([{ topic: queueName, partitions: [partition] }]);
673
+ await heartbeat();
674
+ stopBatch = true;
675
+ break;
676
+ }
677
+ if (!message.value) {
678
+ this.logger.warn(`Skipping empty Kafka message at ${delayKey}`);
679
+ offsetEntry.settled = true;
680
+ await heartbeat();
453
681
  continue;
682
+ }
683
+ let job;
684
+ const headers = {};
454
685
  try {
455
686
  const parsed = JSON.parse(message.value.toString());
456
687
  (0, errors_1.validateJobStructure)(parsed);
457
- const headers = {};
688
+ job = parsed;
458
689
  if (message.headers) {
459
690
  for (const [key, value] of Object.entries(message.headers)) {
460
691
  headers[key] = (value === null || value === void 0 ? void 0 : value.toString()) || '';
461
692
  }
462
693
  }
463
- const rawCorrelationId = headers['x-correlation-id'];
464
- if (rawCorrelationId) {
465
- try {
466
- parsed.correlationId = (0, errors_1.sanitizeCorrelationId)(rawCorrelationId);
467
- }
468
- catch (error) {
469
- this.logger.warn(`Invalid correlationId in message: ${error.message}`);
470
- }
471
- }
472
- const processAfter = headers['x-process-after'];
473
- if (processAfter && parseInt(processAfter) > Date.now()) {
474
- const delay = parseInt(processAfter) - Date.now();
475
- const delayKey = `${queueName}-${partition}-${message.offset}`;
476
- if (this.processedDelayedJobs.has(delayKey)) {
477
- resolveOffset(message.offset);
478
- await heartbeat();
479
- continue;
480
- }
481
- const scheduled = this.delayedScheduler.schedule(queueName, parsed, delay);
482
- if (scheduled) {
483
- this.processedDelayedJobs.set(delayKey, Date.now());
484
- this.logger.debug(`Delayed batch job scheduled locally: ${parsed.id}, delay: ${delay}ms`);
485
- resolveOffset(message.offset);
486
- await commitOffsetsIfNecessary();
487
- await heartbeat();
488
- continue;
489
- }
490
- }
491
- jobs.push(parsed);
492
- messages.push({ message, headers });
493
694
  }
494
695
  catch (error) {
495
- this.logger.error(`Failed to parse job message: ${error.message}`);
696
+ this.logger.error(`Failed to parse job message: ${error instanceof Error ? error.message : String(error)}`);
697
+ offsetEntry.settled = true;
698
+ await heartbeat();
699
+ continue;
496
700
  }
497
- }
498
- for (let i = 0; i < jobs.length; i += batchSize) {
499
- const chunk = jobs.slice(i, i + batchSize);
500
- const chunkMessages = messages.slice(i, i + batchSize);
501
- if (idempotencyStore) {
502
- const filteredChunk = [];
503
- const filteredMessages = [];
504
- for (let j = 0; j < chunk.length; j++) {
505
- const job = chunk[j];
506
- const { headers } = chunkMessages[j];
507
- const idempotencyKey = this.getIdempotencyKey(job, headers);
508
- const canProcess = await idempotencyStore.markProcessing(idempotencyKey, lockTtl);
509
- if (canProcess) {
510
- filteredChunk.push(job);
511
- filteredMessages.push(chunkMessages[j]);
512
- }
513
- else {
514
- this.logger.debug(`Job ${job.id} skipped (idempotency check)`);
515
- }
701
+ const rawCorrelationId = headers['x-correlation-id'];
702
+ if (rawCorrelationId) {
703
+ try {
704
+ job.correlationId = (0, errors_1.sanitizeCorrelationId)(rawCorrelationId);
705
+ }
706
+ catch (error) {
707
+ this.logger.warn(`Invalid correlationId in message: ${error instanceof Error ? error.message : String(error)}`);
516
708
  }
517
- if (filteredChunk.length === 0)
709
+ }
710
+ 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;
711
+ const processAfter = headers['x-process-after'];
712
+ if (processAfter && Number.parseInt(String(processAfter), 10) > Date.now()) {
713
+ const delay = Number.parseInt(String(processAfter), 10) - Date.now();
714
+ if (this.processedDelayedJobs.has(delayKey)) {
715
+ offsetEntry.settled = true;
716
+ await heartbeat();
518
717
  continue;
519
- const startTime = Date.now();
520
- const result = await processor(filteredChunk, options || {});
521
- for (let j = 0; j < filteredChunk.length; j++) {
522
- const job = filteredChunk[j];
523
- const { headers } = filteredMessages[j];
524
- const idempotencyKey = this.getIdempotencyKey(job, headers);
525
- const jobResult = result.results[j];
526
- if (jobResult.success) {
527
- await idempotencyStore.markComplete(idempotencyKey, completedTtl);
718
+ }
719
+ const wasAlreadyScheduled = this.delayedScheduler.isScheduled(job.id);
720
+ const scheduled = this.delayedScheduler.schedule(queueName, job, delay, deferDelayedCommits ? (error) => this.onDelayedJobExecuted(delayKey, error) : undefined);
721
+ if (scheduled) {
722
+ if (deferDelayedCommits && wasAlreadyScheduled) {
723
+ offsetEntry.settled = true;
724
+ }
725
+ else if (deferDelayedCommits) {
726
+ this.pendingDelayeds.set(delayKey, {
727
+ topic: queueName,
728
+ partition,
729
+ offset: message.offset,
730
+ consumerKey,
731
+ resolveOffset,
732
+ commitOffsetsIfNecessary,
733
+ });
734
+ consumer.pause([{ topic: queueName, partitions: [partition] }]);
735
+ await heartbeat();
736
+ await flushChunk();
737
+ stopBatch = true;
738
+ break;
528
739
  }
529
740
  else {
530
- await idempotencyStore.releaseLock(idempotencyKey);
741
+ this.processedDelayedJobs.set(delayKey, Date.now());
742
+ offsetEntry.settled = true;
531
743
  }
744
+ await heartbeat();
745
+ continue;
532
746
  }
533
- const duration = Date.now() - startTime;
534
- this.logger.debug(`Batch chunk processed: ${result.successful}/${result.totalJobs} succeeded in ${duration}ms`);
535
747
  }
536
- else {
537
- const startTime = Date.now();
538
- const result = await processor(chunk, options || {});
539
- const duration = Date.now() - startTime;
540
- this.logger.debug(`Batch chunk processed: ${result.successful}/${result.totalJobs} succeeded in ${duration}ms`);
541
- }
542
- const lastMessage = chunkMessages[chunkMessages.length - 1];
543
- if (lastMessage) {
544
- resolveOffset(lastMessage.message.offset);
545
- await commitOffsetsIfNecessary();
546
- }
547
- await heartbeat();
748
+ chunk.push({
749
+ job,
750
+ headers,
751
+ message,
752
+ offsetEntry,
753
+ idempotencyKey: this.getIdempotencyKey(job, headers),
754
+ });
755
+ if (chunk.length >= batchSize)
756
+ await flushChunk();
757
+ if (stopBatch)
758
+ break;
548
759
  }
760
+ await flushChunk();
761
+ await this.drainPartitionOffsets(partitionKey);
549
762
  },
550
- });
763
+ };
764
+ runOptions.eachBatchAutoResolve = false;
765
+ await consumer.run(runOptions);
551
766
  this.logger.log(`Batch consumer started for topic: ${queueName} (batchSize: ${batchSize})`);
552
767
  }
768
+ async onDelayedJobExecuted(key, error) {
769
+ var _a;
770
+ const pending = this.pendingDelayeds.get(key);
771
+ if (!pending) {
772
+ return;
773
+ }
774
+ this.pendingDelayeds.delete(key);
775
+ if (this.isShuttingDown) {
776
+ return;
777
+ }
778
+ if (error) {
779
+ this.logger.warn(`Failed to re-queue delayed job ${key}: ${error.message}; resuming partition without committing`);
780
+ this.resumePendingDelayedPartition(pending);
781
+ return;
782
+ }
783
+ try {
784
+ const partitionKey = `${pending.topic}-${pending.partition}`;
785
+ const entry = (_a = this.partitionOffsets.get(partitionKey)) === null || _a === void 0 ? void 0 : _a.find((item) => item.offset === pending.offset);
786
+ if (entry)
787
+ entry.settled = true;
788
+ await this.drainPartitionOffsets(partitionKey);
789
+ this.processedDelayedJobs.set(key, Date.now());
790
+ this.logger.debug(`Committed offset for executed delayed job: ${key}`);
791
+ }
792
+ catch (err) {
793
+ this.logger.warn(`Failed to commit offset for delayed job ${key}: ${err.message}`);
794
+ }
795
+ finally {
796
+ this.resumePendingDelayedPartition(pending);
797
+ }
798
+ }
799
+ async drainPartitionOffsets(partitionKey) {
800
+ var _a;
801
+ const entries = this.partitionOffsets.get(partitionKey);
802
+ if (!entries)
803
+ return;
804
+ const settledPrefix = [];
805
+ for (const entry of entries) {
806
+ if (!entry.settled)
807
+ break;
808
+ if ((_a = entry.isStale) === null || _a === void 0 ? void 0 : _a.call(entry))
809
+ return;
810
+ if (!entry.resolved) {
811
+ entry.resolveOffset(entry.offset);
812
+ entry.resolved = true;
813
+ }
814
+ settledPrefix.push(entry);
815
+ }
816
+ const lastSettled = settledPrefix.at(-1);
817
+ if (lastSettled) {
818
+ const nextOffset = (BigInt(lastSettled.offset) + BigInt(1)).toString();
819
+ try {
820
+ await lastSettled.commitOffsetsIfNecessary({
821
+ topics: [{ topic: lastSettled.topic, partitions: [{ partition: lastSettled.partition, offset: nextOffset }] }],
822
+ });
823
+ entries.splice(0, settledPrefix.length);
824
+ }
825
+ catch (error) {
826
+ this.logger.warn(`Failed to commit settled prefix for ${partitionKey}: ${error instanceof Error ? error.message : String(error)}`);
827
+ }
828
+ }
829
+ if (entries.length === 0)
830
+ this.partitionOffsets.delete(partitionKey);
831
+ }
832
+ scheduleActiveLockRevisit(consumer, topic, partition, offset) {
833
+ var _a, _b;
834
+ const key = `${topic}-${partition}-${offset}`;
835
+ if (this.activeLockTimers.has(key))
836
+ return;
837
+ const delay = Math.max(100, Math.min((_b = (_a = this.options.idempotency) === null || _a === void 0 ? void 0 : _a.lockTtl) !== null && _b !== void 0 ? _b : 60000, 30000));
838
+ const timer = setTimeout(() => {
839
+ this.activeLockTimers.delete(key);
840
+ if (this.isShuttingDown || this.consumers.size === 0)
841
+ return;
842
+ try {
843
+ consumer.seek({ topic, partition, offset });
844
+ consumer.resume([{ topic, partitions: [partition] }]);
845
+ }
846
+ catch (error) {
847
+ this.logger.warn(`Failed to revisit active-lock offset ${key}: ${error instanceof Error ? error.message : String(error)}`);
848
+ }
849
+ }, delay);
850
+ this.activeLockTimers.set(key, timer);
851
+ }
852
+ resumePendingDelayedPartition(pending) {
853
+ const consumer = this.consumers.get(pending.consumerKey);
854
+ if (!consumer) {
855
+ return;
856
+ }
857
+ try {
858
+ consumer.resume([{ topic: pending.topic, partitions: [pending.partition] }]);
859
+ }
860
+ catch (error) {
861
+ this.logger.warn(`Failed to resume partition ${pending.topic}-${pending.partition}: ${error.message}`);
862
+ }
863
+ }
553
864
  async addBatch(queueName, jobs, batchId) {
865
+ var _a;
866
+ for (const j of jobs) {
867
+ (0, validation_1.validateJobData)(j.data);
868
+ if ((_a = j.opts) === null || _a === void 0 ? void 0 : _a.jobId)
869
+ (0, validation_1.validateJobId)(j.opts.jobId);
870
+ }
554
871
  const producer = await this.ensureProducer();
555
872
  await this.ensureTopicExists(queueName);
556
873
  const messages = jobs.map((j) => {
@@ -607,15 +924,15 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
607
924
  });
608
925
  this.logger.debug(`Job sent to DLQ: ${job.id} -> ${dlqTopic}`);
609
926
  }
610
- async getJob(queueName, jobId) {
927
+ async getJob(_queueName, _jobId) {
611
928
  this.logger.warn('getJob is not efficiently supported in Kafka. Consider using a separate state store.');
612
929
  return null;
613
930
  }
614
- async getJobs(queueName, status, start = 0, end = 100) {
931
+ async getJobs(queueName, status, _start = 0, _end = 100) {
615
932
  this.logger.warn('getJobs is not efficiently supported in Kafka. Consider using a separate state store.');
616
933
  return [];
617
934
  }
618
- async removeJob(queueName, jobId) {
935
+ async removeJob(_queueName, _jobId) {
619
936
  this.logger.warn('removeJob is not supported in Kafka. Messages cannot be deleted from topics.');
620
937
  }
621
938
  async pause(queueName) {
@@ -632,7 +949,7 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
632
949
  this.logger.log(`Consumer resumed for topic: ${queueName}`);
633
950
  }
634
951
  }
635
- async clean(queueName, grace, status) {
952
+ async clean(_queueName, _grace, _status) {
636
953
  this.logger.warn('clean is not supported in Kafka. Use topic retention policies instead.');
637
954
  return [];
638
955
  }
@@ -680,6 +997,11 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
680
997
  this.cleanupTimer = null;
681
998
  }
682
999
  this.processedDelayedJobs.clear();
1000
+ for (const timer of this.activeLockTimers.values())
1001
+ clearTimeout(timer);
1002
+ this.activeLockTimers.clear();
1003
+ this.partitionOffsets.clear();
1004
+ this.pendingDelayeds.clear();
683
1005
  try {
684
1006
  await this.delayedScheduler.shutdown({ executeImmediately: !force });
685
1007
  this.logger.debug('Delayed scheduler shutdown complete');
@@ -687,6 +1009,15 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
687
1009
  catch (error) {
688
1010
  this.logger.warn(`Failed to shutdown delayed scheduler: ${error.message}`);
689
1011
  }
1012
+ for (const [name, consumer] of this.consumers) {
1013
+ try {
1014
+ const topic = name.includes(':') ? name.slice(0, name.indexOf(':')) : name;
1015
+ consumer.resume([{ topic }]);
1016
+ }
1017
+ catch (error) {
1018
+ this.logger.warn(`Failed to resume consumer ${name} partitions: ${error.message}`);
1019
+ }
1020
+ }
690
1021
  for (const [name, consumer] of this.consumers) {
691
1022
  try {
692
1023
  if (force) {
@@ -734,6 +1065,8 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
734
1065
  }
735
1066
  this.eventListeners.clear();
736
1067
  this.verifiedTopics.clear();
1068
+ this.registry.clear();
1069
+ this.consumerConcurrency.clear();
737
1070
  try {
738
1071
  await ((_f = (_e = (_d = (_c = this.options) === null || _c === void 0 ? void 0 : _c.idempotency) === null || _d === void 0 ? void 0 : _d.store) === null || _e === void 0 ? void 0 : _e.close) === null || _f === void 0 ? void 0 : _f.call(_e));
739
1072
  }