@@ -18,6 +18,7 @@ import {
1818
1919import { configMap } from './config'
2020import { IKafkaChannelConfig , IKafkaQueueStartOptions } from './types'
21+ import { getKafkaMessageCounts } from './utils'
2122
2223export class KafkaQueueService extends LoggerBase implements IQueue {
2324 private readonly MAX_RECONNECT_ATTEMPTS = 5
@@ -56,65 +57,14 @@ export class KafkaQueueService extends LoggerBase implements IQueue {
5657
5758 async getQueueMessageCount ( conf : IKafkaChannelConfig ) : Promise < number > {
5859 const topic = conf . name
59- // The consumer group ID is the same as the topic name
6060 const groupId = topic
6161
6262 const admin = this . client . admin ( )
6363 await admin . connect ( )
6464
6565 try {
66- this . log . debug ( { topic, groupId } , 'Fetching message count for topic and consumer group' )
67-
68- const topicOffsets = await admin . fetchTopicOffsets ( topic )
69- this . log . debug ( { topic, groupId, topicOffsets } , 'Topic offsets fetched' )
70-
71- const offsetsResponse = await admin . fetchOffsets ( {
72- groupId : groupId ,
73- topics : [ topic ] ,
74- } )
75- this . log . debug ( { topic, groupId, offsetsResponse } , 'Consumer group offsets fetched' )
76-
77- const offsets = offsetsResponse [ 0 ] . partitions
78- this . log . debug ( { topic, groupId, offsets } , 'Consumer group offsets' )
79-
80- let totalLeft = 0
81- for ( const offset of offsets ) {
82- const topicOffset = topicOffsets . find ( ( p ) => p . partition === offset . partition )
83- if ( topicOffset ) {
84- // If consumer offset is -1, it means no committed offset, so lag is the total messages in partition
85- if ( offset . offset === '-1' ) {
86- const lag = Number ( topicOffset . offset ) - Number ( topicOffset . low )
87- totalLeft += lag
88- this . log . debug (
89- {
90- partition : offset . partition ,
91- topicOffset : topicOffset . offset ,
92- topicLow : topicOffset . low ,
93- consumerOffset : offset . offset ,
94- lag,
95- } ,
96- 'Partition lag calculated (no committed offset)' ,
97- )
98- } else {
99- const lag = Number ( topicOffset . offset ) - Number ( offset . offset )
100- totalLeft += lag
101- this . log . debug (
102- {
103- partition : offset . partition ,
104- topicOffset : topicOffset . offset ,
105- consumerOffset : offset . offset ,
106- lag,
107- } ,
108- 'Partition lag calculated' ,
109- )
110- }
111- } else {
112- this . log . debug ( { partition : offset . partition } , 'No topic offset found for partition' )
113- }
114- }
115-
116- this . log . debug ( { topic, groupId, totalLeft } , 'Total messages left calculated' )
117- return totalLeft
66+ const counts = await getKafkaMessageCounts ( this . log , admin , topic , groupId )
67+ return counts . unconsumed
11868 } catch ( err ) {
11969 this . log . error ( { topic, groupId, err } , 'Failed to get message count!' )
12070 throw err
0 commit comments