Skip to main content

confluent_kafka/admin/
config_entry.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 configuration entry containing name, value and additional metadata.
16
17use crate::common::Error;
18
19/// Data type of configuration entry.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
21#[non_exhaustive]
22#[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry$ConfigType")]
23pub enum ConfigType {
24    /// Unknown data type.
25    #[default]
26    Unknown,
27    /// Boolean.
28    Boolean,
29    /// String.
30    String,
31    /// Integer.
32    Int,
33    /// Short.
34    Short,
35    /// Long.
36    Long,
37    /// Double.
38    Double,
39    /// List.
40    List,
41    /// Class.
42    Class,
43    /// Password.
44    Password,
45}
46
47impl ConfigType {
48    /// Maps a `DescribeConfigsResponse.ConfigType` wire id to the public
49    /// [`ConfigType`].
50    ///
51    /// Mirrors the composition of `DescribeConfigsResponse.ConfigType.forId`
52    /// and `.type()`. Unlike Java's `forId`, which throws
53    /// `IllegalArgumentException` for a negative id, this returns
54    /// [`ConfigType::Unknown`] for any unrecognized id so response parsing never
55    /// panics on a recoverable path.
56    pub(crate) fn for_id(id: i8) -> ConfigType {
57        match id {
58            1 => ConfigType::Boolean,
59            2 => ConfigType::String,
60            3 => ConfigType::Int,
61            4 => ConfigType::Short,
62            5 => ConfigType::Long,
63            6 => ConfigType::Double,
64            7 => ConfigType::List,
65            8 => ConfigType::Class,
66            9 => ConfigType::Password,
67            _ => ConfigType::Unknown,
68        }
69    }
70
71    /// The name of this constant in Java's
72    /// `org.apache.kafka.clients.admin.ConfigEntry$ConfigType`. The Java enum does not override
73    /// `toString()`, so `Enum.toString()` returns this name.
74    fn name(&self) -> &'static str {
75        match self {
76            ConfigType::Unknown => "UNKNOWN",
77            ConfigType::Boolean => "BOOLEAN",
78            ConfigType::String => "STRING",
79            ConfigType::Int => "INT",
80            ConfigType::Short => "SHORT",
81            ConfigType::Long => "LONG",
82            ConfigType::Double => "DOUBLE",
83            ConfigType::List => "LIST",
84            ConfigType::Class => "CLASS",
85            ConfigType::Password => "PASSWORD",
86        }
87    }
88}
89
90/// Renders the Java constant name (`PASSWORD`, `UNKNOWN`, ...), as Java's
91/// `Enum.toString()` does.
92impl std::fmt::Display for ConfigType {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        write!(f, "{}", self.name())
95    }
96}
97
98/// Source of configuration entries.
99#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
100#[non_exhaustive]
101#[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry$ConfigSource")]
102pub enum ConfigSource {
103    /// Dynamic topic config that is configured for a specific topic.
104    DynamicTopicConfig,
105    /// Dynamic broker logger config that is configured for a specific broker.
106    DynamicBrokerLoggerConfig,
107    /// Dynamic broker config that is configured for a specific broker.
108    DynamicBrokerConfig,
109    /// Dynamic broker config that is configured as default for all brokers in
110    /// the cluster.
111    DynamicDefaultBrokerConfig,
112    /// Dynamic client metrics subscription config that is configured for all
113    /// clients.
114    DynamicClientMetricsConfig,
115    /// Dynamic group config that is configured for a specific group.
116    DynamicGroupConfig,
117    /// Static broker config provided as broker properties at start up (e.g.
118    /// `server.properties` file).
119    StaticBrokerConfig,
120    /// Built-in default configuration for configs that have a default value.
121    DefaultConfig,
122    /// Source unknown, e.g. in the `ConfigEntry` used for alter requests where
123    /// source is not set.
124    Unknown,
125}
126
127impl ConfigSource {
128    /// Maps a `DescribeConfigsResponse.ConfigSource` wire id (also carried on
129    /// `CreatableTopicConfigs.configSource`) to the public [`ConfigSource`].
130    ///
131    /// Mirrors the composition of `DescribeConfigsResponse.ConfigSource.forId`
132    /// and `KafkaAdminClient.configSource`. Unlike Java's `configSource`, which
133    /// throws `IllegalArgumentException` for the `UNKNOWN` / client-metrics /
134    /// group ids, this returns [`ConfigSource::Unknown`] for unrecognized ids so
135    /// response parsing never panics on a recoverable path.
136    pub(crate) fn for_id(id: i8) -> ConfigSource {
137        match id {
138            1 => ConfigSource::DynamicTopicConfig,
139            2 => ConfigSource::DynamicBrokerConfig,
140            3 => ConfigSource::DynamicDefaultBrokerConfig,
141            4 => ConfigSource::StaticBrokerConfig,
142            5 => ConfigSource::DefaultConfig,
143            6 => ConfigSource::DynamicBrokerLoggerConfig,
144            7 => ConfigSource::DynamicClientMetricsConfig,
145            8 => ConfigSource::DynamicGroupConfig,
146            _ => ConfigSource::Unknown,
147        }
148    }
149
150    /// The name of this constant in Java's
151    /// `org.apache.kafka.clients.admin.ConfigEntry$ConfigSource`. The Java enum does not override
152    /// `toString()`, so `Enum.toString()` returns this name.
153    fn name(&self) -> &'static str {
154        match self {
155            ConfigSource::DynamicTopicConfig => "DYNAMIC_TOPIC_CONFIG",
156            ConfigSource::DynamicBrokerLoggerConfig => "DYNAMIC_BROKER_LOGGER_CONFIG",
157            ConfigSource::DynamicBrokerConfig => "DYNAMIC_BROKER_CONFIG",
158            ConfigSource::DynamicDefaultBrokerConfig => "DYNAMIC_DEFAULT_BROKER_CONFIG",
159            ConfigSource::DynamicClientMetricsConfig => "DYNAMIC_CLIENT_METRICS_CONFIG",
160            ConfigSource::DynamicGroupConfig => "DYNAMIC_GROUP_CONFIG",
161            ConfigSource::StaticBrokerConfig => "STATIC_BROKER_CONFIG",
162            ConfigSource::DefaultConfig => "DEFAULT_CONFIG",
163            ConfigSource::Unknown => "UNKNOWN",
164        }
165    }
166}
167
168/// Renders the Java constant name (`DYNAMIC_BROKER_CONFIG`, `UNKNOWN`, ...), as
169/// Java's `Enum.toString()` does.
170impl std::fmt::Display for ConfigSource {
171    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172        write!(f, "{}", self.name())
173    }
174}
175
176/// Class representing a configuration synonym of a [`ConfigEntry`].
177#[derive(Clone, Debug, PartialEq, Eq, Hash)]
178#[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry$ConfigSynonym")]
179pub struct ConfigSynonym {
180    name: String,
181    value: Option<String>,
182    source: ConfigSource,
183}
184
185impl ConfigSynonym {
186    /// Create a configuration synonym with the provided values.
187    ///
188    /// Package-private in Java; the caller is `describeConfigs` response parsing.
189    #[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry$ConfigSynonym#ConfigSynonym")]
190    pub(crate) fn new(name: String, value: Option<String>, source: ConfigSource) -> Self {
191        Self { name, value, source }
192    }
193
194    /// Returns the name of this configuration.
195    #[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry$ConfigSynonym#name")]
196    pub fn name(&self) -> &str {
197        &self.name
198    }
199
200    /// Returns the value of this configuration, which may be `None` if the
201    /// configuration is sensitive.
202    #[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry$ConfigSynonym#value")]
203    pub fn value(&self) -> Option<&str> {
204        self.value.as_deref()
205    }
206
207    /// Returns the source of this configuration.
208    #[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry$ConfigSynonym#source")]
209    pub fn source(&self) -> ConfigSource {
210        self.source
211    }
212}
213
214/// Java's `ConfigSynonym.toString()`: the
215/// source renders as its Java constant name and a missing value as `null`.
216impl std::fmt::Display for ConfigSynonym {
217    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218        write!(
219            f,
220            "ConfigSynonym(name={}, value={}, source={})",
221            self.name,
222            self.value.as_deref().unwrap_or("null"),
223            self.source
224        )
225    }
226}
227
228/// What Java's `ConfigEntry.toString()` prints in place of a sensitive value.
229const REDACTED: &str = "Redacted";
230
231/// A class representing a configuration entry containing name, value and
232/// additional metadata.
233///
234/// # Translation notes
235///
236/// `Debug` renders what `Display` renders.
237#[derive(Clone, PartialEq, Eq, Hash)]
238#[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry")]
239pub struct ConfigEntry {
240    name: String,
241    value: Option<String>,
242    source: ConfigSource,
243    is_sensitive: bool,
244    is_read_only: bool,
245    synonyms: Vec<ConfigSynonym>,
246    /// `None` for Java's `null` type, which the `createTopics` entries carry
247    /// (the `configEntry` helper of `KafkaAdminClient#getCreateTopicsCall`).
248    config_type: Option<ConfigType>,
249    documentation: Option<String>,
250}
251
252/// The parameters of Java's widest `ConfigEntry` constructor
253/// (`ConfigEntry(String, String, ConfigSource, boolean, boolean, List, ConfigType, String)`),
254/// taken by [`ConfigEntry::with_options`].
255///
256/// It has no `Default`: `name` and `value` are mandatory. Build it with
257/// [`ConfigEntryOptionsBuilder`], whose [`build`](ConfigEntryOptionsBuilder::build)
258/// returns an error if either was not set.
259///
260/// `Debug` renders a sensitive `value` as `"Redacted"`, as the [`ConfigEntry`]
261/// built from it renders it.
262#[non_exhaustive]
263#[derive(Clone, PartialEq, Eq)]
264// the options of ConfigEntry's constructor overloads
265#[doc(alias = "rust-only")]
266pub struct ConfigEntryOptions {
267    /// The non-null config name. Java's `name`.
268    pub(crate) name: String,
269    /// The config value or `None`. Java's `value`.
270    pub(crate) value: Option<String>,
271    /// The source of this config entry. Java's `source`; starts as
272    /// [`ConfigSource::Unknown`], as in the two-argument constructor.
273    pub(crate) source: ConfigSource,
274    /// Whether the config value is sensitive; the broker never returns the
275    /// value if it is sensitive. Java's `isSensitive`; starts as `false`.
276    pub(crate) is_sensitive: bool,
277    /// Whether the config is read-only and cannot be updated. Java's
278    /// `isReadOnly`; starts as `false`.
279    pub(crate) is_read_only: bool,
280    /// Synonym configs in order of precedence. Java's `synonyms`; starts empty.
281    pub(crate) synonyms: Vec<ConfigSynonym>,
282    /// The config data type, or `None` for Java's `null`. Java's `type`;
283    /// starts as `Some(`[`ConfigType::Unknown`]`)`.
284    pub(crate) config_type: Option<ConfigType>,
285    /// The config documentation. Java's `documentation`; starts as `None`.
286    pub(crate) documentation: Option<String>,
287}
288
289/// Renders every field as the derive it replaces did, except that the value of
290/// a sensitive entry renders as `"Redacted"`, the word Java's
291/// `ConfigEntry.toString()` prints for it.
292///
293/// This struct has no Java counterpart, so it has no Java rendering of its
294/// own. It carries the values of the [`ConfigEntry`] it builds, which never
295/// renders a sensitive value, so a derived `Debug` here would print what the
296/// entry itself hides.
297impl std::fmt::Debug for ConfigEntryOptions {
298    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
299        // Destructured exhaustively, so a field added to the struct must be
300        // considered here.
301        let Self {
302            name,
303            value,
304            source,
305            is_sensitive,
306            is_read_only,
307            synonyms,
308            config_type,
309            documentation,
310        } = self;
311        let mut debug = f.debug_struct("ConfigEntryOptions");
312        debug.field("name", name);
313        if *is_sensitive {
314            debug.field("value", &REDACTED);
315        } else {
316            debug.field("value", value);
317        }
318        debug
319            .field("source", source)
320            .field("is_sensitive", is_sensitive)
321            .field("is_read_only", is_read_only)
322            .field("synonyms", synonyms)
323            .field("config_type", config_type)
324            .field("documentation", documentation)
325            .finish()
326    }
327}
328
329/// Fluent builder for [`ConfigEntryOptions`].
330///
331/// [`Self::new`] takes no parameters, every parameter has a fluent setter, and
332/// [`Self::build`] returns an error if a mandatory one (`name`, `value`) was not
333/// set.
334#[derive(Debug)]
335// builds ConfigEntryOptions
336#[doc(alias = "rust-only")]
337pub struct ConfigEntryOptionsBuilder {
338    name: Option<String>,
339    value: Option<Option<String>>,
340    source: ConfigSource,
341    is_sensitive: bool,
342    is_read_only: bool,
343    synonyms: Vec<ConfigSynonym>,
344    config_type: Option<ConfigType>,
345    documentation: Option<String>,
346}
347
348impl Default for ConfigEntryOptionsBuilder {
349    fn default() -> Self {
350        Self::new()
351    }
352}
353
354impl ConfigEntryOptionsBuilder {
355    /// Creates a builder with every mandatory parameter unset and every other
356    /// parameter at the value Java passes on the caller's behalf.
357    pub fn new() -> Self {
358        Self {
359            name: None,
360            value: None,
361            source: ConfigSource::Unknown,
362            is_sensitive: false,
363            is_read_only: false,
364            synonyms: Vec::new(),
365            config_type: Some(ConfigType::Unknown),
366            documentation: None,
367        }
368    }
369
370    /// Sets `name`, a mandatory parameter: [`Self::build`] returns an error if it
371    /// was not set.
372    ///
373    /// # Arguments
374    ///
375    /// - `name` - the non-None config name
376    ///
377    /// # Returns
378    ///
379    /// This builder.
380    pub fn set_name(mut self, name: String) -> Self {
381        self.name = Some(name);
382        self
383    }
384    /// Sets `value`, a mandatory parameter: [`Self::build`] returns an error if it
385    /// was not set.
386    ///
387    /// # Arguments
388    ///
389    /// - `value` - the config value or `None`
390    ///
391    /// # Returns
392    ///
393    /// This builder.
394    pub fn set_value(mut self, value: Option<String>) -> Self {
395        self.value = Some(value);
396        self
397    }
398    /// Sets `source`.
399    ///
400    /// # Arguments
401    ///
402    /// - `source` - the source of this config entry
403    ///
404    /// # Returns
405    ///
406    /// This builder.
407    pub fn set_source(mut self, source: ConfigSource) -> Self {
408        self.source = source;
409        self
410    }
411    /// Sets `is_sensitive`.
412    ///
413    /// # Arguments
414    ///
415    /// - `is_sensitive` - whether the config value is sensitive, the broker never returns the value
416    ///   if
417    ///   it is sensitive
418    ///
419    /// # Returns
420    ///
421    /// This builder.
422    pub fn set_is_sensitive(mut self, is_sensitive: bool) -> Self {
423        self.is_sensitive = is_sensitive;
424        self
425    }
426    /// Sets `is_read_only`.
427    ///
428    /// # Arguments
429    ///
430    /// - `is_read_only` - whether the config is read-only and cannot be updated
431    ///
432    /// # Returns
433    ///
434    /// This builder.
435    pub fn set_is_read_only(mut self, is_read_only: bool) -> Self {
436        self.is_read_only = is_read_only;
437        self
438    }
439    /// Sets `synonyms`.
440    ///
441    /// # Arguments
442    ///
443    /// - `synonyms` - synonym configs in order of precedence
444    ///
445    /// # Returns
446    ///
447    /// This builder.
448    pub fn set_synonyms(mut self, synonyms: Vec<ConfigSynonym>) -> Self {
449        self.synonyms = synonyms;
450        self
451    }
452    /// Sets `config_type`.
453    ///
454    /// # Arguments
455    ///
456    /// - `config_type` - the config data type, or `None` for Java's `null`,
457    ///   which the `createTopics` entries carry
458    ///
459    /// # Returns
460    ///
461    /// This builder.
462    pub fn set_config_type(mut self, config_type: Option<ConfigType>) -> Self {
463        self.config_type = config_type;
464        self
465    }
466    /// Sets `documentation`.
467    ///
468    /// # Arguments
469    ///
470    /// - `documentation` - the config documentation
471    ///
472    /// # Returns
473    ///
474    /// This builder.
475    pub fn set_documentation(mut self, documentation: Option<String>) -> Self {
476        self.documentation = documentation;
477        self
478    }
479
480    /// Returns the built options.
481    ///
482    /// Only the presence of the mandatory parameters is checked here; semantic
483    /// validation belongs to [`ConfigEntry::with_options`].
484    ///
485    /// # Errors
486    ///
487    /// - `Error::is_local_illegal_argument_error` if `name` or `value` was not set,
488    ///   naming the first one missing.
489    pub fn build(self) -> Result<ConfigEntryOptions, Error> {
490        Ok(ConfigEntryOptions {
491            name: self.name.ok_or_else(|| Self::missing("name"))?,
492            value: self.value.ok_or_else(|| Self::missing("value"))?,
493            source: self.source,
494            is_sensitive: self.is_sensitive,
495            is_read_only: self.is_read_only,
496            synonyms: self.synonyms,
497            config_type: self.config_type,
498            documentation: self.documentation,
499        })
500    }
501
502    /// Builds the [`Error::LocalIllegalArgument`] naming a mandatory parameter
503    /// [`Self::build`] found unset.
504    fn missing(parameter: &str) -> Error {
505        Error::local_illegal_argument(format!(
506            "ConfigEntryOptionsBuilder::build: mandatory parameter `{parameter}` was not set"
507        ))
508    }
509}
510
511impl ConfigEntry {
512    /// Create a configuration entry with the provided values.
513    ///
514    /// # Arguments
515    ///
516    /// - `name` - the non-None config name
517    /// - `value` - the config value or `None`
518    #[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry#ConfigEntry")]
519    pub fn new(name: String, value: Option<String>) -> Self {
520        Self::with_options(
521            ConfigEntryOptionsBuilder::new()
522                .set_name(name)
523                .set_value(value)
524                .build()
525                .expect("ConfigEntryOptionsBuilder::build: every mandatory parameter is set above"),
526        )
527    }
528
529    /// Create a configuration with the provided values.
530    ///
531    /// # Arguments
532    ///
533    /// - `options` - the parameters of Java's widest constructor: `name`, `value`,
534    ///   `source`, `is_sensitive`, `is_read_only`, `synonyms`, `config_type` and
535    ///   `documentation`
536    #[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry#ConfigEntry")]
537    pub fn with_options(options: ConfigEntryOptions) -> Self {
538        let ConfigEntryOptions {
539            name,
540            value,
541            source,
542            is_sensitive,
543            is_read_only,
544            synonyms,
545            config_type,
546            documentation,
547        } = options;
548        Self {
549            name,
550            value,
551            source,
552            is_sensitive,
553            is_read_only,
554            synonyms,
555            config_type,
556            documentation,
557        }
558    }
559
560    /// Returns the config name.
561    #[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry#name")]
562    pub fn name(&self) -> &str {
563        &self.name
564    }
565
566    /// Returns the value or `None`. `None` is returned if the config is unset or
567    /// if `is_sensitive` is true.
568    #[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry#value")]
569    pub fn value(&self) -> Option<&str> {
570        self.value.as_deref()
571    }
572
573    /// Returns the source of this configuration entry.
574    #[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry#source")]
575    pub fn source(&self) -> ConfigSource {
576        self.source
577    }
578
579    /// Returns whether the config value is the default or if it's been
580    /// explicitly set.
581    #[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry#isDefault")]
582    pub fn is_default(&self) -> bool {
583        self.source == ConfigSource::DefaultConfig
584    }
585
586    /// Returns whether the config value is sensitive. The value is always set to
587    /// `None` by the broker if the config value is sensitive.
588    #[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry#isSensitive")]
589    pub fn is_sensitive(&self) -> bool {
590        self.is_sensitive
591    }
592
593    /// Returns whether the config is read-only and cannot be updated.
594    #[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry#isReadOnly")]
595    pub fn is_read_only(&self) -> bool {
596        self.is_read_only
597    }
598
599    /// Returns all config values that may be used as the value of this config
600    /// along with their source, in the order of precedence. The list starts
601    /// with the value returned in this `ConfigEntry`. The list is empty if
602    /// synonyms were not requested.
603    #[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry#synonyms")]
604    pub fn synonyms(&self) -> &[ConfigSynonym] {
605        &self.synonyms
606    }
607
608    /// Returns the config data type.
609    #[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry#type")]
610    pub fn r#type(&self) -> Option<ConfigType> {
611        self.config_type
612    }
613
614    /// Returns the config documentation.
615    #[doc(alias = "org.apache.kafka.clients.admin.ConfigEntry#documentation")]
616    pub fn documentation(&self) -> Option<&str> {
617        self.documentation.as_deref()
618    }
619}
620
621impl std::fmt::Display for ConfigEntry {
622    /// Redacts sensitive value.
623    ///
624    /// Java's `toString()`: the source and
625    /// type render as their Java constant names (a missing type as `null`), and
626    /// the synonyms as Java's `AbstractCollection.toString()` renders the list
627    /// (`[a, b]`, `[]` when empty), each synonym through its own `Display`.
628    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
629        let value = if self.is_sensitive {
630            REDACTED
631        } else {
632            self.value.as_deref().unwrap_or("null")
633        };
634        write!(
635            f,
636            "ConfigEntry(name={}, value={}, source={}, isSensitive={}, isReadOnly={}, synonyms=[",
637            self.name, value, self.source, self.is_sensitive, self.is_read_only
638        )?;
639        for (i, synonym) in self.synonyms.iter().enumerate() {
640            if i > 0 {
641                f.write_str(", ")?;
642            }
643            write!(f, "{synonym}")?;
644        }
645        f.write_str("], type=")?;
646        match self.config_type {
647            Some(config_type) => write!(f, "{config_type}")?,
648            None => f.write_str("null")?,
649        }
650        write!(f, ", documentation={})", self.documentation.as_deref().unwrap_or("null"))
651    }
652}
653
654/// Renders exactly what the redacting [`Display`](std::fmt::Display) renders.
655///
656/// Java has a single `toString()`, which prints
657/// `Redacted` for the value of a sensitive entry; a derived `Debug` would be a
658/// second, unredacted rendering. [`Config`](crate::admin::Config) and
659/// [`AlterConfigOp`](crate::admin::AlterConfigOp) embed entries, so their
660/// derived `Debug` renders through this one.
661impl std::fmt::Debug for ConfigEntry {
662    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
663        std::fmt::Display::fmt(self, f)
664    }
665}
666
667#[cfg(test)]
668mod tests {
669    use super::*;
670
671    #[test]
672    fn simple_constructor_defaults() {
673        let entry = ConfigEntry::new("k".to_string(), Some("v".to_string()));
674        assert_eq!(entry.name(), "k");
675        assert_eq!(entry.value(), Some("v"));
676        assert_eq!(entry.source(), ConfigSource::Unknown);
677        assert!(!entry.is_sensitive());
678        assert!(!entry.is_read_only());
679        assert!(entry.synonyms().is_empty());
680        assert_eq!(entry.r#type(), Some(ConfigType::Unknown));
681        assert_eq!(entry.documentation(), None);
682    }
683
684    #[test]
685    fn is_default_only_for_default_config_source() {
686        let default = ConfigEntry::with_options(
687            ConfigEntryOptionsBuilder::new()
688                .set_name("k".to_string())
689                .set_value(None)
690                .set_source(ConfigSource::DefaultConfig)
691                .set_config_type(Some(ConfigType::String))
692                .build()
693                .unwrap(),
694        );
695        assert!(default.is_default());
696        assert!(!ConfigEntry::new("k".to_string(), None).is_default());
697    }
698
699    #[test]
700    fn display_redacts_sensitive_value() {
701        let entry = ConfigEntry::with_options(
702            ConfigEntryOptionsBuilder::new()
703                .set_name("password".to_string())
704                .set_value(Some("secret".to_string()))
705                .set_is_sensitive(true)
706                .set_config_type(Some(ConfigType::Password))
707                .build()
708                .unwrap(),
709        );
710        let s = entry.to_string();
711        assert!(s.contains("value=Redacted"), "{s}");
712        assert!(!s.contains("secret"), "{s}");
713    }
714
715    /// New test, no Java original (Java has no `ConfigEntryTest`): every
716    /// `ConfigType` renders its Java constant name, as Java's `Enum.toString()`
717    /// does (`org.apache.kafka.clients.admin.ConfigEntry$ConfigType`).
718    #[test]
719    fn config_type_display_matches_java_constant_names() {
720        for (config_type, java) in [
721            (ConfigType::Unknown, "UNKNOWN"),
722            (ConfigType::Boolean, "BOOLEAN"),
723            (ConfigType::String, "STRING"),
724            (ConfigType::Int, "INT"),
725            (ConfigType::Short, "SHORT"),
726            (ConfigType::Long, "LONG"),
727            (ConfigType::Double, "DOUBLE"),
728            (ConfigType::List, "LIST"),
729            (ConfigType::Class, "CLASS"),
730            (ConfigType::Password, "PASSWORD"),
731        ] {
732            assert_eq!(config_type.to_string(), java);
733        }
734    }
735
736    /// New test, no Java original: every `ConfigSource` renders its Java
737    /// constant name, as Java's `Enum.toString()` does
738    /// (`org.apache.kafka.clients.admin.ConfigEntry$ConfigSource`).
739    #[test]
740    fn config_source_display_matches_java_constant_names() {
741        for (source, java) in [
742            (ConfigSource::DynamicTopicConfig, "DYNAMIC_TOPIC_CONFIG"),
743            (ConfigSource::DynamicBrokerLoggerConfig, "DYNAMIC_BROKER_LOGGER_CONFIG"),
744            (ConfigSource::DynamicBrokerConfig, "DYNAMIC_BROKER_CONFIG"),
745            (ConfigSource::DynamicDefaultBrokerConfig, "DYNAMIC_DEFAULT_BROKER_CONFIG"),
746            (ConfigSource::DynamicClientMetricsConfig, "DYNAMIC_CLIENT_METRICS_CONFIG"),
747            (ConfigSource::DynamicGroupConfig, "DYNAMIC_GROUP_CONFIG"),
748            (ConfigSource::StaticBrokerConfig, "STATIC_BROKER_CONFIG"),
749            (ConfigSource::DefaultConfig, "DEFAULT_CONFIG"),
750            (ConfigSource::Unknown, "UNKNOWN"),
751        ] {
752            assert_eq!(source.to_string(), java);
753        }
754    }
755
756    /// New test, no Java original: `ConfigSynonym`'s `Display` is the string
757    /// Java's `ConfigSynonym.toString()` builds,
758    /// with a missing value rendered as `null`.
759    #[test]
760    fn config_synonym_display_matches_java_to_string() {
761        let synonym = ConfigSynonym::new(
762            "log.retention.ms".to_string(),
763            Some("604800000".to_string()),
764            ConfigSource::DynamicBrokerConfig,
765        );
766        assert_eq!(
767            synonym.to_string(),
768            "ConfigSynonym(name=log.retention.ms, value=604800000, source=DYNAMIC_BROKER_CONFIG)"
769        );
770        let without_value = ConfigSynonym::new("log.retention.hours".to_string(), None, ConfigSource::DefaultConfig);
771        assert_eq!(
772            without_value.to_string(),
773            "ConfigSynonym(name=log.retention.hours, value=null, source=DEFAULT_CONFIG)"
774        );
775    }
776
777    /// New test, no Java original: `Display` is the string Java's
778    /// `ConfigEntry.toString()` builds for an entry
779    /// with two synonyms and a non-default source, type and documentation. The
780    /// synonyms render as Java's list of `ConfigSynonym.toString()`s.
781    #[test]
782    fn display_matches_java_to_string() {
783        let entry = ConfigEntry::with_options(
784            ConfigEntryOptionsBuilder::new()
785                .set_name("log.retention.ms".to_string())
786                .set_value(Some("604800000".to_string()))
787                .set_source(ConfigSource::DynamicBrokerConfig)
788                .set_is_read_only(true)
789                .set_synonyms(vec![
790                    ConfigSynonym::new(
791                        "log.retention.ms".to_string(),
792                        Some("604800000".to_string()),
793                        ConfigSource::DynamicBrokerConfig,
794                    ),
795                    ConfigSynonym::new(
796                        "log.retention.hours".to_string(),
797                        Some("168".to_string()),
798                        ConfigSource::DefaultConfig,
799                    ),
800                ])
801                .set_config_type(Some(ConfigType::Long))
802                .set_documentation(Some("The retention time.".to_string()))
803                .build()
804                .unwrap(),
805        );
806        assert_eq!(
807            entry.to_string(),
808            "ConfigEntry(name=log.retention.ms, value=604800000, source=DYNAMIC_BROKER_CONFIG, \
809             isSensitive=false, isReadOnly=true, \
810             synonyms=[ConfigSynonym(name=log.retention.ms, value=604800000, \
811             source=DYNAMIC_BROKER_CONFIG), ConfigSynonym(name=log.retention.hours, value=168, \
812             source=DEFAULT_CONFIG)], type=LONG, documentation=The retention time.)"
813        );
814    }
815
816    /// New test, no Java original: the entry Java's two-argument constructor
817    /// builds renders an empty synonym list as `[]`,
818    /// the `UNKNOWN` source and type, and `null` for a missing value and
819    /// documentation; a sensitive entry renders `Redacted` with the same shape.
820    #[test]
821    fn display_matches_java_to_string_for_defaults_and_sensitive_entry() {
822        assert_eq!(
823            ConfigEntry::new("cleanup.policy".to_string(), None).to_string(),
824            "ConfigEntry(name=cleanup.policy, value=null, source=UNKNOWN, isSensitive=false, \
825             isReadOnly=false, synonyms=[], type=UNKNOWN, documentation=null)"
826        );
827        assert_eq!(
828            sensitive_entry().to_string(),
829            "ConfigEntry(name=ssl.keystore.password, value=Redacted, source=DYNAMIC_BROKER_CONFIG, \
830             isSensitive=true, isReadOnly=false, synonyms=[], type=PASSWORD, documentation=null)"
831        );
832    }
833
834    /// A distinctive secret for the `Debug` tests.
835    const SECRET: &str = "ssl-keystore-S3cr3t-5b72";
836
837    /// A sensitive entry holding [`SECRET`].
838    fn sensitive_entry() -> ConfigEntry {
839        ConfigEntry::with_options(sensitive_options())
840    }
841
842    /// Options for a sensitive entry holding [`SECRET`].
843    fn sensitive_options() -> ConfigEntryOptions {
844        ConfigEntryOptionsBuilder::new()
845            .set_name("ssl.keystore.password".to_string())
846            .set_value(Some(SECRET.to_string()))
847            .set_source(ConfigSource::DynamicBrokerConfig)
848            .set_is_sensitive(true)
849            .set_config_type(Some(ConfigType::Password))
850            .build()
851            .unwrap()
852    }
853
854    /// New test, no Java original: `Debug` renders exactly what `Display` does
855    /// (Java has a single `toString()`): `Redacted` for a sensitive value,
856    /// while a non-sensitive value still prints.
857    #[test]
858    fn debug_redacts_sensitive_value() {
859        let sensitive = sensitive_entry();
860        assert_eq!(sensitive.value(), Some(SECRET));
861        for rendered in [format!("{sensitive:?}"), format!("{sensitive:#?}")] {
862            assert_eq!(rendered, sensitive.to_string());
863            assert!(rendered.contains("name=ssl.keystore.password"), "{rendered}");
864            assert!(rendered.contains("value=Redacted"), "{rendered}");
865            assert!(!rendered.contains(SECRET), "secret leaked: {rendered}");
866        }
867
868        let plain = ConfigEntry::new("retention.ms".to_string(), Some("604800000".to_string()));
869        for rendered in [format!("{plain:?}"), format!("{plain:#?}")] {
870            assert_eq!(rendered, plain.to_string());
871            assert!(rendered.contains("value=604800000"), "{rendered}");
872        }
873    }
874
875    /// New test, no Java original (Java has no such struct): `Debug` renders a
876    /// sensitive value as `"Redacted"`, as the entry built from the options
877    /// renders it, and every other field as the derive did.
878    #[test]
879    fn options_debug_redacts_sensitive_value() {
880        let options = sensitive_options();
881        assert_eq!(options.value.as_deref(), Some(SECRET));
882        let rendered = format!("{options:?}");
883        assert_eq!(
884            rendered,
885            "ConfigEntryOptions { name: \"ssl.keystore.password\", value: \"Redacted\", \
886             source: DynamicBrokerConfig, is_sensitive: true, is_read_only: false, synonyms: [], \
887             config_type: Some(Password), documentation: None }"
888        );
889        let pretty = format!("{options:#?}");
890        assert!(pretty.contains("value: \"Redacted\""), "{pretty}");
891        for rendered in [rendered, pretty] {
892            assert!(!rendered.contains(SECRET), "secret leaked: {rendered}");
893        }
894    }
895
896    /// New test, no Java original: the options of a non-sensitive entry render
897    /// the value, as the derive did.
898    #[test]
899    fn options_debug_renders_non_sensitive_value() {
900        let options = ConfigEntryOptionsBuilder::new()
901            .set_name("retention.ms".to_string())
902            .set_value(Some("604800000".to_string()))
903            .build()
904            .unwrap();
905        let rendered = format!("{options:?}");
906        assert!(rendered.contains("value: Some(\"604800000\")"), "{rendered}");
907        assert!(rendered.contains("is_sensitive: false"), "{rendered}");
908    }
909
910    #[test]
911    fn equality() {
912        let a = ConfigEntry::new("k".to_string(), Some("v".to_string()));
913        let b = ConfigEntry::new("k".to_string(), Some("v".to_string()));
914        let c = ConfigEntry::new("k".to_string(), Some("other".to_string()));
915        assert_eq!(a, b);
916        assert_ne!(a, c);
917    }
918
919    /// The entry `KafkaAdminClient#createTopics` builds: a
920    /// source, the two flags, no synonyms, and `null` type and documentation.
921    fn entry_without_type() -> ConfigEntry {
922        ConfigEntry::with_options(
923            ConfigEntryOptionsBuilder::new()
924                .set_name("compression.type".to_string())
925                .set_value(Some("producer".to_string()))
926                .set_source(ConfigSource::DefaultConfig)
927                .set_config_type(None)
928                .build()
929                .unwrap(),
930        )
931    }
932
933    /// New test, no Java original: an entry without a type renders `type=null`,
934    /// as Java's `toString()` renders the `null` type of a `createTopics` entry.
935    #[test]
936    fn display_matches_java_to_string_for_an_entry_without_type() {
937        let entry = entry_without_type();
938        assert_eq!(entry.r#type(), None);
939        assert_eq!(
940            entry.to_string(),
941            "ConfigEntry(name=compression.type, value=producer, source=DEFAULT_CONFIG, \
942             isSensitive=false, isReadOnly=false, synonyms=[], type=null, documentation=null)"
943        );
944    }
945
946    /// New test, no Java original: Java's `equals` compares the types with
947    /// `Objects.equals` (`ConfigEntry#equals`), so a `null` type differs
948    /// from `UNKNOWN`, and two `null` types are equal.
949    #[test]
950    fn equality_tells_a_missing_type_from_unknown() {
951        let with_unknown = ConfigEntry::with_options(
952            ConfigEntryOptionsBuilder::new()
953                .set_name("compression.type".to_string())
954                .set_value(Some("producer".to_string()))
955                .set_source(ConfigSource::DefaultConfig)
956                .build()
957                .unwrap(),
958        );
959        assert_eq!(with_unknown.r#type(), Some(ConfigType::Unknown));
960        assert_ne!(entry_without_type(), with_unknown);
961        assert_eq!(entry_without_type(), entry_without_type());
962    }
963
964    /// The mandatory parameters are validated in
965    /// [`ConfigEntryOptionsBuilder::build`], not named in the constructor, so a
966    /// builder left untouched panics naming the first one it finds unset.
967    #[test]
968    fn config_entry_options_builder_build_errors_when_no_mandatory_parameter_is_set() {
969        let Err(error) = ConfigEntryOptionsBuilder::new().build() else {
970            panic!("build must reject the unset mandatory parameter");
971        };
972        assert!(matches!(error, Error::LocalIllegalArgument(_)), "{error:?}");
973        assert_eq!(
974            error.message(),
975            "ConfigEntryOptionsBuilder::build: mandatory parameter `name` was not set"
976        );
977    }
978
979    /// Validation covers every mandatory parameter, not just the first: setting
980    /// all but one still panics, naming the one left unset.
981    #[test]
982    fn config_entry_options_builder_build_errors_when_only_value_is_unset() {
983        let Err(error) = ConfigEntryOptionsBuilder::new()
984            .set_name("compression.type".to_string())
985            .build()
986        else {
987            panic!("build must reject the unset mandatory parameter");
988        };
989        assert!(matches!(error, Error::LocalIllegalArgument(_)), "{error:?}");
990        assert_eq!(
991            error.message(),
992            "ConfigEntryOptionsBuilder::build: mandatory parameter `value` was not set"
993        );
994    }
995}