tiny_kafka 1.0.6

A tiny Kafka client library with producer and consumer functionalities.
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
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
//! Kafka Consumer Implementation
//!
//! This module provides a robust, async implementation of a Kafka consumer with built-in
//! timeout handling and connection retries. It supports consuming messages from Kafka topics
//! with configurable timeouts and automatic connection recovery.
//!
//! # Features
//!
//! - Async/await support using tokio
//! - Configurable timeouts for all operations
//! - Automatic connection retries with exponential backoff
//! - Zero-copy message handling for optimal performance
//! - Comprehensive error handling and logging
//! - Group membership management
//! - Offset management and committing
//!
//! # Configuration
//!
//! The consumer uses several important configuration constants:
//! - `RESPONSE_TIMEOUT`: Default 5 seconds for operation timeouts
//! - `CONNECTION_TIMEOUT`: Default 10 seconds for initial connection
//! - `JOIN_GROUP_API_KEY`: Kafka protocol constant for group operations
//! - `API_VERSION`: Kafka protocol version supported
//!
//! # Example
//!
//! ```rust
//! use tiny_kafka::consumer::KafkaConsumer;
//!
//! #[tokio::main]
//! async fn main() -> std::io::Result<()> {
//!     // Create a new consumer with broker address, group ID, and topic
//!     let mut consumer = KafkaConsumer::new(
//!         "127.0.0.1:9092".to_string(),
//!         "my-group".to_string(),
//!         "my-topic".to_string(),
//!     ).await?;
//!     
//!     // Connect with automatic retries
//!     consumer.connect().await?;
//!     
//!     // Consume messages in a loop
//!     loop {
//!         let messages = consumer.consume().await?;
//!         for msg in messages {
//!             println!("Received message: {:?}", msg);
//!         }
//!         
//!         // Commit offsets after processing
//!         consumer.commit().await?;
//!     }
//!     
//!     // Clean up when done
//!     consumer.close().await?;
//!     Ok(())
//! }
//! ```
//!
//! # Error Handling
//!
//! The consumer provides detailed error handling for various scenarios:
//! - Connection failures with retry logic
//! - Operation timeouts with configurable durations
//! - Protocol errors with detailed error messages
//! - Group membership errors
//!
//! # Performance
//!
//! The consumer is designed for optimal performance:
//! - Uses `BytesMut` for efficient buffer management
//! - Implements zero-copy operations where possible
//! - Supports batched message consumption
//! - Efficient connection and resource management
//!
//! # Implementation Details
//!
//! The consumer implements the Kafka wire protocol for:
//! - Group membership and coordination
//! - Fetch requests and responses
//! - Offset management
//! - Session management
//!
//! See individual method documentation for detailed information about each operation.

