@@ -55,32 +55,68 @@ export class KafkaQueueService extends LoggerBase implements IQueue {
5555 }
5656
5757 async getQueueMessageCount ( conf : IKafkaChannelConfig ) : Promise < number > {
58- const groupId = conf . name
5958 const topic = conf . name
59+ // The consumer group ID is the same as the topic name
60+ const groupId = topic
6061
6162 const admin = this . client . admin ( )
6263 await admin . connect ( )
6364
6465 try {
66+ this . log . debug ( { topic, groupId } , 'Fetching message count for topic and consumer group' )
67+
6568 const topicOffsets = await admin . fetchTopicOffsets ( topic )
69+ this . log . debug ( { topic, groupId, topicOffsets } , 'Topic offsets fetched' )
70+
6671 const offsetsResponse = await admin . fetchOffsets ( {
6772 groupId : groupId ,
6873 topics : [ topic ] ,
6974 } )
75+ this . log . debug ( { topic, groupId, offsetsResponse } , 'Consumer group offsets fetched' )
7076
7177 const offsets = offsetsResponse [ 0 ] . partitions
78+ this . log . debug ( { topic, groupId, offsets } , 'Consumer group offsets' )
7279
7380 let totalLeft = 0
7481 for ( const offset of offsets ) {
7582 const topicOffset = topicOffsets . find ( ( p ) => p . partition === offset . partition )
76- if ( topicOffset . offset !== offset . offset ) {
77- totalLeft += Number ( topicOffset . offset ) - Number ( offset . offset )
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' )
78113 }
79114 }
80115
116+ this . log . debug ( { topic, groupId, totalLeft } , 'Total messages left calculated' )
81117 return totalLeft
82118 } catch ( err ) {
83- this . log . error ( err , 'Failed to get message count!' )
119+ this . log . error ( { topic , groupId , err } , 'Failed to get message count!' )
84120 throw err
85121 } finally {
86122 await admin . disconnect ( )
0 commit comments