Skip to main content

confluent_kafka/producer/
record_metadata.rs

1// Copyright 2025 Confluent Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The metadata for a record that has been acknowledged by the server.
16//!
17//! Translated from `org.apache.kafka.clients.producer.RecordMetadata`.
18
19use std::fmt;
20
21use crate::common::TopicPartition;
22use crate::common::record::internal::RecordBatch;
23
24/// The metadata for a record that has been acknowledged by the server.
25#[derive(Clone, Debug)]
26#[doc(alias = "org.apache.kafka.clients.producer.RecordMetadata")]
27pub struct RecordMetadata {
28    /// The offset of the record in the topic/partition.
29    offset: i64,
30    /// The timestamp of the message.
31    /// If LogAppendTime is used for the topic, the timestamp will be the timestamp returned
32    /// by the broker.
33    /// If CreateTime is used for the topic, the timestamp is the timestamp in the
34    /// corresponding ProducerRecord if the user provided one. Otherwise, it will be the
35    /// producer local time when the producer record was handed to the producer.
36    timestamp: i64,
37    /// The size of the serialized, uncompressed key in bytes. -1 if key is null.
38    serialized_key_size: i32,
39    /// The size of the serialized, uncompressed value in bytes. -1 if value is null.
40    serialized_value_size: i32,
41    /// The topic and partition the record was sent to.
42    topic_partition: TopicPartition,
43}
44
45impl RecordMetadata {
46    /// Value used when the offset is unknown (i.e., `ProduceResponse.INVALID_OFFSET`).
47    ///
48    /// Not a field of Java's `RecordMetadata`, which reads
49    /// `ProduceResponse.INVALID_OFFSET` directly; users test `has_offset()`.
50    pub(crate) const INVALID_OFFSET: i64 = -1;
51
52    /// Partition value for record without partition assigned.
53    pub const UNKNOWN_PARTITION: i32 = -1;
54
55    /// Creates a new instance with the provided parameters.
56    ///
57    /// # Arguments
58    ///
59    /// - `topic_partition` - the partition
60    /// - `base_offset` - the batch offset
61    /// - `batch_index` - the record's index
62    /// - `timestamp` - the timestamp
63    /// - `serialized_key_size` - the key size
64    /// - `serialized_value_size` - the value size
65    #[doc(alias = "org.apache.kafka.clients.producer.RecordMetadata#RecordMetadata")]
66    pub fn new(
67        topic_partition: TopicPartition,
68        base_offset: i64,
69        batch_index: i32,
70        timestamp: i64,
71        serialized_key_size: i32,
72        serialized_value_size: i32,
73    ) -> Self {
74        // Ignore the batch_index if the base offset is -1, since this indicates the offset
75        // is unknown
76        let offset = if base_offset == -1 {
77            base_offset
78        } else {
79            base_offset + batch_index as i64
80        };
81        Self { offset, timestamp, serialized_key_size, serialized_value_size, topic_partition }
82    }
83
84    /// Indicates whether the record metadata includes the offset.
85    ///
86    /// # Returns
87    ///
88    /// true if the offset is included in the metadata, false otherwise.
89    #[doc(alias = "org.apache.kafka.clients.producer.RecordMetadata#hasOffset")]
90    pub fn has_offset(&self) -> bool {
91        self.offset != RecordMetadata::INVALID_OFFSET
92    }
93
94    /// The offset of the record in the topic/partition.
95    /// Returns -1 if [`has_offset()`](Self::has_offset) returns false.
96    ///
97    /// # Returns
98    ///
99    /// the offset of the record, or -1 if `Self::has_offset` returns false.
100    #[doc(alias = "org.apache.kafka.clients.producer.RecordMetadata#offset")]
101    pub fn offset(&self) -> i64 {
102        self.offset
103    }
104
105    /// Indicates whether the record metadata includes the timestamp.
106    ///
107    /// # Returns
108    ///
109    /// true if a valid timestamp exists, false otherwise.
110    #[doc(alias = "org.apache.kafka.clients.producer.RecordMetadata#hasTimestamp")]
111    pub fn has_timestamp(&self) -> bool {
112        self.timestamp != RecordBatch::NO_TIMESTAMP
113    }
114
115    /// The timestamp of the record in the topic/partition.
116    /// Returns -1 if [`has_timestamp()`](Self::has_timestamp) returns false.
117    ///
118    /// # Returns
119    ///
120    /// the timestamp of the record, or -1 if the `Self::has_timestamp` returns false.
121    #[doc(alias = "org.apache.kafka.clients.producer.RecordMetadata#timestamp")]
122    pub fn timestamp(&self) -> i64 {
123        self.timestamp
124    }
125
126    /// Returns the size of the serialized, uncompressed key in bytes. If key
127    /// is `None`, the returned size is -1.
128    #[doc(alias = "org.apache.kafka.clients.producer.RecordMetadata#serializedKeySize")]
129    pub fn serialized_key_size(&self) -> i32 {
130        self.serialized_key_size
131    }
132
133    /// Returns the size of the serialized, uncompressed value in bytes. If
134    /// value is `None`, the returned size is -1.
135    #[doc(alias = "org.apache.kafka.clients.producer.RecordMetadata#serializedValueSize")]
136    pub fn serialized_value_size(&self) -> i32 {
137        self.serialized_value_size
138    }
139
140    /// Returns the topic the record was appended to.
141    #[doc(alias = "org.apache.kafka.clients.producer.RecordMetadata#topic")]
142    pub fn topic(&self) -> &str {
143        self.topic_partition.topic()
144    }
145
146    /// Returns the partition the record was sent to.
147    #[doc(alias = "org.apache.kafka.clients.producer.RecordMetadata#partition")]
148    pub fn partition(&self) -> i32 {
149        self.topic_partition.partition()
150    }
151}
152
153impl fmt::Display for RecordMetadata {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        write!(f, "{}@{}", self.topic_partition, self.offset)
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    /// Translated from `RecordMetadataTest.testConstructionWithMissingBatchIndex`.
164    #[test]
165    #[doc(alias = "org.apache.kafka.clients.producer.RecordMetadataTest#testConstructionWithMissingBatchIndex")]
166    fn test_construction_with_missing_batch_index() {
167        let tp = TopicPartition::new("foo".to_string(), 0);
168        let timestamp = 2340234_i64;
169        let key_size = 3;
170        let value_size = 5;
171
172        let metadata = RecordMetadata::new(tp, -1, -1, timestamp, key_size, value_size);
173        assert_eq!("foo", metadata.topic());
174        assert_eq!(0, metadata.partition());
175        assert_eq!(timestamp, metadata.timestamp());
176        assert!(!metadata.has_offset());
177        assert_eq!(-1, metadata.offset());
178        assert_eq!(key_size, metadata.serialized_key_size());
179        assert_eq!(value_size, metadata.serialized_value_size());
180    }
181
182    /// Translated from `RecordMetadataTest.testConstructionWithBatchIndexOffset`.
183    #[test]
184    #[doc(alias = "org.apache.kafka.clients.producer.RecordMetadataTest#testConstructionWithBatchIndexOffset")]
185    fn test_construction_with_batch_index_offset() {
186        let tp = TopicPartition::new("foo".to_string(), 0);
187        let timestamp = 2340234_i64;
188        let key_size = 3;
189        let value_size = 5;
190        let base_offset = 15_i64;
191        let batch_index = 3;
192
193        let metadata = RecordMetadata::new(tp, base_offset, batch_index, timestamp, key_size, value_size);
194        assert_eq!("foo", metadata.topic());
195        assert_eq!(0, metadata.partition());
196        assert_eq!(timestamp, metadata.timestamp());
197        assert_eq!(base_offset + batch_index as i64, metadata.offset());
198        assert_eq!(key_size, metadata.serialized_key_size());
199        assert_eq!(value_size, metadata.serialized_value_size());
200    }
201
202    #[test]
203    fn test_record_metadata_with_offset() {
204        let tp = TopicPartition::new("test-topic".to_string(), 0);
205        let metadata = RecordMetadata::new(tp, 100, 5, 1234567890, 10, 20);
206        assert!(metadata.has_offset());
207        assert_eq!(metadata.offset(), 105);
208        assert!(metadata.has_timestamp());
209        assert_eq!(metadata.timestamp(), 1234567890);
210        assert_eq!(metadata.serialized_key_size(), 10);
211        assert_eq!(metadata.serialized_value_size(), 20);
212        assert_eq!(metadata.topic(), "test-topic");
213        assert_eq!(metadata.partition(), 0);
214    }
215
216    #[test]
217    fn test_record_metadata_unknown_offset() {
218        let tp = TopicPartition::new("test-topic".to_string(), 0);
219        let metadata = RecordMetadata::new(tp, -1, 5, RecordBatch::NO_TIMESTAMP, -1, -1);
220        assert!(!metadata.has_offset());
221        assert_eq!(metadata.offset(), -1);
222        assert!(!metadata.has_timestamp());
223    }
224
225    #[test]
226    fn test_record_metadata_display() {
227        let tp = TopicPartition::new("test-topic".to_string(), 3);
228        let metadata = RecordMetadata::new(tp, 42, 0, 0, 0, 0);
229        assert_eq!(metadata.to_string(), "test-topic-3@42");
230    }
231}