mockforge-kafka 0.3.118

Kafka protocol support for MockForge
Documentation
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
use std::collections::HashMap;

/// Manages consumer groups for the Kafka broker
#[derive(Debug)]
pub struct ConsumerGroupManager {
    groups: HashMap<String, ConsumerGroup>,
}

#[derive(Debug)]
pub struct ConsumerGroup {
    pub group_id: String,
    pub members: HashMap<String, GroupMember>,
    pub coordinator: GroupCoordinator,
    pub offsets: HashMap<(String, i32), i64>, // (topic, partition) -> offset
}

#[derive(Debug)]
pub struct GroupMember {
    pub member_id: String,
    pub client_id: String,
    pub assignment: Vec<PartitionAssignment>,
}

#[derive(Debug, Clone)]
pub struct PartitionAssignment {
    pub topic: String,
    pub partitions: Vec<i32>,
}

#[derive(Debug)]
pub struct GroupCoordinator {
    pub coordinator_id: i32,
    pub host: String,
    pub port: i32,
}

impl ConsumerGroupManager {
    /// Create a new consumer group manager
    pub fn new() -> Self {
        Self {
            groups: HashMap::new(),
        }
    }
}

impl Default for ConsumerGroupManager {
    fn default() -> Self {
        Self::new()
    }
}

impl ConsumerGroupManager {
    /// Get a reference to all groups (for internal use)
    pub fn groups(&self) -> &HashMap<String, ConsumerGroup> {
        &self.groups
    }

    /// Join a consumer group
    pub async fn join_group(
        &mut self,
        group_id: &str,
        member_id: &str,
        client_id: &str,
    ) -> Result<JoinGroupResponse> {
        let group = self.groups.entry(group_id.to_string()).or_insert_with(|| ConsumerGroup {
            group_id: group_id.to_string(),
            members: HashMap::new(),
            coordinator: GroupCoordinator {
                coordinator_id: 1,
                host: "localhost".to_string(),
                port: 9092,
            },
            offsets: HashMap::new(),
        });

        group.members.insert(
            member_id.to_string(),
            GroupMember {
                member_id: member_id.to_string(),
                client_id: client_id.to_string(),
                assignment: vec![],
            },
        );

        Ok(JoinGroupResponse {
            generation_id: 1,
            protocol_name: "consumer".to_string(),
            leader: member_id.to_string(),
            member_id: member_id.to_string(),
            members: group.members.keys().cloned().collect(),
        })
    }

    /// Sync group assignment
    pub async fn sync_group(
        &mut self,
        group_id: &str,
        assignments: Vec<PartitionAssignment>,
        topics: &HashMap<String, crate::topics::Topic>,
    ) -> Result<()> {
        if let Some(group) = self.groups.get_mut(group_id) {
            // If assignments are provided, use them (leader assignment)
            if !assignments.is_empty() {
                // Distribute assignments to members
                for assignment in assignments {
                    // For simplicity, assign to all members (in real Kafka, leader assigns specific partitions to specific members)
                    for member in group.members.values_mut() {
                        member.assignment.push(assignment.clone());
                    }
                }
            } else {
                // Simple round-robin assignment if no assignments provided
                Self::assign_partitions_round_robin(group, topics);
            }
            Ok(())
        } else {
            Err(anyhow::anyhow!("Group {} does not exist", group_id))
        }
    }

    /// Assign partitions to group members using round-robin strategy
    fn assign_partitions_round_robin(
        group: &mut ConsumerGroup,
        topics: &HashMap<String, crate::topics::Topic>,
    ) {
        // Clear existing assignments for rebalance
        for member in group.members.values_mut() {
            member.assignment.clear();
        }

        let mut member_ids: Vec<String> = group.members.keys().cloned().collect();
        member_ids.sort(); // Sort for deterministic assignment

        let mut member_idx = 0;
        for (topic_name, topic) in topics {
            let num_partitions = topic.config.num_partitions as usize;
            for partition_id in 0..num_partitions {
                let member_id = &member_ids[member_idx % member_ids.len()];
                if let Some(member) = group.members.get_mut(member_id.as_str()) {
                    // Find or create assignment for this topic
                    let assignment = member.assignment.iter_mut().find(|a| a.topic == *topic_name);
                    if let Some(assignment) = assignment {
                        assignment.partitions.push(partition_id as i32);
                    } else {
                        member.assignment.push(PartitionAssignment {
                            topic: topic_name.clone(),
                            partitions: vec![partition_id as i32],
                        });
                    }
                }
                member_idx += 1;
            }
        }
    }

