@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
@@ -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,6 +31,8 @@ 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();
@@ -35,6 +40,8 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
35
40
  this.DELAYED_JOB_TTL_MS = 3600000;
36
41
  this.cleanupTimer = null;
37
42
  this.pendingDelayeds = new Map();
43
+ this.partitionOffsets = new Map();
44
+ this.activeLockTimers = new Map();
38
45
  this.isShuttingDown = false;
39
46
  this.type = provider_enum_1.QueueProviderType.KAFKA;
40
47
  this.metrics = options.metrics;
@@ -190,7 +197,10 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
190
197
  }
191
198
  }
192
199
  async add(queueName, jobName, data, opts) {
193
- 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);
194
204
  await this.ensureTopicExists(queueName);
195
205
  const producer = await this.ensureProducer();
196
206
  const sanitizedCorrelationId = (0, errors_1.sanitizeCorrelationId)(opts === null || opts === void 0 ? void 0 : opts.correlationId);
@@ -203,26 +213,7 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
203
213
  attemptsMade: 0,
204
214
  correlationId: sanitizedCorrelationId,
205
215
  };
206
- const headers = {
207
- 'x-job-name': jobName,
208
- 'x-job-id': job.id,
209
- '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,
210
- 'x-attempts': '0',
211
- 'x-max-attempts': String((opts === null || opts === void 0 ? void 0 : opts.attempts) || 1),
212
- };
213
- if (sanitizedCorrelationId) {
214
- headers['x-correlation-id'] = sanitizedCorrelationId;
215
- }
216
- if (opts === null || opts === void 0 ? void 0 : opts.headers) {
217
- Object.assign(headers, opts.headers);
218
- }
219
- if (opts === null || opts === void 0 ? void 0 : opts.delay) {
220
- headers['x-delay'] = String(opts.delay);
221
- headers['x-process-after'] = String(Date.now() + opts.delay);
222
- }
223
- if ((opts === null || opts === void 0 ? void 0 : opts.priority) !== undefined) {
224
- headers['x-priority'] = String(opts.priority);
225
- }
216
+ const headers = this.buildMessageHeaders(job);
226
217
  await producer.send({
227
218
  topic: queueName,
228
219
  messages: [{
@@ -232,13 +223,19 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
232
223
  }],
233
224
  });
234
225
  this.logger.debug(`Job added: ${jobName} (${job.id}) to topic ${queueName}`);
235
- (_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, {
236
227
  delay: opts === null || opts === void 0 ? void 0 : opts.delay,
237
228
  priority: opts === null || opts === void 0 ? void 0 : opts.priority,
238
229
  });
239
230
  return job;
240
231
  }
241
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
+ }
242
239
  await this.ensureTopicExists(queueName);
243
240
  const producer = await this.ensureProducer();
244
241
  const createdJobs = jobs.map((j) => {
@@ -253,23 +250,11 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
253
250
  correlationId: (0, errors_1.sanitizeCorrelationId)((_b = j.opts) === null || _b === void 0 ? void 0 : _b.correlationId),
254
251
  });
255
252
  });
