@drarzter/kafka-client 0.7.2 → 0.7.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.
package/dist/core.d.mts CHANGED
@@ -16,7 +16,6 @@ declare class KafkaClient<T extends TopicMapConstraint<T>> implements IKafkaClie
16
16
  /** Maps transactionalId → Producer for each active retry level consumer. */
17
17
  private readonly retryTxProducers;
18
18
  private readonly consumers;
19
- private readonly admin;
20
19
  private readonly logger;
21
20
  private readonly autoCreateTopicsEnabled;
22
21
  private readonly strictSchemasEnabled;
@@ -36,20 +35,20 @@ declare class KafkaClient<T extends TopicMapConstraint<T>> implements IKafkaClie
36
35
  private readonly onRebalance;
37
36
  /** Transactional producer ID — configurable via `KafkaClientOptions.transactionalId`. */
38
37
  private readonly txId;
39
- /** Per-topic event counters, lazily created on first event. Aggregated by `getMetrics()`. */
40
- private readonly _topicMetrics;
41
38
  /** Monotonically increasing Lamport clock stamped on every outgoing message. */
42
39
  private _lamportClock;
43
40
  /** Per-groupId deduplication state: `"topic:partition"` → last processed clock. */
44
41
  private readonly dedupStates;
45
- /** Circuit breaker state per `"${gid}:${topic}:${partition}"` key. */
46
- private readonly circuitStates;
47
- /** Circuit breaker config per groupId, set at startConsumer/startBatchConsumer time. */
48
- private readonly circuitConfigs;
49
- private isAdminConnected;
50
- private inFlightTotal;
51
- private readonly drainResolvers;
42
+ private readonly circuitBreaker;
43
+ private readonly adminOps;
44
+ private readonly metrics;
45
+ private readonly inFlight;
52
46
  readonly clientId: ClientId;
47
+ private readonly _producerOpsDeps;
48
+ private readonly _consumerOpsDeps;
49
+ private readonly _retryTopicDeps;
50
+ /** DLQ header keys added by the pipeline — stripped before re-publishing. */
51
+ private static readonly DLQ_HEADER_KEYS;
53
52
  constructor(clientId: ClientId, groupId: GroupId, brokers: string[], options?: KafkaClientOptions);
54
53
  /**
55
54
  * Send a single typed message. Accepts a topic key or a `TopicDescriptor`.
@@ -170,8 +169,6 @@ declare class KafkaClient<T extends TopicMapConstraint<T>> implements IKafkaClie
170
169
  private pauseTopicAllPartitions;
171
170
  /** Resume all assigned partitions of a topic for a consumer group (used for queue backpressure). */
172
171
  private resumeTopicAllPartitions;
173
- /** DLQ header keys added by `sendToDlq` — stripped before re-publishing. */
174
- private static readonly DLQ_HEADER_KEYS;
175
172
  /**
176
173
  * Re-publish messages from a dead letter queue back to the original topic.
177
174
  *
@@ -295,95 +292,12 @@ declare class KafkaClient<T extends TopicMapConstraint<T>> implements IKafkaClie
295
292
  * NestJS apps get drain for free via `onModuleDestroy` → `disconnect()`.
296
293
  */
297
294
  enableGracefulShutdown(signals?: NodeJS.Signals[], drainTimeoutMs?: number): void;
298
- /**
299
- * Increment the in-flight handler count and return a promise that calls the given handler.
300
- * When the promise resolves or rejects, decrement the in flight handler count.
301
- * If the in flight handler count reaches 0, call all previously registered drain resolvers.
302
- * @param fn The handler to call when the promise is resolved or rejected.
303
- * @returns A promise that resolves or rejects with the result of calling the handler.
304
- */
305
- private trackInFlight;
306
- /**
307
- * Waits for all in-flight handlers to complete or for a given timeout, whichever comes first.
308
- * @param timeoutMs Maximum time to wait in milliseconds.
309
- * @returns A promise that resolves when all handlers have completed or the timeout is reached.
310
- * @private
311
- */
312
- private waitForDrain;
313
- /**
314
- * Prepare a send payload by registering the topic's schema and then building the payload.
315
- * @param topicOrDesc - topic name or topic descriptor
316
- * @param messages - batch of messages to send
317
- * @returns - prepared payload
318
- */
319
295
  private preparePayload;
