Skip to main content

confluent_kafka/common/quota/
client_quota_entity.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//! Client quota entity type.
16//!
17//! Corresponds to `org.apache.kafka.common.quota.ClientQuotaEntity`.
18
19use std::collections::HashMap;
20use std::hash::{Hash, Hasher};
21
22/// Describes a client quota entity, which is a mapping of entity types to their
23/// names.
24///
25/// # Translation notes
26///
27/// A `None` name is Java's `null`.
28#[derive(Clone, Debug, Eq)]
29#[doc(alias = "org.apache.kafka.common.quota.ClientQuotaEntity")]
30pub struct ClientQuotaEntity {
31    entries: HashMap<String, Option<String>>,
32}
33
34impl ClientQuotaEntity {
35    /// The entity type value for a user.
36    pub const USER: &str = "user";
37
38    /// The entity type value for a client id.
39    pub const CLIENT_ID: &str = "client-id";
40
41    /// The entity type value for an IP address.
42    pub const IP: &str = "ip";
43
44    /// Returns whether the given entity type is one of the built-in types.
45    ///
46    /// # Arguments
47    ///
48    /// - `entity_type` - the entity type to check
49    #[doc(alias = "org.apache.kafka.common.quota.ClientQuotaEntity#isValidEntityType")]
50    pub fn is_valid_entity_type(entity_type: &str) -> bool {
51        entity_type == ClientQuotaEntity::USER
52            || entity_type == ClientQuotaEntity::CLIENT_ID
53            || entity_type == ClientQuotaEntity::IP
54    }
55
56    /// Constructs a quota entity for the given types and names. If a name is
57    /// `None`, then it is mapped to the built-in default entity
58    /// name.
59    ///
60    /// # Arguments
61    ///
62    /// - `entries` - maps entity type to its name
63    #[doc(alias = "org.apache.kafka.common.quota.ClientQuotaEntity#ClientQuotaEntity")]
64    pub fn new(entries: HashMap<String, Option<String>>) -> Self {
65        Self { entries }
66    }
67
68    /// # Returns
69    ///
70    /// map of entity type to its name (`None`: default)
71    #[doc(alias = "org.apache.kafka.common.quota.ClientQuotaEntity#entries")]
72    pub fn entries(&self) -> &HashMap<String, Option<String>> {
73        &self.entries
74    }
75}
76
77impl PartialEq for ClientQuotaEntity {
78    fn eq(&self, other: &Self) -> bool {
79        self.entries == other.entries
80    }
81}
82
83// `HashMap` does not implement `Hash`, so we implement it manually with an
84// order-independent accumulation, matching Java's `Objects.hash(entries)`
85// where `Map.hashCode()` is the order-independent sum of its entry hashes.
86impl Hash for ClientQuotaEntity {
87    fn hash<H: Hasher>(&self, state: &mut H) {
88        crate::common::utils::Utils::hash_unordered(&self.entries, state);
89    }
90}
91
92impl std::fmt::Display for ClientQuotaEntity {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        write!(f, "ClientQuotaEntity(entries={:?})", self.entries)
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    fn entity(pairs: &[(&str, &str)]) -> ClientQuotaEntity {
103        ClientQuotaEntity::new(pairs.iter().map(|(k, v)| ((*k).to_string(), Some((*v).to_string()))).collect())
104    }
105
106    // New test, no Java original: the four `common/quota` classes have no
107    // dedicated Java test files (upstream gap, see DoD #3 note in PLAN.md).
108    #[test]
109    fn is_valid_entity_type_matches_builtins() {
110        assert!(ClientQuotaEntity::is_valid_entity_type(ClientQuotaEntity::USER));
111        assert!(ClientQuotaEntity::is_valid_entity_type(ClientQuotaEntity::CLIENT_ID));
112        assert!(ClientQuotaEntity::is_valid_entity_type(ClientQuotaEntity::IP));
113        assert!(!ClientQuotaEntity::is_valid_entity_type("group"));
114    }
115
116    // New test, no Java original.
117    #[test]
118    fn equality_is_order_independent() {
119        let a = entity(&[(ClientQuotaEntity::USER, "u1"), (ClientQuotaEntity::CLIENT_ID, "c1")]);
120        let b = entity(&[(ClientQuotaEntity::CLIENT_ID, "c1"), (ClientQuotaEntity::USER, "u1")]);
121        assert_eq!(a, b);
122        assert_ne!(a, entity(&[(ClientQuotaEntity::USER, "u2")]));
123    }
124
125    // New test, no Java original: equal entities must hash equal so they can be
126    // used as `HashMap` keys.
127    #[test]
128    fn equal_entities_hash_equal() {
129        use std::collections::HashMap as Map;
130        let mut map: Map<ClientQuotaEntity, i32> = Map::new();
131        map.insert(
132            entity(&[(ClientQuotaEntity::USER, "u1"), (ClientQuotaEntity::CLIENT_ID, "c1")]),
133            7,
134        );
135        assert_eq!(
136            map.get(&entity(&[
137                (ClientQuotaEntity::CLIENT_ID, "c1"),
138                (ClientQuotaEntity::USER, "u1")
139            ])),
140            Some(&7)
141        );
142    }
143
144    // New test, no Java original.
145    #[test]
146    fn entries_accessor_round_trips() {
147        let e = entity(&[(ClientQuotaEntity::USER, "u1")]);
148        assert_eq!(e.entries().get(ClientQuotaEntity::USER), Some(&Some("u1".to_string())));
149    }
150
151    // New test, no Java original: a `None` name (the built-in default entity,
152    // e.g. `--entity-type users --entity-default`) is representable and stays
153    // distinct from an entity literally named "" (`Some("")`).
154    #[test]
155    fn default_entity_none_distinct_from_empty_name() {
156        let default_user = ClientQuotaEntity::new(HashMap::from([(ClientQuotaEntity::USER.to_string(), None)]));
157        let empty_named_user =
158            ClientQuotaEntity::new(HashMap::from([(ClientQuotaEntity::USER.to_string(), Some(String::new()))]));
159        assert_eq!(default_user.entries().get(ClientQuotaEntity::USER), Some(&None));
160        assert_eq!(
161            empty_named_user.entries().get(ClientQuotaEntity::USER),
162            Some(&Some(String::new()))
163        );
164        assert_ne!(default_user, empty_named_user);
165    }
166}