256
- const messages = createdJobs.map((job) => {
257
- var _a, _b;
258
- const headers = {
259
- 'x-job-name': job.name,
260
- 'x-job-id': job.id,
261
- 'x-attempts': '0',
262
- 'x-max-attempts': String(((_a = job.opts) === null || _a === void 0 ? void 0 : _a.attempts) || 1),
263
- };
264
- if ((_b = job.opts) === null || _b === void 0 ? void 0 : _b.correlationId) {
265
- headers['x-correlation-id'] = job.opts.correlationId;
266
- }
267
- return {
268
- key: job.id,
269
- value: JSON.stringify(job),
270
- headers,
271
- };
272
- });
253
+ const messages = createdJobs.map((job) => ({
254
+ key: job.id,
255
+ value: JSON.stringify(job),
256
+ headers: this.buildMessageHeaders(job),
257
+ }));
273
258
  await producer.send({
274
259
  topic: queueName,
275
260
  messages,
@@ -277,153 +262,200 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
277
262
  this.logger.debug(`${createdJobs.length} jobs added to topic ${queueName}`);
278
263
  return createdJobs;
279
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
+ }
280
282
  async process(queueName, processor, options) {
281
- var _a, _b, _c, _d, _e;
282
- const consumerKey = (options === null || options === void 0 ? void 0 : options.name) ? `${queueName}:${options.name}` : queueName;
283
- 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;
284
287
  this.logger.warn(`Consumer already exists for ${consumerKey}`);
285
288
  return false;
286
289
  }
287
- await this.ensureTopicExists(queueName);
288
- const kafka = await this.getKafka();
289
- const groupId = `${this.options.groupId}-${queueName}`;
290
- const consumer = kafka.consumer({
291
- groupId,
292
- sessionTimeout: this.options.sessionTimeout || 30000,
293
- heartbeatInterval: this.options.heartbeatInterval || 3000,
294
- maxWaitTimeInMs: 100,
295
- retry: { retries: 5 },
296
- });
297
- await consumer.connect();
298
- await consumer.subscribe({ topic: queueName, fromBeginning: false });
299
- const idempotencyStore = (_a = this.options.idempotency) === null || _a === void 0 ? void 0 : _a.store;
300
- const lockTtl = (_c = (_b = this.options.idempotency) === null || _b === void 0 ? void 0 : _b.lockTtl) !== null && _c !== void 0 ? _c : 60000;
301
- const completedTtl = (_e = (_d = this.options.idempotency) === null || _d === void 0 ? void 0 : _d.completedTtl) !== null && _e !== void 0 ? _e : 3600000;
302
- this.consumers.set(consumerKey, consumer);
303
- await consumer.run({
304
- partitionsConsumedConcurrently: (options === null || options === void 0 ? void 0 : options.concurrency) || 1,
305
- eachMessage: async ({ message, partition, heartbeat }) => {
306
- var _a, _b, _c, _d, _e, _f, _g;
307
- if (!message.value)
308
- return;
309
- let job;
310
- try {
311
- const parsed = JSON.parse(message.value.toString());
312
- (0, errors_1.validateJobStructure)(parsed);
313
- job = parsed;
314
- }
315
- catch (error) {
316
- this.logger.error(`Failed to parse or validate job message: ${error.message}`);
317
- return;
318
- }
319
- const headers = {};
320
- if (message.headers) {
321
- for (const [key, value] of Object.entries(message.headers)) {
322
- headers[key] = (value === null || value === void 0 ? void 0 : value.toString()) || '';
323
- }
324
- }
325
- const rawCorrelationId = headers['x-correlation-id'];
326
- 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;
327
322
  try {
328
- job.correlationId = (0, errors_1.sanitizeCorrelationId)(rawCorrelationId);
323
+ const parsed = JSON.parse(message.value.toString());
324
+ (0, errors_1.validateJobStructure)(parsed);
325
+ job = parsed;
329
326
  }
330
327
  catch (error) {
331
- this.logger.warn(`Invalid correlationId in message: ${error.message}`);
332
- }
333
- }
334
- if ((options === null || options === void 0 ? void 0 : options.name) && job.name !== options.name) {
335
- return;
336
- }
337
- const idempotencyKey = idempotencyStore ? this.getIdempotencyKey(job, headers) : job.id;
338
- if (idempotencyStore) {
339
- const canProcess = await idempotencyStore.markProcessing(idempotencyKey, lockTtl);
340
- if (!canProcess) {
341
- 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}`);
342
329
  return;
343
330
  }
344
- }
345
- const processAfter = headers['x-process-after'];
346
- if (processAfter && parseInt(processAfter) > Date.now()) {
347
- const delay = parseInt(processAfter) - Date.now();
348
- if (idempotencyStore) {
349
- 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
+ }
350
336
  }
351
- const delayKey = `${queueName}-${partition}-${message.offset}`;
352
- if (this.processedDelayedJobs.has(delayKey)) {
353
- 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
+ }
354
348
  }
355
- const scheduled = this.delayedScheduler.schedule(queueName, job, delay);
356
- if (scheduled) {
357
- this.processedDelayedJobs.set(delayKey, Date.now());
358
- 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}"`);
359
352
  return;
360
353
  }
361
- }
362
- 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');
363
- let lockRenewal;
364
- if (idempotencyStore) {
365
- lockRenewal = new lock_renewal_1.LockRenewal(idempotencyStore, idempotencyKey, lockTtl, Math.floor(lockTtl / 2));
366
- lockRenewal.start();
367
- }
368
- try {
369
- this.emitEvent(queueName, queue_event_enum_1.QueueEvent.ACTIVE, job);
370
- (_c = this.metrics) === null || _c === void 0 ? void 0 : _c.jobStarted(queueName, job.name, job.id);
371
- const startTime = Date.now();
372
- const result = await processor(job);
373
- job.returnvalue = result;
354
+ const idempotencyKey = idempotencyStore ? this.getIdempotencyKey(job, headers) : job.id;
374
355
  if (idempotencyStore) {
375
- 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
+ }
376
361
  }
377
- const duration = Date.now() - startTime;
378
- (_d = this.metrics) === null || _d === void 0 ? void 0 : _d.jobCompleted(queueName, job.name, job.id, duration);
379
- this.emitEvent(queueName, queue_event_enum_1.QueueEvent.COMPLETED, job, result);
380
- this.logger.debug(`Job completed: ${job.name} (${job.id})`);
381
- }
382
- catch (error) {
383
- const currentAttempts = job.attemptsMade + 1;
384
- job.failedReason = (0, sanitize_1.sanitizeErrorMessage)(error instanceof Error ? error.message : String(error));
385
- (_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;
386
381
  if (idempotencyStore) {
387
- await idempotencyStore.releaseLock(idempotencyKey);
382
+ lockRenewal = new lock_renewal_1.LockRenewal(idempotencyStore, idempotencyKey, lockTtl, Math.floor(lockTtl / 2));
383
+ lockRenewal.start();
388
384
  }
389
- if (currentAttempts < maxAttempts) {
390
- const delay = this.calculateBackoff(job);
391
- (_f = this.metrics) === null || _f === void 0 ? void 0 : _f.jobRetried(queueName, job.name, job.id, currentAttempts, delay);
392
- await this.add(queueName, job.name, job.data, {
393
- ...job.opts,
394
- delay,
395
- jobId: `${idempotencyKey}-retry-${currentAttempts}`,
396
- correlationId: job.correlationId,
397
- headers: {
398
- ...(_g = job.opts) === null || _g === void 0 ? void 0 : _g.headers,
399
- 'x-original-job-id': idempotencyKey,
400
- 'x-retry-count': String(currentAttempts),
401
- },
402
- });
403
- 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})`);
404
398
  }
405
- else {
406
- if (this.options.enableDLQ) {
407
- 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}`);
408
428
  }
