confluent_kafka/common/metric_name.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//! The `MetricName` class encapsulates a metric's name, logical group and its
16//! related attributes (`org.apache.kafka.common.MetricName`).
17
18use std::collections::BTreeMap;
19
20/// The `MetricName` class encapsulates a metric's name, logical group and its
21/// related attributes. It should be constructed using `Metrics::metric_name(...)`.
22///
23/// This class captures the following parameters:
24/// - `name`: The name of the metric
25/// - `group`: logical group name of the metrics to which this metric belongs.
26/// - `description`: A human-readable description to include in the metric. This is optional.
27/// - `tags`: additional key/value attributes of the metric. This is optional.
28///
29/// `group` and `tags` parameters can be used to create unique metric names while
30/// reporting in any custom reporting.
31///
32/// Two `MetricName`s are equal if their `name`, `group`, and `tags` match;
33/// `description` is intentionally excluded from equality and hashing.
34#[derive(Clone, Debug)]
35#[doc(alias = "org.apache.kafka.common.MetricName")]
36pub struct MetricName {
37 name: String,
38 group: String,
39 description: String,
40 // Java stores tags in an (insertion-ordered) `Map`, but equality and hashing
41 // are order-independent. `BTreeMap` gives us deterministic iteration plus
42 // order-independent `Eq`/`Hash`, value-identical to Java's `Map.equals`.
43 tags: BTreeMap<String, String>,
44}
45
46impl MetricName {
47 /// Create a `MetricName`.
48 ///
49 /// Please create `MetricName` via [`crate::common::metrics::Metrics::metric_name_with_description_tags`].
50 ///
51 /// # Arguments
52 ///
53 /// - `name` - The name of the metric
54 /// - `group` - logical group name of the metrics to which this metric belongs
55 /// - `description` - A human-readable description to include in the metric
56 /// - `tags` - additional key/value attributes of the metric
57 #[doc(alias = "org.apache.kafka.common.MetricName#MetricName")]
58 pub fn new(
59 name: impl Into<String>,
60 group: impl Into<String>,
61 description: impl Into<String>,
62 tags: BTreeMap<String, String>,
63 ) -> Self {
64 Self { name: name.into(), group: group.into(), description: description.into(), tags }
65 }
66
67 /// Returns the name of the metric.
68 #[doc(alias = "org.apache.kafka.common.MetricName#name")]
69 pub fn name(&self) -> &str {
70 &self.name
71 }
72
73 /// Returns the logical group name of the metrics to which this metric belongs.
74 #[doc(alias = "org.apache.kafka.common.MetricName#group")]
75 pub fn group(&self) -> &str {
76 &self.group
77 }
78
79 /// Returns the additional key/value attributes of the metric.
80 #[doc(alias = "org.apache.kafka.common.MetricName#tags")]
81 pub fn tags(&self) -> &BTreeMap<String, String> {
82 &self.tags
83 }
84
85 /// Returns a human-readable description of the metric.
86 #[doc(alias = "org.apache.kafka.common.MetricName#description")]
87 pub fn description(&self) -> &str {
88 &self.description
89 }
90}
91
92impl PartialEq for MetricName {
93 fn eq(&self, other: &Self) -> bool {
94 // Mirrors Java: equality is on group, name, and tags only (not description).
95 self.group == other.group && self.name == other.name && self.tags == other.tags
96 }
97}
98
99impl Eq for MetricName {}
100
101impl std::hash::Hash for MetricName {
102 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
103 // Mirrors Java: hashCode is on group, name, and tags only.
104 self.group.hash(state);
105 self.name.hash(state);
106 self.tags.hash(state);
107 }
108}
109
110impl std::fmt::Display for MetricName {
111 /// Java's `MetricName.toString()`. The tags render as Java's `Map.toString()`
112 /// does, `{k1=v1, k2=v2}` (in key order here: the tags are a `BTreeMap`).
113 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114 write!(
115 f,
116 "MetricName [name={}, group={}, description={}, tags={{",
117 self.name, self.group, self.description
118 )?;
119 for (i, (key, value)) in self.tags.iter().enumerate() {
120 if i > 0 {
121 f.write_str(", ")?;
122 }
123 write!(f, "{key}={value}")?;
124 }
125 f.write_str("}]")
126 }
127}
128
129#[cfg(test)]
130mod tests {
131 use super::*;
132
133 fn tags(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
134 pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
135 }
136
137 #[test]
138 fn equality_ignores_description() {
139 let n1 = MetricName::new("n", "g", "desc-a", tags(&[("k", "v")]));
140 let n2 = MetricName::new("n", "g", "desc-b", tags(&[("k", "v")]));
141 assert_eq!(n1, n2);
142 }
143
144 #[test]
145 fn equality_is_tag_order_independent() {
146 let mut t1 = BTreeMap::new();
147 t1.insert("a".to_string(), "1".to_string());
148 t1.insert("b".to_string(), "2".to_string());
149 let mut t2 = BTreeMap::new();
150 t2.insert("b".to_string(), "2".to_string());
151 t2.insert("a".to_string(), "1".to_string());
152 assert_eq!(MetricName::new("n", "g", "", t1), MetricName::new("n", "g", "", t2));
153 }
154
155 #[test]
156 fn inequality_on_name_group_tags() {
157 let base = MetricName::new("n", "g", "", tags(&[("k", "v")]));
158 assert_ne!(base, MetricName::new("n2", "g", "", tags(&[("k", "v")])));
159 assert_ne!(base, MetricName::new("n", "g2", "", tags(&[("k", "v")])));
160 assert_ne!(base, MetricName::new("n", "g", "", tags(&[("k", "v2")])));
161 }
162}