Skip to main content

confluent_kafka/consumer/
offset_and_timestamp.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//! Container holding an offset and its timestamp.
16//!
17//! Translated from `org.apache.kafka.clients.consumer.OffsetAndTimestamp`.
18
19use std::fmt;
20
21use crate::common::Error;
22
23/// A container class for offset and timestamp.
24// In an `offsets_for_times` result map the value is an
25// `Option<OffsetAndTimestamp>`: an unresolved partition (queried but with no
26// offset at/after the target time) is present with `None`, as Java maps it to
27// `null` (see `Consumer::offsets_for_times`).
28#[derive(Clone, Debug, PartialEq, Eq, Hash)]
29#[doc(alias = "org.apache.kafka.clients.consumer.OffsetAndTimestamp")]
30pub struct OffsetAndTimestamp {
31    timestamp: i64,
32    offset: i64,
33    leader_epoch: Option<i32>,
34}
35
36impl OffsetAndTimestamp {
37    /// Constructs a new OffsetAndTimestamp with the given offset and timestamp.
38    ///
39    /// # Arguments
40    ///
41    /// - `offset` - The offset
42    /// - `timestamp` - The timestamp
43    ///
44    /// # Returns
45    ///
46    /// The new `OffsetAndTimestamp`.
47    ///
48    /// # Errors
49    ///
50    /// - `Error::is_local_illegal_argument_error` If the offset or timestamp is
51    ///   negative
52    #[doc(alias = "org.apache.kafka.clients.consumer.OffsetAndTimestamp#OffsetAndTimestamp")]
53    pub fn new(offset: i64, timestamp: i64) -> Result<Self, Error> {
54        Self::with_leader_epoch(offset, timestamp, None)
55    }
56
57    /// Constructs a new OffsetAndTimestamp with the given offset, timestamp,
58    /// and leader epoch.
59    ///
60    /// # Arguments
61    ///
62    /// - `offset` - The offset
63    /// - `timestamp` - The timestamp
64    /// - `leader_epoch` - The leader epoch
65    ///
66    /// # Returns
67    ///
68    /// The new `OffsetAndTimestamp`.
69    ///
70    /// # Errors
71    ///
72    /// - `Error::is_local_illegal_argument_error` If the offset or timestamp is
73    ///   negative
74    #[doc(alias = "org.apache.kafka.clients.consumer.OffsetAndTimestamp#OffsetAndTimestamp")]
75    pub fn with_leader_epoch(offset: i64, timestamp: i64, leader_epoch: Option<i32>) -> Result<Self, Error> {
76        if offset < 0 {
77            return Err(Error::local_illegal_argument("Invalid negative offset"));
78        }
79        if timestamp < 0 {
80            return Err(Error::local_illegal_argument("Invalid negative timestamp"));
81        }
82        Ok(Self { offset, timestamp, leader_epoch })
83    }
84
85    /// The timestamp.
86    ///
87    /// # Returns
88    ///
89    /// The timestamp
90    #[doc(alias = "org.apache.kafka.clients.consumer.OffsetAndTimestamp#timestamp")]
91    pub fn timestamp(&self) -> i64 {
92        self.timestamp
93    }
94
95    /// The offset.
96    ///
97    /// # Returns
98    ///
99    /// The offset
100    #[doc(alias = "org.apache.kafka.clients.consumer.OffsetAndTimestamp#offset")]
101    pub fn offset(&self) -> i64 {
102        self.offset
103    }
104
105    /// Get the leader epoch corresponding to the offset that was found (if
106    /// one exists). This can be provided to `seek()` to ensure the log hasn't
107    /// been truncated prior to fetching.
108    ///
109    /// # Returns
110    ///
111    /// The leader epoch or empty if it is not known
112    #[doc(alias = "org.apache.kafka.clients.consumer.OffsetAndTimestamp#leaderEpoch")]
113    pub fn leader_epoch(&self) -> Option<i32> {
114        self.leader_epoch
115    }
116}
117
118impl fmt::Display for OffsetAndTimestamp {
119    // Matches Java's `toString()`:
120    // `(timestamp=N, leaderEpoch=X, offset=M)`
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        write!(
123            f,
124            "(timestamp={}, leaderEpoch={}, offset={})",
125            self.timestamp,
126            match self.leader_epoch {
127                Some(e) => e.to_string(),
128                None => "null".to_string(),
129            },
130            self.offset
131        )
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    #[test]
140    fn test_accessors() {
141        let oat = OffsetAndTimestamp::new(10, 100).unwrap();
142        assert_eq!(oat.offset(), 10);
143        assert_eq!(oat.timestamp(), 100);
144        assert_eq!(oat.leader_epoch(), None);
145    }
146
147    #[test]
148    fn test_with_leader_epoch() {
149        let oat = OffsetAndTimestamp::with_leader_epoch(10, 100, Some(5)).unwrap();
150        assert_eq!(oat.leader_epoch(), Some(5));
151    }
152
153    #[test]
154    fn test_invalid_negative_offset() {
155        let err = OffsetAndTimestamp::new(-1, 100).unwrap_err();
156        assert!(err.message().contains("Invalid negative offset"));
157    }
158
159    #[test]
160    fn test_invalid_negative_timestamp() {
161        let err = OffsetAndTimestamp::new(10, -1).unwrap_err();
162        assert!(err.message().contains("Invalid negative timestamp"));
163    }
164
165    #[test]
166    fn test_display() {
167        let oat = OffsetAndTimestamp::with_leader_epoch(10, 100, Some(5)).unwrap();
168        assert_eq!(oat.to_string(), "(timestamp=100, leaderEpoch=5, offset=10)");
169
170        let oat = OffsetAndTimestamp::new(10, 100).unwrap();
171        assert_eq!(oat.to_string(), "(timestamp=100, leaderEpoch=null, offset=10)");
172    }
173
174    #[test]
175    fn test_equality() {
176        let a = OffsetAndTimestamp::with_leader_epoch(10, 100, Some(5)).unwrap();
177        let b = OffsetAndTimestamp::with_leader_epoch(10, 100, Some(5)).unwrap();
178        let c = OffsetAndTimestamp::with_leader_epoch(10, 100, Some(6)).unwrap();
179        assert_eq!(a, b);
180        assert_ne!(a, c);
181    }
182}