Skip to main content

confluent_kafka/common/
metric_name_template.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 template for a `MetricName` (`org.apache.kafka.common.MetricNameTemplate`).
16
17use indexmap::IndexSet;
18
19/// A template for a `MetricName`. It contains a name, group, and description, as
20/// well as all the tags that will be used to create the metric name. Tag values
21/// are omitted from the template, but are filled in at runtime with their
22/// specified values. The order of the tags is maintained so that the metric
23/// names can be compared and sorted lexicographically.
24#[derive(Clone, Debug)]
25#[doc(alias = "org.apache.kafka.common.MetricNameTemplate")]
26pub struct MetricNameTemplate {
27    name: String,
28    group: String,
29    description: String,
30    // Java uses a `LinkedHashSet<String>` to preserve insertion order while
31    // remaining a set. `IndexSet` is the order-preserving Rust equivalent.
32    tags: IndexSet<String>,
33}
34
35impl MetricNameTemplate {
36    /// Create a new template. The order of the tags is preserved.
37    ///
38    /// # Arguments
39    ///
40    /// - `name` - the name of the metric
41    /// - `group` - the name of the group
42    /// - `description` - the description of the metric
43    /// - `tag_names` - the names of the metric tags in the preferred order
44    #[doc(alias = "org.apache.kafka.common.MetricNameTemplate#MetricNameTemplate")]
45    pub fn new(
46        name: impl Into<String>,
47        group: impl Into<String>,
48        description: impl Into<String>,
49        tag_names: IndexSet<String>,
50    ) -> Self {
51        Self {
52            name: name.into(),
53            group: group.into(),
54            description: description.into(),
55            tags: tag_names,
56        }
57    }
58
59    /// Get the name of the metric.
60    ///
61    /// # Returns
62    ///
63    /// the metric name
64    #[doc(alias = "org.apache.kafka.common.MetricNameTemplate#name")]
65    pub fn name(&self) -> &str {
66        &self.name
67    }
68
69    /// Get the name of the group.
70    ///
71    /// # Returns
72    ///
73    /// the group name
74    #[doc(alias = "org.apache.kafka.common.MetricNameTemplate#group")]
75    pub fn group(&self) -> &str {
76        &self.group
77    }
78
79    /// Get the description of the metric.
80    ///
81    /// # Returns
82    ///
83    /// the metric description
84    #[doc(alias = "org.apache.kafka.common.MetricNameTemplate#description")]
85    pub fn description(&self) -> &str {
86        &self.description
87    }
88
89    /// Get the ordered set of tag names for the metric.
90    ///
91    /// # Returns
92    ///
93    /// the ordered set of tag names, possibly empty
94    #[doc(alias = "org.apache.kafka.common.MetricNameTemplate#tags")]
95    pub fn tags(&self) -> &IndexSet<String> {
96        &self.tags
97    }
98}
99
100impl PartialEq for MetricNameTemplate {
101    fn eq(&self, other: &Self) -> bool {
102        // Mirrors Java: equality is on name, group, and tags (set equality,
103        // order-independent).
104        self.name == other.name && self.group == other.group && self.tags == other.tags
105    }
106}
107
108impl Eq for MetricNameTemplate {}
109
110impl std::hash::Hash for MetricNameTemplate {
111    // Java's `MetricNameTemplate.hashCode()` is `Objects.hash(name, group,
112    // tags)`, the `LinkedHashSet` hashing independently of its order, as
113    // equality compares it.
114    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
115        self.name.hash(state);
116        self.group.hash(state);
117        crate::common::utils::Utils::hash_unordered(&self.tags, state);
118    }
119}
120
121impl std::fmt::Display for MetricNameTemplate {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        write!(f, "name={}, group={}, tags={:?}", self.name, self.group, self.tags)
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    fn set(items: &[&str]) -> IndexSet<String> {
132        items.iter().map(|s| s.to_string()).collect()
133    }
134
135    #[test]
136    fn equality_is_tag_order_independent() {
137        let a = MetricNameTemplate::new("n", "g", "d", set(&["a", "b"]));
138        let b = MetricNameTemplate::new("n", "g", "different", set(&["b", "a"]));
139        assert_eq!(a, b);
140    }
141
142    #[test]
143    fn inequality_on_name_group_tags() {
144        let base = MetricNameTemplate::new("n", "g", "", set(&["a"]));
145        assert_ne!(base, MetricNameTemplate::new("n2", "g", "", set(&["a"])));
146        assert_ne!(base, MetricNameTemplate::new("n", "g2", "", set(&["a"])));
147        assert_ne!(base, MetricNameTemplate::new("n", "g", "", set(&["b"])));
148    }
149}