320
- private notifyAfterSend;
321
- /**
322
- * Returns the KafkaMetrics for a given topic.
323
- * If the topic hasn't seen any events, initializes a zero-valued snapshot.
324
- * @param topic - name of the topic to get the metrics for
325
- * @returns - KafkaMetrics for the given topic
326
- */
327
- private metricsFor;
328
- /**
329
- * Notifies instrumentation hooks of a retry event.
330
- * @param envelope The original message envelope that triggered the retry.
331
- * @param attempt The current retry attempt (1-indexed).
332
- * @param maxRetries The maximum number of retries configured for this topic.
333
- */
334
- private notifyRetry;
335
- /**
336
- * Called whenever a message is routed to the dead letter queue.
337
- * @param envelope The original message envelope.
338
- * @param reason The reason for routing to the dead letter queue.
339
- * @param gid The group ID of the consumer that triggered the circuit breaker, if any.
340
- */
341
- private notifyDlq;
342
- /**
343
- * Notify all instrumentation hooks about a duplicate message detection.
344
- * Invoked by the consumer after a message has been successfully processed
345
- * and the Lamport clock detected a duplicate.
346
- * @param envelope The processed message envelope.
347
- * @param strategy The duplicate detection strategy used.
348
- */
349
- private notifyDuplicate;
350
- /**
351
- * Notify all instrumentation hooks about a successfully processed message.
352
- * Invoked by the consumer after a message has been successfully processed
353
- * by the handler.
354
- * @param envelope The processed message envelope.
355
- * @param gid The optional consumer group ID.
356
- */
357
- private notifyMessage;
358
296
  /**
359
297
  * Start a timer that logs a warning if `fn` hasn't resolved within `timeoutMs`.
360
298
  * The handler itself is not cancelled — the warning is diagnostic only.
361
299
  */
362
300
  private wrapWithTimeoutWarning;
363
- /**
364
- * When `retryTopics: true` and `autoCreateTopics: false`, verify that every
365
- * `<topic>.retry.<level>` topic already exists. Throws a clear error at startup
366
- * rather than silently discovering missing topics on the first handler failure.
367
- */
368
- private validateRetryTopicsExist;
369
- /**
370
- * When `autoCreateTopics` is disabled, verify that `<topic>.dlq` exists for every
371
- * consumed topic. Throws a clear error at startup rather than silently discovering
372
- * missing DLQ topics on the first handler failure.
373
- */
374
- private validateDlqTopicsExist;
375
- /**
376
- * When `deduplication.strategy: 'topic'` and `autoCreateTopics: false`, verify
377
- * that every `<topic>.duplicates` destination topic already exists. Throws a
378
- * clear error at startup rather than silently dropping duplicates on first hit.
379
- */
380
- private validateDuplicatesTopicsExist;
381
- /**
382
- * Connect the admin client if not already connected.
383
- * The flag is only set to `true` after a successful connect — if `admin.connect()`
384
- * throws the flag remains `false` so the next call will retry the connection.
385
- */
386
- private ensureAdminConnected;
387
301
  /**
388
302
  * Create and connect a transactional producer for EOS retry routing.
389
303
  * Each retry level consumer gets its own producer with a unique `transactionalId`
@@ -392,56 +306,24 @@ declare class KafkaClient<T extends TopicMapConstraint<T>> implements IKafkaClie
392
306
  private createRetryTxProducer;
393
307
  /**
394
308
  * Ensure that a topic exists by creating it if it doesn't already exist.
395
- * If `autoCreateTopics` is disabled, this method will not create the topic and
396
- * will return immediately.
397
- * If multiple concurrent calls are made to `ensureTopic` for the same topic,
398
- * they are deduplicated to prevent multiple calls to `admin.createTopics()`.
399
- * @param topic - The topic to ensure exists.
400
- * @returns A promise that resolves when the topic has been created or already exists.
309
+ * If `autoCreateTopics` is disabled, returns immediately.
310
+ * Concurrent calls for the same topic are deduplicated.
401
311
  */
