1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
|
package protocol
import (
"encoding/binary"
"fmt"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/kafka/consumer"
)
// Heartbeat API (key 12) - Consumer group heartbeat
// Consumers send periodic heartbeats to stay in the group and receive rebalancing signals
// HeartbeatRequest represents a Heartbeat request from a Kafka client
type HeartbeatRequest struct {
GroupID string
GenerationID int32
MemberID string
GroupInstanceID string // Optional static membership ID
}
// HeartbeatResponse represents a Heartbeat response to a Kafka client
type HeartbeatResponse struct {
CorrelationID uint32
ErrorCode int16
}
// LeaveGroup API (key 13) - Consumer graceful departure
// Consumers call this when shutting down to trigger immediate rebalancing
// LeaveGroupRequest represents a LeaveGroup request from a Kafka client
type LeaveGroupRequest struct {
GroupID string
MemberID string
GroupInstanceID string // Optional static membership ID
Members []LeaveGroupMember // For newer versions, can leave multiple members
}
// LeaveGroupMember represents a member leaving the group (for batch departures)
type LeaveGroupMember struct {
MemberID string
GroupInstanceID string
Reason string // Optional reason for leaving
}
// LeaveGroupResponse represents a LeaveGroup response to a Kafka client
type LeaveGroupResponse struct {
CorrelationID uint32
ErrorCode int16
Members []LeaveGroupMemberResponse // Per-member responses for newer versions
}
// LeaveGroupMemberResponse represents per-member leave group response
type LeaveGroupMemberResponse struct {
MemberID string
GroupInstanceID string
ErrorCode int16
}
// Error codes specific to consumer coordination are imported from errors.go
func (h *Handler) handleHeartbeat(correlationID uint32, apiVersion uint16, requestBody []byte) ([]byte, error) {
// Parse Heartbeat request
request, err := h.parseHeartbeatRequest(requestBody, apiVersion)
if err != nil {
return h.buildHeartbeatErrorResponseV(correlationID, ErrorCodeInvalidGroupID, apiVersion), nil
}
// Validate request
if request.GroupID == "" || request.MemberID == "" {
return h.buildHeartbeatErrorResponseV(correlationID, ErrorCodeInvalidGroupID, apiVersion), nil
}
// Get consumer group
group := h.groupCoordinator.GetGroup(request.GroupID)
if group == nil {
return h.buildHeartbeatErrorResponseV(correlationID, ErrorCodeInvalidGroupID, apiVersion), nil
}
group.Mu.Lock()
defer group.Mu.Unlock()
// Update group's last activity
group.LastActivity = time.Now()
// Validate member exists
member, exists := group.Members[request.MemberID]
if !exists {
return h.buildHeartbeatErrorResponseV(correlationID, ErrorCodeUnknownMemberID, apiVersion), nil
}
// Validate generation
if request.GenerationID != group.Generation {
return h.buildHeartbeatErrorResponseV(correlationID, ErrorCodeIllegalGeneration, apiVersion), nil
}
// Update member's last heartbeat
member.LastHeartbeat = time.Now()
// Check if rebalancing is in progress
var errorCode int16 = ErrorCodeNone
switch group.State {
case consumer.GroupStatePreparingRebalance, consumer.GroupStateCompletingRebalance:
// Signal the consumer that rebalancing is happening
errorCode = ErrorCodeRebalanceInProgress
case consumer.GroupStateDead:
errorCode = ErrorCodeInvalidGroupID
case consumer.GroupStateEmpty:
// This shouldn't happen if member exists, but handle gracefully
errorCode = ErrorCodeUnknownMemberID
case consumer.GroupStateStable:
// Normal case - heartbeat accepted
errorCode = ErrorCodeNone
}
// Build successful response
response := HeartbeatResponse{
CorrelationID: correlationID,
ErrorCode: errorCode,
}
return h.buildHeartbeatResponseV(response, apiVersion), nil
}
func (h *Handler) handleLeaveGroup(correlationID uint32, apiVersion uint16, requestBody []byte) ([]byte, error) {
// Parse LeaveGroup request
request, err := h.parseLeaveGroupRequest(requestBody)
if err != nil {
return h.buildLeaveGroupErrorResponse(correlationID, ErrorCodeInvalidGroupID, apiVersion), nil
}
// Validate request
if request.GroupID == "" || request.MemberID == "" {
return h.buildLeaveGroupErrorResponse(correlationID, ErrorCodeInvalidGroupID, apiVersion), nil
}
// Get consumer group
group := h.groupCoordinator.GetGroup(request.GroupID)
if group == nil {
return h.buildLeaveGroupErrorResponse(correlationID, ErrorCodeInvalidGroupID, apiVersion), nil
}
group.Mu.Lock()
defer group.Mu.Unlock()
// Update group's last activity
group.LastActivity = time.Now()
// Validate member exists
member, exists := group.Members[request.MemberID]
if !exists {
return h.buildLeaveGroupErrorResponse(correlationID, ErrorCodeUnknownMemberID, apiVersion), nil
}
// For static members, only remove if GroupInstanceID matches or is not provided
if h.groupCoordinator.IsStaticMember(member) {
if request.GroupInstanceID != "" && *member.GroupInstanceID != request.GroupInstanceID {
return h.buildLeaveGroupErrorResponse(correlationID, ErrorCodeFencedInstanceID, apiVersion), nil
}
// Unregister static member
h.groupCoordinator.UnregisterStaticMemberLocked(group, *member.GroupInstanceID)
}
// Remove the member from the group
delete(group.Members, request.MemberID)
// Update group state based on remaining members
if len(group.Members) == 0 {
// Group becomes empty
group.State = consumer.GroupStateEmpty
group.Generation++
group.Leader = ""
} else {
// Trigger rebalancing for remaining members
group.State = consumer.GroupStatePreparingRebalance
group.Generation++
// If the leaving member was the leader, select a new leader
if group.Leader == request.MemberID {
// Select first remaining member as new leader
for memberID := range group.Members {
group.Leader = memberID
break
}
}
// Mark remaining members as pending to trigger rebalancing
for _, member := range group.Members {
member.State = consumer.MemberStatePending
}
}
// Update group's subscribed topics (may have changed with member leaving)
h.updateGroupSubscriptionFromMembers(group)
// Build successful response
response := LeaveGroupResponse{
CorrelationID: correlationID,
ErrorCode: ErrorCodeNone,
Members: []LeaveGroupMemberResponse{
{
MemberID: request.MemberID,
GroupInstanceID: request.GroupInstanceID,
ErrorCode: ErrorCodeNone,
},
},
}
return h.buildLeaveGroupResponse(response, apiVersion), nil
}
func (h *Handler) parseHeartbeatRequest(data []byte, apiVersion uint16) (*HeartbeatRequest, error) {
if len(data) < 8 {
return nil, fmt.Errorf("request too short")
}
offset := 0
isFlexible := IsFlexibleVersion(12, apiVersion) // Heartbeat API key = 12
// ADMINCLIENT COMPATIBILITY FIX: Parse top-level tagged fields at the beginning for flexible versions
if isFlexible {
_, consumed, err := DecodeTaggedFields(data[offset:])
if err == nil {
offset += consumed
}
}
// Parse GroupID
var groupID string
if isFlexible {
// FLEXIBLE V4+ FIX: GroupID is a compact string
groupIDBytes, consumed := parseCompactString(data[offset:])
if consumed == 0 {
return nil, fmt.Errorf("invalid group ID compact string")
}
if groupIDBytes != nil {
groupID = string(groupIDBytes)
}
offset += consumed
} else {
// Non-flexible parsing (v0-v3)
groupIDLength := int(binary.BigEndian.Uint16(data[offset:]))
offset += 2
if offset+groupIDLength > len(data) {
return nil, fmt.Errorf("invalid group ID length")
}
groupID = string(data[offset : offset+groupIDLength])
offset += groupIDLength
}
// Generation ID (4 bytes) - always fixed-length
if offset+4 > len(data) {
return nil, fmt.Errorf("missing generation ID")
}
generationID := int32(binary.BigEndian.Uint32(data[offset:]))
offset += 4
// Parse MemberID
var memberID string
if isFlexible {
// FLEXIBLE V4+ FIX: MemberID is a compact string
memberIDBytes, consumed := parseCompactString(data[offset:])
if consumed == 0 {
return nil, fmt.Errorf("invalid member ID compact string")
}
if memberIDBytes != nil {
memberID = string(memberIDBytes)
}
offset += consumed
} else {
// Non-flexible parsing (v0-v3)
if offset+2 > len(data) {
return nil, fmt.Errorf("missing member ID length")
}
memberIDLength := int(binary.BigEndian.Uint16(data[offset:]))
offset += 2
if offset+memberIDLength > len(data) {
return nil, fmt.Errorf("invalid member ID length")
}
memberID = string(data[offset : offset+memberIDLength])
offset += memberIDLength
}
// Parse GroupInstanceID (nullable string) - for Heartbeat v1+
var groupInstanceID string
if apiVersion >= 1 {
if isFlexible {
// FLEXIBLE V4+ FIX: GroupInstanceID is a compact nullable string
groupInstanceIDBytes, consumed := parseCompactString(data[offset:])
if consumed == 0 && len(data) > offset && data[offset] == 0x00 {
groupInstanceID = "" // null
offset += 1
} else {
if groupInstanceIDBytes != nil {
groupInstanceID = string(groupInstanceIDBytes)
}
offset += consumed
}
} else {
// Non-flexible v1-v3: regular nullable string
if offset+2 <= len(data) {
instanceIDLength := int16(binary.BigEndian.Uint16(data[offset:]))
offset += 2
if instanceIDLength == -1 {
groupInstanceID = "" // null string
} else if instanceIDLength >= 0 && offset+int(instanceIDLength) <= len(data) {
groupInstanceID = string(data[offset : offset+int(instanceIDLength)])
offset += int(instanceIDLength)
}
}
}
}
// Parse request-level tagged fields (v4+)
if isFlexible {
if offset < len(data) {
_, consumed, err := DecodeTaggedFields(data[offset:])
if err == nil {
offset += consumed
}
}
}
return &HeartbeatRequest{
GroupID: groupID,
GenerationID: generationID,
MemberID: memberID,
GroupInstanceID: groupInstanceID,
}, nil
}
func (h *Handler) parseLeaveGroupRequest(data []byte) (*LeaveGroupRequest, error) {
if len(data) < 4 {
return nil, fmt.Errorf("request too short")
}
offset := 0
// GroupID (string)
groupIDLength := int(binary.BigEndian.Uint16(data[offset:]))
offset += 2
if offset+groupIDLength > len(data) {
return nil, fmt.Errorf("invalid group ID length")
}
groupID := string(data[offset : offset+groupIDLength])
offset += groupIDLength
// MemberID (string)
if offset+2 > len(data) {
return nil, fmt.Errorf("missing member ID length")
}
memberIDLength := int(binary.BigEndian.Uint16(data[offset:]))
offset += 2
if offset+memberIDLength > len(data) {
return nil, fmt.Errorf("invalid member ID length")
}
memberID := string(data[offset : offset+memberIDLength])
offset += memberIDLength
// GroupInstanceID (string, v3+) - optional field
var groupInstanceID string
if offset+2 <= len(data) {
instanceIDLength := int(binary.BigEndian.Uint16(data[offset:]))
offset += 2
if instanceIDLength != 0xFFFF && offset+instanceIDLength <= len(data) {
groupInstanceID = string(data[offset : offset+instanceIDLength])
}
}
return &LeaveGroupRequest{
GroupID: groupID,
MemberID: memberID,
GroupInstanceID: groupInstanceID,
Members: []LeaveGroupMember{}, // Would parse members array for batch operations
}, nil
}
func (h *Handler) buildHeartbeatResponse(response HeartbeatResponse) []byte {
result := make([]byte, 0, 12)
// NOTE: Correlation ID is handled by writeResponseWithCorrelationID
// Do NOT include it in the response body
// Error code (2 bytes)
errorCodeBytes := make([]byte, 2)
binary.BigEndian.PutUint16(errorCodeBytes, uint16(response.ErrorCode))
result = append(result, errorCodeBytes...)
// Throttle time (4 bytes, 0 = no throttling)
result = append(result, 0, 0, 0, 0)
return result
}
func (h *Handler) buildHeartbeatResponseV(response HeartbeatResponse, apiVersion uint16) []byte {
isFlexible := IsFlexibleVersion(12, apiVersion) // Heartbeat API key = 12
result := make([]byte, 0, 16)
// NOTE: Correlation ID is handled by writeResponseWithCorrelationID
// Do NOT include it in the response body
if isFlexible {
// FLEXIBLE V4+ FORMAT
// NOTE: Response header tagged fields are handled by writeResponseWithHeader
// Do NOT include them in the response body
// Throttle time (4 bytes, 0 = no throttling) - comes first in flexible format
result = append(result, 0, 0, 0, 0)
// Error code (2 bytes)
errorCodeBytes := make([]byte, 2)
binary.BigEndian.PutUint16(errorCodeBytes, uint16(response.ErrorCode))
result = append(result, errorCodeBytes...)
// Response body tagged fields (varint: 0x00 = empty)
result = append(result, 0x00)
} else if apiVersion >= 1 {
// NON-FLEXIBLE V1-V3 FORMAT: throttle_time_ms BEFORE error_code
// CRITICAL FIX: Kafka protocol specifies throttle_time_ms comes FIRST in v1+
// Throttle time (4 bytes, 0 = no throttling) - comes first in v1-v3
result = append(result, 0, 0, 0, 0)
// Error code (2 bytes)
errorCodeBytes := make([]byte, 2)
binary.BigEndian.PutUint16(errorCodeBytes, uint16(response.ErrorCode))
result = append(result, errorCodeBytes...)
} else {
// V0 FORMAT: Only error_code, NO throttle_time_ms
// Error code (2 bytes)
errorCodeBytes := make([]byte, 2)
binary.BigEndian.PutUint16(errorCodeBytes, uint16(response.ErrorCode))
result = append(result, errorCodeBytes...)
}
return result
}
func (h *Handler) buildLeaveGroupResponse(response LeaveGroupResponse, apiVersion uint16) []byte {
// LeaveGroup v0 only includes correlation_id and error_code (no throttle_time_ms, no members)
if apiVersion == 0 {
return h.buildLeaveGroupV0Response(response)
}
// For v1+ use the full response format
return h.buildLeaveGroupFullResponse(response)
}
func (h *Handler) buildLeaveGroupV0Response(response LeaveGroupResponse) []byte {
result := make([]byte, 0, 6)
// NOTE: Correlation ID is handled by writeResponseWithCorrelationID
// Do NOT include it in the response body
// Error code (2 bytes) - that's it for v0!
errorCodeBytes := make([]byte, 2)
binary.BigEndian.PutUint16(errorCodeBytes, uint16(response.ErrorCode))
result = append(result, errorCodeBytes...)
return result
}
func (h *Handler) buildLeaveGroupFullResponse(response LeaveGroupResponse) []byte {
estimatedSize := 16
for _, member := range response.Members {
estimatedSize += len(member.MemberID) + len(member.GroupInstanceID) + 8
}
result := make([]byte, 0, estimatedSize)
// NOTE: Correlation ID is handled by writeResponseWithCorrelationID
// Do NOT include it in the response body
// For LeaveGroup v1+, throttle_time_ms comes first (4 bytes)
result = append(result, 0, 0, 0, 0)
// Error code (2 bytes)
errorCodeBytes := make([]byte, 2)
binary.BigEndian.PutUint16(errorCodeBytes, uint16(response.ErrorCode))
result = append(result, errorCodeBytes...)
// Members array length (4 bytes)
membersLengthBytes := make([]byte, 4)
binary.BigEndian.PutUint32(membersLengthBytes, uint32(len(response.Members)))
result = append(result, membersLengthBytes...)
// Members
for _, member := range response.Members {
// Member ID length (2 bytes)
memberIDLength := make([]byte, 2)
binary.BigEndian.PutUint16(memberIDLength, uint16(len(member.MemberID)))
result = append(result, memberIDLength...)
// Member ID
result = append(result, []byte(member.MemberID)...)
// Group instance ID length (2 bytes)
instanceIDLength := make([]byte, 2)
binary.BigEndian.PutUint16(instanceIDLength, uint16(len(member.GroupInstanceID)))
result = append(result, instanceIDLength...)
// Group instance ID
if len(member.GroupInstanceID) > 0 {
result = append(result, []byte(member.GroupInstanceID)...)
}
// Error code (2 bytes)
memberErrorBytes := make([]byte, 2)
binary.BigEndian.PutUint16(memberErrorBytes, uint16(member.ErrorCode))
result = append(result, memberErrorBytes...)
}
return result
}
func (h *Handler) buildHeartbeatErrorResponse(correlationID uint32, errorCode int16) []byte {
response := HeartbeatResponse{
CorrelationID: correlationID,
ErrorCode: errorCode,
}
return h.buildHeartbeatResponse(response)
}
func (h *Handler) buildHeartbeatErrorResponseV(correlationID uint32, errorCode int16, apiVersion uint16) []byte {
response := HeartbeatResponse{
CorrelationID: correlationID,
ErrorCode: errorCode,
}
return h.buildHeartbeatResponseV(response, apiVersion)
}
func (h *Handler) buildLeaveGroupErrorResponse(correlationID uint32, errorCode int16, apiVersion uint16) []byte {
response := LeaveGroupResponse{
CorrelationID: correlationID,
ErrorCode: errorCode,
Members: []LeaveGroupMemberResponse{},
}
return h.buildLeaveGroupResponse(response, apiVersion)
}
func (h *Handler) updateGroupSubscriptionFromMembers(group *consumer.ConsumerGroup) {
// Update group's subscribed topics from remaining members
group.SubscribedTopics = make(map[string]bool)
for _, member := range group.Members {
for _, topic := range member.Subscription {
group.SubscribedTopics[topic] = true
}
}
}
|