Skip to main content

confluent_kafka/admin/
alter_config_op.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//! An alter configuration operation.
16
17use super::ConfigEntry;
18
19/// The operation type of an [`AlterConfigOp`].
20#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
21#[non_exhaustive]
22#[doc(alias = "org.apache.kafka.clients.admin.AlterConfigOp$OpType")]
23pub enum OpType {
24    /// Set the value of the configuration entry.
25    Set,
26    /// Revert the configuration entry to the default value (possibly null).
27    Delete,
28    /// (For list-type configuration entries only.) Add the specified values to
29    /// the current value of the configuration entry. If the configuration value
30    /// has not been set, adds to the default value.
31    Append,
32    /// (For list-type configuration entries only.) Removes the specified values
33    /// from the current value of the configuration entry. It is legal to remove
34    /// values that are not currently in the configuration entry. Removing all
35    /// entries from the current configuration value leaves an empty list and
36    /// does NOT revert to the default value of the entry.
37    Subtract,
38}
39
40impl OpType {
41    /// Returns the wire id for this operation type.
42    #[doc(alias = "org.apache.kafka.clients.admin.AlterConfigOp$OpType#id")]
43    pub fn id(&self) -> i8 {
44        match self {
45            OpType::Set => 0,
46            OpType::Delete => 1,
47            OpType::Append => 2,
48            OpType::Subtract => 3,
49        }
50    }
51
52    /// Returns the operation type for the given wire id, or `None` if the id is
53    /// unrecognized.
54    ///
55    /// # Arguments
56    ///
57    /// - `id` - the wire id
58    #[doc(alias = "org.apache.kafka.clients.admin.AlterConfigOp$OpType#forId")]
59    pub fn for_id(id: i8) -> Option<OpType> {
60        match id {
61            0 => Some(OpType::Set),
62            1 => Some(OpType::Delete),
63            2 => Some(OpType::Append),
64            3 => Some(OpType::Subtract),
65            _ => None,
66        }
67    }
68
69    /// The name of this constant in Java's
70    /// `org.apache.kafka.clients.admin.AlterConfigOp$OpType`. The Java enum does not override
71    /// `toString()`, so `Enum.toString()` returns this name.
72    fn name(&self) -> &'static str {
73        match self {
74            OpType::Set => "SET",
75            OpType::Delete => "DELETE",
76            OpType::Append => "APPEND",
77            OpType::Subtract => "SUBTRACT",
78        }
79    }
80}
81
82/// Renders the Java constant name (`SET`, `DELETE`, ...), as Java's
83/// `Enum.toString()` does.
84impl std::fmt::Display for OpType {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        write!(f, "{}", self.name())
87    }
88}
89
90/// A class representing an alter configuration entry containing name, value and
91/// operation type.
92///
93/// # Translation notes
94///
95/// The derived `Debug` renders the entry through [`ConfigEntry`]'s `Debug`,
96/// which redacts a sensitive value as Java's `ConfigEntry.toString()` does.
97#[derive(Clone, Debug, PartialEq, Eq, Hash)]
98#[doc(alias = "org.apache.kafka.clients.admin.AlterConfigOp")]
99pub struct AlterConfigOp {
100    config_entry: ConfigEntry,
101    op_type: OpType,
102}
103
104impl AlterConfigOp {
105    /// Creates a new alter config operation.
106    ///
107    /// # Arguments
108    ///
109    /// - `config_entry` - the config entry to alter
110    /// - `operation_type` - how to alter it
111    #[doc(alias = "org.apache.kafka.clients.admin.AlterConfigOp#AlterConfigOp")]
112    pub fn new(config_entry: ConfigEntry, operation_type: OpType) -> Self {
113        Self { config_entry, op_type: operation_type }
114    }
115
116    /// Returns the config entry.
117    #[doc(alias = "org.apache.kafka.clients.admin.AlterConfigOp#configEntry")]
118    pub fn config_entry(&self) -> &ConfigEntry {
119        &self.config_entry
120    }
121
122    /// Returns the operation type.
123    #[doc(alias = "org.apache.kafka.clients.admin.AlterConfigOp#opType")]
124    pub fn op_type(&self) -> OpType {
125        self.op_type
126    }
127}
128
129impl std::fmt::Display for AlterConfigOp {
130    /// Java's `toString()`, which renders
131    /// the operation type as its Java constant name and the entry through
132    /// `ConfigEntry.toString()`, the redacting rendering.
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        write!(f, "AlterConfigOp{{opType={}, configEntry={}}}", self.op_type, self.config_entry)
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141    use crate::admin::ConfigEntryOptionsBuilder;
142    use crate::admin::config_entry::ConfigType;
143
144    #[test]
145    fn op_type_id_round_trip() {
146        for op in [OpType::Set, OpType::Delete, OpType::Append, OpType::Subtract] {
147            assert_eq!(OpType::for_id(op.id()), Some(op));
148        }
149    }
150
151    #[test]
152    fn op_type_ids_match_java() {
153        assert_eq!(OpType::Set.id(), 0);
154        assert_eq!(OpType::Delete.id(), 1);
155        assert_eq!(OpType::Append.id(), 2);
156        assert_eq!(OpType::Subtract.id(), 3);
157    }
158
159    #[test]
160    fn op_type_for_unknown_id_is_none() {
161        assert_eq!(OpType::for_id(7), None);
162    }
163
164    #[test]
165    fn accessors_return_constructor_values() {
166        let entry = ConfigEntry::new("retention.ms".to_string(), Some("1000".to_string()));
167        let op = AlterConfigOp::new(entry.clone(), OpType::Set);
168        assert_eq!(op.config_entry(), &entry);
169        assert_eq!(op.op_type(), OpType::Set);
170    }
171
172    #[test]
173    fn equality_compares_entry_and_op() {
174        let entry = ConfigEntry::new("a".to_string(), Some("b".to_string()));
175        let a = AlterConfigOp::new(entry.clone(), OpType::Set);
176        let b = AlterConfigOp::new(entry.clone(), OpType::Set);
177        let c = AlterConfigOp::new(entry, OpType::Delete);
178        assert_eq!(a, b);
179        assert_ne!(a, c);
180    }
181
182    /// A distinctive secret for the redaction tests.
183    const SECRET: &str = "sasl-jaas-S3cr3t-2e96";
184
185    /// A `Set` operation on a sensitive entry holding [`SECRET`].
186    fn sensitive_op() -> AlterConfigOp {
187        let entry = ConfigEntry::with_options(
188            ConfigEntryOptionsBuilder::new()
189                .set_name("listener.name.sasl.plain.sasl.jaas.config".to_string())
190                .set_value(Some(SECRET.to_string()))
191                .set_is_sensitive(true)
192                .set_config_type(Some(ConfigType::Password))
193                .build()
194                .unwrap(),
195        );
196        AlterConfigOp::new(entry, OpType::Set)
197    }
198
199    /// New test, no Java original (Java has no `AlterConfigOpTest`): every
200    /// `OpType` renders its Java constant name, as Java's `Enum.toString()` does
201    /// (`org.apache.kafka.clients.admin.AlterConfigOp$OpType`).
202    #[test]
203    fn op_type_display_matches_java_constant_names() {
204        for (op_type, java) in [
205            (OpType::Set, "SET"),
206            (OpType::Delete, "DELETE"),
207            (OpType::Append, "APPEND"),
208            (OpType::Subtract, "SUBTRACT"),
209        ] {
210            assert_eq!(op_type.to_string(), java);
211        }
212    }
213
214    /// New test, no Java original: `Display` is the string Java's `toString()`
215    /// builds, which renders the entry through
216    /// `ConfigEntry.toString()`, the redacting rendering.
217    #[test]
218    fn display_redacts_sensitive_value() {
219        let op = sensitive_op();
220        assert_eq!(op.config_entry().value(), Some(SECRET));
221        let rendered = op.to_string();
222        assert_eq!(
223            rendered,
224            "AlterConfigOp{opType=SET, configEntry=ConfigEntry(\
225             name=listener.name.sasl.plain.sasl.jaas.config, value=Redacted, source=UNKNOWN, \
226             isSensitive=true, isReadOnly=false, synonyms=[], type=PASSWORD, documentation=null)}"
227        );
228        assert_eq!(
229            rendered,
230            format!("AlterConfigOp{{opType=SET, configEntry={}}}", op.config_entry())
231        );
232        assert!(!rendered.contains(SECRET), "secret leaked: {rendered}");
233    }
234
235    /// New test, no Java original: a non-sensitive `Delete` operation renders
236    /// the value and Java's `DELETE` constant name.
237    #[test]
238    fn display_matches_java_to_string_for_delete() {
239        let op = AlterConfigOp::new(
240            ConfigEntry::new("retention.ms".to_string(), Some("604800000".to_string())),
241            OpType::Delete,
242        );
243        assert_eq!(
244            op.to_string(),
245            "AlterConfigOp{opType=DELETE, configEntry=ConfigEntry(name=retention.ms, \
246             value=604800000, source=UNKNOWN, isSensitive=false, isReadOnly=false, synonyms=[], \
247             type=UNKNOWN, documentation=null)}"
248        );
249    }
250
251    /// New test, no Java original: the derived `Debug` renders the entry through
252    /// its redacting `Debug`, while a non-sensitive value still prints.
253    #[test]
254    fn debug_redacts_sensitive_value() {
255        let op = sensitive_op();
256        for rendered in [format!("{op:?}"), format!("{op:#?}")] {
257            assert!(rendered.starts_with("AlterConfigOp"), "{rendered}");
258            assert!(rendered.contains("op_type: Set"), "{rendered}");
259            assert!(rendered.contains(&op.config_entry().to_string()), "{rendered}");
260            assert!(rendered.contains("value=Redacted"), "{rendered}");
261            assert!(!rendered.contains(SECRET), "secret leaked: {rendered}");
262        }
263
264        let plain = AlterConfigOp::new(
265            ConfigEntry::new("retention.ms".to_string(), Some("604800000".to_string())),
266            OpType::Set,
267        );
268        let rendered = format!("{plain:?}");
269        assert!(rendered.contains("value=604800000"), "{rendered}");
270    }
271}