402
312
  private ensureTopic;
403
313
  /** Shared consumer setup: groupId check, schema map, connect, subscribe. */
404
314
  private setupConsumer;
405
315
  /** Create or retrieve the deduplication context for a consumer group. */
406
316
  private resolveDeduplicationContext;
407
- /**
408
- * An object containing the necessary dependencies for building a send payload.
409
- *
410
- * @property {Map<string, SchemaLike>} schemaRegistry - A map of topic names to their schemas.
411
- * @property {boolean} strictSchemasEnabled - Whether strict schema validation is enabled.
412
- * @property {KafkaInstrumentation} instrumentation - An object for creating a span for instrumentation.
413
- * @property {KafkaLogger} logger - A logger for logging messages.
414
- * @property {() => number} nextLamportClock - A function that returns the next value of the logical clock.
415
- */
416
- private get producerOpsDeps();
417
- /**
418
- * ConsumerOpsDeps object properties:
419
- *
420
- * @property {Map<string, Consumer>} consumers - A map of consumer group IDs to their corresponding consumer instances.
421
- * @property {Map<string, { fromBeginning: boolean; autoCommit: boolean }>} consumerCreationOptions - A map of consumer group IDs to their creation options.
422
- * @property {Kafka} kafka - The Kafka client instance.
423
- * @property {function(string, Partition[]): void} onRebalance - An optional callback function called when a consumer group is rebalanced.
424
- * @property {KafkaLogger} logger - The logger instance used for logging consumer operations.
425
- */
426
- private get consumerOpsDeps();
317
+ /** Guard checks shared by startConsumer and startBatchConsumer. */
318
+ private validateTopicConsumerOpts;
319
+ /** Create EOS transactional producer context for atomic main → retry.1 routing. */
320
+ private makeEosMainContext;
321
+ /** Start companion retry-level consumers and register them under the main groupId. */
322
+ private launchRetryChain;
427
323
  /** Build MessageHandlerDeps with circuit breaker callbacks bound to the given groupId. */
428
324
  private messageDepsFor;
429
- /**
430
- * The dependencies object passed to the retry topic consumers.
431
- *
432
- * `logger`: The logger instance passed to the retry topic consumers.
433
- * `producer`: The producer instance passed to the retry topic consumers.
434
- * `instrumentation`: The instrumentation instance passed to the retry topic consumers.
435
- * `onMessageLost`: The callback function passed to the retry topic consumers for tracking lost messages.
436
- * `onRetry`: The callback function passed to the retry topic consumers for tracking retry attempts.
437
- * `onDlq`: The callback function passed to the retry topic consumers for tracking dead-letter queue routing.
438
- * `onMessage`: The callback function passed to the retry topic consumers for tracking message delivery.
439
- * `ensureTopic`: A function that ensures a topic exists before subscribing to it.
440
- * `getOrCreateConsumer`: A function that creates or retrieves a consumer instance.
441
- * `runningConsumers`: A map of consumer group IDs to their corresponding consumer instances.
442
- * `createRetryTxProducer`: A function that creates a retry transactional producer instance.
443
- */
444
- private get retryTopicDeps();
325
+ /** Build the deps object passed to retry topic consumers. */
326
+ private buildRetryTopicDeps;
445
327
  }
446
328
 
