Skip to main content

confluent_kafka/admin/
offset_spec.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//! Specification of the desired offsets when listing offsets.
16//!
17//! Its nested subclass with data, [`TimestampSpec`], is reached through this
18//! module.
19
20/// Specifies the desired offsets when using `Admin::list_offsets`.
21// Java models the variants as nested subclasses of `OffsetSpec`; the Rust translation uses a
22// single closed enum since the variants carry no behavior beyond their timestamp mapping
23// (`getOffsetFromSpec`). The one subclass with data, `TimestampSpec`, stays behind its variant as
24// a struct, so a field Java adds to it arrives without changing the variant's shape.
25#[derive(Clone, Debug)]
26#[non_exhaustive]
27#[doc(alias = "org.apache.kafka.clients.admin.OffsetSpec")]
28pub enum OffsetSpec {
29    /// Retrieve the earliest offset of a partition.
30    Earliest,
31    /// Retrieve the latest offset of a partition.
32    Latest,
33    /// Retrieve the offset with the largest timestamp of a partition.
34    MaxTimestamp,
35    /// Retrieve the local log start offset.
36    EarliestLocal,
37    /// Retrieve the highest offset of data stored in remote storage.
38    LatestTiered,
39    /// Retrieve the earliest offset of records pending upload to remote storage.
40    EarliestPendingUpload,
41    /// Retrieve the earliest offset whose timestamp is greater than or equal to
42    /// the given timestamp (in milliseconds).
43    Timestamp(TimestampSpec),
44}
45
46/// The offset whose timestamp is greater than or equal to a requested
47/// timestamp (in milliseconds).
48///
49/// Java keeps its constructor and `timestamp()` package-private: the value is
50/// built with [`OffsetSpec::for_timestamp`] and only `KafkaAdminClient`'s
51/// `getOffsetFromSpec` reads it, so outside the crate it is opaque.
52#[derive(Clone, Debug)]
53#[doc(alias = "org.apache.kafka.clients.admin.OffsetSpec$TimestampSpec")]
54pub struct TimestampSpec {
55    timestamp: i64,
56}
57
58impl TimestampSpec {
59    /// Translated from the package-private constructor `TimestampSpec(long)`.
60    #[doc(alias = "org.apache.kafka.clients.admin.OffsetSpec$TimestampSpec#TimestampSpec")]
61    pub(crate) fn new(timestamp: i64) -> Self {
62        Self { timestamp }
63    }
64
65    /// The requested timestamp, in milliseconds.
66    ///
67    /// Translated from the package-private `TimestampSpec.timestamp()`.
68    #[doc(alias = "org.apache.kafka.clients.admin.OffsetSpec$TimestampSpec#timestamp")]
69    pub(crate) fn timestamp(&self) -> i64 {
70        self.timestamp
71    }
72}
73
74impl OffsetSpec {
75    /// Used to retrieve the latest offset of a partition.
76    #[doc(alias = "org.apache.kafka.clients.admin.OffsetSpec#latest")]
77    pub fn latest() -> Self {
78        Self::Latest
79    }
80
81    /// Used to retrieve the earliest offset of a partition.
82    #[doc(alias = "org.apache.kafka.clients.admin.OffsetSpec#earliest")]
83    pub fn earliest() -> Self {
84        Self::Earliest
85    }
86
87    /// Used to retrieve the earliest offset whose timestamp is greater than or
88    /// equal to the given timestamp (in milliseconds).
89    ///
90    /// # Arguments
91    ///
92    /// - `timestamp` - in milliseconds
93    #[doc(alias = "org.apache.kafka.clients.admin.OffsetSpec#forTimestamp")]
94    pub fn for_timestamp(timestamp: i64) -> Self {
95        Self::Timestamp(TimestampSpec::new(timestamp))
96    }
97
98    /// Used to retrieve the offset with the largest timestamp of a partition as message
99    /// timestamps can be specified client side this may not match the log end offset returned by
100    /// [`OffsetSpec::latest`].
101    #[doc(alias = "org.apache.kafka.clients.admin.OffsetSpec#maxTimestamp")]
102    pub fn max_timestamp() -> Self {
103        Self::MaxTimestamp
104    }
105
106    /// Used to retrieve the local log start offset. Local log start offset is the offset of a log
107    /// above which reads are guaranteed to be served from the disk of the leader broker.
108    ///
109    /// Note: When tiered Storage is not enabled, it behaves the same as retrieving the earliest
110    /// timestamp offset.
111    #[doc(alias = "org.apache.kafka.clients.admin.OffsetSpec#earliestLocal")]
112    pub fn earliest_local() -> Self {
113        Self::EarliestLocal
114    }
115
116    /// Used to retrieve the highest offset of data stored in remote storage.
117    ///
118    /// Note: When tiered storage is not enabled, we will return unknown offset.
119    #[doc(alias = "org.apache.kafka.clients.admin.OffsetSpec#latestTiered")]
120    pub fn latest_tiered() -> Self {
121        Self::LatestTiered
122    }
123
124    /// Used to retrieve the earliest offset of records that are pending upload to remote storage.
125    ///
126    /// Note: When tiered storage is not enabled, we will return unknown offset.
127    #[doc(alias = "org.apache.kafka.clients.admin.OffsetSpec#earliestPendingUpload")]
128    pub fn earliest_pending_upload() -> Self {
129        Self::EarliestPendingUpload
130    }
131}
132
133/// What tells two specs apart, `OffsetSpec` having no `PartialEq` (Java's
134/// `OffsetSpec` does not override `equals`): the kind and, for a
135/// `TimestampSpec`, its timestamp. The tests here and in the C binding
136/// compare specs through it.
137#[cfg(test)]
138pub(crate) fn spec_key(spec: &OffsetSpec) -> (std::mem::Discriminant<OffsetSpec>, Option<i64>) {
139    let timestamp = match spec {
140        OffsetSpec::Timestamp(timestamp_spec) => Some(timestamp_spec.timestamp()),
141        _ => None,
142    };
143    (std::mem::discriminant(spec), timestamp)
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    #[test]
151    fn factories_produce_expected_variants() {
152        assert_eq!(spec_key(&OffsetSpec::latest()), spec_key(&OffsetSpec::Latest));
153        assert_eq!(spec_key(&OffsetSpec::earliest()), spec_key(&OffsetSpec::Earliest));
154        assert_eq!(spec_key(&OffsetSpec::max_timestamp()), spec_key(&OffsetSpec::MaxTimestamp));
155        assert_eq!(spec_key(&OffsetSpec::earliest_local()), spec_key(&OffsetSpec::EarliestLocal));
156        assert_eq!(spec_key(&OffsetSpec::latest_tiered()), spec_key(&OffsetSpec::LatestTiered));
157        assert_eq!(
158            spec_key(&OffsetSpec::earliest_pending_upload()),
159            spec_key(&OffsetSpec::EarliestPendingUpload)
160        );
161        assert_eq!(
162            spec_key(&OffsetSpec::for_timestamp(42)),
163            spec_key(&OffsetSpec::Timestamp(TimestampSpec::new(42)))
164        );
165    }
166
167    #[test]
168    fn timestamp_spec_keeps_its_timestamp() {
169        let OffsetSpec::Timestamp(spec) = OffsetSpec::for_timestamp(42) else {
170            panic!("forTimestamp builds a TimestampSpec");
171        };
172        assert_eq!(spec.timestamp(), 42);
173        assert_ne!(
174            spec_key(&OffsetSpec::for_timestamp(42)),
175            spec_key(&OffsetSpec::for_timestamp(43))
176        );
177    }
178}