Skip to main content

confluent_kafka/admin/
describe_producers_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::describe_producers`.
16
17use std::collections::HashMap;
18
19use crate::admin::ProducerState;
20use crate::common::{Error, KafkaFuture, TopicPartition};
21
22/// The producer state of a single partition.
23#[derive(Clone, Debug)]
24#[doc(alias = "org.apache.kafka.clients.admin.DescribeProducersResult$PartitionProducerState")]
25pub struct PartitionProducerState {
26    active_producers: Vec<ProducerState>,
27}
28
29impl PartitionProducerState {
30    /// Creates a new `PartitionProducerState` from the active producers.
31    ///
32    /// # Arguments
33    ///
34    /// - `active_producers` - the producers currently active on the partition.
35    #[doc(
36        alias = "org.apache.kafka.clients.admin.DescribeProducersResult$PartitionProducerState#PartitionProducerState"
37    )]
38    pub fn new(active_producers: Vec<ProducerState>) -> Self {
39        Self { active_producers }
40    }
41
42    /// Returns the active producers for this partition.
43    #[doc(alias = "org.apache.kafka.clients.admin.DescribeProducersResult$PartitionProducerState#activeProducers")]
44    pub fn active_producers(&self) -> &[ProducerState] {
45        &self.active_producers
46    }
47}
48
49impl std::fmt::Display for PartitionProducerState {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        write!(f, "PartitionProducerState(activeProducers={:?})", self.active_producers)
52    }
53}
54
55/// The result of `Admin::describe_producers`.
56#[derive(Clone, Debug)]
57#[doc(alias = "org.apache.kafka.clients.admin.DescribeProducersResult")]
58pub struct DescribeProducersResult {
59    futures: HashMap<TopicPartition, KafkaFuture<PartitionProducerState>>,
60}
61
62impl DescribeProducersResult {
63    /// Creates a result from the per-partition futures.
64    #[doc(alias = "org.apache.kafka.clients.admin.DescribeProducersResult#DescribeProducersResult")]
65    pub(crate) fn new(futures: HashMap<TopicPartition, KafkaFuture<PartitionProducerState>>) -> Self {
66        Self { futures }
67    }
68
69    /// Returns the future for a specific partition.
70    ///
71    /// # Arguments
72    ///
73    /// - `partition` - the partition to check.
74    ///
75    /// # Errors
76    ///
77    /// Returns an error answering `Error::is_local_illegal_argument_error` if `partition` was not
78    /// requested.
79    #[doc(alias = "org.apache.kafka.clients.admin.DescribeProducersResult#partitionResult")]
80    pub fn partition_result(&self, partition: &TopicPartition) -> Result<KafkaFuture<PartitionProducerState>, Error> {
81        self.futures.get(partition).cloned().ok_or_else(|| {
82            Error::local_illegal_argument(format!("Topic partition {partition} was not included in the request"))
83        })
84    }
85
86    /// Returns a future yielding a map of every requested partition's producer
87    /// state. Fails if any partition's request fails.
88    #[doc(alias = "org.apache.kafka.clients.admin.DescribeProducersResult#all")]
89    pub fn all(&self) -> KafkaFuture<HashMap<TopicPartition, PartitionProducerState>> {
90        KafkaFuture::join_map(self.futures.iter().map(|(tp, f)| (tp.clone(), f.clone())).collect())
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97    use crate::common::internals::KafkaFutureImpl;
98
99    fn state(producer_id: i64) -> PartitionProducerState {
100        PartitionProducerState::new(vec![ProducerState::new(producer_id, 1, 0, 0, None, None)])
101    }
102
103    #[tokio::test]
104    async fn all_collects_every_partition() {
105        let h0: KafkaFutureImpl<PartitionProducerState> = KafkaFutureImpl::new();
106        let h1: KafkaFutureImpl<PartitionProducerState> = KafkaFutureImpl::new();
107        let mut map = HashMap::new();
108        map.insert(TopicPartition::new("t", 0), h0.future());
109        map.insert(TopicPartition::new("t", 1), h1.future());
110        let result = DescribeProducersResult::new(map);
111        h0.complete(state(10));
112        h1.complete(state(20));
113        let all = result.all().get().await.unwrap();
114        assert_eq!(all.len(), 2);
115        assert_eq!(all[&TopicPartition::new("t", 0)].active_producers()[0].producer_id(), 10);
116    }
117
118    #[test]
119    fn partition_result_errors_for_unknown_partition() {
120        let result = DescribeProducersResult::new(HashMap::new());
121        let err = result.partition_result(&TopicPartition::new("t", 0)).unwrap_err();
122        assert!(err.message().contains("was not included in the request"));
123    }
124}