447
329
  /** Error thrown when a consumer message handler fails. */
package/dist/core.d.ts CHANGED
@@ -16,7 +16,6 @@ declare class KafkaClient<T extends TopicMapConstraint<T>> implements IKafkaClie
16
16
  /** Maps transactionalId → Producer for each active retry level consumer. */
17
17
  private readonly retryTxProducers;
18
18
  private readonly consumers;
19
- private readonly admin;
20
19
  private readonly logger;
21
20
  private readonly autoCreateTopicsEnabled;
22
21
  private readonly strictSchemasEnabled;
@@ -36,20 +35,20 @@ declare class KafkaClient<T extends TopicMapConstraint<T>> implements IKafkaClie
36
35
  private readonly onRebalance;
37
36
  /** Transactional producer ID — configurable via `KafkaClientOptions.transactionalId`. */
38
37
  private readonly txId;
39
- /** Per-topic event counters, lazily created on first event. Aggregated by `getMetrics()`. */
40
- private readonly _topicMetrics;
41
38
  /** Monotonically increasing Lamport clock stamped on every outgoing message. */
42
39
  private _lamportClock;
43
40
  /** Per-groupId deduplication state: `"topic:partition"` → last processed clock. */
44
41
  private readonly dedupStates;
45
- /** Circuit breaker state per `"${gid}:${topic}:${partition}"` key. */
46
- private readonly circuitStates;
47
- /** Circuit breaker config per groupId, set at startConsumer/startBatchConsumer time. */
48
- private readonly circuitConfigs;
49
- private isAdminConnected;
50
- private inFlightTotal;
51
- private readonly drainResolvers;
42
+ private readonly circuitBreaker;
43
+ private readonly adminOps;
44
+ private readonly metrics;
45
+ private readonly inFlight;
52
46
  readonly clientId: ClientId;
47
+ private readonly _producerOpsDeps;
48
+ private readonly _consumerOpsDeps;
49
+ private readonly _retryTopicDeps;
50
+ /** DLQ header keys added by the pipeline — stripped before re-publishing. */
51
+ private static readonly DLQ_HEADER_KEYS;
53
52
  constructor(clientId: ClientId, groupId: GroupId, brokers: string[], options?: KafkaClientOptions);
54
53
  /**
55
54
  * Send a single typed message. Accepts a topic key or a `TopicDescriptor`.
@@ -170,8 +169,6 @@ declare class KafkaClient<T extends TopicMapConstraint<T>> implements IKafkaClie
170
169
  private pauseTopicAllPartitions;
171
170
  /** Resume all assigned partitions of a topic for a consumer group (used for queue backpressure). */
172
171
  private resumeTopicAllPartitions;
173
- /** DLQ header keys added by `sendToDlq` — stripped before re-publishing. */
174
- private static readonly DLQ_HEADER_KEYS;
175
172
  /**
176
173
  * Re-publish messages from a dead letter queue back to the original topic.
177
174
  *
@@ -295,95 +292,12 @@ declare class KafkaClient<T extends TopicMapConstraint<T>> implements IKafkaClie
295
292
  * NestJS apps get drain for free via `onModuleDestroy` → `disconnect()`.
296
293
  */
297
294
  enableGracefulShutdown(signals?: NodeJS.Signals[], drainTimeoutMs?: number): void;
298
- /**
299
- * Increment the in-flight handler count and return a promise that calls the given handler.
300
- * When the promise resolves or rejects, decrement the in flight handler count.
301
- * If the in flight handler count reaches 0, call all previously registered drain resolvers.
302
- * @param fn The handler to call when the promise is resolved or rejected.
303
- * @returns A promise that resolves or rejects with the result of calling the handler.
304
- */
305
- private trackInFlight;
306
- /**
307
- * Waits for all in-flight handlers to complete or for a given timeout, whichever comes first.
308
- * @param timeoutMs Maximum time to wait in milliseconds.
309
- * @returns A promise that resolves when all handlers have completed or the timeout is reached.
310
- * @private
311
- */
312
- private waitForDrain;
313
- /**
314
- * Prepare a send payload by registering the topic's schema and then building the payload.
315
- * @param topicOrDesc - topic name or topic descriptor
316
- * @param messages - batch of messages to send
317
- * @returns - prepared payload
318
- */
319
295
  private preparePayload;