409
- this.emitEvent(queueName, queue_event_enum_1.QueueEvent.FAILED, job, new Error(job.failedReason));
410
- this.logger.error(`Job failed: ${job.name} (${job.id}): ${job.failedReason}`);
411
429
  }
412
- }
413
- finally {
414
- if (lockRenewal) {
415
- lockRenewal.stop();
430
+ finally {
431
+ if (lockRenewal) {
432
+ lockRenewal.stop();
433
+ }
416
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();
417
448
  }
418
- await heartbeat();
419
- },
420
- });
421
- this.logger.log(`Consumer started for topic: ${queueName}${(options === null || options === void 0 ? void 0 : options.name) ? ` (${options.name})` : ''} in group ${groupId}`);
422
- return true;
449
+ catch (disconnectError) {
450
+ this.logger.warn(`Failed to disconnect consumer during registration rollback: ${disconnectError.message}`);
451
+ }
452
+ }
453
+ throw error;
454
+ }
423
455
  }
424
456
  async processBatch(queueName, processor, options) {
425
- var _a, _b, _c, _d, _e, _f;
426
- const { batchSize = 10 } = options || {};
457
+ var _a;
458
+ const { batchSize = 10, continueOnError = true, retryFailedIndividually = false, } = options || {};
427
459
  const consumerKey = `${queueName}:batch`;
428
460
  if (this.consumers.has(consumerKey)) {
429
461
  throw new errors_1.QueueError(`Batch consumer already exists for ${queueName}. Cannot register duplicate batch processor.`, 'WORKER_EXISTS', queueName);
@@ -440,156 +472,301 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
440
472
  });