    /// Commit consumer offsets
    pub async fn commit_offsets(
        &mut self,
        group_id: &str,
        offsets: HashMap<(String, i32), i64>,
    ) -> Result<()> {
        if let Some(group) = self.groups.get_mut(group_id) {
            group.offsets.extend(offsets);
            Ok(())
        } else {
            Err(anyhow::anyhow!("Group {} does not exist", group_id))
        }
    }

    /// Get committed offsets for a group
    pub fn get_committed_offsets(&self, group_id: &str) -> HashMap<(String, i32), i64> {
        self.groups.get(group_id).map(|g| g.offsets.clone()).unwrap_or_default()
    }

    /// Simulate consumer lag
    pub async fn simulate_lag(
        &mut self,
        group_id: &str,
        topic: &str,
        lag: i64,
        topics: &HashMap<String, crate::topics::Topic>,
    ) {
        if let Some(group) = self.groups.get_mut(group_id) {
            // Get actual partition count from topics
            let num_partitions =
                topics.get(topic).map(|t| t.config.num_partitions).unwrap_or(1) as usize;
            // Simulate lag by setting committed offsets behind
            for partition in 0..num_partitions {
                let key = (topic.to_string(), partition as i32);
                let current_offset = group.offsets.get(&key).copied().unwrap_or(0);
                group.offsets.insert(key, current_offset.saturating_sub(lag));
            }
            tracing::info!(
                "Simulated lag of {} messages for group {} on topic {}",
                lag,
                group_id,
                topic
            );
        }
    }

    /// Trigger rebalance for a group
    pub async fn trigger_rebalance(&mut self, group_id: &str) {
        if let Some(group) = self.groups.get_mut(group_id) {
            // Simulate rebalance by clearing assignments and forcing rejoin
            for member in group.members.values_mut() {
                member.assignment.clear();
            }
            tracing::info!("Triggered rebalance for group {}", group_id);
        }
    }

    /// Reset consumer offsets
    pub async fn reset_offsets(
        &mut self,
        group_id: &str,
        topic: &str,
        to: &str,
        topics: &HashMap<String, crate::topics::Topic>,
    ) {
        if let Some(group) = self.groups.get_mut(group_id) {
            if let Some(topic_data) = topics.get(topic) {
                let num_partitions = topic_data.config.num_partitions as usize;
                for partition in 0..num_partitions {
                    let key = (topic.to_string(), partition as i32);
                    let target_offset = match to {
                        "earliest" => 0,
                        "latest" => topic_data.partitions[partition].high_watermark,
                        _ => return, // Invalid reset target
                    };
                    group.offsets.insert(key, target_offset);
                }
                tracing::info!("Reset offsets for group {} on topic {} to {}", group_id, topic, to);
            }
        }
    }
}

/// Response for join group request
#[derive(Debug)]
pub struct JoinGroupResponse {
    pub generation_id: i32,
    pub protocol_name: String,
    pub leader: String,
    pub member_id: String,
    pub members: Vec<String>,
}