320
- private notifyAfterSend;
321
- /**
322
- * Returns the KafkaMetrics for a given topic.
323
- * If the topic hasn't seen any events, initializes a zero-valued snapshot.
324
- * @param topic - name of the topic to get the metrics for
325
- * @returns - KafkaMetrics for the given topic
326
- */
327
- private metricsFor;
328
- /**
329
- * Notifies instrumentation hooks of a retry event.
330
- * @param envelope The original message envelope that triggered the retry.
331
- * @param attempt The current retry attempt (1-indexed).
332
- * @param maxRetries The maximum number of retries configured for this topic.
333
- */
334
- private notifyRetry;
335
- /**
336
- * Called whenever a message is routed to the dead letter queue.
337
- * @param envelope The original message envelope.
338
- * @param reason The reason for routing to the dead letter queue.
339
- * @param gid The group ID of the consumer that triggered the circuit breaker, if any.
340
- */
341
- private notifyDlq;
342
- /**
343
- * Notify all instrumentation hooks about a duplicate message detection.
344
- * Invoked by the consumer after a message has been successfully processed
345
- * and the Lamport clock detected a duplicate.
346
- * @param envelope The processed message envelope.
347
- * @param strategy The duplicate detection strategy used.
348
- */
349
- private notifyDuplicate;
350
- /**
351
- * Notify all instrumentation hooks about a successfully processed message.
352
- * Invoked by the consumer after a message has been successfully processed
353
- * by the handler.
354
- * @param envelope The processed message envelope.
355
- * @param gid The optional consumer group ID.
356
- */
357
- private notifyMessage;
358
296
  /**
359
297
  * Start a timer that logs a warning if `fn` hasn't resolved within `timeoutMs`.
360
298
  * The handler itself is not cancelled — the warning is diagnostic only.
361
299
  */
362
300
  private wrapWithTimeoutWarning;
363
- /**
364
- * When `retryTopics: true` and `autoCreateTopics: false`, verify that every
365
- * `<topic>.retry.<level>` topic already exists. Throws a clear error at startup
366
- * rather than silently discovering missing topics on the first handler failure.
367
- */
368
- private validateRetryTopicsExist;
369
- /**
370
- * When `autoCreateTopics` is disabled, verify that `<topic>.dlq` exists for every
371
- * consumed topic. Throws a clear error at startup rather than silently discovering
372
- * missing DLQ topics on the first handler failure.
373
- */
374
- private validateDlqTopicsExist;
375
- /**
376
- * When `deduplication.strategy: 'topic'` and `autoCreateTopics: false`, verify
377
- * that every `<topic>.duplicates` destination topic already exists. Throws a
378
- * clear error at startup rather than silently dropping duplicates on first hit.
379
- */
380
- private validateDuplicatesTopicsExist;
381
- /**
382
- * Connect the admin client if not already connected.
383
- * The flag is only set to `true` after a successful connect — if `admin.connect()`
384
- * throws the flag remains `false` so the next call will retry the connection.
385
- */
386
- private ensureAdminConnected;
387
301
  /**
388
302
  * Create and connect a transactional producer for EOS retry routing.
389
303
  * Each retry level consumer gets its own producer with a unique `transactionalId`
@@ -392,56 +306,24 @@ declare class KafkaClient<T extends TopicMapConstraint<T>> implements IKafkaClie
392
306
  private createRetryTxProducer;
393
307
  /**
394
308
  * Ensure that a topic exists by creating it if it doesn't already exist.
395
- * If `autoCreateTopics` is disabled, this method will not create the topic and
396
- * will return immediately.
397
- * If multiple concurrent calls are made to `ensureTopic` for the same topic,
398
- * they are deduplicated to prevent multiple calls to `admin.createTopics()`.
399
- * @param topic - The topic to ensure exists.
400
- * @returns A promise that resolves when the topic has been created or already exists.
309
+ * If `autoCreateTopics` is disabled, returns immediately.
310
+ * Concurrent calls for the same topic are deduplicated.
401
311
  */