441
473
  await consumer.connect();
442
474
  await consumer.subscribe({ topic: queueName, fromBeginning: false });
443
- const idempotencyStore = (_a = this.options.idempotency) === null || _a === void 0 ? void 0 : _a.store;
444
- const lockTtl = (_c = (_b = this.options.idempotency) === null || _b === void 0 ? void 0 : _b.lockTtl) !== null && _c !== void 0 ? _c : 60000;
445
- const completedTtl = (_e = (_d = this.options.idempotency) === null || _d === void 0 ? void 0 : _d.completedTtl) !== null && _e !== void 0 ? _e : 3600000;
446
475
  this.consumers.set(consumerKey, consumer);
447
- const delayedCommitMode = (_f = this.options.delayedOffsetCommit) !== null && _f !== void 0 ? _f : 'onExecute';
476
+ const delayedCommitMode = (_a = this.options.delayedOffsetCommit) !== null && _a !== void 0 ? _a : 'onExecute';
448
477
  const deferDelayedCommits = delayedCommitMode === 'onExecute';
449
478
  const runOptions = {
450
- eachBatch: async ({ batch, resolveOffset, heartbeat, commitOffsetsIfNecessary, }) => {
479
+ eachBatch: async ({ batch, resolveOffset, heartbeat, commitOffsetsIfNecessary, isStale }) => {
480
+ var _a, _b;
451
481
  const partition = batch.partition;
452
- const jobs = [];
453
- 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
+ };
454
668
  for (const message of batch.messages) {
455
- if (!message.value)
456
- continue;
457
- if (deferDelayedCommits &&
458
- this.pendingDelayeds.has(`${queueName}-${partition}-${message.offset}`)) {
669
+ const offsetEntry = registerOffset(message.offset);
670
+ const delayKey = `${queueName}-${partition}-${message.offset}`;
671
+ if (deferDelayedCommits && this.pendingDelayeds.has(delayKey)) {
459
672
  consumer.pause([{ topic: queueName, partitions: [partition] }]);
460
673
  await heartbeat();
674
+ stopBatch = true;
461
675
  break;
462
676
  }
677
+ if (!message.value) {
678
+ this.logger.warn(`Skipping empty Kafka message at ${delayKey}`);
679
+ offsetEntry.settled = true;
680
+ await heartbeat();
681
+ continue;
682
+ }
683
+ let job;
684
+ const headers = {};
463
685
  try {
464
686
  const parsed = JSON.parse(message.value.toString());
465
687
  (0, errors_1.validateJobStructure)(parsed);
466
- const headers = {};
688
+ job = parsed;
467
689
  if (message.headers) {
468
690
  for (const [key, value] of Object.entries(message.headers)) {
469
691
  headers[key] = (value === null || value === void 0 ? void 0 : value.toString()) || '';
470
692
  }
471
693
  }
472
- const rawCorrelationId = headers['x-correlation-id'];
473
- if (rawCorrelationId) {
474
- try {
475
- parsed.correlationId = (0, errors_1.sanitizeCorrelationId)(rawCorrelationId);
476
- }
477
- catch (error) {
478
- this.logger.warn(`Invalid correlationId in message: ${error.message}`);
479
- }
480
- }
481
- const processAfter = headers['x-process-after'];
482
- if (processAfter && parseInt(processAfter) > Date.now()) {
483
- const delay = parseInt(processAfter) - Date.now();
484
- const delayKey = `${queueName}-${partition}-${message.offset}`;
485
- if (this.processedDelayedJobs.has(delayKey)) {
486
- resolveOffset(message.offset);
487
- await heartbeat();
488
- continue;
489
- }
490
- const wasAlreadyScheduled = this.delayedScheduler.isScheduled(parsed.id);
491
- const scheduled = this.delayedScheduler.schedule(queueName, parsed, delay, deferDelayedCommits
492
- ? (error) => this.onDelayedJobExecuted(delayKey, error)
493
- : undefined);
494
- if (scheduled) {
495
- if (deferDelayedCommits && wasAlreadyScheduled) {
496
- this.logger.debug(`Duplicate delayed batch job ${parsed.id} already in-flight; advancing past offset without arming`);
497
- resolveOffset(message.offset);
498
- await heartbeat();
499
- continue;
500
- }
501
- if (deferDelayedCommits) {
502
- this.pendingDelayeds.set(delayKey, {
503
- topic: queueName,
504
- partition,
505
- offset: message.offset,
506
- consumerKey,
507
- resolveOffset,
508
- commitOffsetsIfNecessary,
509
- });
510
- this.logger.debug(`Delayed batch job deferred (commit on execute): ${parsed.id}, delay: ${delay}ms`);
511
- consumer.pause([{ topic: queueName, partitions: [partition] }]);
512
- await heartbeat();
513
- break;
514
- }
515
- this.processedDelayedJobs.set(delayKey, Date.now());
516
- this.logger.debug(`Delayed batch job scheduled locally: ${parsed.id}, delay: ${delay}ms`);
517
- resolveOffset(message.offset);
518
- await commitOffsetsIfNecessary();
519
- await heartbeat();
520
- continue;
521
- }
522
- }
523
- jobs.push(parsed);
524
- messages.push({ message, headers });
525
694
  }
526
695
  catch (error) {
527
- this.logger.error(`Failed to parse job message: ${error.message}`);
528
- if (deferDelayedCommits) {
529
- resolveOffset(message.offset);
530
- }
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;
531
700
  }
532
- }
533
- for (let i = 0; i < jobs.length; i += batchSize) {
534
- const chunk = jobs.slice(i, i + batchSize);
535
- const chunkMessages = messages.slice(i, i + batchSize);
536
- if (idempotencyStore) {
537
- const filteredChunk = [];
538
- const filteredMessages = [];
539
- for (let j = 0; j < chunk.length; j++) {
540
- const job = chunk[j];
541
- const { headers } = chunkMessages[j];
542
- const idempotencyKey = this.getIdempotencyKey(job, headers);
543
- const canProcess = await idempotencyStore.markProcessing(idempotencyKey, lockTtl);
544
- if (canProcess) {
545
- filteredChunk.push(job);
546
- filteredMessages.push(chunkMessages[j]);
547
- }
548
- else {
549
- this.logger.debug(`Job ${job.id} skipped (idempotency check)`);
550
- }
701
+ const rawCorrelationId = headers['x-correlation-id'];
702
+ if (rawCorrelationId) {
703
+ try {
704
+ job.correlationId = (0, errors_1.sanitizeCorrelationId)(rawCorrelationId);
551
705
  }
552
- if (filteredChunk.length === 0)
706
+ catch (error) {
707
+ this.logger.warn(`Invalid correlationId in message: ${error instanceof Error ? error.message : String(error)}`);
708
+ }
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();
553
717
  continue;
554
- const startTime = Date.now();
555
- const result = await processor(filteredChunk, options || {});
556
- for (let j = 0; j < filteredChunk.length; j++) {
557
- const job = filteredChunk[j];
558
- const { headers } = filteredMessages[j];
559
- const idempotencyKey = this.getIdempotencyKey(job, headers);
560
- const jobResult = result.results[j];
561
- if (jobResult.success) {
562
- 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;
563
739
  }
564
740
  else {
565
- await idempotencyStore.releaseLock(idempotencyKey);
741
+ this.processedDelayedJobs.set(delayKey, Date.now());
742
+ offsetEntry.settled = true;
566
743
  }
744
+ await heartbeat();
745
+ continue;
567
746
  }
568
- const duration = Date.now() - startTime;
569
- this.logger.debug(`Batch chunk processed: ${result.successful}/${result.totalJobs} succeeded in ${duration}ms`);
570
- }
571
- else {
572
- const startTime = Date.now();
573
- const result = await processor(chunk, options || {});
574
- const duration = Date.now() - startTime;
575
- this.logger.debug(`Batch chunk processed: ${result.successful}/${result.totalJobs} succeeded in ${duration}ms`);
576
- }
577
- const lastMessage = chunkMessages[chunkMessages.length - 1];
578
- if (lastMessage) {
579
- resolveOffset(lastMessage.message.offset);
580
- await commitOffsetsIfNecessary();
581
747
  }
582
- 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;
583
759
  }
760
+ await flushChunk();
761
+ await this.drainPartitionOffsets(partitionKey);
584
762
  },
585
763
  };
586
- if (deferDelayedCommits) {
587
- runOptions.eachBatchAutoResolve = false;
588
- }
764
+ runOptions.eachBatchAutoResolve = false;
589
765
  await consumer.run(runOptions);
590
766
  this.logger.log(`Batch consumer started for topic: ${queueName} (batchSize: ${batchSize})`);
591
767
  }
592
768
  async onDelayedJobExecuted(key, error) {
769
+ var _a;
593
770
  const pending = this.pendingDelayeds.get(key);
594
771
  if (!pending) {
595
772
  return;
@@ -604,17 +781,11 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
604
781
  return;
605
782
  }
606
783
  try {
607
- pending.resolveOffset(pending.offset);
608
- await pending.commitOffsetsIfNecessary({
609
- topics: [
610
- {
611
- topic: pending.topic,
612
- partitions: [
613
- { partition: pending.partition, offset: String(Number(pending.offset) + 1) },
614
- ],
615
- },
616
- ],
617
- });
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);
618
789
  this.processedDelayedJobs.set(key, Date.now());
619
790
  this.logger.debug(`Committed offset for executed delayed job: ${key}`);
620
791
  }
@@ -625,6 +796,59 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
625
796
  this.resumePendingDelayedPartition(pending);
626
797
  }
627
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
+ }
628
852
  resumePendingDelayedPartition(pending) {
629
853
  const consumer = this.consumers.get(pending.consumerKey);
630
854
  if (!consumer) {
@@ -638,6 +862,12 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
638
862
  }
639
863
  }
