Skip to main content

confluent_kafka/admin/
list_offsets_result.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 result of `Admin::list_offsets`.
16
17use std::collections::HashMap;
18
19use crate::common::{Error, KafkaFuture, TopicPartition};
20
21/// The result of `Admin::list_offsets`.
22#[derive(Clone, Debug)]
23#[doc(alias = "org.apache.kafka.clients.admin.ListOffsetsResult")]
24pub struct ListOffsetsResult {
25    futures: HashMap<TopicPartition, KafkaFuture<ListOffsetsResultInfo>>,
26}
27
28impl ListOffsetsResult {
29    /// Creates a result from the per-partition futures.
30    ///
31    /// # Arguments
32    ///
33    /// - `futures` - the future of each partition's offset.
34    #[doc(alias = "org.apache.kafka.clients.admin.ListOffsetsResult#ListOffsetsResult")]
35    pub fn new(futures: HashMap<TopicPartition, KafkaFuture<ListOffsetsResultInfo>>) -> Self {
36        Self { futures }
37    }
38
39    /// Returns a future which can be used to check the result for a given
40    /// partition.
41    ///
42    /// # Arguments
43    ///
44    /// - `partition` - the partition to check.
45    ///
46    /// # Errors
47    ///
48    /// Returns an error answering `Error::is_local_illegal_argument_error` if the offset for
49    /// `partition`
50    /// was not attempted.
51    #[doc(alias = "org.apache.kafka.clients.admin.ListOffsetsResult#partitionResult")]
52    pub fn partition_result(&self, partition: &TopicPartition) -> Result<KafkaFuture<ListOffsetsResultInfo>, Error> {
53        self.futures.get(partition).cloned().ok_or_else(|| {
54            Error::local_illegal_argument(format!("List Offsets for partition \"{partition}\" was not attempted"))
55        })
56    }
57
58    /// Returns a future which succeeds only if offsets for all specified
59    /// partitions have been successfully retrieved.
60    #[doc(alias = "org.apache.kafka.clients.admin.ListOffsetsResult#all")]
61    pub fn all(&self) -> KafkaFuture<HashMap<TopicPartition, ListOffsetsResultInfo>> {
62        KafkaFuture::join_map(self.futures.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
63    }
64}
65
66/// Per-partition offset information returned by `Admin::list_offsets`.
67#[derive(Clone, Debug)]
68#[doc(alias = "org.apache.kafka.clients.admin.ListOffsetsResult$ListOffsetsResultInfo")]
69pub struct ListOffsetsResultInfo {
70    offset: i64,
71    timestamp: i64,
72    leader_epoch: Option<i32>,
73}
74
75impl ListOffsetsResultInfo {
76    /// Creates a new result info.
77    ///
78    /// # Arguments
79    ///
80    /// - `offset` - the offset.
81    /// - `timestamp` - the timestamp of the record at the offset.
82    /// - `leader_epoch` - the leader epoch, or `None` if not known.
83    #[doc(alias = "org.apache.kafka.clients.admin.ListOffsetsResult$ListOffsetsResultInfo#ListOffsetsResultInfo")]
84    pub fn new(offset: i64, timestamp: i64, leader_epoch: Option<i32>) -> Self {
85        Self { offset, timestamp, leader_epoch }
86    }
87
88    /// Returns the offset.
89    #[doc(alias = "org.apache.kafka.clients.admin.ListOffsetsResult$ListOffsetsResultInfo#offset")]
90    pub fn offset(&self) -> i64 {
91        self.offset
92    }
93
94    /// Returns the timestamp associated with the offset.
95    #[doc(alias = "org.apache.kafka.clients.admin.ListOffsetsResult$ListOffsetsResultInfo#timestamp")]
96    pub fn timestamp(&self) -> i64 {
97        self.timestamp
98    }
99
100    /// Returns the leader epoch associated with the offset, if known.
101    #[doc(alias = "org.apache.kafka.clients.admin.ListOffsetsResult$ListOffsetsResultInfo#leaderEpoch")]
102    pub fn leader_epoch(&self) -> Option<i32> {
103        self.leader_epoch
104    }
105}
106
107impl std::fmt::Display for ListOffsetsResultInfo {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        write!(
110            f,
111            "ListOffsetsResultInfo(offset={}, timestamp={}, leaderEpoch={:?})",
112            self.offset, self.timestamp, self.leader_epoch
113        )
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120    use crate::common::internals::KafkaFutureImpl;
121
122    #[tokio::test]
123    async fn partition_result_returns_future_or_errors() {
124        let h: KafkaFutureImpl<ListOffsetsResultInfo> = KafkaFutureImpl::new();
125        let tp = TopicPartition::new("t", 0);
126        let mut map = HashMap::new();
127        map.insert(tp.clone(), h.future());
128        let result = ListOffsetsResult::new(map);
129        h.complete(ListOffsetsResultInfo::new(10, -1, Some(5)));
130        assert_eq!(result.partition_result(&tp).unwrap().get().await.unwrap().offset(), 10);
131        let err = result.partition_result(&TopicPartition::new("unknown", 0)).unwrap_err();
132        assert!(err.message().contains("was not attempted"));
133    }
134
135    #[tokio::test]
136    async fn all_collects_every_partition() {
137        let h0: KafkaFutureImpl<ListOffsetsResultInfo> = KafkaFutureImpl::new();
138        let h1: KafkaFutureImpl<ListOffsetsResultInfo> = KafkaFutureImpl::new();
139        let mut map = HashMap::new();
140        map.insert(TopicPartition::new("t", 0), h0.future());
141        map.insert(TopicPartition::new("t", 1), h1.future());
142        let result = ListOffsetsResult::new(map);
143        h0.complete(ListOffsetsResultInfo::new(10, -1, Some(5)));
144        h1.complete(ListOffsetsResultInfo::new(20, -1, None));
145        let all = result.all().get().await.unwrap();
146        assert_eq!(all.get(&TopicPartition::new("t", 0)).unwrap().offset(), 10);
147        assert_eq!(all.get(&TopicPartition::new("t", 1)).unwrap().leader_epoch(), None);
148    }
149}