Skip to main content

confluent_kafka/common/quota/
client_quota_alteration.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 alteration type.
16//!
17//! Corresponds to `org.apache.kafka.common.quota.ClientQuotaAlteration`.
18
19use crate::common::quota::ClientQuotaEntity;
20
21/// A single quota alteration operation.
22///
23/// Equality and hashing follow Java's `Objects.equals(value, that.value)` and
24/// `Objects.hash(key, value)`, which compare and hash a `Double` through
25/// `Double.doubleToLongBits`: every `NaN` is equal to every other, and `0.0`
26/// differs from `-0.0`.
27#[derive(Clone, Debug)]
28#[doc(alias = "org.apache.kafka.common.quota.ClientQuotaAlteration$Op")]
29pub struct Op {
30    key: String,
31    value: Option<f64>,
32}
33
34/// Java's `Double.doubleToLongBits`: the bits of `value`, with every `NaN`
35/// folded into the canonical one.
36fn double_to_long_bits(value: f64) -> u64 {
37    if value.is_nan() {
38        f64::NAN.to_bits()
39    } else {
40        value.to_bits()
41    }
42}
43
44impl PartialEq for Op {
45    fn eq(&self, other: &Self) -> bool {
46        self.key == other.key && self.value.map(double_to_long_bits) == other.value.map(double_to_long_bits)
47    }
48}
49
50impl Eq for Op {}
51
52impl std::hash::Hash for Op {
53    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
54        self.key.hash(state);
55        self.value.map(double_to_long_bits).hash(state);
56    }
57}
58
59impl Op {
60    /// Constructs an alteration op.
61    ///
62    /// # Arguments
63    ///
64    /// - `key` - the quota type to alter
65    /// - `value` - if set then the existing value is updated, otherwise if
66    ///   `None`, the existing value is cleared
67    #[doc(alias = "org.apache.kafka.common.quota.ClientQuotaAlteration$Op#Op")]
68    pub fn new(key: impl Into<String>, value: Option<f64>) -> Self {
69        Self { key: key.into(), value }
70    }
71
72    /// # Returns
73    ///
74    /// the quota type to alter
75    #[doc(alias = "org.apache.kafka.common.quota.ClientQuotaAlteration$Op#key")]
76    pub fn key(&self) -> &str {
77        &self.key
78    }
79
80    /// # Returns
81    ///
82    /// if set then the existing value is updated, otherwise if `None`, the
83    /// existing value is cleared
84    #[doc(alias = "org.apache.kafka.common.quota.ClientQuotaAlteration$Op#value")]
85    pub fn value(&self) -> Option<f64> {
86        self.value
87    }
88}
89
90impl std::fmt::Display for Op {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        match self.value {
93            Some(v) => write!(f, "ClientQuotaAlteration.Op(key={}, value={v})", self.key),
94            None => write!(f, "ClientQuotaAlteration.Op(key={}, value=null)", self.key),
95        }
96    }
97}
98
99/// Describes a configuration alteration to be made to a client quota entity.
100#[derive(Clone, Debug)]
101#[doc(alias = "org.apache.kafka.common.quota.ClientQuotaAlteration")]
102pub struct ClientQuotaAlteration {
103    entity: ClientQuotaEntity,
104    ops: Vec<Op>,
105}
106
107impl ClientQuotaAlteration {
108    /// Constructs an alteration.
109    ///
110    /// # Arguments
111    ///
112    /// - `entity` - the entity whose config will be modified
113    /// - `ops` - the alteration to perform
114    #[doc(alias = "org.apache.kafka.common.quota.ClientQuotaAlteration#ClientQuotaAlteration")]
115    pub fn new(entity: ClientQuotaEntity, ops: Vec<Op>) -> Self {
116        Self { entity, ops }
117    }
118
119    /// # Returns
120    ///
121    /// the entity whose config will be modified
122    #[doc(alias = "org.apache.kafka.common.quota.ClientQuotaAlteration#entity")]
123    pub fn entity(&self) -> &ClientQuotaEntity {
124        &self.entity
125    }
126
127    /// # Returns
128    ///
129    /// the alteration to perform
130    #[doc(alias = "org.apache.kafka.common.quota.ClientQuotaAlteration#ops")]
131    pub fn ops(&self) -> &[Op] {
132        &self.ops
133    }
134}
135
136impl std::fmt::Display for ClientQuotaAlteration {
137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        write!(f, "ClientQuotaAlteration(entity={}, ops={:?})", self.entity, self.ops)
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145    use std::collections::HashMap;
146
147    fn entity() -> ClientQuotaEntity {
148        let mut m = HashMap::new();
149        m.insert(ClientQuotaEntity::USER.to_string(), Some("u1".to_string()));
150        ClientQuotaEntity::new(m)
151    }
152
153    // New test, no Java original: the four `common/quota` classes have no
154    // dedicated Java test files (upstream gap, see DoD #3 note in PLAN.md).
155    #[test]
156    fn op_set_vs_remove() {
157        let set = Op::new("consumer_byte_rate", Some(10000.0));
158        assert_eq!(set.key(), "consumer_byte_rate");
159        assert_eq!(set.value(), Some(10000.0));
160
161        // A `None` value signals removal (Java `null`).
162        let remove = Op::new("producer_byte_rate", None);
163        assert_eq!(remove.value(), None);
164    }
165
166    // New test, no Java original.
167    #[test]
168    fn op_equality() {
169        assert_eq!(Op::new("k", Some(1.0)), Op::new("k", Some(1.0)));
170        assert_ne!(Op::new("k", Some(1.0)), Op::new("k", None));
171    }
172
173    // New test, no Java original: pins `Double.equals` on the value, under
174    // which every NaN is equal and the two zeros differ, and hashing agrees.
175    #[test]
176    fn op_compares_its_value_as_java_double_equals() {
177        use std::hash::BuildHasher;
178        let other_nan = f64::from_bits(f64::NAN.to_bits() ^ 1);
179        assert!(other_nan.is_nan());
180        let a = Op::new("k", Some(f64::NAN));
181        let b = Op::new("k", Some(other_nan));
182        assert_eq!(a, b);
183        let state = std::collections::hash_map::RandomState::new();
184        assert_eq!(state.hash_one(&a), state.hash_one(&b));
185        assert_ne!(Op::new("k", Some(0.0)), Op::new("k", Some(-0.0)));
186    }
187
188    // New test, no Java original.
189    #[test]
190    fn alteration_accessors() {
191        let alt = ClientQuotaAlteration::new(entity(), vec![Op::new("consumer_byte_rate", Some(1.0))]);
192        assert_eq!(alt.entity(), &entity());
193        assert_eq!(alt.ops().len(), 1);
194    }
195}