confluent_kafka/common/metrics/quota_violation_error.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//! `org.apache.kafka.common.metrics.QuotaViolationException`.
16
17use crate::common::config::config_def::java_double_to_string;
18use crate::common::error::{ErrorCode, ErrorHierarchy, ErrorMessage, ErrorSource};
19use crate::common::{Error, MetricName};
20
21/// Thrown when a sensor records a value that causes a metric to go outside the bounds configured
22/// as its quota
23///
24/// # Translation notes
25///
26/// No protocol code; keeps only the metric name.
27// Hand-written rather than declared with `kafka_error_type!` because it adds subclass state (the
28// metric, the recorded value and the bound) and overrides `toString()` instead of taking the
29// generated `"<TypeName>: <message>"` form.
30//
31// Two deliberate deviations from the Java class:
32//
33// - Java holds the `KafkaMetric` itself and exposes it as `metric()`. This holds the metric's
34// `MetricName`, because `KafkaMetric` owns a `Box<dyn Measurable>` and so is neither `Clone` nor
35// `Debug`, both of which `Error` requires. Nothing is lost for a client: Java's own `toString()`
36// uses only `metric.metricName()`, and the client has no caller of `metric()` (the broker's
37// `ClientQuotaManager` is the only one in the Kafka tree).
38// - Java overrides `fillInStackTrace()` to skip capturing a stack trace, since quota violations
39// are frequent and the trace is never read. Rust errors do not capture one at all, so there is
40// nothing to suppress.
41#[derive(Clone, Debug)]
42#[doc(alias = "org.apache.kafka.common.metrics.QuotaViolationException")]
43pub struct QuotaViolationError {
44 metric_name: MetricName,
45 value: f64,
46 bound: f64,
47 source: Option<Box<Error>>,
48}
49
50impl QuotaViolationError {
51 /// Creates the error.
52 ///
53 /// # Arguments
54 ///
55 /// - `metric_name` - the name of the metric that violated its quota
56 /// - `value` - the value that was recorded
57 /// - `bound` - the quota bound that was crossed
58 #[doc(alias = "org.apache.kafka.common.metrics.QuotaViolationException#QuotaViolationException")]
59 pub fn new(metric_name: MetricName, value: f64, bound: f64) -> Self {
60 Self { metric_name, value, bound, source: None }
61 }
62
63 /// Returns the name of the metric that violated its quota.
64 // stands in for Java's metric(), keeping only the KafkaMetric's name
65 #[doc(alias = "rust-only")]
66 pub fn metric_name(&self) -> &MetricName {
67 &self.metric_name
68 }
69
70 /// Returns the value that was recorded.
71 #[doc(alias = "org.apache.kafka.common.metrics.QuotaViolationException#value")]
72 pub fn value(&self) -> f64 {
73 self.value
74 }
75
76 /// Returns the quota bound that was crossed.
77 #[doc(alias = "org.apache.kafka.common.metrics.QuotaViolationException#bound")]
78 pub fn bound(&self) -> f64 {
79 self.bound
80 }
81
82 /// Returns the underlying cause, if any: Java's `getCause()`.
83 #[doc(alias = "rust-only")]
84 pub fn source(&self) -> Option<&Error> {
85 self.source.as_deref()
86 }
87}
88
89impl ErrorSource for QuotaViolationError {
90 fn source(&self) -> Option<&Error> {
91 self.source.as_deref()
92 }
93}
94
95impl std::error::Error for QuotaViolationError {
96 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
97 self.source.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
98 }
99}
100
101impl ErrorMessage for QuotaViolationError {
102 /// Java's constructor calls the no-argument `super()`, so `getMessage()`
103 /// returns `null`; the empty string is this crate's spelling of that. The
104 /// descriptive text lives in `Display`, exactly as it does in Java's
105 /// `toString()` override.
106 fn message(&self) -> &str {
107 ""
108 }
109}
110
111// No protocol code: `QuotaViolationException` has no entry in `Errors.java`, and
112// walking its superclasses (Java's `Errors.forException`) finds none either, so
113// the trait default of `Errors::UnknownServerError` is the right answer.
114impl ErrorCode for QuotaViolationError {}
115
116impl ErrorHierarchy for QuotaViolationError {
117 fn is_kafka_error(&self) -> bool {
118 true
119 }
120 fn is_quota_violation_error(&self) -> bool {
121 true
122 }
123}
124
125impl std::fmt::Display for QuotaViolationError {
126 /// Java's `toString()` override:
127 /// `getClass().getName() + ": '" + metric.metricName() + "' violated quota.
128 /// Actual: " + value + ", Threshold: " + bound`.
129 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130 write!(
131 f,
132 "QuotaViolationError: '{}' violated quota. Actual: {}, Threshold: {}",
133 self.metric_name,
134 java_double_to_string(self.value),
135 java_double_to_string(self.bound)
136 )
137 }
138}