Skip to main content

confluent_kafka/common/
metric.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 metric tracked for monitoring purposes (`org.apache.kafka.common.Metric`).
16
17use crate::common::MetricName;
18
19/// The type-erased value of a metric.
20///
21/// Java's `Metric.metricValue()` returns `Object`, which may be a measurable
22/// `Double` or a non-measurable gauge value of any type. This enum captures the
23/// value kinds the consumer metrics produce.
24#[derive(Clone, Debug, PartialEq)]
25#[non_exhaustive]
26// the value `Metric::metric_value` returns, replacing Java's `Object`
27#[doc(alias = "rust-only")]
28pub enum MetricValue {
29    /// A measurable (or `Double`-valued gauge) reading.
30    Double(f64),
31    /// A string-valued gauge reading.
32    String(String),
33    /// A long-valued gauge reading.
34    Long(i64),
35    /// An integer-valued gauge reading.
36    Int(i32),
37}
38
39impl MetricValue {
40    /// Returns the value as an `f64` if it is a [`MetricValue::Double`].
41    pub fn as_double(&self) -> Option<f64> {
42        match self {
43            MetricValue::Double(v) => Some(*v),
44            _ => None,
45        }
46    }
47
48    /// Returns the value as a `&str` if it is a [`MetricValue::String`].
49    pub fn as_string(&self) -> Option<&str> {
50        match self {
51            MetricValue::String(v) => Some(v),
52            _ => None,
53        }
54    }
55
56    /// Returns the value as an `i64` if it is a [`MetricValue::Long`].
57    pub fn as_long(&self) -> Option<i64> {
58        match self {
59            MetricValue::Long(v) => Some(*v),
60            _ => None,
61        }
62    }
63
64    /// Returns the value as an `i32` if it is a [`MetricValue::Int`].
65    pub fn as_int(&self) -> Option<i32> {
66        match self {
67            MetricValue::Int(v) => Some(*v),
68            _ => None,
69        }
70    }
71}
72
73/// A metric tracked for monitoring purposes.
74#[doc(alias = "org.apache.kafka.common.Metric")]
75pub trait Metric {
76    /// Returns a name for this metric.
77    #[doc(alias = "org.apache.kafka.common.Metric#metricName")]
78    fn metric_name(&self) -> &MetricName;
79
80    /// Returns the value of the metric, which may be measurable or a
81    /// non-measurable gauge.
82    #[doc(alias = "org.apache.kafka.common.Metric#metricValue")]
83    fn metric_value(&self) -> MetricValue;
84}