Skip to main content

confluent_kafka/common/config/
config_resource.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//! A resource that has configs.
16//!
17//! Corresponds to `org.apache.kafka.common.config.ConfigResource`.
18
19/// Type of a [`ConfigResource`].
20#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
21#[non_exhaustive]
22#[doc(alias = "org.apache.kafka.common.config.ConfigResource$Type")]
23pub enum Type {
24    /// A consumer group.
25    Group,
26    /// A client-metrics subscription.
27    ClientMetrics,
28    /// A broker logger.
29    BrokerLogger,
30    /// A broker.
31    Broker,
32    /// A topic.
33    Topic,
34    /// An unknown resource type.
35    Unknown,
36}
37
38/// Java's inherited `Enum.toString()`: the constant's name.
39impl std::fmt::Display for Type {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        f.write_str(match self {
42            Self::Group => "GROUP",
43            Self::ClientMetrics => "CLIENT_METRICS",
44            Self::BrokerLogger => "BROKER_LOGGER",
45            Self::Broker => "BROKER",
46            Self::Topic => "TOPIC",
47            Self::Unknown => "UNKNOWN",
48        })
49    }
50}
51
52impl Type {
53    /// Returns the wire id for this resource type.
54    #[doc(alias = "org.apache.kafka.common.config.ConfigResource$Type#id")]
55    pub fn id(&self) -> i8 {
56        match self {
57            Type::Group => 32,
58            Type::ClientMetrics => 16,
59            Type::BrokerLogger => 8,
60            Type::Broker => 4,
61            Type::Topic => 2,
62            Type::Unknown => 0,
63        }
64    }
65
66    /// Returns the resource type for the given wire id, or
67    /// [`Type::Unknown`] if the id is unrecognized.
68    ///
69    /// # Arguments
70    ///
71    /// - `id` - the wire id
72    #[doc(alias = "org.apache.kafka.common.config.ConfigResource$Type#forId")]
73    pub fn for_id(id: i8) -> Type {
74        match id {
75            32 => Type::Group,
76            16 => Type::ClientMetrics,
77            8 => Type::BrokerLogger,
78            4 => Type::Broker,
79            2 => Type::Topic,
80            _ => Type::Unknown,
81        }
82    }
83}
84
85/// A class representing resources that have configs.
86#[derive(Clone, Debug, PartialEq, Eq, Hash)]
87#[doc(alias = "org.apache.kafka.common.config.ConfigResource")]
88pub struct ConfigResource {
89    resource_type: Type,
90    name: String,
91}
92
93impl ConfigResource {
94    /// Create an instance of this class with the provided parameters.
95    ///
96    /// # Arguments
97    ///
98    /// - `resource_type` - a non-None resource type
99    /// - `name` - a non-None resource name
100    #[doc(alias = "org.apache.kafka.common.config.ConfigResource#ConfigResource")]
101    pub fn new(resource_type: Type, name: String) -> Self {
102        Self { resource_type, name }
103    }
104
105    /// Returns the resource type.
106    #[doc(alias = "org.apache.kafka.common.config.ConfigResource#type")]
107    pub fn r#type(&self) -> Type {
108        self.resource_type
109    }
110
111    /// Returns the resource name.
112    #[doc(alias = "org.apache.kafka.common.config.ConfigResource#name")]
113    pub fn name(&self) -> &str {
114        &self.name
115    }
116
117    /// Returns true if this is the default resource of a resource type.
118    /// Resource name is empty for the default resource.
119    #[doc(alias = "org.apache.kafka.common.config.ConfigResource#isDefault")]
120    pub fn is_default(&self) -> bool {
121        self.name.is_empty()
122    }
123}
124
125impl std::fmt::Display for ConfigResource {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        write!(f, "ConfigResource(type={}, name='{}')", self.resource_type, self.name)
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    /// Translated from `ConfigResourceTest.shouldRoundTripEveryType`.
136    #[test]
137    #[doc(alias = "org.apache.kafka.common.config.ConfigResourceTest#shouldRoundTripEveryType")]
138    fn should_round_trip_every_type() {
139        for t in [
140            Type::Group,
141            Type::ClientMetrics,
142            Type::BrokerLogger,
143            Type::Broker,
144            Type::Topic,
145            Type::Unknown,
146        ] {
147            assert_eq!(Type::for_id(t.id()), t);
148        }
149    }
150
151    #[test]
152    fn type_ids_match_java() {
153        assert_eq!(Type::Group.id(), 32);
154        assert_eq!(Type::ClientMetrics.id(), 16);
155        assert_eq!(Type::BrokerLogger.id(), 8);
156        assert_eq!(Type::Broker.id(), 4);
157        assert_eq!(Type::Topic.id(), 2);
158        assert_eq!(Type::Unknown.id(), 0);
159    }
160
161    #[test]
162    fn for_id_unknown_falls_back() {
163        assert_eq!(Type::for_id(99), Type::Unknown);
164    }
165
166    /// Translated from `ConfigResourceTest.shouldGetTypeFromId`.
167    #[test]
168    #[doc(alias = "org.apache.kafka.common.config.ConfigResourceTest#shouldGetTypeFromId")]
169    fn should_get_type_from_id() {
170        assert_eq!(Type::Topic, Type::for_id(2));
171        assert_eq!(Type::Broker, Type::for_id(4));
172        assert_eq!(Type::ClientMetrics, Type::for_id(16));
173        assert_eq!(Type::Group, Type::for_id(32));
174    }
175
176    /// Translated from `ConfigResourceTest.shouldReturnUnknownForUnknownCode`.
177    #[test]
178    #[doc(alias = "org.apache.kafka.common.config.ConfigResourceTest#shouldReturnUnknownForUnknownCode")]
179    fn should_return_unknown_for_unknown_code() {
180        assert_eq!(Type::Unknown, Type::for_id(-1));
181        assert_eq!(Type::Unknown, Type::for_id(0));
182        assert_eq!(Type::Unknown, Type::for_id(1));
183    }
184
185    #[test]
186    fn is_default_when_name_empty() {
187        assert!(ConfigResource::new(Type::Broker, String::new()).is_default());
188        assert!(!ConfigResource::new(Type::Broker, "0".to_string()).is_default());
189    }
190
191    #[test]
192    fn equality_uses_type_and_name() {
193        let a = ConfigResource::new(Type::Topic, "t".to_string());
194        let b = ConfigResource::new(Type::Topic, "t".to_string());
195        let c = ConfigResource::new(Type::Broker, "t".to_string());
196        assert_eq!(a, b);
197        assert_ne!(a, c);
198    }
199
200    /// Java's `toString()` prints the type's constant name.
201    #[test]
202    fn to_string_follows_java() {
203        assert_eq!(
204            ConfigResource::new(Type::ClientMetrics, "m".to_string()).to_string(),
205            "ConfigResource(type=CLIENT_METRICS, name='m')"
206        );
207    }
208}