Skip to main content

confluent_kafka/common/metrics/
metric_config.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//! Configuration values for metrics (`org.apache.kafka.common.metrics.MetricConfig`).
16
17use std::collections::BTreeMap;
18
19use crate::common::metrics::TimeUnit;
20use crate::common::metrics::{Quota, RecordingLevel};
21
22/// Configuration values for metrics.
23#[derive(Clone, Debug)]
24#[doc(alias = "org.apache.kafka.common.metrics.MetricConfig")]
25pub struct MetricConfig {
26    quota: Option<Quota>,
27    samples: i32,
28    event_window: i64,
29    time_window_ms: i64,
30    tags: BTreeMap<String, String>,
31    recording_level: RecordingLevel,
32}
33
34impl Default for MetricConfig {
35    fn default() -> Self {
36        Self {
37            quota: None,
38            samples: MetricConfig::DEFAULT_NUM_SAMPLES,
39            event_window: i64::MAX,
40            time_window_ms: MetricConfig::DEFAULT_TIME_WINDOW_MS,
41            tags: BTreeMap::new(),
42            recording_level: RecordingLevel::Info,
43        }
44    }
45}
46
47impl MetricConfig {
48    /// Default number of samples for a windowed stat.
49    pub const DEFAULT_NUM_SAMPLES: i32 = 2;
50
51    /// 30 seconds, the default time window, in milliseconds.
52    const DEFAULT_TIME_WINDOW_MS: i64 = 30 * 1000;
53
54    /// Create a `MetricConfig` with default values.
55    #[doc(alias = "org.apache.kafka.common.metrics.MetricConfig#MetricConfig")]
56    pub fn new() -> Self {
57        Self::default()
58    }
59
60    /// Returns the configured quota, `None` when there is none.
61    #[doc(alias = "org.apache.kafka.common.metrics.MetricConfig#quota")]
62    pub fn quota(&self) -> Option<&Quota> {
63        self.quota.as_ref()
64    }
65
66    /// Sets the quota.
67    ///
68    /// # Arguments
69    ///
70    /// - `quota` - the quota a sensor using this config enforces
71    ///
72    /// # Returns
73    ///
74    /// This config, for chaining.
75    #[doc(alias = "org.apache.kafka.common.metrics.MetricConfig#quota")]
76    pub fn set_quota(mut self, quota: Quota) -> Self {
77        self.quota = Some(quota);
78        self
79    }
80
81    /// Returns the number of events in an event window.
82    #[doc(alias = "org.apache.kafka.common.metrics.MetricConfig#eventWindow")]
83    pub fn event_window(&self) -> i64 {
84        self.event_window
85    }
86
87    /// Sets the event window.
88    ///
89    /// # Arguments
90    ///
91    /// - `window` - the number of events in a sample window
92    ///
93    /// # Returns
94    ///
95    /// This config, for chaining.
96    #[doc(alias = "org.apache.kafka.common.metrics.MetricConfig#eventWindow")]
97    pub fn set_event_window(mut self, window: i64) -> Self {
98        self.event_window = window;
99        self
100    }
101
102    /// Returns the time window in milliseconds.
103    #[doc(alias = "org.apache.kafka.common.metrics.MetricConfig#timeWindowMs")]
104    pub fn time_window_ms(&self) -> i64 {
105        self.time_window_ms
106    }
107
108    /// Set the time window in milliseconds.
109    pub(crate) fn set_time_window_ms(mut self, window_ms: i64) -> Self {
110        self.time_window_ms = window_ms;
111        self
112    }
113
114    /// Sets the time window, expressed in the given unit.
115    ///
116    /// # Arguments
117    ///
118    /// - `window` - the length of a sample window, in `unit`
119    /// - `unit` - the unit of `window`
120    ///
121    /// # Returns
122    ///
123    /// This config, for chaining.
124    #[doc(alias = "org.apache.kafka.common.metrics.MetricConfig#timeWindow")]
125    pub fn set_time_window(mut self, window: i64, unit: TimeUnit) -> Self {
126        self.time_window_ms = unit.to_millis(window);
127        self
128    }
129
130    /// Returns the default tags for metrics using this config.
131    #[doc(alias = "org.apache.kafka.common.metrics.MetricConfig#tags")]
132    pub fn tags(&self) -> &BTreeMap<String, String> {
133        &self.tags
134    }
135
136    /// Sets the default tags.
137    ///
138    /// # Arguments
139    ///
140    /// - `tags` - the default tags for metrics using this config
141    ///
142    /// # Returns
143    ///
144    /// This config, for chaining.
145    #[doc(alias = "org.apache.kafka.common.metrics.MetricConfig#tags")]
146    pub fn set_tags(mut self, tags: BTreeMap<String, String>) -> Self {
147        self.tags = tags;
148        self
149    }
150
151    /// Returns the number of samples for windowed stats.
152    #[doc(alias = "org.apache.kafka.common.metrics.MetricConfig#samples")]
153    pub fn samples(&self) -> i32 {
154        self.samples
155    }
156
157    /// Sets the number of samples.
158    ///
159    /// # Arguments
160    ///
161    /// - `samples` - the number of samples for windowed stats, at least 1
162    ///
163    /// # Returns
164    ///
165    /// This config, for chaining.
166    ///
167    /// # Panics
168    ///
169    /// If `samples < 1`, with the message of Java's
170    /// `IllegalArgumentException`: a broken argument precondition. The client configs reject `metrics.num.samples`
171    /// below 1 before it reaches here.
172    #[doc(alias = "org.apache.kafka.common.metrics.MetricConfig#samples")]
173    pub fn set_samples(mut self, samples: i32) -> Self {
174        assert!(samples >= 1, "The number of samples must be at least 1.");
175        self.samples = samples;
176        self
177    }
178
179    /// Returns the recording level.
180    #[doc(alias = "org.apache.kafka.common.metrics.MetricConfig#recordLevel")]
181    pub fn record_level(&self) -> RecordingLevel {
182        self.recording_level
183    }
184
185    /// Sets the recording level.
186    ///
187    /// # Arguments
188    ///
189    /// - `recording_level` - the level at which sensors using this config record
190    ///
191    /// # Returns
192    ///
193    /// This config, for chaining.
194    #[doc(alias = "org.apache.kafka.common.metrics.MetricConfig#recordLevel")]
195    pub fn set_record_level(mut self, recording_level: RecordingLevel) -> Self {
196        self.recording_level = recording_level;
197        self
198    }
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204
205    #[test]
206    fn defaults_match_java() {
207        let c = MetricConfig::new();
208        assert_eq!(c.samples(), 2);
209        assert_eq!(c.event_window(), i64::MAX);
210        assert_eq!(c.time_window_ms(), 30_000);
211        assert_eq!(c.record_level(), RecordingLevel::Info);
212        assert!(c.quota().is_none());
213        assert!(c.tags().is_empty());
214    }
215
216    #[test]
217    #[should_panic(expected = "The number of samples must be at least 1.")]
218    fn samples_below_one_panics() {
219        let _ = MetricConfig::new().set_samples(0);
220    }
221
222    #[test]
223    fn samples_at_the_bounds_are_accepted() {
224        assert_eq!(MetricConfig::new().set_samples(1).samples(), 1);
225        assert_eq!(MetricConfig::new().set_samples(i32::MAX).samples(), i32::MAX);
226    }
227}