Skip to main content

kafrust_protocol/api/
txn_offset_commit.rs

1use crate::codec::{Decoder, Encoder};
2use crate::error::Result;
3use crate::header::RequestHeader;
4
5pub const API_KEY: i16 = 28;
6
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct TxnOffsetCommitRequestV0 {
9    pub correlation_id: i32,
10    pub client_id: Option<String>,
11    pub transactional_id: String,
12    pub group_id: String,
13    pub producer_id: i64,
14    pub producer_epoch: i16,
15    pub topics: Vec<TxnOffsetCommitTopic>,
16}
17
18impl TxnOffsetCommitRequestV0 {
19    pub fn encode(&self) -> Result<Vec<u8>> {
20        let mut encoder = Encoder::new();
21        RequestHeader {
22            api_key: API_KEY,
23            api_version: 0,
24            correlation_id: self.correlation_id,
25            client_id: self.client_id.clone(),
26        }
27        .encode_v1(&mut encoder)?;
28        encoder.write_string(&self.transactional_id)?;
29        encoder.write_string(&self.group_id)?;
30        encoder.write_i64(self.producer_id);
31        encoder.write_i16(self.producer_epoch);
32        encoder.write_array(Some(&self.topics), |encoder, topic| topic.encode(encoder))?;
33        Ok(encoder.into_bytes())
34    }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct TxnOffsetCommitRequestV3 {
39    pub correlation_id: i32,
40    pub client_id: Option<String>,
41    pub transactional_id: String,
42    pub group_id: String,
43    pub producer_id: i64,
44    pub producer_epoch: i16,
45    pub generation_id: i32,
46    pub member_id: String,
47    pub group_instance_id: Option<String>,
48    pub topics: Vec<TxnOffsetCommitTopicV3>,
49}
50
51impl TxnOffsetCommitRequestV3 {
52    pub fn encode(&self) -> Result<Vec<u8>> {
53        let mut encoder = Encoder::new();
54        RequestHeader {
55            api_key: API_KEY,
56            api_version: 3,
57            correlation_id: self.correlation_id,
58            client_id: self.client_id.clone(),
59        }
60        .encode_v2(&mut encoder)?;
61        encoder.write_compact_string(&self.transactional_id)?;
62        encoder.write_compact_string(&self.group_id)?;
63        encoder.write_i64(self.producer_id);
64        encoder.write_i16(self.producer_epoch);
65        encoder.write_i32(self.generation_id);
66        encoder.write_compact_string(&self.member_id)?;
67        encoder.write_compact_nullable_string(self.group_instance_id.as_deref())?;
68        encoder.write_compact_array(Some(&self.topics), |encoder, topic| topic.encode(encoder))?;
69        encoder.write_empty_tagged_fields();
70        Ok(encoder.into_bytes())
71    }
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct TxnOffsetCommitTopicV3 {
76    pub name: String,
77    pub partitions: Vec<TxnOffsetCommitPartitionV3>,
78}
79
80impl TxnOffsetCommitTopicV3 {
81    fn encode(&self, encoder: &mut Encoder) -> Result<()> {
82        encoder.write_compact_string(&self.name)?;
83        encoder.write_compact_array(Some(&self.partitions), |encoder, partition| {
84            partition.encode(encoder)
85        })?;
86        encoder.write_empty_tagged_fields();
87        Ok(())
88    }
89}
90
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct TxnOffsetCommitPartitionV3 {
93    pub partition_index: i32,
94    pub committed_offset: i64,
95    pub committed_leader_epoch: i32,
96    pub committed_metadata: Option<String>,
97}
98
99impl TxnOffsetCommitPartitionV3 {
100    fn encode(&self, encoder: &mut Encoder) -> Result<()> {
101        encoder.write_i32(self.partition_index);
102        encoder.write_i64(self.committed_offset);
103        encoder.write_i32(self.committed_leader_epoch);
104        encoder.write_compact_nullable_string(self.committed_metadata.as_deref())?;
105        encoder.write_empty_tagged_fields();
106        Ok(())
107    }
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct TxnOffsetCommitTopic {
112    pub name: String,
113    pub partitions: Vec<TxnOffsetCommitPartition>,
114}
115
116impl TxnOffsetCommitTopic {
117    fn encode(&self, encoder: &mut Encoder) -> Result<()> {
118        encoder.write_string(&self.name)?;
119        encoder.write_array(Some(&self.partitions), |encoder, partition| {
120            partition.encode(encoder)
121        })
122    }
123}
124
125#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct TxnOffsetCommitPartition {
127    pub partition_index: i32,
128    pub committed_offset: i64,
129    pub committed_metadata: Option<String>,
130}
131
132impl TxnOffsetCommitPartition {
133    fn encode(&self, encoder: &mut Encoder) -> Result<()> {
134        encoder.write_i32(self.partition_index);
135        encoder.write_i64(self.committed_offset);
136        encoder.write_nullable_string(self.committed_metadata.as_deref())
137    }
138}
139
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct TxnOffsetCommitResponseV0 {
142    pub throttle_time_ms: i32,
143    pub topics: Vec<TxnOffsetCommitTopicResult>,
144}
145
146impl TxnOffsetCommitResponseV0 {
147    pub fn decode_body(decoder: &mut Decoder<'_>) -> Result<Self> {
148        Ok(Self {
149            throttle_time_ms: decoder.read_i32()?,
150            topics: decoder
151                .read_array(
152                    "transaction offset commit topic results",
153                    TxnOffsetCommitTopicResult::decode,
154                )?
155                .unwrap_or_default(),
156        })
157    }
158}
159
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub struct TxnOffsetCommitResponseV3 {
162    pub throttle_time_ms: i32,
163    pub topics: Vec<TxnOffsetCommitTopicResult>,
164}
165
166impl TxnOffsetCommitResponseV3 {
167    pub fn decode_body(decoder: &mut Decoder<'_>) -> Result<Self> {
168        let throttle_time_ms = decoder.read_i32()?;
169        let topics = decoder
170            .read_compact_array("transaction offset commit topic results", |decoder| {
171                let name = decoder.read_compact_string()?;
172                let partitions = decoder
173                    .read_compact_array("transaction offset commit partition results", |decoder| {
174                        let partition_index = decoder.read_i32()?;
175                        let error_code = decoder.read_i16()?;
176                        let _tagged_fields = decoder.read_tagged_fields()?;
177                        Ok(TxnOffsetCommitPartitionResult {
178                            partition_index,
179                            error_code,
180                        })
181                    })?
182                    .unwrap_or_default();
183                let _tagged_fields = decoder.read_tagged_fields()?;
184                Ok(TxnOffsetCommitTopicResult { name, partitions })
185            })?
186            .unwrap_or_default();
187        let _tagged_fields = decoder.read_tagged_fields()?;
188        Ok(Self {
189            throttle_time_ms,
190            topics,
191        })
192    }
193}
194
195#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct TxnOffsetCommitTopicResult {
197    pub name: String,
198    pub partitions: Vec<TxnOffsetCommitPartitionResult>,
199}
200
201impl TxnOffsetCommitTopicResult {
202    fn decode(decoder: &mut Decoder<'_>) -> Result<Self> {
203        Ok(Self {
204            name: decoder.read_string()?,
205            partitions: decoder
206                .read_array(
207                    "transaction offset commit partition results",
208                    TxnOffsetCommitPartitionResult::decode,
209                )?
210                .unwrap_or_default(),
211        })
212    }
213}
214
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct TxnOffsetCommitPartitionResult {
217    pub partition_index: i32,
218    pub error_code: i16,
219}
220
221impl TxnOffsetCommitPartitionResult {
222    fn decode(decoder: &mut Decoder<'_>) -> Result<Self> {
223        Ok(Self {
224            partition_index: decoder.read_i32()?,
225            error_code: decoder.read_i16()?,
226        })
227    }
228}
229
230#[cfg(test)]
231#[allow(clippy::unwrap_used)]
232mod tests {
233    use super::{
234        TxnOffsetCommitPartition, TxnOffsetCommitPartitionV3, TxnOffsetCommitRequestV0,
235        TxnOffsetCommitRequestV3, TxnOffsetCommitResponseV0, TxnOffsetCommitResponseV3,
236        TxnOffsetCommitTopic, TxnOffsetCommitTopicV3, API_KEY,
237    };
238    use crate::codec::Decoder;
239
240    #[test]
241    fn encodes_txn_offset_commit_v0_request() {
242        let request = TxnOffsetCommitRequestV0 {
243            correlation_id: 61,
244            client_id: Some("kafrust".to_owned()),
245            transactional_id: "orders-tx".to_owned(),
246            group_id: "orders-group".to_owned(),
247            producer_id: 42,
248            producer_epoch: 3,
249            topics: vec![TxnOffsetCommitTopic {
250                name: "orders".to_owned(),
251                partitions: vec![TxnOffsetCommitPartition {
252                    partition_index: 2,
253                    committed_offset: 81,
254                    committed_metadata: Some("processed".to_owned()),
255                }],
256            }],
257        };
258        let encoded = request.encode().unwrap();
259
260        assert_eq!(&encoded[0..8], &[0, 28, 0, 0, 0, 0, 0, 61]);
261        assert!(encoded.ends_with(b"processed"));
262        assert_eq!(API_KEY, 28);
263    }
264
265    #[test]
266    fn decodes_txn_offset_commit_v0_response() {
267        let bytes = [
268            0, 0, 0, 5, // throttle time
269            0, 0, 0, 1, // topic count
270            0, 6, b'o', b'r', b'd', b'e', b'r', b's', 0, 0, 0, 1, // partition count
271            0, 0, 0, 2, // partition index
272            0, 27, // rebalance in progress
273        ];
274        let mut decoder = Decoder::new(&bytes);
275        let response = TxnOffsetCommitResponseV0::decode_body(&mut decoder).unwrap();
276
277        assert_eq!(response.throttle_time_ms, 5);
278        assert_eq!(response.topics[0].partitions[0].partition_index, 2);
279        assert_eq!(response.topics[0].partitions[0].error_code, 27);
280        assert!(decoder.is_empty());
281    }
282
283    #[test]
284    fn encodes_txn_offset_commit_v3_with_group_generation() {
285        let request = TxnOffsetCommitRequestV3 {
286            correlation_id: 62,
287            client_id: Some("kafrust".to_owned()),
288            transactional_id: "orders-tx".to_owned(),
289            group_id: "orders-group".to_owned(),
290            producer_id: 42,
291            producer_epoch: 3,
292            generation_id: 7,
293            member_id: "member-1".to_owned(),
294            group_instance_id: Some("instance-1".to_owned()),
295            topics: vec![TxnOffsetCommitTopicV3 {
296                name: "orders".to_owned(),
297                partitions: vec![TxnOffsetCommitPartitionV3 {
298                    partition_index: 2,
299                    committed_offset: 81,
300                    committed_leader_epoch: -1,
301                    committed_metadata: None,
302                }],
303            }],
304        };
305        let encoded = request.encode().unwrap();
306
307        assert_eq!(&encoded[0..8], &[0, 28, 0, 3, 0, 0, 0, 62]);
308        assert_eq!(encoded[17], 0); // request-header tagged fields
309        assert!(encoded.windows(8).any(|bytes| bytes == b"member-1"));
310        assert!(encoded.windows(10).any(|bytes| bytes == b"instance-1"));
311        assert_eq!(encoded.last(), Some(&0)); // request tagged fields
312    }
313
314    #[test]
315    fn decodes_txn_offset_commit_v3_flexible_response() {
316        let bytes = [
317            0, 0, 0, 5, // throttle time
318            2, // compact topic count (1 + 1)
319            7, b'o', b'r', b'd', b'e', b'r', b's', // compact topic name
320            2,    // compact partition count
321            0, 0, 0, 2, // partition index
322            0, 22, // illegal generation
323            0,  // partition tagged fields
324            0,  // topic tagged fields
325            0,  // response tagged fields
326        ];
327        let mut decoder = Decoder::new(&bytes);
328        let response = TxnOffsetCommitResponseV3::decode_body(&mut decoder).unwrap();
329
330        assert_eq!(response.throttle_time_ms, 5);
331        assert_eq!(response.topics[0].name, "orders");
332        assert_eq!(response.topics[0].partitions[0].partition_index, 2);
333        assert_eq!(response.topics[0].partitions[0].error_code, 22);
334        assert!(decoder.is_empty());
335    }
336}