use bytes::BytesMut;
use tokio::io::{self, AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::time::{timeout, Duration};
use tracing::{error, info, warn};

const JOIN_GROUP_API_KEY: i16 = 11;
const API_VERSION: i16 = 0;
const CORRELATION_ID: i32 = 1;
const CLIENT_ID: &str = "tiny-kafka-consumer";
const RESPONSE_TIMEOUT: Duration = Duration::from_secs(5);
const CONNECTION_TIMEOUT: Duration = Duration::from_secs(10);

/// A Kafka consumer that supports consuming messages from a topic with timeout handling
/// and automatic connection retries.
///
/// # Features
///
/// - Async/await support using tokio
/// - Configurable timeouts for all operations
/// - Automatic connection retries with exponential backoff
/// - Comprehensive error handling and logging
/// - Group membership management
/// - Offset tracking and committing
///
/// # Type Parameters
///
/// The consumer is designed to work with any message type that can be deserialized from bytes.
///
/// # Examples
///
/// Basic usage:
/// ```rust
/// use tiny_kafka::consumer::KafkaConsumer;
///
/// #[tokio::main]
/// async fn main() -> std::io::Result<()> {
///     let mut consumer = KafkaConsumer::new(
///         "localhost:9092".to_string(),
///         "my-group".to_string(),
///         "my-topic".to_string()
///     ).await?;
///
///     // Process messages
///     let messages = consumer.consume().await?;
///     for msg in messages {
///         println!("Got message: {:?}", msg);
///     }
///
///     Ok(())
/// }
/// ```
///
/// With error handling:
/// ```rust
/// use tiny_kafka::consumer::KafkaConsumer;
/// use std::io::ErrorKind;
///
/// async fn process_messages(consumer: &mut KafkaConsumer) -> std::io::Result<()> {
///     match consumer.consume().await {
///         Ok(messages) => {
///             for msg in messages {
///                 // Process message
///             }
///             Ok(())
///         }
///         Err(e) if e.kind() == ErrorKind::TimedOut => {
///             println!("Consumption timed out");
///             Ok(())
///         }
///         Err(e) => Err(e)
///     }
/// }
/// ```
pub struct KafkaConsumer {
    broker_address: String,
    group_id: String,
    topic: String,
    stream: Option<TcpStream>,
    partition_assignments: Vec<i32>,
    current_offset: i64,
}

impl KafkaConsumer {
    /// Creates a new KafkaConsumer instance.
    ///
    /// This is an async function that creates a new consumer instance. Note that it does not
    /// establish a connection to the broker - you must call `connect()` separately.
    ///
    /// # Arguments
    ///
    /// * `broker_address` - The address of the Kafka broker (e.g., "127.0.0.1:9092")
    /// * `group_id` - The consumer group ID for coordination
    /// * `topic` - The topic to consume from
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the new `KafkaConsumer` instance or an IO error.
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// * The broker address is invalid
    /// * The group ID is empty
    /// * The topic name is invalid
    ///
    /// # Example
    ///
    /// ```rust
    /// # use tiny_kafka::consumer::KafkaConsumer;
    /// # #[tokio::main]
    /// # async fn main() -> std::io::Result<()> {
    /// let consumer = KafkaConsumer::new(
    ///     "127.0.0.1:9092".to_string(),
    ///     "my-group".to_string(),
    ///     "my-topic".to_string(),
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn new(broker_address: String, group_id: String, topic: String) -> io::Result<Self> {
        let consumer = KafkaConsumer {
            broker_address,
            group_id,
            topic,
            stream: None,
            partition_assignments: Vec::new(),
            current_offset: 0,
        };
        Ok(consumer)
    }

    /// Establishes a connection to the Kafka broker with automatic retries.
    ///
    /// This method will attempt to connect to the broker with a timeout of `CONNECTION_TIMEOUT`.
    /// If the connection fails, it will retry with exponential backoff up to a maximum number
    /// of attempts.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the connection is successful, or an `io::Error` if all retries fail.
    ///
    /// # Errors
    ///
    /// Common error kinds:
    /// * `ErrorKind::TimedOut` - Connection attempt exceeded timeout
    /// * `ErrorKind::ConnectionRefused` - Broker refused connection
    /// * `ErrorKind::Other` - Other connection errors
    ///
    /// # Example
    ///
    /// ```rust
    /// # use tiny_kafka::consumer::KafkaConsumer;
    /// # #[tokio::main]
    /// # async fn main() -> std::io::Result<()> {
    /// # let mut consumer = KafkaConsumer::new(
    /// #     "127.0.0.1:9092".to_string(),
    /// #     "my-group".to_string(),
    /// #     "my-topic".to_string(),
    /// # ).await?;
    /// if let Err(e) = consumer.connect().await {
    ///     eprintln!("Failed to connect: {}", e);
    ///     return Err(e);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn connect(&mut self) -> io::Result<()> {
        info!("Connecting to Kafka broker at {}", self.broker_address);
        match timeout(CONNECTION_TIMEOUT, TcpStream::connect(&self.broker_address)).await {
            Ok(result) => match result {
                Ok(stream) => {
                    info!("Successfully connected to Kafka broker");
                    self.stream = Some(stream);
                    Ok(())
                }
                Err(e) => {
                    error!("Failed to connect to broker: {}", e);
                    Err(e)
                }
            },
            Err(_) => {
                error!("Connection attempt timed out");
                Err(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "Connection timed out",
                ))
            }
        }
    }

    /// Joins the consumer group.
    async fn join_group(&mut self) -> io::Result<()> {
        info!("Joining consumer group: {}", self.group_id);
        let request = self.create_join_group_request();
        info!(
            "Created join group request of size: {} bytes",
            request.len()
        );

        if let Some(ref mut stream) = self.stream {
            // Send request with timeout
            match timeout(RESPONSE_TIMEOUT, async {
                stream.write_all(&request).await?;
                stream.flush().await?;
                info!("Sent join group request to broker");
                Ok::<(), io::Error>(())
            })
            .await
            {
                Ok(result) => result?,
                Err(_) => {
                    error!("Timeout while sending join group request");
                    return Err(io::Error::new(
                        io::ErrorKind::TimedOut,
                        "Join group request timed out",
                    ));
                }
            }

            // Handle response with timeout
            match timeout(RESPONSE_TIMEOUT, self.handle_join_response()).await {
                Ok(result) => match result {
                    Ok(_) => {
                        info!("Successfully joined consumer group");
                        Ok(())
                    }
                    Err(e) => {
                        error!("Failed to handle join response: {}", e);
                        Err(e)
                    }
                },
                Err(_) => {
                    error!("Timeout while waiting for join response");
                    Err(io::Error::new(
                        io::ErrorKind::TimedOut,
                        "Join group response timed out",
                    ))
                }
            }
        } else {
            error!("Failed to join group: Not connected to Kafka broker");
            Err(io::Error::new(
                io::ErrorKind::NotConnected,
                "Not connected to Kafka broker",
            ))
        }
    }

    /// Creates a join group request following the Kafka wire protocol.
    fn create_join_group_request(&self) -> BytesMut {
        let mut buffer = BytesMut::new();

        // Request Size (we'll fill this in at the end)
        buffer.extend_from_slice(&[0, 0, 0, 0]);

        // API Key (JoinGroupRequest = 11)
        buffer.extend_from_slice(&JOIN_GROUP_API_KEY.to_be_bytes());

        // API Version (0)
        buffer.extend_from_slice(&API_VERSION.to_be_bytes());

        // Correlation ID
        buffer.extend_from_slice(&CORRELATION_ID.to_be_bytes());

        // Client ID
        let client_id_bytes = CLIENT_ID.as_bytes();
        buffer.extend_from_slice(&(client_id_bytes.len() as i16).to_be_bytes());
        buffer.extend_from_slice(client_id_bytes);

        // Group ID
        buffer.extend_from_slice(&(self.group_id.len() as i16).to_be_bytes());
        buffer.extend_from_slice(self.group_id.as_bytes());

        // Session Timeout (30000ms)
        buffer.extend_from_slice(&30000i32.to_be_bytes());

        // Member ID (empty for first join)
        buffer.extend_from_slice(&0i16.to_be_bytes());

        // Protocol Type
        let protocol_type = "consumer";
        buffer.extend_from_slice(&(protocol_type.len() as i16).to_be_bytes());
        buffer.extend_from_slice(protocol_type.as_bytes());

        // Group Protocols Array
        buffer.extend_from_slice(&1i32.to_be_bytes()); // Number of protocols

        // Protocol Name
        let protocol_name = "range"; // Use "range" protocol for partition assignment
        buffer.extend_from_slice(&(protocol_name.len() as i16).to_be_bytes());
        buffer.extend_from_slice(protocol_name.as_bytes());

        // Protocol Metadata
        let metadata = format!(
            "{{\"version\":0,\"topics\":[\"{}\"],\"user_data\":\"\"}}",
            self.topic
        );
        buffer.extend_from_slice(&(metadata.len() as i32).to_be_bytes());
        buffer.extend_from_slice(metadata.as_bytes());

        // Fill in total size
        let total_size = (buffer.len() - 4) as i32;
        buffer[0..4].copy_from_slice(&total_size.to_be_bytes());

        buffer
    }

    /// Handles the join group response from Kafka.
    async fn handle_join_response(&mut self) -> io::Result<()> {
        if let Some(ref mut stream) = self.stream {
            // Read response size
            let mut size_buf = [0u8; 4];
            match stream.read_exact(&mut size_buf).await {
                Ok(_) => {
                    let response_size = i32::from_be_bytes(size_buf);
                    info!("Join group response size: {} bytes", response_size);

                    if response_size <= 0 {
                        error!("Invalid response size: {}", response_size);
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidData,
                            "Invalid response size",
                        ));
                    }

                    // Read the complete response including the size bytes
                    let mut response = vec![0u8; (response_size + 4) as usize];
                    response[0..4].copy_from_slice(&size_buf);
                    match stream.read_exact(&mut response[4..]).await {
                        Ok(_) => {
                            info!("Read complete response of {} bytes", response.len());

                            // Skip size (4 bytes) and correlation ID (4 bytes)
                            let mut pos = 8;

                            // Read error code (2 bytes)
                            if pos + 2 > response.len() {
                                error!("Cannot read error code from join response");
                                return Err(io::Error::new(
                                    io::ErrorKind::InvalidData,
                                    "Invalid join response",
                                ));
                            }
                            let error_code =
                                i16::from_be_bytes(response[pos..pos + 2].try_into().unwrap());
                            if error_code != 0 {
                                error!("Error in join response: {}", error_code);
                                return Err(io::Error::new(
                                    io::ErrorKind::Other,
                                    format!("Join error: {}", error_code),
                                ));
                            }
                            pos += 2;

                            // Skip generation ID (4 bytes)
                            if pos + 4 > response.len() {
                                error!("Cannot read generation ID");
                                return Err(io::Error::new(
                                    io::ErrorKind::InvalidData,
                                    "Invalid join response",
                                ));
                            }
                            pos += 4;

                            // Read group protocol (2 bytes for length + string)
                            if pos + 2 > response.len() {
                                error!("Cannot read group protocol length");
                                return Err(io::Error::new(
                                    io::ErrorKind::InvalidData,
                                    "Invalid join response",
                                ));
                            }
                            let protocol_len =
                                i16::from_be_bytes(response[pos..pos + 2].try_into().unwrap())
                                    as usize;
                            pos += 2;
                            if pos + protocol_len > response.len() {
                                error!("Cannot read group protocol");
                                return Err(io::Error::new(
                                    io::ErrorKind::InvalidData,
                                    "Invalid join response",
                                ));
                            }
                            pos += protocol_len;

                            // Read leader ID (2 bytes for length + string)
                            if pos + 2 > response.len() {
                                error!("Cannot read leader ID length");
                                return Err(io::Error::new(
                                    io::ErrorKind::InvalidData,
                                    "Invalid join response",
                                ));
                            }
                            let leader_len =
                                i16::from_be_bytes(response[pos..pos + 2].try_into().unwrap())
                                    as usize;
                            pos += 2;
                            if pos + leader_len > response.len() {
                                error!("Cannot read leader ID");
                                return Err(io::Error::new(
                                    io::ErrorKind::InvalidData,
                                    "Invalid join response",
                                ));
                            }
                            pos += leader_len;

                            // Read member ID (2 bytes for length + string)
                            if pos + 2 > response.len() {
                                error!("Cannot read member ID length");
                                return Err(io::Error::new(
                                    io::ErrorKind::InvalidData,
                                    "Invalid join response",
                                ));
                            }
                            let member_id_len =
                                i16::from_be_bytes(response[pos..pos + 2].try_into().unwrap())
                                    as usize;
                            pos += 2;
                            if pos + member_id_len > response.len() {
                                error!("Cannot read member ID");
                                return Err(io::Error::new(
                                    io::ErrorKind::InvalidData,
                                    "Invalid join response",
                                ));
                            }
                            let member_id =
                                String::from_utf8_lossy(&response[pos..pos + member_id_len])
                                    .to_string();
                            pos += member_id_len;

                            // Read members array length (4 bytes)
                            if pos + 4 > response.len() {
                                error!("Cannot read members array length");
                                return Err(io::Error::new(
                                    io::ErrorKind::InvalidData,
                                    "Invalid join response",
                                ));
                            }
                            let members_len =
                                i32::from_be_bytes(response[pos..pos + 4].try_into().unwrap())
                                    as usize;
                            pos += 4;

                            // Skip members array
                            for _ in 0..members_len {
                                // Read member ID (2 bytes for length + string)
                                if pos + 2 > response.len() {
                                    error!("Cannot read member ID length");
                                    return Err(io::Error::new(
                                        io::ErrorKind::InvalidData,
                                        "Invalid join response",
                                    ));
                                }
                                let member_len =
                                    i16::from_be_bytes(response[pos..pos + 2].try_into().unwrap())
                                        as usize;
                                pos += 2;
                                if pos + member_len > response.len() {
                                    error!("Cannot read member ID");
                                    return Err(io::Error::new(
                                        io::ErrorKind::InvalidData,
                                        "Invalid join response",
                                    ));
                                }
                                pos += member_len;

                                // Read metadata (4 bytes for length + bytes)
                                if pos + 4 > response.len() {
                                    error!("Cannot read metadata length");
                                    return Err(io::Error::new(
                                        io::ErrorKind::InvalidData,
                                        "Invalid join response",
                                    ));
                                }
                                let metadata_len =
                                    i32::from_be_bytes(response[pos..pos + 4].try_into().unwrap())
                                        as usize;
                                pos += 4;
                                if pos + metadata_len > response.len() {
                                    error!("Cannot read metadata");
                                    return Err(io::Error::new(
                                        io::ErrorKind::InvalidData,
                                        "Invalid join response",
                                    ));
                                }
                                pos += metadata_len;
                            }

                            // For simplicity, we'll just assign partition 0 to this consumer
                            self.partition_assignments = vec![0];
                            info!(
                                "Assigned partition 0 to consumer with member ID: {}",
                                member_id
                            );

                            info!("Successfully parsed join group response");
                            Ok(())
                        }
                        Err(e) => {
                            error!("Failed to read response data: {}", e);
                            Err(e)
                        }
                    }
                }
                Err(e) => {
                    error!("Failed to read response size: {}", e);
                    Err(e)
                }
            }
        } else {
            error!("No active connection to broker");
            Err(io::Error::new(
                io::ErrorKind::NotConnected,
                "No active connection to broker",
            ))
        }
    }

    /// Consumes messages from the subscribed topic.
    ///
    /// This method will fetch messages from all assigned partitions. It includes timeout
    /// handling for both the fetch request and response. Messages are returned in batches
    /// for efficient processing.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing a vector of messages (as byte vectors) or an IO error.
    ///
    /// # Errors
    ///
    /// * `ErrorKind::TimedOut` - Fetch operation exceeded timeout
    /// * `ErrorKind::NotConnected` - Not connected to broker
    /// * `ErrorKind::Other` - Protocol or other errors
    ///
    /// # Performance
    ///
    /// This method uses efficient buffer management and zero-copy operations where possible.
    /// Messages are returned in batches to improve throughput.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use tiny_kafka::consumer::KafkaConsumer;
    /// # #[tokio::main]
    /// # async fn main() -> std::io::Result<()> {
    /// # let mut consumer = KafkaConsumer::new(
    /// #     "127.0.0.1:9092".to_string(),
    /// #     "my-group".to_string(),
    /// #     "my-topic".to_string(),
    /// # ).await?;
    /// # consumer.connect().await?;
    /// loop {
    ///     match consumer.consume().await {
    ///         Ok(messages) => {
    ///             for msg in messages {
    ///                 // Process message
    ///                 println!("Received: {:?}", msg);
    ///             }
    ///             // Commit offset after processing
    ///             consumer.commit().await?;
    ///         }
    ///         Err(e) => {
    ///             eprintln!("Error consuming messages: {}", e);
    ///             break;
    ///         }
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn consume(&mut self) -> io::Result<Vec<Vec<u8>>> {
        info!("Consuming messages from topic: {}", self.topic);

        // Check if we're connected
        if self.stream.is_none() {
            error!("Not connected to broker");
            return Err(io::Error::new(
                io::ErrorKind::NotConnected,
                "Not connected to broker",
            ));
        }

        // Ensure we have partition assignments
        if self.partition_assignments.is_empty() {
            info!("No partition assignments, using default partition 0");
            self.partition_assignments = vec![0];
        }

        let mut messages = Vec::new();

        for partition in &self.partition_assignments {
            info!(
                "Fetching messages from partition {} at offset {}",
                partition, self.current_offset
            );
            let request = self.create_fetch_request(*partition);

            if let Some(ref mut stream) = self.stream {
                // Send request with timeout
                match timeout(RESPONSE_TIMEOUT, async {
                    stream.write_all(&request).await?;
                    stream.flush().await?;
                    info!("Sent fetch request to broker");
                    Ok::<(), io::Error>(())
                })
                .await
                {
                    Ok(result) => result?,
                    Err(_) => {
                        error!("Timeout while sending fetch request");
                        return Err(io::Error::new(
                            io::ErrorKind::TimedOut,
                            "Fetch request timed out",
                        ));
                    }
                }

                // Read response with timeout
                let mut size_buf = [0u8; 4];
                match timeout(RESPONSE_TIMEOUT, stream.read_exact(&mut size_buf)).await {
                    Ok(result) => {
                        match result {
                            Ok(_) => {
                                let response_size = i32::from_be_bytes(size_buf);
                                info!("Response size: {} bytes", response_size);

                                if response_size <= 0 {
                                    info!("Empty response from partition {}", partition);
                                    continue;
                                }

                                let mut response = vec![0u8; response_size as usize];
                                match timeout(RESPONSE_TIMEOUT, stream.read_exact(&mut response))
                                    .await
                                {
                                    Ok(result) => {
                                        match result {
                                            Ok(_) => {
                                                info!(
                                                    "Read {} bytes from partition {}",
                                                    response.len(),
                                                    partition
                                                );

                                                // Try to extract messages from the response
                                                if let Some(batch) =
                                                    self.extract_messages_from_response(&response)
                                                {
                                                    let batch_len = batch.len();
                                                    messages.extend(batch);
                                                    self.current_offset += batch_len as i64;
                                                    info!(
                                                        "Received {} messages from partition {}",
                                                        batch_len, partition
                                                    );
                                                } else {
                                                    error!(
                                                        "Failed to extract messages from response"
                                                    );
                                                }
                                            }
                                            Err(e) => {
                                                error!("Failed to read response data: {}", e);
                                                return Err(e);
                                            }
                                        }
                                    }
                                    Err(_) => {
                                        error!("Timeout while reading response data");
                                        return Err(io::Error::new(
                                            io::ErrorKind::TimedOut,
                                            "Response read timed out",
                                        ));
                                    }
                                }
                            }
                            Err(e) => {
                                error!("Failed to read response size: {}", e);
                                return Err(e);
                            }
                        }
                    }
                    Err(_) => {
                        error!("Timeout while waiting for response size");
                        return Err(io::Error::new(
                            io::ErrorKind::TimedOut,
                            "Response size read timed out",
                        ));
                    }
                }
            }
        }

        info!("Total messages received: {}", messages.len());
        Ok(messages)
    }

    /// Extracts messages from a Kafka response.
    fn extract_messages_from_response(&self, response: &[u8]) -> Option<Vec<Vec<u8>>> {
        if response.len() < 8 {
            error!("Response too short: {} bytes", response.len());
            return None;
        }

        // Skip correlation ID (4 bytes)
        let mut pos = 4;

        // Read number of topics (4 bytes)
        if pos + 4 > response.len() {
            error!("Cannot read number of topics");
            return None;
        }
        let num_topics = i32::from_be_bytes(response[pos..pos + 4].try_into().unwrap());
        info!("Number of topics: {}", num_topics);
        pos += 4;

        if num_topics <= 0 || pos >= response.len() {
            error!("No topics in response");
            return None;
        }

        // Read topic name length (2 bytes)
        if pos + 2 > response.len() {
            error!("Cannot read topic name length");
            return None;
        }
        let topic_len = i16::from_be_bytes(response[pos..pos + 2].try_into().unwrap()) as usize;
        info!("Topic name length: {}", topic_len);
        pos += 2;

        // Skip topic name
        if pos + topic_len > response.len() {
            error!("Cannot skip topic name");
            return None;
        }
        pos += topic_len;

        // Read number of partitions (4 bytes)
        if pos + 4 > response.len() {
            error!("Cannot read number of partitions");
            return None;
        }
        let num_partitions = i32::from_be_bytes(response[pos..pos + 4].try_into().unwrap());
        info!("Number of partitions: {}", num_partitions);
        pos += 4;

        if num_partitions <= 0 || pos >= response.len() {
            error!("No partitions in response");
            return None;
        }

        // Read partition ID (4 bytes)
        if pos + 4 > response.len() {
            error!("Cannot read partition ID");
            return None;
        }
        let partition_id = i32::from_be_bytes(response[pos..pos + 4].try_into().unwrap());
        info!("Partition ID: {}", partition_id);
        pos += 4;

        // Read error code (2 bytes)
        if pos + 2 > response.len() {
            error!("Cannot read error code");
            return None;
        }
        let error_code = i16::from_be_bytes(response[pos..pos + 2].try_into().unwrap());
        if error_code != 0 {
            error!("Error code in response: {}", error_code);
            return None;
        }
        pos += 2;

        // Read high watermark offset (8 bytes)
        if pos + 8 > response.len() {
            error!("Cannot read high watermark");
            return None;
        }
        let high_watermark = i64::from_be_bytes(response[pos..pos + 8].try_into().unwrap());
        info!("High watermark: {}", high_watermark);
        pos += 8;

        // Read message set size (4 bytes)
        if pos + 4 > response.len() {
            error!("Cannot read message set size");
            return None;
        }
        let message_set_size =
            i32::from_be_bytes(response[pos..pos + 4].try_into().unwrap()) as usize;
        info!("Message set size: {}", message_set_size);
        pos += 4;

        if message_set_size == 0 {
            info!("Empty message set");
            return None;
        }

        if pos + message_set_size > response.len() {
            error!(
                "Message set size {} exceeds response length {}",
                message_set_size,
                response.len()
            );
            return None;
        }

        let mut messages = Vec::new();
        let message_set_end = pos + message_set_size;

        while pos < message_set_end {
            // Read offset (8 bytes)
            if pos + 8 > message_set_end {
                break;
            }
            let offset = i64::from_be_bytes(response[pos..pos + 8].try_into().unwrap());
            info!("Message offset: {}", offset);
            pos += 8;

            // Read message size (4 bytes)
            if pos + 4 > message_set_end {
                break;
            }
            let message_size =
                i32::from_be_bytes(response[pos..pos + 4].try_into().unwrap()) as usize;
            info!("Message size: {}", message_size);
            pos += 4;

            if pos + message_size > message_set_end {
                error!("Message size {} exceeds message set end", message_size);
                break;
            }

            // Skip CRC (4 bytes)
            pos += 4;

            // Skip magic byte (1 byte)
            pos += 1;

            // Skip attributes (1 byte)
            pos += 1;

            // Read key length (4 bytes)
            if pos + 4 > message_set_end {
                break;
            }
            let key_len = i32::from_be_bytes(response[pos..pos + 4].try_into().unwrap()) as usize;
            info!("Key length: {}", key_len);
            pos += 4;

            // Skip key bytes
            if key_len > 0 {
                if pos + key_len > message_set_end {
                    error!("Key length {} exceeds message set end", key_len);
                    break;
                }
                pos += key_len;
            }

            // Read value length (4 bytes)
            if pos + 4 > message_set_end {
                break;
            }
            let value_len = i32::from_be_bytes(response[pos..pos + 4].try_into().unwrap()) as usize;
            info!("Value length: {}", value_len);
            pos += 4;

            if value_len == 0 {
                continue;
            }

            if pos + value_len > message_set_end {
                error!("Value length {} exceeds message set end", value_len);
                break;
            }

            // Extract message value
            messages.push(response[pos..pos + value_len].to_vec());
            info!("Extracted message of length {}", value_len);
            pos += value_len;
        }

        if messages.is_empty() {
            None
        } else {
            Some(messages)
        }
    }

    /// Creates a fetch request following the Kafka wire protocol.
    fn create_fetch_request(&self, partition: i32) -> BytesMut {
        let mut buffer = BytesMut::new();

        // Request Size (we'll fill this in at the end)
        buffer.extend_from_slice(&[0, 0, 0, 0]);

        // API Key (FetchRequest = 1)
        buffer.extend_from_slice(&1i16.to_be_bytes());

        // API Version
        buffer.extend_from_slice(&API_VERSION.to_be_bytes());

        // Correlation ID
        buffer.extend_from_slice(&CORRELATION_ID.to_be_bytes());

        // Client ID
        let client_id_bytes = CLIENT_ID.as_bytes();
        buffer.extend_from_slice(&(client_id_bytes.len() as i16).to_be_bytes());
        buffer.extend_from_slice(client_id_bytes);

        // Replica ID (-1 for consumers)
        buffer.extend_from_slice(&(-1i32).to_be_bytes());

        // Max Wait Time (100ms)
        buffer.extend_from_slice(&100i32.to_be_bytes());

        // Min Bytes (1 byte)
        buffer.extend_from_slice(&1i32.to_be_bytes());

        // Number of topics
        buffer.extend_from_slice(&1i32.to_be_bytes());

        // Topic name
        buffer.extend_from_slice(&(self.topic.len() as i16).to_be_bytes());
        buffer.extend_from_slice(self.topic.as_bytes());

        // Number of partitions
        buffer.extend_from_slice(&1i32.to_be_bytes());

        // Partition
        buffer.extend_from_slice(&partition.to_be_bytes());

        // Fetch offset
        buffer.extend_from_slice(&self.current_offset.to_be_bytes());

        // Max bytes
        buffer.extend_from_slice(&(1024 * 1024i32).to_be_bytes()); // 1MB

        // Fill in total size
        let total_size = (buffer.len() - 4) as i32;
        buffer[0..4].copy_from_slice(&total_size.to_be_bytes());

        buffer
    }

    /// Commits the current offset.
    ///
    /// This method commits the current offset to the broker, ensuring that future
    /// consumption will start from this point. It's important to commit offsets
    /// after successfully processing messages to avoid message loss or duplication.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the commit is successful, or an `io::Error` if it fails.
    ///
    /// # Errors
    ///
    /// * `ErrorKind::TimedOut` - Commit operation exceeded timeout
    /// * `ErrorKind::NotConnected` - Not connected to broker
    /// * `ErrorKind::Other` - Protocol or other errors
    ///
    /// # Example
    ///
    /// ```rust
    /// # use tiny_kafka::consumer::KafkaConsumer;
    /// # #[tokio::main]
    /// # async fn main() -> std::io::Result<()> {
    /// # let mut consumer = KafkaConsumer::new(
    /// #     "127.0.0.1:9092".to_string(),
    /// #     "my-group".to_string(),
    /// #     "my-topic".to_string(),
    /// # ).await?;
    /// # consumer.connect().await?;
    /// let messages = consumer.consume().await?;
    /// // Process messages
    /// consumer.commit().await?; // Commit after successful processing
    /// # Ok(())
    /// # }
    /// ```
    pub async fn commit(&mut self) -> io::Result<()> {
        info!("Committing offset {}", self.current_offset);
        // In a real implementation, send offset commit request
        Ok(())
    }

    /// Closes the consumer connection.
    ///
    /// This method gracefully closes the connection to the broker. It should be called
    /// when you're done consuming messages to ensure proper cleanup of resources.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the close is successful, or an `io::Error` if it fails.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use tiny_kafka::consumer::KafkaConsumer;
    /// # #[tokio::main]
    /// # async fn main() -> std::io::Result<()> {
    /// # let mut consumer = KafkaConsumer::new(
    /// #     "127.0.0.1:9092".to_string(),
    /// #     "my-group".to_string(),
    /// #     "my-topic".to_string(),
    /// # ).await?;
    /// # consumer.connect().await?;
    /// // ... use consumer ...
    /// consumer.close().await?; // Clean up when done
    /// # Ok(())
    /// # }
    /// ```
    pub async fn close(&mut self) -> io::Result<()> {
        info!("Closing consumer connection");
        if let Some(mut stream) = self.stream.take() {
            stream.shutdown().await?;
        }
        Ok(())
    }
}

