Skip to main content

confluent_kafka/common/metrics/
metrics.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 registry of sensors and metrics (`org.apache.kafka.common.metrics.Metrics`).
16
17use std::collections::{BTreeMap, HashMap};
18use std::sync::{Arc, Mutex};
19
20use crate::common::metrics::internals::MetricsUtils;
21use crate::common::metrics::metrics_view::SharedMetricMap;
22use crate::common::metrics::{
23    KafkaMetric, Measurable, MetricConfig, MetricValueProvider, MetricsReporter, MetricsView, RecordingLevel, Sensor,
24    gauge,
25};
26use crate::common::utils::{SystemTime, Time};
27use crate::common::{Error, Metric, MetricName, MetricNameTemplate, MetricValue};
28
29/// The shared registry state (metrics map + reporters) that is referenced both
30/// by [`Metrics`] and by [`Sensor`] (so a sensor can register its metrics).
31///
32/// Java keeps the metrics map and reporters on `Metrics` itself; the sensor
33/// calls back into the registry via its `registry` field. We extract the shared
34/// portion into an `Arc<MetricsShared>` so the back-reference does not form an
35/// ownership cycle.
36pub(crate) struct MetricsShared {
37    metrics: SharedMetricMap,
38    reporters: Mutex<Vec<Arc<dyn MetricsReporter>>>,
39}
40
41impl MetricsShared {
42    fn new(reporters: Vec<Arc<dyn MetricsReporter>>) -> Self {
43        Self { metrics: SharedMetricMap::default(), reporters: Mutex::new(reporters) }
44    }
45
46    /// Register a metric if not present, or return the already-existing metric
47    /// with the same name. When a metric is newly registered, returns `None`.
48    pub(crate) fn register_metric(&self, metric: Arc<KafkaMetric>) -> Option<Arc<KafkaMetric>> {
49        let metric_name = metric.metric_name().clone();
50        if let Some(existing) = self.metrics.insert_if_absent(metric_name, Arc::clone(&metric)) {
51            return Some(existing);
52        }
53        // Newly added metric: notify reporters (outside the metrics lock,
54        // mirroring Java which holds the Metrics monitor but reporters are
55        // separate objects).
56        let reporters = self.reporters.lock().expect("reporters mutex poisoned");
57        for reporter in reporters.iter() {
58            reporter.metric_change(&metric);
59        }
60        None
61    }
62
63    /// Remove a metric if it exists and return it; notify reporters on removal.
64    fn remove_metric(&self, metric_name: &MetricName) -> Option<Arc<KafkaMetric>> {
65        let removed = self.metrics.remove(metric_name);
66        if let Some(metric) = &removed {
67            let reporters = self.reporters.lock().expect("reporters mutex poisoned");
68            for reporter in reporters.iter() {
69                reporter.metric_removal(metric);
70            }
71        }
72        removed
73    }
74}
75
76/// A registry of sensors and metrics.
77///
78/// A metric is a named, numerical measurement. A sensor is a handle to record
79/// numerical measurements as they occur. Each [`Sensor`] has zero or more
80/// associated metrics. For example, a [`Sensor`] might represent message sizes,
81/// and we might associate with this sensor a metric for the average, maximum,
82/// or other statistics computed off the sequence of message sizes that are
83/// recorded by the sensor.
84///
85/// # Translation notes
86///
87/// The subset of Java's `Metrics` the clients use: JMX, the sensor-expiry
88/// task and the quota machinery are omitted.
89#[doc(alias = "org.apache.kafka.common.metrics.Metrics")]
90pub struct Metrics {
91    config: Arc<MetricConfig>,
92    shared: Arc<MetricsShared>,
93    sensors: Mutex<HashMap<String, Arc<Sensor>>>,
94    // childrenSensors keyed by the parent sensor's name (Java keys by Sensor
95    // identity; sensor names are unique in the registry so the name is an
96    // equivalent stable key).
97    children_sensors: Mutex<HashMap<String, Vec<Arc<Sensor>>>>,
98    time: Arc<dyn Time>,
99}
100
101/// The parameters of [`Metrics::sensor_with_options`].
102///
103/// Java's widest `sensor` overload
104/// (`sensor(String, MetricConfig, long, Sensor.RecordingLevel, Sensor...)`)
105/// carries four parameters beyond the overload group's `{name}` intersection,
106/// so the overload naming rule makes this struct the method's *only* parameter:
107/// every Java parameter lives here, `name` included. This struct has no Java
108/// counterpart: it exists solely to satisfy that naming rule.
109///
110/// It is `#[non_exhaustive]`, so build it from [`SensorOptionsBuilder::new`]
111/// and set the fields you need. Every other field's initial value is Java's —
112/// what its narrower `sensor` overloads pass on the caller's behalf. `name` has
113/// no such initial value: Java declares no `sensor` overload that omits it, so
114/// there is no Java-derived default to fall back on, and
115/// [`SensorOptionsBuilder::build`] returns an error if it was not set. `SensorOptions`
116/// itself has deliberately no `Default` for the same reason.
117// No `Debug` — `Sensor` is not `Debug`, and adding it there is out of scope for
118// a naming change. No `Copy` either: `config` is an `Option<Arc<..>>`.
119#[derive(Clone)]
120#[non_exhaustive]
121#[derive(Debug)]
122// the options of the Metrics.sensor overloads (CLAUDE.md §2)
123#[doc(alias = "rust-only")]
124pub struct SensorOptions<'a> {
125    /// Java's `name`, the sensor's unique registry key.
126    pub(crate) name: &'a str,
127    /// Java's `config`. Starts as `None`, meaning the registry's own config,
128    /// as Java's narrower `sensor` overloads pass.
129    pub(crate) config: Option<Arc<MetricConfig>>,
130    /// Java's `inactiveSensorExpirationTimeSeconds`. Starts as `i64::MAX`, as
131    /// Java's narrower `sensor` overloads pass.
132    pub(crate) inactive_sensor_expiration_time_seconds: i64,
133    /// Java's `recordingLevel`. Starts as `INFO`, as Java's narrower `sensor`
134    /// overloads pass.
135    pub(crate) recording_level: RecordingLevel,
136    /// Java's `parents` varargs. Starts empty, as Java's narrower `sensor`
137    /// overloads pass.
138    pub(crate) parents: &'a [Arc<Sensor>],
139}
140
141/// Fluent builder for [`SensorOptions`].
142///
143/// [`Self::new`] takes no parameters, every parameter has a fluent setter,
144/// and [`Self::build`] validates the mandatory ones — returning
145/// [`Error::LocalIllegalArgument`] if they were not set.
146#[derive(Debug)]
147// builds SensorOptions (CLAUDE.md §2)
148#[doc(alias = "rust-only")]
149pub struct SensorOptionsBuilder<'a> {
150    name: Option<&'a str>,
151    config: Option<Arc<MetricConfig>>,
152    inactive_sensor_expiration_time_seconds: i64,
153    recording_level: RecordingLevel,
154    parents: &'a [Arc<Sensor>],
155}
156
157impl<'a> Default for SensorOptionsBuilder<'a> {
158    fn default() -> Self {
159        Self::new()
160    }
161}
162
163impl<'a> SensorOptionsBuilder<'a> {
164    /// Creates a builder with every mandatory parameter unset and every other
165    /// parameter at the value Java passes on the caller's behalf.
166    pub fn new() -> Self {
167        Self {
168            name: None,
169            config: None,
170            inactive_sensor_expiration_time_seconds: i64::MAX,
171            recording_level: RecordingLevel::Info,
172            parents: &[],
173        }
174    }
175
176    /// Sets `SensorOptions::name`, a mandatory parameter: [`Self::build`]
177    /// returns an error if it was not set.
178    ///
179    /// # Arguments
180    ///
181    /// - `name` - the sensor's unique name
182    ///
183    /// # Returns
184    ///
185    /// This builder, for chaining.
186    pub fn set_name(mut self, name: &'a str) -> Self {
187        self.name = Some(name);
188        self
189    }
190    /// Sets `SensorOptions::config`.
191    ///
192    /// # Arguments
193    ///
194    /// - `config` - the sensor's default config, `None` for the registry's
195    ///
196    /// # Returns
197    ///
198    /// This builder, for chaining.
199    pub fn set_config(mut self, config: Option<Arc<MetricConfig>>) -> Self {
200        self.config = config;
201        self
202    }
203    /// Sets `SensorOptions::inactive_sensor_expiration_time_seconds`.
204    ///
205    /// # Arguments
206    ///
207    /// - `inactive_sensor_expiration_time_seconds` - how long the sensor may go without a recording before it can be removed
208    ///
209    /// # Returns
210    ///
211    /// This builder, for chaining.
212    pub fn set_inactive_sensor_expiration_time_seconds(mut self, inactive_sensor_expiration_time_seconds: i64) -> Self {
213        self.inactive_sensor_expiration_time_seconds = inactive_sensor_expiration_time_seconds;
214        self
215    }
216    /// Sets `SensorOptions::recording_level`.
217    ///
218    /// # Arguments
219    ///
220    /// - `recording_level` - the sensor's recording level
221    ///
222    /// # Returns
223    ///
224    /// This builder, for chaining.
225    pub fn set_recording_level(mut self, recording_level: RecordingLevel) -> Self {
226        self.recording_level = recording_level;
227        self
228    }
229    /// Sets `SensorOptions::parents`.
230    ///
231    /// # Arguments
232    ///
233    /// - `parents` - the parent sensors
234    ///
235    /// # Returns
236    ///
237    /// This builder, for chaining.
238    pub fn set_parents(mut self, parents: &'a [Arc<Sensor>]) -> Self {
239        self.parents = parents;
240        self
241    }
242
243    /// Returns the built options.
244    ///
245    /// The mandatory parameters are validated here rather than being named in
246    /// the constructor, so a later Java version that makes one of
247    /// them optional changes the set this accepts instead of adding a second
248    /// constructor. Today there is one mandatory set: `name`.
249    ///
250    /// # Errors
251    ///
252    /// Returns [`Error::LocalIllegalArgument`] naming the first parameter of that
253    /// set which was not given a setter call. Only presence is checked here;
254    /// semantic validation belongs to the method the options are passed to.
255    pub fn build(self) -> Result<SensorOptions<'a>, Error> {
256        Ok(SensorOptions {
257            name: self.name.ok_or_else(|| Self::missing("name"))?,
258            config: self.config,
259            inactive_sensor_expiration_time_seconds: self.inactive_sensor_expiration_time_seconds,
260            recording_level: self.recording_level,
261            parents: self.parents,
262        })
263    }
264
265    /// Builds the [`Error::LocalIllegalArgument`] naming a mandatory parameter
266    /// [`Self::build`] found unset.
267    fn missing(parameter: &str) -> Error {
268        Error::local_illegal_argument(format!(
269            "SensorOptionsBuilder::build: mandatory parameter `{parameter}` was not set"
270        ))
271    }
272}
273
274impl std::fmt::Debug for Metrics {
275    // How many sensors and metrics the registry holds, not their state.
276    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
277        let sensors = self.sensors.lock().expect("sensors mutex poisoned").len();
278        let metrics = self.shared.metrics.len();
279        f.debug_struct("Metrics")
280            .field("sensors", &sensors)
281            .field("metrics", &metrics)
282            .finish_non_exhaustive()
283    }
284}
285
286impl Metrics {
287    // Java's `Metrics` constructors have an EMPTY parameter-name intersection,
288    // and the no-arg `Metrics()` matches it, so that one keeps the plain name
289    // `new` and every sibling is suffixed with its full Rust parameter list
290    // (CLAUDE.md §2). The two `MetricsContext` overloads are not translated —
291    // `MetricsContext` itself is untranslated.
292    //
293    // `Metrics(defaultConfig, reporters, time, boolean enableExpiration)` is
294    // likewise not translated. Its one distinguishing parameter exists solely to
295    // decide whether the constructor starts a `ScheduledThreadPoolExecutor` running
296    // `ExpireSensorTask` every 30s; it does not gate whether sensors *can* expire
297    // — Java's own `MetricsTest.testRemoveInactiveMetrics` builds a `Metrics`
298    // through the `enableExpiration = false` path (the
299    // `Metrics(defaultConfig, reporters, time)` overload passes `false`) and drives the task by hand. This translation has no scheduler at all: it
300    // exposes the task as `expire_sensors()` (below) for the caller to drive, which
301    // is exactly that Java test's shape. So a Rust `enable_expiration` parameter
302    // would select nothing, and an ignored parameter is a worse contract than an
303    // absent overload.
304
305    /// Create a metrics repository with the supplied default config and clock,
306    /// no reporters.
307    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#Metrics")]
308    pub(crate) fn with_default_config_time(default_config: Arc<MetricConfig>, time: Arc<dyn Time>) -> Self {
309        Self::with_default_config_reporters_time(default_config, Vec::new(), time)
310    }
311
312    /// Create a metrics repository with a default config, no reporters, and the
313    /// system clock.
314    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#Metrics")]
315    pub fn new() -> Self {
316        Self::with_default_config_reporters_time(Arc::new(MetricConfig::new()), Vec::new(), Arc::new(SystemTime))
317    }
318
319    /// Create a metrics repository with the supplied default config.
320    ///
321    /// # Arguments
322    ///
323    /// - `default_config` - The default config to use for all metrics that don't override their
324    ///   config
325    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#Metrics")]
326    pub fn with_default_config(default_config: Arc<MetricConfig>) -> Self {
327        Self::with_default_config_reporters_time(default_config, Vec::new(), Arc::new(SystemTime))
328    }
329
330    /// Create a metrics repository with the supplied clock.
331    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#Metrics")]
332    #[cfg_attr(not(test), expect(dead_code))] // translated overload; only tests pass a clock
333    pub(crate) fn with_time(time: Arc<dyn Time>) -> Self {
334        Self::with_default_config_reporters_time(Arc::new(MetricConfig::new()), Vec::new(), time)
335    }
336
337    /// Create a metrics repository with a default config, reporters, and clock.
338    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#Metrics")]
339    pub(crate) fn with_default_config_reporters_time(
340        default_config: Arc<MetricConfig>,
341        reporters: Vec<Arc<dyn MetricsReporter>>,
342        time: Arc<dyn Time>,
343    ) -> Self {
344        for reporter in &reporters {
345            reporter.init(&[]);
346        }
347        let metrics = Metrics {
348            config: default_config,
349            shared: Arc::new(MetricsShared::new(reporters)),
350            sensors: Mutex::new(HashMap::new()),
351            children_sensors: Mutex::new(HashMap::new()),
352            time,
353        };
354        // Java registers a "count" gauge in kafka-metrics-count group. The gauge is stored in the very map it
355        // reads, so it holds the shared state weakly: a strong `Arc` would be a
356        // cycle keeping the registry, and everything its metrics' providers
357        // capture, allocated after the last `Metrics` is dropped (Java's
358        // garbage collector frees the same graph). The upgrade fails only once
359        // the registry is gone, when no one can read the gauge any more.
360        let shared = Arc::downgrade(&metrics.shared);
361        let count_gauge = gauge::new(move |_config, _now| {
362            let n = shared.upgrade().map_or(0, |shared| shared.metrics.len());
363            MetricValue::Double(n as f64)
364        });
365        metrics
366            .add_metric_with_config_metric_value_provider(
367                metrics.metric_name_with_description_tags(
368                    "count",
369                    "kafka-metrics-count",
370                    "total number of registered metrics",
371                    BTreeMap::new(),
372                ),
373                None,
374                Box::new(count_gauge),
375            )
376            .expect("count metric registration should not fail on a fresh registry");
377        metrics
378    }
379
380    // Java's five `metricName` overloads intersect on `{name, group}`, and
381    // `metricName(String name, String group)` is exactly that pair — so it keeps the plain name and the others
382    // are suffixed with their Rust parameters beyond it (CLAUDE.md §2).
383
384    /// Returns a `MetricName` with the given name, group, description and tags,
385    /// plus default tags specified in the metric configuration. Tags in `tags`
386    /// take precedence over default tags with the same key.
387    ///
388    /// # Arguments
389    ///
390    /// - `name` - The name of the metric
391    /// - `group` - logical group name of the metrics to which this metric belongs
392    /// - `description` - A human-readable description to include in the metric
393    /// - `tags` - additional key/value attributes of the metric
394    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#metricName")]
395    pub fn metric_name_with_description_tags(
396        &self,
397        name: impl Into<String>,
398        group: impl Into<String>,
399        description: impl Into<String>,
400        tags: BTreeMap<String, String>,
401    ) -> MetricName {
402        let mut combined = self.config.tags().clone();
403        combined.extend(tags);
404        MetricName::new(name, group, description, combined)
405    }
406
407    /// Returns a `MetricName` with the given name, group and description, plus the
408    /// default tags specified in the metric configuration.
409    ///
410    /// # Arguments
411    ///
412    /// - `name` - The name of the metric
413    /// - `group` - logical group name of the metrics to which this metric belongs
414    /// - `description` - A human-readable description to include in the metric
415    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#metricName")]
416    pub fn metric_name_with_description(
417        &self,
418        name: impl Into<String>,
419        group: impl Into<String>,
420        description: impl Into<String>,
421    ) -> MetricName {
422        self.metric_name_with_description_tags(name, group, description, BTreeMap::new())
423    }
424
425    /// Returns a `MetricName` with the given name, group and tags, plus the default
426    /// tags specified in the metric configuration. Tags in `tags` take precedence
427    /// over default tags with the same key.
428    ///
429    /// # Arguments
430    ///
431    /// - `name` - The name of the metric
432    /// - `group` - logical group name of the metrics to which this metric belongs
433    /// - `tags` - additional key/value attributes of the metric
434    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#metricName")]
435    pub fn metric_name_with_tags(
436        &self,
437        name: impl Into<String>,
438        group: impl Into<String>,
439        tags: BTreeMap<String, String>,
440    ) -> MetricName {
441        self.metric_name_with_description_tags(name, group, "", tags)
442    }
443
444    /// Returns a `MetricName` with name and group (empty description, default tags).
445    ///
446    /// # Arguments
447    ///
448    /// - `name` - The name of the metric
449    /// - `group` - logical group name of the metrics to which this metric belongs
450    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#metricName")]
451    pub fn metric_name(&self, name: impl Into<String>, group: impl Into<String>) -> MetricName {
452        self.metric_name_with_description_tags(name, group, "", BTreeMap::new())
453    }
454
455    /// Returns a `MetricName` from `key, value` tag pairs, plus default tags.
456    ///
457    /// # Arguments
458    ///
459    /// - `name` - The name of the metric
460    /// - `group` - logical group name of the metrics to which this metric belongs
461    /// - `description` - A human-readable description to include in the metric
462    /// - `key_value` - additional key/value attributes of the metric (must come in pairs)
463    ///
464    /// # Errors
465    ///
466    /// - `Error::is_local_illegal_argument_error` if `key_value` has an odd length
467    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#metricName")]
468    pub fn metric_name_with_description_key_value(
469        &self,
470        name: impl Into<String>,
471        group: impl Into<String>,
472        description: impl Into<String>,
473        key_value: &[&str],
474    ) -> Result<MetricName, Error> {
475        Ok(self.metric_name_with_description_tags(name, group, description, MetricsUtils::get_tags(key_value)?))
476    }
477
478    /// Returns the default config of this registry.
479    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#config")]
480    pub fn config(&self) -> &Arc<MetricConfig> {
481        &self.config
482    }
483
484    /// Get the sensor with the given name if it exists.
485    ///
486    /// # Arguments
487    ///
488    /// - `name` - The name of the sensor
489    ///
490    /// # Returns
491    ///
492    /// Return the sensor or None if no such sensor exists
493    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#getSensor")]
494    pub fn get_sensor(&self, name: &str) -> Option<Arc<Sensor>> {
495        self.sensors.lock().expect("sensors mutex poisoned").get(name).cloned()
496    }
497
498    // Java's eight `sensor` overloads intersect on `{name}`, and
499    // `sensor(String name)` is exactly that — so it keeps the plain name and the
500    // others name their parameters beyond it after `_with_` (CLAUDE.md §2). Only
501    // `sensor(String, MetricConfig, long, RecordingLevel, Sensor...)` would need
502    // more than three parameters in its name, so it alone takes the `Options`
503    // shape: `SensorOptions` is that method's only parameter and carries every
504    // Java parameter including `name`, which is why it is `sensor_with_options`,
505    // naming no parameter at all. `sensor(String, MetricConfig, long, Sensor...)`
506    // keeps four parameters spelled out because its name needs only three of
507    // them.
508
509    /// Get or create a sensor with the given unique name and no parents at INFO
510    /// recording level.
511    ///
512    /// # Arguments
513    ///
514    /// - `name` - The sensor name
515    ///
516    /// # Returns
517    ///
518    /// The sensor
519    ///
520    /// # Errors
521    ///
522    /// - `Error::is_local_illegal_argument_error` if the sensor would be its own
523    ///   ancestor
524    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#sensor")]
525    pub fn sensor(&self, name: &str) -> Result<Arc<Sensor>, Error> {
526        self.sensor_with_options(SensorOptionsBuilder::new().set_name(name).build()?)
527    }
528
529    /// Get or create a sensor with the given name, recording level, and no parents.
530    ///
531    /// # Arguments
532    ///
533    /// - `name` - The sensor name.
534    /// - `recording_level` - The recording level.
535    ///
536    /// # Returns
537    ///
538    /// The sensor
539    ///
540    /// # Errors
541    ///
542    /// - `Error::is_local_illegal_argument_error` if the sensor would be its own
543    ///   ancestor
544    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#sensor")]
545    pub fn sensor_with_recording_level(
546        &self,
547        name: &str,
548        recording_level: RecordingLevel,
549    ) -> Result<Arc<Sensor>, Error> {
550        self.sensor_with_options(
551            SensorOptionsBuilder::new()
552                .set_name(name)
553                .set_recording_level(recording_level)
554                .build()?,
555        )
556    }
557
558    /// Get or create a sensor with parents at INFO recording level.
559    ///
560    /// # Arguments
561    ///
562    /// - `name` - The name of the sensor
563    /// - `parents` - The parent sensors
564    ///
565    /// # Returns
566    ///
567    /// The sensor that is created
568    ///
569    /// # Errors
570    ///
571    /// - `Error::is_local_illegal_argument_error` if the sensor would be its own
572    ///   ancestor
573    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#sensor")]
574    pub fn sensor_with_parents(&self, name: &str, parents: &[Arc<Sensor>]) -> Result<Arc<Sensor>, Error> {
575        self.sensor_with_options(SensorOptionsBuilder::new().set_name(name).set_parents(parents).build()?)
576    }
577
578    /// Get or create a sensor with the given name, recording level and parents.
579    ///
580    /// # Arguments
581    ///
582    /// - `name` - The name of the sensor.
583    /// - `recording_level` - The recording level.
584    /// - `parents` - The parent sensors.
585    ///
586    /// # Returns
587    ///
588    /// The sensor that is created
589    ///
590    /// # Errors
591    ///
592    /// - `Error::is_local_illegal_argument_error` if the sensor would be its own
593    ///   ancestor
594    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#sensor")]
595    pub fn sensor_with_recording_level_parents(
596        &self,
597        name: &str,
598        recording_level: RecordingLevel,
599        parents: &[Arc<Sensor>],
600    ) -> Result<Arc<Sensor>, Error> {
601        self.sensor_with_options(
602            SensorOptionsBuilder::new()
603                .set_name(name)
604                .set_recording_level(recording_level)
605                .set_parents(parents)
606                .build()?,
607        )
608    }
609
610    /// Get or create a sensor with a config and parents, at INFO recording level.
611    ///
612    /// # Arguments
613    ///
614    /// - `name` - The name of the sensor
615    /// - `config` - A default configuration to use for this sensor for metrics that don't have
616    ///   their own config
617    /// - `parents` - The parent sensors
618    ///
619    /// # Returns
620    ///
621    /// The sensor that is created
622    ///
623    /// # Errors
624    ///
625    /// - `Error::is_local_illegal_argument_error` if the sensor would be its own
626    ///   ancestor
627    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#sensor")]
628    pub fn sensor_with_config_parents(
629        &self,
630        name: &str,
631        config: Option<Arc<MetricConfig>>,
632        parents: &[Arc<Sensor>],
633    ) -> Result<Arc<Sensor>, Error> {
634        self.sensor_with_config_recording_level_parents(name, config, RecordingLevel::Info, parents)
635    }
636
637    /// Get or create a sensor with a config, recording level and parents.
638    ///
639    /// # Arguments
640    ///
641    /// - `name` - The name of the sensor
642    /// - `config` - A default configuration to use for this sensor for metrics that don't have
643    ///   their own config
644    /// - `recording_level` - The recording level.
645    /// - `parents` - The parent sensors
646    ///
647    /// # Returns
648    ///
649    /// The sensor that is created
650    ///
651    /// # Errors
652    ///
653    /// - `Error::is_local_illegal_argument_error` if the sensor would be its own
654    ///   ancestor
655    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#sensor")]
656    pub fn sensor_with_config_recording_level_parents(
657        &self,
658        name: &str,
659        config: Option<Arc<MetricConfig>>,
660        recording_level: RecordingLevel,
661        parents: &[Arc<Sensor>],
662    ) -> Result<Arc<Sensor>, Error> {
663        self.sensor_with_options(
664            SensorOptionsBuilder::new()
665                .set_name(name)
666                .set_config(config)
667                .set_recording_level(recording_level)
668                .set_parents(parents)
669                .build()?,
670        )
671    }
672
673    /// Get or create a sensor with a config, expiration and parents, at INFO
674    /// recording level.
675    ///
676    /// # Arguments
677    ///
678    /// - `name` - The name of the sensor
679    /// - `config` - A default configuration to use for this sensor for metrics that don't have
680    ///   their own config
681    /// - `inactive_sensor_expiration_time_seconds` - If no value is recorded on the Sensor for this
682    ///   duration of time, it is eligible for removal
683    /// - `parents` - The parent sensors
684    ///
685    /// # Returns
686    ///
687    /// The sensor that is created
688    ///
689    /// # Errors
690    ///
691    /// - `Error::is_local_illegal_argument_error` if the sensor would be its own
692    ///   ancestor
693    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#sensor")]
694    pub fn sensor_with_config_inactive_sensor_expiration_time_seconds_parents(
695        &self,
696        name: &str,
697        config: Option<Arc<MetricConfig>>,
698        inactive_sensor_expiration_time_seconds: i64,
699        parents: &[Arc<Sensor>],
700    ) -> Result<Arc<Sensor>, Error> {
701        self.sensor_with_options(
702            SensorOptionsBuilder::new()
703                .set_name(name)
704                .set_config(config)
705                .set_inactive_sensor_expiration_time_seconds(inactive_sensor_expiration_time_seconds)
706                .set_parents(parents)
707                .build()?,
708        )
709    }
710
711    /// Get or create a sensor with a config, expiration, recording level and parents.
712    ///
713    /// # Arguments
714    ///
715    /// - `options` - every parameter, `name` included
716    ///
717    /// # Returns
718    ///
719    /// The sensor
720    ///
721    /// # Errors
722    ///
723    /// - `Error::is_local_illegal_argument_error` if the sensor would be its own
724    ///   ancestor
725    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#sensor")]
726    pub fn sensor_with_options(&self, options: SensorOptions<'_>) -> Result<Arc<Sensor>, Error> {
727        let SensorOptions { name, config, inactive_sensor_expiration_time_seconds, recording_level, parents } = options;
728        // Java's double-checked locking in
729        // `org.apache.kafka.common.metrics.Metrics#sensor`: a lock-free
730        // (here: briefly locked) fast path, then ONE critical section that
731        // re-checks, creates, inserts and registers the children, so two
732        // concurrent callers for the same name always get the same sensor and
733        // the parent's children list gets it exactly once. Java's
734        // `synchronized (this)` maps to holding the `sensors` guard for the
735        // whole section.
736        //
737        // Lock order: `sensors` -> `children_sensors`. No path takes them in
738        // the opposite order (`remove_sensor` releases `sensors` before it
739        // takes `children_sensors`). `Sensor::new` takes no `Metrics` lock (it
740        // only walks the parent chain in `check_forest`), so it is safe to run
741        // under the guard.
742        if let Some(existing) = self.get_sensor(name) {
743            return Ok(existing);
744        }
745        let mut sensors = self.sensors.lock().expect("sensors mutex poisoned");
746        if let Some(existing) = sensors.get(name) {
747            return Ok(Arc::clone(existing));
748        }
749        let sensor_config = config.unwrap_or_else(|| Arc::clone(&self.config));
750        let sensor = Arc::new(Sensor::new(
751            Some(Arc::downgrade(&self.shared)),
752            name,
753            parents.to_vec(),
754            sensor_config,
755            Arc::clone(&self.time),
756            inactive_sensor_expiration_time_seconds,
757            recording_level,
758        )?);
759        sensors.insert(name.to_string(), Arc::clone(&sensor));
760        {
761            let mut children = self.children_sensors.lock().expect("children sensors mutex poisoned");
762            for parent in parents {
763                children.entry(parent.name().to_string()).or_default().push(Arc::clone(&sensor));
764            }
765        }
766        drop(sensors);
767        Ok(sensor)
768    }
769
770    /// Remove a sensor (if it exists), its associated metrics, and its children.
771    ///
772    /// # Arguments
773    ///
774    /// - `name` - The name of the sensor to be removed
775    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#removeSensor")]
776    pub fn remove_sensor(&self, name: &str) {
777        let sensor = self.get_sensor(name);
778        let Some(sensor) = sensor else {
779            return;
780        };
781        let mut child_sensors: Option<Vec<Arc<Sensor>>> = None;
782        {
783            let removed = {
784                let mut sensors = self.sensors.lock().expect("sensors mutex poisoned");
785                // Remove only if the mapping still points to this sensor.
786                if sensors.get(name).map(Arc::as_ptr) == Some(Arc::as_ptr(&sensor)) {
787                    sensors.remove(name)
788                } else {
789                    None
790                }
791            };
792            if removed.is_some() {
793                for metric in sensor.metrics() {
794                    self.shared.remove_metric(metric.metric_name());
795                }
796                let mut children = self.children_sensors.lock().expect("children sensors mutex poisoned");
797                child_sensors = children.remove(name);
798                for parent in sensor.parents() {
799                    if let Some(siblings) = children.get_mut(parent.name()) {
800                        siblings.retain(|s| !Arc::ptr_eq(s, &sensor));
801                    }
802                }
803            }
804        }
805        if let Some(children) = child_sensors {
806            for child in children {
807                self.remove_sensor(child.name());
808            }
809        }
810    }
811
812    // Java's four `addMetric` overloads intersect
813    // on `{metricName}` alone, and no overload takes just a metric name — so
814    // under CLAUDE.md §2's strict reading NOBODY keeps the plain `add_metric`,
815    // and each translated form carries its Rust parameters beyond the metric
816    // name.
817
818    /// Add a metric to monitor an object that implements measurable. This
819    /// metric won't be associated with any sensor. This is a way to expose
820    /// existing values as metrics.
821    ///
822    /// This method is kept for binary compatibility purposes, it has the same
823    /// behaviour as [`Self::add_metric_with_metric_value_provider`].
824    ///
825    /// # Arguments
826    ///
827    /// - `metric_name` - The name of the metric
828    /// - `measurable` - The measurable that will be measured by this metric
829    ///
830    /// # Errors
831    ///
832    /// - `Error::is_local_illegal_argument_error` if a metric with same name already exists.
833    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#addMetric")]
834    pub fn add_metric_with_measurable(
835        &self,
836        metric_name: MetricName,
837        measurable: Box<dyn Measurable>,
838    ) -> Result<(), Error> {
839        self.add_metric_with_config_metric_value_provider(metric_name, None, Box::new(measurable))
840    }
841
842    /// Add a metric to monitor an object that implements `MetricValueProvider`.
843    /// This metric won't be associated with any sensor. This is a way to expose
844    /// existing values as metrics. User is expected to add any additional
845    /// synchronization to update and access metric values, if required.
846    ///
847    /// # Arguments
848    ///
849    /// - `metric_name` - The name of the metric
850    /// - `metric_value_provider` - The metric value provider associated with this metric
851    ///
852    /// # Errors
853    ///
854    /// - `Error::is_local_illegal_argument_error` if a metric with same name already exists.
855    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#addMetric")]
856    pub fn add_metric_with_metric_value_provider(
857        &self,
858        metric_name: MetricName,
859        metric_value_provider: Box<dyn MetricValueProvider>,
860    ) -> Result<(), Error> {
861        self.add_metric_with_config_metric_value_provider(metric_name, None, metric_value_provider)
862    }
863
864    /// Add a metric to monitor an object that implements `MetricValueProvider`.
865    /// This metric won't be associated with any sensor. This is a way to expose
866    /// existing values as metrics. User is expected to add any additional
867    /// synchronization to update and access metric values, if required.
868    ///
869    /// # Arguments
870    ///
871    /// - `metric_name` - The name of the metric
872    /// - `config` - The configuration to use when measuring this measurable, `None`
873    ///   for the registry's default config
874    /// - `provider` - The metric value provider associated with this metric
875    ///
876    /// # Errors
877    ///
878    /// - `Error::is_local_illegal_argument_error` if a metric with same name already exists.
879    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#addMetric")]
880    pub fn add_metric_with_config_metric_value_provider(
881        &self,
882        metric_name: MetricName,
883        config: Option<Arc<MetricConfig>>,
884        provider: Box<dyn MetricValueProvider>,
885    ) -> Result<(), Error> {
886        let metric_config = config.unwrap_or_else(|| Arc::clone(&self.config));
887        let metric = Arc::new(KafkaMetric::new(
888            metric_name.clone(),
889            provider,
890            metric_config,
891            Arc::clone(&self.time),
892        ));
893        if self.shared.register_metric(metric).is_some() {
894            return Err(Error::local_illegal_argument(format!(
895                "A metric named '{metric_name}' already exists, can't register another one."
896            )));
897        }
898        Ok(())
899    }
900
901    /// Create or get an existing metric to monitor an object that implements
902    /// `MetricValueProvider`. This metric won't be associated with any sensor.
903    /// This is a way to expose existing values as metrics. This method takes
904    /// care of synchronisation while updating/accessing metrics by concurrent
905    /// threads.
906    ///
907    /// # Arguments
908    ///
909    /// - `metric_name` - The name of the metric
910    /// - `config` - The configuration to use when measuring this metric, `None`
911    ///   for the registry's default config
912    /// - `provider` - The metric value provider associated with this metric
913    ///
914    /// # Returns
915    ///
916    /// Existing KafkaMetric if already registered or else a newly created one
917    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#addMetricIfAbsent")]
918    pub fn add_metric_if_absent(
919        &self,
920        metric_name: MetricName,
921        config: Option<Arc<MetricConfig>>,
922        provider: Box<dyn MetricValueProvider>,
923    ) -> Arc<KafkaMetric> {
924        let metric_config = config.unwrap_or_else(|| Arc::clone(&self.config));
925        let metric = Arc::new(KafkaMetric::new(metric_name, provider, metric_config, Arc::clone(&self.time)));
926        match self.shared.register_metric(Arc::clone(&metric)) {
927            Some(existing) => existing,
928            None => metric,
929        }
930    }
931
932    /// Remove a metric if it exists and return it. `metric_removal` is invoked
933    /// on each reporter when a metric is removed.
934    ///
935    /// # Arguments
936    ///
937    /// - `metric_name` - The name of the metric
938    ///
939    /// # Returns
940    ///
941    /// the removed `KafkaMetric` or None if no such metric exists
942    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#removeMetric")]
943    pub fn remove_metric(&self, metric_name: &MetricName) -> Option<Arc<KafkaMetric>> {
944        self.shared.remove_metric(metric_name)
945    }
946
947    /// Add a `MetricsReporter`
948    ///
949    /// # Arguments
950    ///
951    /// - `reporter` - the reporter, initialized with every existing metric
952    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#addReporter")]
953    pub fn add_reporter(&self, reporter: Arc<dyn MetricsReporter>) {
954        let existing: Vec<Arc<KafkaMetric>> = self.shared.metrics.current().values().cloned().collect();
955        reporter.init(&existing);
956        self.shared.reporters.lock().expect("reporters mutex poisoned").push(reporter);
957    }
958
959    /// Get all the metrics currently maintained indexed by metricName
960    ///
961    /// # Returns
962    ///
963    /// a live, read-only view of the metrics: it sees every metric registered
964    /// or removed after the call
965    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#metrics")]
966    pub fn metrics(&self) -> MetricsView {
967        MetricsView::of(self.shared.metrics.clone())
968    }
969
970    /// Returns the metric with the given name, if registered.
971    ///
972    /// # Arguments
973    ///
974    /// - `metric_name` - the name of the metric
975    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#metric")]
976    pub fn metric(&self, metric_name: &MetricName) -> Option<Arc<KafkaMetric>> {
977        self.shared.metrics.get(metric_name)
978    }
979
980    /// The children of a parent sensor, keyed by the parent sensor.
981    /// For testing use only (mirrors Java's package-private `childrenSensors()`).
982    #[cfg(test)]
983    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#childrenSensors")]
984    pub(crate) fn children_sensors(&self, parent: &Arc<Sensor>) -> Option<Vec<Arc<Sensor>>> {
985        self.children_sensors
986            .lock()
987            .expect("children sensors mutex poisoned")
988            .get(parent.name())
989            .cloned()
990    }
991
992    // Java's two `metricInstance` overloads intersect on
993    // `{template}`, and neither takes just a template — so nobody keeps the plain
994    // `metric_instance` (CLAUDE.md §2, strict reading).
995
996    /// Returns a `MetricName` built from a template and tag pairs.
997    ///
998    /// # Arguments
999    ///
1000    /// - `template` - the template of the metric name
1001    /// - `key_value` - the tags, as key and value pairs
1002    ///
1003    /// # Errors
1004    ///
1005    /// - `Error::is_local_illegal_argument_error` if `key_value` has an odd length,
1006    ///   or if the tags, with the default config's tags, are not the template's
1007    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#metricInstance")]
1008    pub fn metric_instance_with_key_value(
1009        &self,
1010        template: &MetricNameTemplate,
1011        key_value: &[&str],
1012    ) -> Result<MetricName, Error> {
1013        self.metric_instance_with_tags(template, MetricsUtils::get_tags(key_value)?)
1014    }
1015
1016    /// Returns a `MetricName` built from a template and a tags map.
1017    ///
1018    /// # Arguments
1019    ///
1020    /// - `template` - the template of the metric name
1021    /// - `tags` - the tags
1022    ///
1023    /// # Errors
1024    ///
1025    /// - `Error::is_local_illegal_argument_error` if the tags, with the default
1026    ///   config's tags, are not the template's
1027    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#metricInstance")]
1028    pub fn metric_instance_with_tags(
1029        &self,
1030        template: &MetricNameTemplate,
1031        tags: BTreeMap<String, String>,
1032    ) -> Result<MetricName, Error> {
1033        // Check that the runtime tags + default config tags match the template tags.
1034        let mut runtime_tag_keys: std::collections::HashSet<String> = tags.keys().cloned().collect();
1035        runtime_tag_keys.extend(self.config.tags().keys().cloned());
1036        let template_tag_keys: std::collections::HashSet<String> = template.tags().iter().cloned().collect();
1037        if runtime_tag_keys != template_tag_keys {
1038            return Err(Error::local_illegal_argument(format!(
1039                "For '{}', runtime-defined metric tags do not match the tags in the template. \
1040                 Runtime = {runtime_tag_keys:?} Template = {template_tag_keys:?}",
1041                template.name()
1042            )));
1043        }
1044        Ok(self.metric_name_with_description_tags(template.name(), template.group(), template.description(), tags))
1045    }
1046
1047    /// Iterate over every sensor and remove the ones that have expired.
1048    ///
1049    /// This is the explicit equivalent of Java's `ExpireSensorTask` /
1050    /// `metricsScheduler`; the consumer (or tests) drives it instead of a
1051    /// background thread.
1052    #[cfg(test)]
1053    pub(crate) fn expire_sensors(&self) {
1054        let names: Vec<String> = self.sensors.lock().expect("sensors mutex poisoned").keys().cloned().collect();
1055        for name in names {
1056            let expired = self.get_sensor(&name).map(|s| s.has_expired()).unwrap_or(false);
1057            if expired {
1058                self.remove_sensor(&name);
1059            }
1060        }
1061    }
1062
1063    /// Close this metrics repository.
1064    #[doc(alias = "org.apache.kafka.common.metrics.Metrics#close")]
1065    pub fn close(&self) {
1066        let reporters = self.shared.reporters.lock().expect("reporters mutex poisoned");
1067        for reporter in reporters.iter() {
1068            reporter.close();
1069        }
1070    }
1071}
1072
1073impl Default for Metrics {
1074    fn default() -> Self {
1075        Self::new()
1076    }
1077}
1078
1079#[cfg(test)]
1080mod tests {
1081    use super::*;
1082    use crate::common::MetricValue;
1083    use crate::common::metrics::stats::{CumulativeCount, CumulativeSum, Value};
1084    use crate::common::utils::MockTime;
1085
1086    // Matches MetricsTest.EPS.
1087    const EPS: f64 = 0.000001;
1088
1089    fn metrics_with_mock() -> (Metrics, Arc<MockTime>) {
1090        let time = Arc::new(MockTime::new());
1091        let metrics = Metrics::with_default_config_reporters_time(
1092            Arc::new(MetricConfig::new()),
1093            Vec::new(),
1094            Arc::clone(&time) as Arc<dyn Time>,
1095        );
1096        (metrics, time)
1097    }
1098
1099    fn double_value(metric: &Arc<KafkaMetric>) -> f64 {
1100        match metric.metric_value() {
1101            MetricValue::Double(v) => v,
1102            other => panic!("expected double metric value, got {other:?}"),
1103        }
1104    }
1105
1106    // MetricsTest.testMetricName
1107    #[test]
1108    #[doc(alias = "org.apache.kafka.common.metrics.MetricsTest#testMetricName")]
1109    fn test_metric_name() {
1110        let metrics = Metrics::new();
1111        let n1 = metrics
1112            .metric_name_with_description_key_value(
1113                "name",
1114                "group",
1115                "description",
1116                &["key1", "value1", "key2", "value2"],
1117            )
1118            .unwrap();
1119        let mut tags = BTreeMap::new();
1120        tags.insert("key1".to_string(), "value1".to_string());
1121        tags.insert("key2".to_string(), "value2".to_string());
1122        let n2 = metrics.metric_name_with_description_tags("name", "group", "description", tags);
1123        assert_eq!(n1, n2, "metric names created in two different ways should be equal");
1124
1125        // Creating a MetricName with an odd number of keyValue should fail.
1126        let err = metrics
1127            .metric_name_with_description_key_value("name", "group", "description", &["key1"])
1128            .unwrap_err();
1129        assert!(err.to_string().contains("keyValue needs to be specified in pairs"));
1130    }
1131
1132    // MetricsTest.testMetricInstances
1133    //
1134    // Java's fixture templates come from `SampleMetrics`:
1135    //   METRIC1 / METRIC2 = MetricNameTemplate("name", "group", <desc>, "key1", "key2")
1136    //   METRIC_WITH_INHERITED_TAGS = template over {parent-tag, child-tag}
1137    // They are declared inline here rather than in a shared fixture module,
1138    // since this is the only test that uses them.
1139    //
1140    // The `JmxReporter` Java passes to the `inherited` registry is dropped: JMX
1141    // is out of scope (see the `Metrics` struct docs) and is incidental to the
1142    // assertions, which are all about template/runtime tag reconciliation.
1143    #[test]
1144    #[doc(alias = "org.apache.kafka.common.metrics.MetricsTest#testMetricInstances")]
1145    fn test_metric_instances() {
1146        use indexmap::IndexSet;
1147
1148        let metrics = Metrics::new();
1149
1150        let mut key_tags = IndexSet::new();
1151        key_tags.insert("key1".to_string());
1152        key_tags.insert("key2".to_string());
1153        let metric1 =
1154            MetricNameTemplate::new("name", "group", "The first metric used in testMetricName()", key_tags.clone());
1155        let metric2 = MetricNameTemplate::new("name", "group", "The second metric used in testMetricName()", key_tags);
1156
1157        // The key/value-pair form and the tags-map form must agree.
1158        let n1 = metrics
1159            .metric_instance_with_key_value(&metric1, &["key1", "value1", "key2", "value2"])
1160            .expect("metric_instance from key/value pairs");
1161        let mut tags = BTreeMap::new();
1162        tags.insert("key1".to_string(), "value1".to_string());
1163        tags.insert("key2".to_string(), "value2".to_string());
1164        let n2 = metrics
1165            .metric_instance_with_tags(&metric2, tags)
1166            .expect("metric_instance from tags map");
1167        assert_eq!(n1, n2, "metric names created in two different ways should be equal");
1168
1169        // An odd number of keyValue entries is rejected.
1170        let err = metrics
1171            .metric_instance_with_key_value(&metric1, &["key1"])
1172            .expect_err("odd number of keyValue should fail");
1173        assert!(
1174            err.to_string().contains("keyValue needs to be specified in pairs"),
1175            "unexpected message: {err}"
1176        );
1177
1178        // A registry whose default config carries a parent tag fills that tag in
1179        // for templates that declare it, with the child tag supplied at runtime.
1180        let mut parent_tags = BTreeMap::new();
1181        parent_tags.insert("parent-tag".to_string(), "parent-tag-value".to_string());
1182        let mut child_tags = BTreeMap::new();
1183        child_tags.insert("child-tag".to_string(), "child-tag-value".to_string());
1184
1185        let inherited = Metrics::with_default_config(Arc::new(MetricConfig::new().set_tags(parent_tags.clone())));
1186        let mut inherited_tag_names = IndexSet::new();
1187        inherited_tag_names.insert("parent-tag".to_string());
1188        inherited_tag_names.insert("child-tag".to_string());
1189        let metric_with_inherited_tags =
1190            MetricNameTemplate::new("name", "group", "inherited-tags metric", inherited_tag_names);
1191
1192        let inherited_metric = inherited
1193            .metric_instance_with_tags(&metric_with_inherited_tags, child_tags)
1194            .expect("metric_instance with inherited parent tag");
1195        let filled_out_tags = inherited_metric.tags();
1196        assert_eq!(
1197            Some(&"parent-tag-value".to_string()),
1198            filled_out_tags.get("parent-tag"),
1199            "parent-tag should be set properly"
1200        );
1201        assert_eq!(
1202            Some(&"child-tag-value".to_string()),
1203            filled_out_tags.get("child-tag"),
1204            "child-tag should be set properly"
1205        );
1206
1207        // Supplying only the parent tag at runtime leaves child-tag undefined.
1208        let err = inherited
1209            .metric_instance_with_tags(&metric_with_inherited_tags, parent_tags)
1210            .expect_err("child metric tags not defined at runtime should fail");
1211        assert!(
1212            err.to_string().contains("do not match the tags in the template"),
1213            "unexpected message: {err}"
1214        );
1215
1216        // A runtime tag absent from the template is also rejected.
1217        let mut runtime_tags = BTreeMap::new();
1218        runtime_tags.insert("child-tag".to_string(), "child-tag-value".to_string());
1219        runtime_tags.insert("tag-not-in-template".to_string(), "unexpected-value".to_string());
1220        let err = inherited
1221            .metric_instance_with_tags(&metric_with_inherited_tags, runtime_tags)
1222            .expect_err("runtime tag not in template should fail");
1223        assert!(
1224            err.to_string().contains("do not match the tags in the template"),
1225            "unexpected message: {err}"
1226        );
1227    }
1228
1229    // SensorTest.testIdempotentAdd (Avg/WindowedSum substituted with M1 stats)
1230    #[test]
1231    fn test_idempotent_add() {
1232        let metrics = Metrics::new();
1233        let sensor = metrics.sensor("sensor").unwrap();
1234
1235        assert!(
1236            sensor
1237                .add_with_metric_name(metrics.metric_name("test-metric", "test-group"), Box::new(Value::new()))
1238                .unwrap()
1239        );
1240
1241        // Adding the same metric to the same sensor is a no-op (returns true).
1242        assert!(
1243            sensor
1244                .add_with_metric_name(metrics.metric_name("test-metric", "test-group"), Box::new(Value::new()))
1245                .unwrap()
1246        );
1247
1248        // Adding the same metric to a DIFFERENT sensor is an error.
1249        let another = metrics.sensor("another-sensor").unwrap();
1250        let err = another
1251            .add_with_metric_name(metrics.metric_name("test-metric", "test-group"), Box::new(Value::new()))
1252            .unwrap_err();
1253        assert!(err.to_string().contains("already exists"));
1254
1255        // Adding a different metric with the same name is also a no-op.
1256        assert!(
1257            sensor
1258                .add_with_metric_name(metrics.metric_name("test-metric", "test-group"), Box::new(CumulativeSum::new()))
1259                .unwrap()
1260        );
1261
1262        // Still just the original metric registered on the sensor.
1263        assert_eq!(sensor.metrics().len(), 1);
1264    }
1265
1266    // MetricsTest.testHierarchicalSensors (WindowedCount substituted with CumulativeCount)
1267    #[test]
1268    #[doc(alias = "org.apache.kafka.common.metrics.MetricsTest#testHierarchicalSensors")]
1269    fn test_hierarchical_sensors() {
1270        let metrics = Metrics::new();
1271        let parent1 = metrics.sensor("test.parent1").unwrap();
1272        parent1
1273            .add_with_metric_name(
1274                metrics.metric_name("test.parent1.count", "grp1"),
1275                Box::new(CumulativeCount::new()),
1276            )
1277            .unwrap();
1278        let parent2 = metrics.sensor("test.parent2").unwrap();
1279        parent2
1280            .add_with_metric_name(
1281                metrics.metric_name("test.parent2.count", "grp1"),
1282                Box::new(CumulativeCount::new()),
1283            )
1284            .unwrap();
1285        let child1 = metrics
1286            .sensor_with_parents("test.child1", &[Arc::clone(&parent1), Arc::clone(&parent2)])
1287            .unwrap();
1288        child1
1289            .add_with_metric_name(
1290                metrics.metric_name("test.child1.count", "grp1"),
1291                Box::new(CumulativeCount::new()),
1292            )
1293            .unwrap();
1294        let child2 = metrics.sensor_with_parents("test.child2", &[Arc::clone(&parent1)]).unwrap();
1295        child2
1296            .add_with_metric_name(
1297                metrics.metric_name("test.child2.count", "grp1"),
1298                Box::new(CumulativeCount::new()),
1299            )
1300            .unwrap();
1301        let grandchild = metrics.sensor_with_parents("test.grandchild", &[Arc::clone(&child1)]).unwrap();
1302        grandchild
1303            .add_with_metric_name(
1304                metrics.metric_name("test.grandchild.count", "grp1"),
1305                Box::new(CumulativeCount::new()),
1306            )
1307            .unwrap();
1308
1309        // Increment each sensor one time.
1310        parent1.record().unwrap();
1311        parent2.record().unwrap();
1312        child1.record().unwrap();
1313        child2.record().unwrap();
1314        grandchild.record().unwrap();
1315
1316        let p1 = double_value(&parent1.metrics()[0]);
1317        let p2 = double_value(&parent2.metrics()[0]);
1318        let c1 = double_value(&child1.metrics()[0]);
1319        let c2 = double_value(&child2.metrics()[0]);
1320        let gc = double_value(&grandchild.metrics()[0]);
1321
1322        // Each metric should have a count equal to one + its children's count.
1323        assert_eq!(1.0, gc);
1324        assert_eq!(1.0 + gc, c1);
1325        assert_eq!(1.0, c2);
1326        assert_eq!(1.0 + c1, p2);
1327        assert_eq!(1.0 + c1 + c2, p1);
1328
1329        let p1_children = metrics.children_sensors(&parent1).unwrap();
1330        assert_eq!(p1_children.len(), 2);
1331        assert!(p1_children.iter().any(|s| Arc::ptr_eq(s, &child1)));
1332        assert!(p1_children.iter().any(|s| Arc::ptr_eq(s, &child2)));
1333        let p2_children = metrics.children_sensors(&parent2).unwrap();
1334        assert_eq!(p2_children.len(), 1);
1335        assert!(Arc::ptr_eq(&p2_children[0], &child1));
1336        assert!(metrics.children_sensors(&grandchild).is_none());
1337    }
1338
1339    // MetricsTest.testBadSensorHierarchy
1340    #[test]
1341    #[doc(alias = "org.apache.kafka.common.metrics.MetricsTest#testBadSensorHierarchy")]
1342    fn test_bad_sensor_hierarchy() {
1343        let metrics = Metrics::new();
1344        let p = metrics.sensor("parent").unwrap();
1345        let c1 = metrics.sensor_with_parents("child1", &[Arc::clone(&p)]).unwrap();
1346        let c2 = metrics.sensor_with_parents("child2", &[Arc::clone(&p)]).unwrap();
1347        match metrics.sensor_with_parents("gc", &[c1, c2]) {
1348            Ok(_) => panic!("expected circular dependency error"),
1349            Err(err) => assert!(err.to_string().contains("Circular dependency")),
1350        }
1351    }
1352
1353    // MetricsTest.testRemoveChildSensor
1354    #[test]
1355    #[doc(alias = "org.apache.kafka.common.metrics.MetricsTest#testRemoveChildSensor")]
1356    fn test_remove_child_sensor() {
1357        let metrics = Metrics::new();
1358        let parent = metrics.sensor("parent").unwrap();
1359        let child = metrics.sensor_with_parents("child", &[Arc::clone(&parent)]).unwrap();
1360
1361        let children = metrics.children_sensors(&parent).unwrap();
1362        assert_eq!(children.len(), 1);
1363        assert!(Arc::ptr_eq(&children[0], &child));
1364
1365        metrics.remove_sensor("child");
1366
1367        assert!(metrics.children_sensors(&parent).unwrap().is_empty());
1368    }
1369
1370    // MetricsTest.testRemoveSensor (WindowedCount substituted with CumulativeCount)
1371    #[test]
1372    #[doc(alias = "org.apache.kafka.common.metrics.MetricsTest#testRemoveSensor")]
1373    fn test_remove_sensor() {
1374        let metrics = Metrics::new();
1375        let size = metrics.metrics().len();
1376        let parent1 = metrics.sensor("test.parent1").unwrap();
1377        parent1
1378            .add_with_metric_name(
1379                metrics.metric_name("test.parent1.count", "grp1"),
1380                Box::new(CumulativeCount::new()),
1381            )
1382            .unwrap();
1383        let parent2 = metrics.sensor("test.parent2").unwrap();
1384        parent2
1385            .add_with_metric_name(
1386                metrics.metric_name("test.parent2.count", "grp1"),
1387                Box::new(CumulativeCount::new()),
1388            )
1389            .unwrap();
1390        let child1 = metrics
1391            .sensor_with_parents("test.child1", &[Arc::clone(&parent1), Arc::clone(&parent2)])
1392            .unwrap();
1393        child1
1394            .add_with_metric_name(
1395                metrics.metric_name("test.child1.count", "grp1"),
1396                Box::new(CumulativeCount::new()),
1397            )
1398            .unwrap();
1399        let child2 = metrics.sensor_with_parents("test.child2", &[Arc::clone(&parent2)]).unwrap();
1400        child2
1401            .add_with_metric_name(
1402                metrics.metric_name("test.child2.count", "grp1"),
1403                Box::new(CumulativeCount::new()),
1404            )
1405            .unwrap();
1406        let gchild1 = metrics.sensor_with_parents("test.gchild2", &[Arc::clone(&child2)]).unwrap();
1407        gchild1
1408            .add_with_metric_name(
1409                metrics.metric_name("test.gchild2.count", "grp1"),
1410                Box::new(CumulativeCount::new()),
1411            )
1412            .unwrap();
1413
1414        assert!(metrics.get_sensor("test.parent1").is_some());
1415        metrics.remove_sensor("test.parent1");
1416        assert!(metrics.get_sensor("test.parent1").is_none());
1417        assert!(metrics.metric(&metrics.metric_name("test.parent1.count", "grp1")).is_none());
1418        // child1's only path to removal is via parent1; it is removed too.
1419        assert!(metrics.get_sensor("test.child1").is_none());
1420        assert!(metrics.children_sensors(&parent1).is_none());
1421        assert!(metrics.metric(&metrics.metric_name("test.child1.count", "grp1")).is_none());
1422
1423        assert!(metrics.get_sensor("test.gchild2").is_some());
1424        metrics.remove_sensor("test.gchild2");
1425        assert!(metrics.get_sensor("test.gchild2").is_none());
1426        assert!(metrics.children_sensors(&gchild1).is_none());
1427        assert!(metrics.metric(&metrics.metric_name("test.gchild2.count", "grp1")).is_none());
1428
1429        assert!(metrics.get_sensor("test.child2").is_some());
1430        metrics.remove_sensor("test.child2");
1431        assert!(metrics.get_sensor("test.child2").is_none());
1432        assert!(metrics.children_sensors(&child2).is_none());
1433        assert!(metrics.metric(&metrics.metric_name("test.child2.count", "grp1")).is_none());
1434
1435        assert!(metrics.get_sensor("test.parent2").is_some());
1436        metrics.remove_sensor("test.parent2");
1437        assert!(metrics.get_sensor("test.parent2").is_none());
1438        assert!(metrics.children_sensors(&parent2).is_none());
1439        assert!(metrics.metric(&metrics.metric_name("test.parent2.count", "grp1")).is_none());
1440
1441        assert_eq!(size, metrics.metrics().len());
1442    }
1443
1444    // MetricsTest.testRemoveMetric (WindowedCount substituted with CumulativeCount)
1445    #[test]
1446    #[doc(alias = "org.apache.kafka.common.metrics.MetricsTest#testRemoveMetric")]
1447    fn test_remove_metric() {
1448        let metrics = Metrics::new();
1449        let size = metrics.metrics().len();
1450        metrics
1451            .add_metric_with_measurable(metrics.metric_name("test1", "grp1"), Box::new(CumulativeCount::new()))
1452            .unwrap();
1453        metrics
1454            .add_metric_with_measurable(metrics.metric_name("test2", "grp1"), Box::new(CumulativeCount::new()))
1455            .unwrap();
1456
1457        assert!(metrics.remove_metric(&metrics.metric_name("test1", "grp1")).is_some());
1458        assert!(metrics.metric(&metrics.metric_name("test1", "grp1")).is_none());
1459        assert!(metrics.metric(&metrics.metric_name("test2", "grp1")).is_some());
1460
1461        assert!(metrics.remove_metric(&metrics.metric_name("test2", "grp1")).is_some());
1462        assert!(metrics.metric(&metrics.metric_name("test2", "grp1")).is_none());
1463
1464        assert_eq!(size, metrics.metrics().len());
1465    }
1466
1467    // MetricsTest.testDuplicateMetricName (Avg/CumulativeSum substituted)
1468    #[test]
1469    #[doc(alias = "org.apache.kafka.common.metrics.MetricsTest#testDuplicateMetricName")]
1470    fn test_duplicate_metric_name() {
1471        let metrics = Metrics::new();
1472        metrics
1473            .sensor("test")
1474            .unwrap()
1475            .add_with_metric_name(metrics.metric_name("test", "grp1"), Box::new(Value::new()))
1476            .unwrap();
1477        let err = metrics
1478            .sensor("test2")
1479            .unwrap()
1480            .add_with_metric_name(metrics.metric_name("test", "grp1"), Box::new(CumulativeSum::new()))
1481            .unwrap_err();
1482        assert!(err.to_string().contains("already exists"));
1483    }
1484
1485    // MetricsTest.testRemoveInactiveMetrics (WindowedCount substituted; ExpireSensorTask → expire_sensors)
1486    #[test]
1487    #[doc(alias = "org.apache.kafka.common.metrics.MetricsTest#testRemoveInactiveMetrics")]
1488    fn test_remove_inactive_metrics() {
1489        let (metrics, time) = metrics_with_mock();
1490
1491        let s1 = metrics
1492            .sensor_with_options(
1493                SensorOptionsBuilder::new()
1494                    .set_name("test.s1")
1495                    .set_inactive_sensor_expiration_time_seconds(1)
1496                    .build()
1497                    .unwrap(),
1498            )
1499            .unwrap();
1500        s1.add_with_metric_name(metrics.metric_name("test.s1.count", "grp1"), Box::new(CumulativeCount::new()))
1501            .unwrap();
1502
1503        let s2 = metrics
1504            .sensor_with_options(
1505                SensorOptionsBuilder::new()
1506                    .set_name("test.s2")
1507                    .set_inactive_sensor_expiration_time_seconds(3)
1508                    .build()
1509                    .unwrap(),
1510            )
1511            .unwrap();
1512        s2.add_with_metric_name(metrics.metric_name("test.s2.count", "grp1"), Box::new(CumulativeCount::new()))
1513            .unwrap();
1514
1515        metrics.expire_sensors();
1516        assert!(metrics.get_sensor("test.s1").is_some(), "Sensor test.s1 must be present");
1517        assert!(metrics.metric(&metrics.metric_name("test.s1.count", "grp1")).is_some());
1518        assert!(metrics.get_sensor("test.s2").is_some(), "Sensor test.s2 must be present");
1519        assert!(metrics.metric(&metrics.metric_name("test.s2.count", "grp1")).is_some());
1520
1521        time.sleep(1001);
1522        metrics.expire_sensors();
1523        assert!(
1524            metrics.get_sensor("test.s1").is_none(),
1525            "Sensor test.s1 should have been purged"
1526        );
1527        assert!(metrics.metric(&metrics.metric_name("test.s1.count", "grp1")).is_none());
1528        assert!(metrics.get_sensor("test.s2").is_some(), "Sensor test.s2 must be present");
1529        assert!(metrics.metric(&metrics.metric_name("test.s2.count", "grp1")).is_some());
1530
1531        // Record on s2; resets its clock so it is not purged at the 3s mark.
1532        s2.record().unwrap();
1533        time.sleep(2000);
1534        metrics.expire_sensors();
1535        assert!(metrics.get_sensor("test.s2").is_some(), "Sensor test.s2 must be present");
1536        assert!(metrics.metric(&metrics.metric_name("test.s2.count", "grp1")).is_some());
1537
1538        // After another 1001ms, the metric should be purged.
1539        time.sleep(1001);
1540        metrics.expire_sensors();
1541        assert!(
1542            metrics.get_sensor("test.s2").is_none(),
1543            "Sensor test.s2 should have been purged"
1544        );
1545        assert!(metrics.metric(&metrics.metric_name("test.s2.count", "grp1")).is_none());
1546
1547        // After purging, it should be possible to recreate a metric.
1548        let s1 = metrics
1549            .sensor_with_options(
1550                SensorOptionsBuilder::new()
1551                    .set_name("test.s1")
1552                    .set_inactive_sensor_expiration_time_seconds(1)
1553                    .build()
1554                    .unwrap(),
1555            )
1556            .unwrap();
1557        s1.add_with_metric_name(metrics.metric_name("test.s1.count", "grp1"), Box::new(CumulativeCount::new()))
1558            .unwrap();
1559        assert!(metrics.get_sensor("test.s1").is_some(), "Sensor test.s1 must be present");
1560        assert!(metrics.metric(&metrics.metric_name("test.s1.count", "grp1")).is_some());
1561    }
1562
1563    // MetricsTest.testQuotas
1564    #[test]
1565    #[doc(alias = "org.apache.kafka.common.metrics.MetricsTest#testQuotas")]
1566    fn test_quotas() {
1567        use crate::common::metrics::Quota;
1568        let metrics = Metrics::new();
1569        let sensor = metrics.sensor("test").unwrap();
1570        sensor
1571            .add_with_metric_name_config(
1572                metrics.metric_name("test1.total", "grp1"),
1573                Box::new(CumulativeSum::new()),
1574                Some(Arc::new(MetricConfig::new().set_quota(Quota::upper_bound(5.0)))),
1575            )
1576            .unwrap();
1577        sensor
1578            .add_with_metric_name_config(
1579                metrics.metric_name("test2.total", "grp1"),
1580                Box::new(CumulativeSum::new()),
1581                Some(Arc::new(MetricConfig::new().set_quota(Quota::lower_bound(0.0)))),
1582            )
1583            .unwrap();
1584        sensor.record_with_value(5.0).unwrap();
1585        let error = sensor
1586            .record_with_value(1.0)
1587            .expect_err("Should have gotten a quota violation.");
1588        assert!(error.is_quota_violation_error());
1589        assert_eq!(
1590            error.to_string(),
1591            format!(
1592                "QuotaViolationError: '{}' violated quota. Actual: 6.0, Threshold: 5.0",
1593                metrics.metric_name("test1.total", "grp1")
1594            )
1595        );
1596        assert!(
1597            (6.0 - double_value(&metrics.metric(&metrics.metric_name("test1.total", "grp1")).unwrap())).abs() < EPS
1598        );
1599        sensor.record_with_value(-6.0).unwrap();
1600        let error = sensor
1601            .record_with_value(-1.0)
1602            .expect_err("Should have gotten a quota violation.");
1603        assert!(error.is_quota_violation_error());
1604    }
1605
1606    // The M1-relevant part of MetricsTest.testSimpleStats: the CumulativeSum row.
1607    #[test]
1608    fn test_simple_stats_cumulative() {
1609        let metrics = Metrics::new();
1610        let s2 = metrics.sensor("test.sensor2").unwrap();
1611        s2.add_with_metric_name(metrics.metric_name("s2.total", "grp1"), Box::new(CumulativeSum::new()))
1612            .unwrap();
1613        s2.record_with_value(5.0).unwrap();
1614        assert_eq!(
1615            5.0,
1616            double_value(&metrics.metric(&metrics.metric_name("s2.total", "grp1")).unwrap()),
1617            "s2 reflects the constant value"
1618        );
1619
1620        // CumulativeCount counts invocations regardless of recorded value.
1621        let s = metrics.sensor("test.sensor").unwrap();
1622        s.add_with_metric_name(metrics.metric_name("test.count", "grp1"), Box::new(CumulativeCount::new()))
1623            .unwrap();
1624        for i in 0..10 {
1625            s.record_with_value(i as f64).unwrap();
1626        }
1627        assert_eq!(
1628            10.0,
1629            double_value(&metrics.metric(&metrics.metric_name("test.count", "grp1")).unwrap()),
1630            "Count(0...9) = 10"
1631        );
1632    }
1633
1634    // MetricsTest.testSimpleStats — the Avg/Max/Min/Rate/occurrences/count rows
1635    // (M2). The CumulativeSum (s2.total) and count rows were already covered by
1636    // `test_simple_stats_cumulative` (M1); they are re-asserted here for the full
1637    // method. The Percentiles row is OUT OF SCOPE (consumer doesn't use them; see
1638    // Phase M2 PLAN Skips) and is therefore omitted.
1639    #[test]
1640    #[doc(alias = "org.apache.kafka.common.metrics.MetricsTest#testSimpleStats")]
1641    fn test_simple_stats() {
1642        use crate::common::metrics::TimeUnit;
1643        use crate::common::metrics::stats::{Avg, Max, Meter, Min, WindowedCount};
1644
1645        let (metrics, time) = metrics_with_mock();
1646        let config = metrics.config().clone();
1647
1648        let s = metrics.sensor("test.sensor").unwrap();
1649        s.add_with_metric_name(metrics.metric_name("test.avg", "grp1"), Box::new(Avg::new()))
1650            .unwrap();
1651        s.add_with_metric_name(metrics.metric_name("test.max", "grp1"), Box::new(Max::new()))
1652            .unwrap();
1653        s.add_with_metric_name(metrics.metric_name("test.min", "grp1"), Box::new(Min::new()))
1654            .unwrap();
1655        s.add(Box::new(Meter::with_unit(
1656            TimeUnit::Seconds,
1657            metrics.metric_name("test.rate", "grp1"),
1658            metrics.metric_name("test.total", "grp1"),
1659        )))
1660        .unwrap();
1661        s.add(Box::new(Meter::with_rate_stat(
1662            std::sync::Arc::new(WindowedCount::new().into_sampled_stat()),
1663            metrics.metric_name("test.occurrences", "grp1"),
1664            metrics.metric_name("test.occurrences.total", "grp1"),
1665        )))
1666        .unwrap();
1667        s.add_with_metric_name(metrics.metric_name("test.count", "grp1"), Box::new(WindowedCount::new()))
1668            .unwrap();
1669
1670        let s2 = metrics.sensor("test.sensor2").unwrap();
1671        s2.add_with_metric_name(metrics.metric_name("s2.total", "grp1"), Box::new(CumulativeSum::new()))
1672            .unwrap();
1673        s2.record_with_value(5.0).unwrap();
1674
1675        let mut sum = 0i64;
1676        let count = 10i64;
1677        for i in 0..count {
1678            s.record_with_value(i as f64).unwrap();
1679            sum += i;
1680        }
1681
1682        // prior to any time passing
1683        let mut elapsed_secs = (config.time_window_ms() * (config.samples() as i64 - 1)) as f64 / 1000.0;
1684        assert!(
1685            (count as f64 / elapsed_secs
1686                - double_value(&metrics.metric(&metrics.metric_name("test.occurrences", "grp1")).unwrap()))
1687            .abs()
1688                <= EPS,
1689            "Occurrences(0...{count})"
1690        );
1691
1692        // pretend 2 seconds passed...
1693        let sleep_time_ms = 2i64;
1694        time.sleep(sleep_time_ms * 1000);
1695        elapsed_secs += sleep_time_ms as f64;
1696
1697        assert!(
1698            (5.0 - double_value(&metrics.metric(&metrics.metric_name("s2.total", "grp1")).unwrap())).abs() <= EPS,
1699            "s2 reflects the constant value"
1700        );
1701        assert!(
1702            (4.5 - double_value(&metrics.metric(&metrics.metric_name("test.avg", "grp1")).unwrap())).abs() <= EPS,
1703            "Avg(0...9) = 4.5"
1704        );
1705        assert!(
1706            ((count - 1) as f64 - double_value(&metrics.metric(&metrics.metric_name("test.max", "grp1")).unwrap()))
1707                .abs()
1708                <= EPS,
1709            "Max(0...9) = 9"
1710        );
1711        assert!(
1712            (0.0 - double_value(&metrics.metric(&metrics.metric_name("test.min", "grp1")).unwrap())).abs() <= EPS,
1713            "Min(0...9) = 0"
1714        );
1715        assert!(
1716            (sum as f64 / elapsed_secs
1717                - double_value(&metrics.metric(&metrics.metric_name("test.rate", "grp1")).unwrap()))
1718            .abs()
1719                <= EPS,
1720            "Rate(0...9)"
1721        );
1722        assert!(
1723            (count as f64 / elapsed_secs
1724                - double_value(&metrics.metric(&metrics.metric_name("test.occurrences", "grp1")).unwrap()))
1725            .abs()
1726                <= EPS,
1727            "Occurrences(0...{count})"
1728        );
1729        assert!(
1730            (count as f64 - double_value(&metrics.metric(&metrics.metric_name("test.count", "grp1")).unwrap())).abs()
1731                <= EPS,
1732            "Count(0...9) = 10"
1733        );
1734    }
1735
1736    // MetricsTest.testRateWindowing
1737    #[test]
1738    #[doc(alias = "org.apache.kafka.common.metrics.MetricsTest#testRateWindowing")]
1739    fn test_rate_windowing() {
1740        use crate::common::metrics::TimeUnit;
1741        use crate::common::metrics::internals::MetricsUtils;
1742        use crate::common::metrics::stats::{Meter, WindowedCount};
1743
1744        let time = Arc::new(MockTime::new());
1745        // Use the default time window. Set 3 samples.
1746        let cfg = Arc::new(MetricConfig::new().set_samples(3));
1747        let metrics = Metrics::with_default_config_reporters_time(
1748            Arc::clone(&cfg),
1749            Vec::new(),
1750            Arc::clone(&time) as Arc<dyn Time>,
1751        );
1752
1753        let s = metrics
1754            .sensor_with_options(
1755                SensorOptionsBuilder::new()
1756                    .set_name("test.sensor")
1757                    .set_config(Some(Arc::clone(&cfg)))
1758                    .build()
1759                    .unwrap(),
1760            )
1761            .unwrap();
1762        let rate_metric_name = metrics.metric_name("test.rate", "grp1");
1763        let total_metric_name = metrics.metric_name("test.total", "grp1");
1764        let count_rate_metric_name = metrics.metric_name("test.count.rate", "grp1");
1765        let count_total_metric_name = metrics.metric_name("test.count.total", "grp1");
1766        s.add(Box::new(Meter::with_unit(
1767            TimeUnit::Seconds,
1768            rate_metric_name.clone(),
1769            total_metric_name.clone(),
1770        )))
1771        .unwrap();
1772        s.add(Box::new(Meter::with_rate_stat(
1773            Arc::new(WindowedCount::new().into_sampled_stat()),
1774            count_rate_metric_name.clone(),
1775            count_total_metric_name.clone(),
1776        )))
1777        .unwrap();
1778        let total_metric = metrics.metrics().get(&total_metric_name).unwrap().clone();
1779        let count_total_metric = metrics.metrics().get(&count_total_metric_name).unwrap().clone();
1780
1781        let mut sum = 0i64;
1782        let count = cfg.samples() as i64 - 1;
1783        // Advance 1 window after every record.
1784        for _ in 0..count {
1785            s.record_with_value(100.0).unwrap();
1786            sum += 100;
1787            time.sleep(cfg.time_window_ms());
1788            assert!((sum as f64 - double_value(&total_metric)).abs() <= EPS);
1789        }
1790
1791        // Sleep for half the window.
1792        time.sleep(cfg.time_window_ms() / 2);
1793
1794        // elapsedSecs = sampleWindowSize * (total samples - half of final sample)
1795        let elapsed_secs =
1796            MetricsUtils::convert(cfg.time_window_ms(), TimeUnit::Seconds) * (cfg.samples() as f64 - 0.5);
1797
1798        let rate_metric = metrics.metrics().get(&rate_metric_name).unwrap().clone();
1799        let count_rate_metric = metrics.metrics().get(&count_rate_metric_name).unwrap().clone();
1800        assert!(
1801            (sum as f64 / elapsed_secs - double_value(&rate_metric)).abs() <= EPS,
1802            "Rate(0...2)"
1803        );
1804        assert!(
1805            (count as f64 / elapsed_secs - double_value(&count_rate_metric)).abs() <= EPS,
1806            "Count rate(0...2)"
1807        );
1808        // Java additionally casts `rateMetric.measurable()` back to `Rate` and
1809        // asserts `windowSize == 75s` (== `elapsed_secs` here). Our erased
1810        // `MetricValueProvider` carries no `Any` downcast seam (adding one would
1811        // touch every M1 `Measurable` impl), so that single line is not ported.
1812        // It is fully covered indirectly: the `Rate(0...2)` value assertion above
1813        // pins the window transitively (rate = sampledValue / windowSize, with
1814        // sampledValue == `sum`, so a wrong windowSize fails that assertion), and
1815        // `Rate::window_size` has dedicated bit-for-bit tests in
1816        // `rate.rs::test_rate_with_no_prior_available_samples`.
1817        assert!((sum as f64 - double_value(&total_metric)).abs() <= EPS);
1818        assert!((count as f64 - double_value(&count_total_metric)).abs() <= EPS);
1819
1820        // Verify that rates are expired, but total is cumulative.
1821        time.sleep(cfg.time_window_ms() * cfg.samples() as i64);
1822        assert!((0.0 - double_value(&rate_metric)).abs() <= EPS);
1823        assert!((0.0 - double_value(&count_rate_metric)).abs() <= EPS);
1824        assert!((sum as f64 - double_value(&total_metric)).abs() <= EPS);
1825        assert!((count as f64 - double_value(&count_total_metric)).abs() <= EPS);
1826    }
1827
1828    // The kafka-metrics-count gauge is registered on construction.
1829    #[test]
1830    fn count_metric_registered_on_construction() {
1831        let metrics = Metrics::new();
1832        let count_name = metrics.metric_name_with_description_tags(
1833            "count",
1834            "kafka-metrics-count",
1835            "total number of registered metrics",
1836            BTreeMap::new(),
1837        );
1838        let count_metric = metrics.metric(&count_name).expect("count metric must exist");
1839        // Initially only the count metric itself is registered.
1840        assert_eq!(double_value(&count_metric), 1.0);
1841        // Adding a metric increases the count.
1842        metrics
1843            .add_metric_with_measurable(metrics.metric_name("extra", "grp1"), Box::new(Value::new()))
1844            .unwrap();
1845        assert_eq!(double_value(&count_metric), 2.0);
1846    }
1847
1848    // Audit finding FC-03: the count gauge lives inside the registry it counts,
1849    // so it must not keep that registry alive. Java frees the cycle through the
1850    // garbage collector; Rust must free `MetricsShared` when the last `Metrics`
1851    // is dropped, and the gauge keeps Java's value while the registry is alive.
1852    #[test]
1853    fn dropping_metrics_frees_the_registry_and_its_metrics() {
1854        let metrics = Metrics::new();
1855        let shared = Arc::downgrade(&metrics.shared);
1856        let count_name = metrics.metric_name_with_description_tags(
1857            "count",
1858            "kafka-metrics-count",
1859            "total number of registered metrics",
1860            BTreeMap::new(),
1861        );
1862        let extra_name = metrics.metric_name("extra", "grp1");
1863        metrics
1864            .add_metric_with_measurable(extra_name.clone(), Box::new(Value::new()))
1865            .unwrap();
1866        let extra = Arc::downgrade(&metrics.metric(&extra_name).expect("extra metric must exist"));
1867        let count_metric = metrics.metric(&count_name).expect("count metric must exist");
1868        assert_eq!(
1869            double_value(&count_metric),
1870            2.0,
1871            "Java's gauge reports metrics.size() while alive"
1872        );
1873
1874        metrics.close();
1875        drop(metrics);
1876        assert!(
1877            shared.upgrade().is_none(),
1878            "MetricsShared must be freed once the Metrics is dropped"
1879        );
1880        assert!(
1881            extra.upgrade().is_none(),
1882            "registered metrics must be freed with their registry"
1883        );
1884        // A caller still holding the count metric sees an empty registry.
1885        assert_eq!(double_value(&count_metric), 0.0);
1886    }
1887
1888    // metric_instance validates tag-key match against the template.
1889    #[test]
1890    fn test_metric_instance() {
1891        use crate::common::MetricNameTemplate;
1892        use indexmap::IndexSet;
1893        let metrics = Metrics::new();
1894        let mut tag_names = IndexSet::new();
1895        tag_names.insert("client-id".to_string());
1896        let template = MetricNameTemplate::new("name", "group", "desc", tag_names);
1897
1898        let name = metrics
1899            .metric_instance_with_key_value(&template, &["client-id", "client-1"])
1900            .unwrap();
1901        assert_eq!(name.name(), "name");
1902        assert_eq!(name.tags().get("client-id").map(String::as_str), Some("client-1"));
1903
1904        // Wrong tag keys → error.
1905        let err = metrics.metric_instance_with_key_value(&template, &["wrong", "v"]).unwrap_err();
1906        assert!(err.to_string().contains("do not match the tags in the template"));
1907    }
1908
1909    // ---------------------------------------------------------------------
1910    // Java `default`-style forwarding overloads added to complete the groups
1911    // (DoD #2). Each asserts the added form agrees, by value, with the form it
1912    // forwards to — not merely that it returns.
1913    // ---------------------------------------------------------------------
1914
1915    // Metrics(MetricConfig defaultConfig, Time time)
1916    #[test]
1917    fn test_new_default_config_time_forwards() {
1918        let config = Arc::new(MetricConfig::new().set_samples(7));
1919        let time = Arc::new(MockTime::new());
1920        let metrics = Metrics::with_default_config_time(Arc::clone(&config), Arc::clone(&time) as Arc<dyn Time>);
1921
1922        // The default config is the one we passed, not a fresh one.
1923        assert!(Arc::ptr_eq(metrics.config(), &config));
1924        assert_eq!(metrics.config().samples(), 7);
1925
1926        // ...and the clock is ours, not `SystemTime`: a sensor with a 1s
1927        // inactivity window expires only if the mock clock drives it.
1928        let s = metrics
1929            .sensor_with_config_inactive_sensor_expiration_time_seconds_parents("s", None, 1, &[])
1930            .unwrap();
1931        assert!(!s.has_expired());
1932        time.sleep(2_000);
1933        assert!(s.has_expired());
1934    }
1935
1936    // metricName(String name, String group, String description)
1937    #[test]
1938    fn test_metric_name_description_forwards() {
1939        let mut default_tags = BTreeMap::new();
1940        default_tags.insert("client-id".to_string(), "c1".to_string());
1941        let metrics = Metrics::with_default_config(Arc::new(MetricConfig::new().set_tags(default_tags)));
1942
1943        let added = metrics.metric_name_with_description("n", "g", "the description");
1944        let forwarded = metrics.metric_name_with_description_tags("n", "g", "the description", BTreeMap::new());
1945        assert_eq!(added, forwarded);
1946        // `MetricName` equality deliberately ignores `description`, so assert it
1947        // separately or this test would pass with the description dropped.
1948        assert_eq!(added.description(), "the description");
1949        assert_eq!(added.name(), "n");
1950        assert_eq!(added.group(), "g");
1951        assert_eq!(added.tags().get("client-id").map(String::as_str), Some("c1"));
1952    }
1953
1954    // metricName(String name, String group, Map<String, String> tags)
1955    #[test]
1956    fn test_metric_name_tags_forwards() {
1957        let mut default_tags = BTreeMap::new();
1958        default_tags.insert("client-id".to_string(), "c1".to_string());
1959        let metrics = Metrics::with_default_config(Arc::new(MetricConfig::new().set_tags(default_tags)));
1960
1961        let mut tags = BTreeMap::new();
1962        tags.insert("node-id".to_string(), "n7".to_string());
1963
1964        let added = metrics.metric_name_with_tags("n", "g", tags.clone());
1965        assert_eq!(added, metrics.metric_name_with_description_tags("n", "g", "", tags));
1966        assert_eq!(added.description(), "");
1967        // Supplied tags are merged on top of the configured default tags.
1968        assert_eq!(added.tags().get("client-id").map(String::as_str), Some("c1"));
1969        assert_eq!(added.tags().get("node-id").map(String::as_str), Some("n7"));
1970    }
1971
1972    // The four forwarding `sensor` overloads:
1973    //   :360 (name, recordingLevel, parents...)
1974    //   :372 (name, config, parents...)
1975    //   :386 (name, config, recordingLevel, parents...)
1976    //   :427 (name, config, inactiveSensorExpirationTimeSeconds, parents...)
1977    // Sensors are cached by name, so each form gets its own name and is compared
1978    // against the canonical `sensor_with_options` form by observable state.
1979    #[test]
1980    fn test_sensor_forwarding_overloads() {
1981        let (metrics, time) = metrics_with_mock();
1982        let config = Arc::new(MetricConfig::new().set_samples(9));
1983        let parent = metrics.sensor("parent").unwrap();
1984
1985        // :360 — recording level and parents, default config, no expiry.
1986        let s = metrics
1987            .sensor_with_recording_level_parents("a", RecordingLevel::Debug, std::slice::from_ref(&parent))
1988            .unwrap();
1989        assert!(!s.should_record(), "DEBUG sensor must not record under the default INFO config");
1990        assert_eq!(s.parents().len(), 1);
1991        assert!(Arc::ptr_eq(&s.parents()[0], &parent));
1992
1993        // :372 — config and parents, INFO level (Java's stated default).
1994        let s = metrics
1995            .sensor_with_config_parents("b", Some(Arc::clone(&config)), std::slice::from_ref(&parent))
1996            .unwrap();
1997        assert!(s.should_record());
1998        assert!(Arc::ptr_eq(&s.parents()[0], &parent));
1999        s.add_with_metric_name(metrics.metric_name("b.count", "grp"), Box::new(CumulativeCount::new()))
2000            .unwrap();
2001        assert!(Arc::ptr_eq(
2002            &metrics.metric(&metrics.metric_name("b.count", "grp")).unwrap().config(),
2003            &config
2004        ));
2005
2006        // :386 — config, recording level and parents.
2007        let s = metrics
2008            .sensor_with_config_recording_level_parents(
2009                "c",
2010                Some(Arc::clone(&config)),
2011                RecordingLevel::Debug,
2012                std::slice::from_ref(&parent),
2013            )
2014            .unwrap();
2015        assert!(!s.should_record());
2016        assert!(Arc::ptr_eq(&s.parents()[0], &parent));
2017        s.add_with_metric_name(metrics.metric_name("c.count", "grp"), Box::new(CumulativeCount::new()))
2018            .unwrap();
2019        assert!(Arc::ptr_eq(
2020            &metrics.metric(&metrics.metric_name("c.count", "grp")).unwrap().config(),
2021            &config
2022        ));
2023
2024        // :427 — config, expiry and parents, INFO level.
2025        let s = metrics
2026            .sensor_with_config_inactive_sensor_expiration_time_seconds_parents(
2027                "d",
2028                Some(Arc::clone(&config)),
2029                1,
2030                std::slice::from_ref(&parent),
2031            )
2032            .unwrap();
2033        assert!(s.should_record());
2034        assert!(Arc::ptr_eq(&s.parents()[0], &parent));
2035        assert!(!s.has_expired());
2036        time.sleep(2_000);
2037        assert!(s.has_expired(), "the 1s inactivity window must reach the underlying sensor");
2038
2039        // The canonical `sensor_with_options` form, given the same arguments, agrees.
2040        let canonical = metrics
2041            .sensor_with_options(
2042                SensorOptionsBuilder::new()
2043                    .set_name("e")
2044                    .set_config(Some(Arc::clone(&config)))
2045                    .set_inactive_sensor_expiration_time_seconds(1)
2046                    .set_parents(std::slice::from_ref(&parent))
2047                    .build()
2048                    .unwrap(),
2049            )
2050            .unwrap();
2051        assert!(canonical.should_record());
2052        assert!(Arc::ptr_eq(&canonical.parents()[0], &parent));
2053    }
2054
2055    /// CLAUDE.md §2: the mandatory parameters are validated in
2056    /// [`SensorOptionsBuilder::build`], not named in the constructor, so a
2057    /// builder left untouched panics naming the first one it finds unset.
2058    #[test]
2059    fn sensor_options_builder_build_errors_when_no_mandatory_parameter_is_set() {
2060        let Err(error) = SensorOptionsBuilder::new().build() else {
2061            panic!("build must reject the unset mandatory parameter");
2062        };
2063        assert!(matches!(error, Error::LocalIllegalArgument(_)), "{error:?}");
2064        assert_eq!(
2065            error.message(),
2066            "SensorOptionsBuilder::build: mandatory parameter `name` was not set"
2067        );
2068    }
2069
2070    /// Rust-only regression for the double-checked locking in
2071    /// `Metrics.sensor(...)`: concurrent creators of
2072    /// the same sensor name through one shared `Metrics` must all get the SAME
2073    /// sensor, the registry must hold it, and the parent's children list must
2074    /// hold it exactly once. Before the fix the create-and-insert ran unlocked,
2075    /// so a losing caller kept an orphaned sensor and the parent got a
2076    /// duplicate child.
2077    #[test]
2078    fn test_concurrent_sensor_creation_returns_one_sensor() {
2079        use std::sync::Barrier;
2080        const THREADS: usize = 8;
2081        const ITERATIONS: usize = 200;
2082        for iteration in 0..ITERATIONS {
2083            let metrics = Arc::new(Metrics::new());
2084            let parent = metrics.sensor("parent").unwrap();
2085            let barrier = Arc::new(Barrier::new(THREADS));
2086            let handles: Vec<_> = (0..THREADS)
2087                .map(|_| {
2088                    let metrics = Arc::clone(&metrics);
2089                    let parent = Arc::clone(&parent);
2090                    let barrier = Arc::clone(&barrier);
2091                    std::thread::spawn(move || {
2092                        barrier.wait();
2093                        metrics.sensor_with_parents("child", &[parent])
2094                    })
2095                })
2096                .collect();
2097            let sensors: Vec<Arc<Sensor>> = handles
2098                .into_iter()
2099                .map(|h| h.join().expect("thread panicked").expect("sensor created"))
2100                .collect();
2101            let registered = metrics.get_sensor("child").expect("child registered");
2102            for sensor in &sensors {
2103                assert!(
2104                    Arc::ptr_eq(sensor, &registered),
2105                    "iteration {iteration}: caller got an orphaned sensor"
2106                );
2107            }
2108            let children = metrics.children_sensors(&parent).expect("parent has children");
2109            assert_eq!(1, children.len(), "iteration {iteration}: duplicate child registration");
2110            assert!(Arc::ptr_eq(&children[0], &registered));
2111            // The shared sensor accepts a metric once and only once.
2112            let name = metrics.metric_name("child-count", "group");
2113            assert!(
2114                registered
2115                    .add_with_metric_name(name.clone(), Box::new(CumulativeCount::new()))
2116                    .expect("first add")
2117            );
2118            assert!(metrics.metric(&name).is_some());
2119        }
2120    }
2121
2122    /// A dropped registry frees its shared state. The "count" gauge lives in the
2123    /// map it reads, so before it held the state weakly it kept the map, and
2124    /// every provider and stat in it, allocated for the life of the process.
2125    #[test]
2126    fn test_dropped_registry_is_freed() {
2127        let metrics = Metrics::new();
2128        let sensor = metrics.sensor("s").expect("sensor");
2129        sensor
2130            .add_with_metric_name(metrics.metric_name("s-count", "grp1"), Box::new(CumulativeCount::new()))
2131            .expect("add");
2132        assert_eq!(
2133            Some(MetricValue::Double(2.0)),
2134            metrics
2135                .metric(&metrics.metric_name("count", "kafka-metrics-count"))
2136                .map(|metric| metric.metric_value())
2137        );
2138        let shared = Arc::downgrade(&metrics.shared);
2139        drop(metrics);
2140        assert!(shared.upgrade().is_none(), "the registry's shared state is still referenced");
2141        // A sensor that outlives its registry keeps working on its own.
2142        assert!(
2143            sensor
2144                .add_with_metric_name(MetricName::new("late", "grp1", "", BTreeMap::new()), Box::new(Value::new()))
2145                .expect("add after the registry is gone")
2146        );
2147        sensor.record_with_value(1.0).unwrap();
2148    }
2149
2150    /// A provider capturing an object that holds one of the registry's sensors
2151    /// does not keep the registry alive: the producer's `BufferPool` gauges
2152    /// capture the pool, which holds its `bufferpool-wait-time` sensor. With a
2153    /// strong sensor back-reference this was a cycle through the metrics map.
2154    #[test]
2155    fn test_provider_capturing_a_sensor_does_not_keep_the_registry() {
2156        let metrics = Metrics::new();
2157        let sensor = metrics.sensor("wait-time").expect("sensor");
2158        sensor
2159            .add_with_metric_name(metrics.metric_name("wait-time-total", "grp1"), Box::new(CumulativeSum::new()))
2160            .expect("add");
2161        let sensor_for_gauge = Arc::clone(&sensor);
2162        metrics
2163            .add_metric_with_measurable(
2164                metrics.metric_name("gauge", "grp1"),
2165                Box::new(crate::common::metrics::ClosureMeasurable::new(move |_config, _now| {
2166                    sensor_for_gauge.name().len() as f64
2167                })),
2168            )
2169            .expect("add gauge");
2170        let shared = Arc::downgrade(&metrics.shared);
2171        let weak_sensor = Arc::downgrade(&sensor);
2172        drop(sensor);
2173        drop(metrics);
2174        assert!(shared.upgrade().is_none(), "the registry's shared state is still referenced");
2175        assert!(
2176            weak_sensor.upgrade().is_none(),
2177            "the sensor captured by the gauge is still referenced"
2178        );
2179    }
2180}