type Result<T> = std::result::Result<T, anyhow::Error>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_consumer_group_manager_new() {
        let manager = ConsumerGroupManager::new();
        assert!(manager.groups().is_empty());
    }

    #[test]
    fn test_consumer_group_manager_default() {
        let manager = ConsumerGroupManager::default();
        assert!(manager.groups().is_empty());
    }

    #[test]
    fn test_partition_assignment_clone() {
        let assignment = PartitionAssignment {
            topic: "test-topic".to_string(),
            partitions: vec![0, 1, 2],
        };

        let cloned = assignment.clone();
        assert_eq!(assignment.topic, cloned.topic);
        assert_eq!(assignment.partitions, cloned.partitions);
    }

    #[test]
    fn test_partition_assignment_debug() {
        let assignment = PartitionAssignment {
            topic: "test".to_string(),
            partitions: vec![0],
        };
        let debug = format!("{:?}", assignment);
        assert!(debug.contains("PartitionAssignment"));
        assert!(debug.contains("test"));
    }

    #[test]
    fn test_group_member_debug() {
        let member = GroupMember {
            member_id: "member-1".to_string(),
            client_id: "client-1".to_string(),
            assignment: vec![],
        };
        let debug = format!("{:?}", member);
        assert!(debug.contains("GroupMember"));
        assert!(debug.contains("member-1"));
    }

    #[test]
    fn test_group_coordinator_debug() {
        let coordinator = GroupCoordinator {
            coordinator_id: 1,
            host: "localhost".to_string(),
            port: 9092,
        };
        let debug = format!("{:?}", coordinator);
        assert!(debug.contains("GroupCoordinator"));
        assert!(debug.contains("localhost"));
    }

    #[test]
    fn test_consumer_group_debug() {
        let group = ConsumerGroup {
            group_id: "test-group".to_string(),
            members: HashMap::new(),
            coordinator: GroupCoordinator {
                coordinator_id: 1,
                host: "localhost".to_string(),
                port: 9092,
            },
            offsets: HashMap::new(),
        };
        let debug = format!("{:?}", group);
        assert!(debug.contains("ConsumerGroup"));
        assert!(debug.contains("test-group"));
    }

    #[test]
    fn test_join_group_response_debug() {
        let response = JoinGroupResponse {
            generation_id: 1,
            protocol_name: "consumer".to_string(),
            leader: "member-1".to_string(),
            member_id: "member-1".to_string(),
            members: vec!["member-1".to_string()],
        };
        let debug = format!("{:?}", response);
        assert!(debug.contains("JoinGroupResponse"));
    }

    #[test]
    fn test_consumer_group_manager_debug() {
        let manager = ConsumerGroupManager::new();
        let debug = format!("{:?}", manager);
        assert!(debug.contains("ConsumerGroupManager"));
    }

    #[tokio::test]
    async fn test_join_group() {
        let mut manager = ConsumerGroupManager::new();
        let response = manager.join_group("group-1", "member-1", "client-1").await.unwrap();

        assert_eq!(response.generation_id, 1);
        assert_eq!(response.protocol_name, "consumer");
        assert_eq!(response.member_id, "member-1");
        assert!(response.members.contains(&"member-1".to_string()));
    }

    #[tokio::test]
    async fn test_join_group_multiple_members() {
        let mut manager = ConsumerGroupManager::new();

        manager.join_group("group-1", "member-1", "client-1").await.unwrap();
        let response2 = manager.join_group("group-1", "member-2", "client-2").await.unwrap();

        assert_eq!(response2.members.len(), 2);
    }

    #[tokio::test]
    async fn test_commit_offsets() {
        let mut manager = ConsumerGroupManager::new();
        manager.join_group("group-1", "member-1", "client-1").await.unwrap();

        let mut offsets = HashMap::new();
        offsets.insert(("topic-1".to_string(), 0), 100);
        offsets.insert(("topic-1".to_string(), 1), 200);

        manager.commit_offsets("group-1", offsets).await.unwrap();

        let committed = manager.get_committed_offsets("group-1");
        assert_eq!(committed.get(&("topic-1".to_string(), 0)), Some(&100));
        assert_eq!(committed.get(&("topic-1".to_string(), 1)), Some(&200));
    }

    #[tokio::test]
    async fn test_commit_offsets_nonexistent_group() {
        let mut manager = ConsumerGroupManager::new();

        let mut offsets = HashMap::new();
        offsets.insert(("topic-1".to_string(), 0), 100);

        let result = manager.commit_offsets("nonexistent", offsets).await;
        assert!(result.is_err());
    }

    #[test]
    fn test_get_committed_offsets_nonexistent_group() {
        let manager = ConsumerGroupManager::new();
        let offsets = manager.get_committed_offsets("nonexistent");
        assert!(offsets.is_empty());
    }

    #[tokio::test]
    async fn test_trigger_rebalance() {
        let mut manager = ConsumerGroupManager::new();
        manager.join_group("group-1", "member-1", "client-1").await.unwrap();

        // Add assignment
        if let Some(group) = manager.groups.get_mut("group-1") {
            if let Some(member) = group.members.get_mut("member-1") {
                member.assignment.push(PartitionAssignment {
                    topic: "test".to_string(),
                    partitions: vec![0, 1],
                });
            }
        }

        // Trigger rebalance
        manager.trigger_rebalance("group-1").await;

        // Assignments should be cleared
        if let Some(group) = manager.groups.get("group-1") {
            if let Some(member) = group.members.get("member-1") {
                assert!(member.assignment.is_empty());
            }
        }
    }
}