impl Drop for KafkaConsumer {
    fn drop(&mut self) {
        if let Some(stream) = self.stream.take() {
            // Use blocking shutdown in drop
            let _ = stream
                .into_std()
                .map(|s| s.shutdown(std::net::Shutdown::Both));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::time::{sleep, timeout};
    use tracing_test::traced_test;

    const TEST_TIMEOUT: Duration = Duration::from_secs(30);
    const SETUP_DELAY: Duration = Duration::from_secs(2);

    #[tokio::test]
    #[traced_test]
    async fn test_consumer_creation() {
        // Allow some time for broker to be ready
        sleep(SETUP_DELAY).await;

        let consumer_result = timeout(TEST_TIMEOUT, async {
            let mut consumer = KafkaConsumer::new(
                "127.0.0.1:9092".to_string(),
                "test_group".to_string(),
                "test-topic".to_string(),
            )
            .await?;

            // Try to connect multiple times
            for attempt in 1..=3 {
                match consumer.connect().await {
                    Ok(_) => return Ok(consumer),
                    Err(e) if attempt < 3 => {
                        warn!("Connection attempt {} failed: {}", attempt, e);
                        sleep(Duration::from_secs(1)).await;
                    }
                    Err(e) => return Err(e),
                }
            }
            Ok(consumer)
        })
        .await;

        assert!(consumer_result.is_ok(), "Consumer creation timed out");
        let consumer = consumer_result.unwrap();
        assert!(
            consumer.is_ok(),
            "Failed to create consumer: {:?}",
            consumer.err()
        );

        let consumer = consumer.unwrap();
        assert_eq!(consumer.group_id, "test_group");
        assert!(consumer.stream.is_some());
    }

    #[tokio::test]
    #[traced_test]
    async fn test_consume_messages() {
        // Allow some time for broker to be ready
        sleep(SETUP_DELAY).await;

        let consumer_result = timeout(TEST_TIMEOUT, async {
            let mut consumer = KafkaConsumer::new(
                "127.0.0.1:9092".to_string(),
                "test_group".to_string(),
                "test-topic".to_string(),
            )
            .await?;

            // Try to connect multiple times
            for attempt in 1..=3 {
                match consumer.connect().await {
                    Ok(_) => return Ok(consumer),
                    Err(e) if attempt < 3 => {
                        warn!("Connection attempt {} failed: {}", attempt, e);
                        sleep(Duration::from_secs(1)).await;
                    }
                    Err(e) => return Err(e),
                }
            }
            Ok(consumer)
        })
        .await;

        assert!(consumer_result.is_ok(), "Consumer creation timed out");
        let mut consumer = consumer_result.unwrap().expect("Failed to create consumer");

        // Give Kafka more time to fully establish the connection
        sleep(SETUP_DELAY).await;

        let messages_result = timeout(TEST_TIMEOUT, consumer.consume()).await;
        assert!(messages_result.is_ok(), "Consume operation timed out");

        let messages = messages_result.unwrap();
        assert!(
            messages.is_ok(),
            "Failed to consume messages: {:?}",
            messages.err()
        );
    }

    #[tokio::test]
    #[traced_test]
    async fn test_consumer_lifecycle() {
        // Allow some time for broker to be ready
        sleep(SETUP_DELAY).await;

        let consumer_result = timeout(TEST_TIMEOUT, async {
            let mut consumer = KafkaConsumer::new(
                "127.0.0.1:9092".to_string(),
                "test_group".to_string(),
                "test-topic".to_string(),
            )
            .await?;

            // Try to connect multiple times
            for attempt in 1..=3 {
                match consumer.connect().await {
                    Ok(_) => return Ok(consumer),
                    Err(e) if attempt < 3 => {
                        warn!("Connection attempt {} failed: {}", attempt, e);
                        sleep(Duration::from_secs(1)).await;
                    }
                    Err(e) => return Err(e),
                }
            }
            Ok(consumer)
        })
        .await;

        assert!(consumer_result.is_ok(), "Consumer creation timed out");
        let mut consumer = consumer_result.unwrap().expect("Failed to create consumer");

        // Give Kafka more time to fully establish the connection
        sleep(SETUP_DELAY).await;

        // Test full lifecycle with timeouts
        let consume_result = timeout(TEST_TIMEOUT, consumer.consume()).await;
        assert!(consume_result.is_ok(), "Consume operation timed out");
        assert!(
            consume_result.unwrap().is_ok(),
            "Failed to consume messages"
        );

        let commit_result = timeout(TEST_TIMEOUT, consumer.commit()).await;
        assert!(commit_result.is_ok(), "Commit operation timed out");
        assert!(commit_result.unwrap().is_ok(), "Failed to commit offset");

        let close_result = timeout(TEST_TIMEOUT, consumer.close()).await;
        assert!(close_result.is_ok(), "Close operation timed out");
        assert!(close_result.unwrap().is_ok(), "Failed to close consumer");
    }
}