640
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
+ }
641
871
  const producer = await this.ensureProducer();
642
872
  await this.ensureTopicExists(queueName);
643
873
  const messages = jobs.map((j) => {
@@ -694,15 +924,15 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
694
924
  });
695
925
  this.logger.debug(`Job sent to DLQ: ${job.id} -> ${dlqTopic}`);
696
926
  }
697
- async getJob(queueName, jobId) {
927
+ async getJob(_queueName, _jobId) {
698
928
  this.logger.warn('getJob is not efficiently supported in Kafka. Consider using a separate state store.');
699
929
  return null;
700
930
  }
701
- async getJobs(queueName, status, start = 0, end = 100) {
931
+ async getJobs(queueName, status, _start = 0, _end = 100) {
702
932
  this.logger.warn('getJobs is not efficiently supported in Kafka. Consider using a separate state store.');
703
933
  return [];
704
934
  }
705
- async removeJob(queueName, jobId) {
935
+ async removeJob(_queueName, _jobId) {
706
936
  this.logger.warn('removeJob is not supported in Kafka. Messages cannot be deleted from topics.');
707
937
  }
708
938
  async pause(queueName) {
@@ -719,7 +949,7 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
719
949
  this.logger.log(`Consumer resumed for topic: ${queueName}`);
720
950
  }
721
951
  }
722
- async clean(queueName, grace, status) {
952
+ async clean(_queueName, _grace, _status) {
723
953
  this.logger.warn('clean is not supported in Kafka. Use topic retention policies instead.');
724
954
  return [];
725
955
  }
@@ -767,6 +997,10 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
767
997
  this.cleanupTimer = null;
768
998
  }
769
999
  this.processedDelayedJobs.clear();
1000
+ for (const timer of this.activeLockTimers.values())
1001
+ clearTimeout(timer);
1002
+ this.activeLockTimers.clear();
1003
+ this.partitionOffsets.clear();
770
1004
  this.pendingDelayeds.clear();
771
1005
  try {
772
1006
  await this.delayedScheduler.shutdown({ executeImmediately: !force });
@@ -831,6 +1065,8 @@ class KafkaQueueProvider extends queue_provider_interface_1.QueueProvider {
831
1065
  }
832
1066
  this.eventListeners.clear();
833
1067
  this.verifiedTopics.clear();
1068
+ this.registry.clear();
1069
+ this.consumerConcurrency.clear();
834
1070
  try {
835
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));
836
1072
  }