402
312
  private ensureTopic;
403
313
  /** Shared consumer setup: groupId check, schema map, connect, subscribe. */
404
314
  private setupConsumer;
405
315
  /** Create or retrieve the deduplication context for a consumer group. */
406
316
  private resolveDeduplicationContext;
407
- /**
408
- * An object containing the necessary dependencies for building a send payload.
409
- *
410
- * @property {Map<string, SchemaLike>} schemaRegistry - A map of topic names to their schemas.
411
- * @property {boolean} strictSchemasEnabled - Whether strict schema validation is enabled.
412
- * @property {KafkaInstrumentation} instrumentation - An object for creating a span for instrumentation.
413
- * @property {KafkaLogger} logger - A logger for logging messages.
414
- * @property {() => number} nextLamportClock - A function that returns the next value of the logical clock.
415
- */
416
- private get producerOpsDeps();
417
- /**
418
- * ConsumerOpsDeps object properties:
419
- *
420
- * @property {Map<string, Consumer>} consumers - A map of consumer group IDs to their corresponding consumer instances.
421
- * @property {Map<string, { fromBeginning: boolean; autoCommit: boolean }>} consumerCreationOptions - A map of consumer group IDs to their creation options.
422
- * @property {Kafka} kafka - The Kafka client instance.
423
- * @property {function(string, Partition[]): void} onRebalance - An optional callback function called when a consumer group is rebalanced.
424
- * @property {KafkaLogger} logger - The logger instance used for logging consumer operations.
425
- */
426
- private get consumerOpsDeps();
317
+ /** Guard checks shared by startConsumer and startBatchConsumer. */
318
+ private validateTopicConsumerOpts;
319
+ /** Create EOS transactional producer context for atomic main → retry.1 routing. */
320
+ private makeEosMainContext;
321
+ /** Start companion retry-level consumers and register them under the main groupId. */
322
+ private launchRetryChain;
427
323
  /** Build MessageHandlerDeps with circuit breaker callbacks bound to the given groupId. */
428
324
  private messageDepsFor;
429
- /**
430
- * The dependencies object passed to the retry topic consumers.
431
- *
432
- * `logger`: The logger instance passed to the retry topic consumers.
433
- * `producer`: The producer instance passed to the retry topic consumers.
434
- * `instrumentation`: The instrumentation instance passed to the retry topic consumers.
435
- * `onMessageLost`: The callback function passed to the retry topic consumers for tracking lost messages.
436
- * `onRetry`: The callback function passed to the retry topic consumers for tracking retry attempts.
437
- * `onDlq`: The callback function passed to the retry topic consumers for tracking dead-letter queue routing.
438
- * `onMessage`: The callback function passed to the retry topic consumers for tracking message delivery.
439
- * `ensureTopic`: A function that ensures a topic exists before subscribing to it.
440
- * `getOrCreateConsumer`: A function that creates or retrieves a consumer instance.
441
- * `runningConsumers`: A map of consumer group IDs to their corresponding consumer instances.
442
- * `createRetryTxProducer`: A function that creates a retry transactional producer instance.
443
- */
444
- private get retryTopicDeps();
325
+ /** Build the deps object passed to retry topic consumers. */
326
+ private buildRetryTopicDeps;
445
327
  }
446
328
 
447
329
  /** Error thrown when a consumer message handler fails. */