confluent_kafka/common/local_callback_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//! The error a callback implemented in another language reports when it
16//! raised one of that language's own errors.
17//!
18//! No Java counterpart (DoD #7). A Java listener's `Throwable` reaches
19//! `ConsumerUtils.maybeWrapAsKafkaException` as itself; an error raised by a
20//! Python (or any foreign) callback cannot cross the FFI boundary as a Rust
21//! value. This class stands in for it: it carries the foreign error's text,
22//! for the client's own logs, and an opaque pointer the binding uses to find
23//! the original again when the error comes back out of the client.
24
25use std::ffi::c_void;
26use std::fmt;
27use std::sync::Arc;
28
29/// The function a binding gives to release its opaque pointer: called once,
30/// with the pointer, when the last copy of the error holding it drops.
31pub(crate) type ReleaseFn = unsafe extern "C" fn(opaque: *mut c_void);
32
33/// An opaque pointer the error owns: [`release`](Self::release) runs once,
34/// when the last copy of the error drops, on whatever task or thread drops it.
35#[derive(Debug)]
36struct OwnedOpaque {
37 ptr: *mut c_void,
38 release: ReleaseFn,
39}
40
41impl Drop for OwnedOpaque {
42 fn drop(&mut self) {
43 // SAFETY: `release` and `ptr` were handed over together by the binding that built the
44 // error (`LocalCallbackError::with_release`, whose contract is the one
45 // `kafka_common_Error_local_callback` documents): `release` may be called once, with
46 // `ptr`, on any thread. This is that one call: `OwnedOpaque` is never cloned (copies of
47 // the error share it through the `Arc`), so its `Drop` runs exactly once, when the last
48 // copy goes.
49 unsafe { (self.release)(self.ptr) }
50 }
51}
52
53// SAFETY: Rust never reads through `ptr`; it only copies the address out and, once, hands it
54// back to `release`. The binding that gives a release function promises it may run on any thread
55// (the contract of `kafka_common_Error_local_callback`), so moving the owner — and with it the
56// one call to `release` — to another thread is sound.
57unsafe impl Send for OwnedOpaque {}
58// SAFETY: a shared `&OwnedOpaque` only reads the address (`opaque()`), never through it, and the
59// call to `release` needs the owner by value (its `Drop`), so sharing it across threads shares no
60// memory behind the pointer.
61unsafe impl Sync for OwnedOpaque {}
62
63/// The binding's opaque pointer: borrowed (never dereferenced, freed or
64/// retained by Rust, the binding keeping what it points at alive) or owned,
65/// released once through the binding's function when the last copy of the
66/// error drops.
67#[derive(Clone, Debug)]
68enum Opaque {
69 Borrowed(*mut c_void),
70 Owned(Arc<OwnedOpaque>),
71}
72
73// SAFETY: a borrowed pointer is an identifier only — Rust never reads through it, so copying it
74// across tasks shares no memory. An owned one is `Arc<OwnedOpaque>`, `Send` because
75// `OwnedOpaque` is `Send + Sync` (above).
76unsafe impl Send for Opaque {}
77// SAFETY: as for `Send`: `&Opaque` only reads the address, and `OwnedOpaque` is `Sync`.
78unsafe impl Sync for Opaque {}
79
80impl Opaque {
81 fn ptr(&self) -> *mut c_void {
82 match self {
83 Opaque::Borrowed(ptr) => *ptr,
84 Opaque::Owned(owned) => owned.ptr,
85 }
86 }
87}
88
89/// An error raised by a callback written in another language.
90///
91/// Like Java's `java.lang` runtime exceptions it sits beside `KafkaException`,
92/// not below it, so [`Error::is_kafka_error`](crate::common::Error::is_kafka_error)
93/// is `false` and the client wraps it exactly as Java wraps a listener's
94/// foreign `Throwable`: the rebalance-listener path builds
95/// `KafkaException("User rebalance callback throws an error")` with this error
96/// as its [`source`](crate::common::Error::source), Java's `getCause()`.
97///
98/// The [`opaque`](Self::opaque) pointer lets the binding swap the original
99/// error back in: on receiving an error whose cause chain holds a
100/// `LocalCallbackError`, it reads the pointer back. Rust never dereferences
101/// the pointer. Built with [`new`](Self::new) it does not own it either: the
102/// binding keeps the object alive for as long as it may be read. Built by the
103/// FFI with a release function, the error owns it: every clone shares it, and
104/// the release function runs once, when the last copy drops, on whatever task
105/// or thread drops it.
106// a binding's foreign callback error, no Java class (DoD #7)
107#[doc(alias = "rust-only")]
108#[derive(Clone, Debug)]
109pub struct LocalCallbackError {
110 message: String,
111 opaque: Opaque,
112}
113
114impl LocalCallbackError {
115 /// Creates the error with the foreign error's text and the binding's
116 /// opaque pointer to it, which the error does not own.
117 ///
118 /// # Arguments
119 ///
120 /// - `message` - the foreign error's text, for the client's logs
121 /// - `opaque` - the binding's pointer to the foreign error, never dereferenced by Rust
122 pub fn new(message: impl Into<String>, opaque: *mut c_void) -> Self {
123 Self { message: message.into(), opaque: Opaque::Borrowed(opaque) }
124 }
125
126 /// Create the error owning `opaque`: `release(opaque)` runs exactly once,
127 /// when the last copy of the error (clones and the errors whose cause it
128 /// is included) drops, on whatever task or thread drops it.
129 ///
130 /// # Safety
131 ///
132 /// `release` must be sound to call once with `opaque`, from any thread, at
133 /// any time until the process exits.
134 pub(crate) unsafe fn with_release(message: impl Into<String>, opaque: *mut c_void, release: ReleaseFn) -> Self {
135 Self {
136 message: message.into(),
137 opaque: Opaque::Owned(Arc::new(OwnedOpaque { ptr: opaque, release })),
138 }
139 }
140
141 /// Returns the foreign error's text, as the binding reported it.
142 pub fn message(&self) -> &str {
143 &self.message
144 }
145
146 /// Returns the binding's opaque pointer to the foreign error, exactly as given.
147 /// An owned pointer stays valid while any copy of the error lives.
148 pub fn opaque(&self) -> *mut c_void {
149 self.opaque.ptr()
150 }
151}
152
153// No cause: the foreign error's own cause chain stays in its language.
154impl crate::common::error::ErrorSource for LocalCallbackError {}
155
156impl std::error::Error for LocalCallbackError {}
157
158// No protocol code: raised only on the client side, never by a broker, so the
159// trait default (`Errors::UnknownServerError`) is the right answer.
160impl crate::common::error::ErrorCode for LocalCallbackError {}
161
162impl crate::common::error::ErrorMessage for LocalCallbackError {
163 fn message(&self) -> &str {
164 &self.message
165 }
166}
167
168impl fmt::Display for LocalCallbackError {
169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170 write!(f, "LocalCallbackError: {}", self.message)
171 }
172}
173
174#[cfg(test)]
175mod tests {
176 use std::ptr;
177 use std::sync::Mutex;
178 use std::sync::atomic::{AtomicUsize, Ordering};
179 use std::thread::{self, ThreadId};
180
181 use super::*;
182 use crate::common::Error;
183
184 /// What a test's release function points at: how many times it ran, and
185 /// on which thread it last did.
186 #[derive(Default)]
187 struct ReleaseProbe {
188 count: AtomicUsize,
189 thread: Mutex<Option<ThreadId>>,
190 }
191
192 impl ReleaseProbe {
193 fn opaque(&self) -> *mut c_void {
194 (self as *const ReleaseProbe).cast_mut().cast::<c_void>()
195 }
196
197 fn count(&self) -> usize {
198 self.count.load(Ordering::SeqCst)
199 }
200 }
201
202 /// Counts the call in the `ReleaseProbe` `opaque` points at.
203 ///
204 /// # Safety
205 ///
206 /// `opaque` must point at a live `ReleaseProbe`.
207 unsafe extern "C" fn count_release(opaque: *mut c_void) {
208 // SAFETY: Per this function's `# Safety`, `opaque` points at a live `ReleaseProbe`; it is
209 // only read through a shared reference, whose fields are interior-mutable.
210 let probe = unsafe { &*opaque.cast::<ReleaseProbe>() };
211 *probe.thread.lock().unwrap() = Some(thread::current().id());
212 probe.count.fetch_add(1, Ordering::SeqCst);
213 }
214
215 /// Clones share the owned pointer, so its release runs once, when the
216 /// last copy drops — the copy kept as the cause of a wrapping error
217 /// included.
218 #[test]
219 fn owned_opaque_is_released_once_after_the_last_copy() {
220 let probe = ReleaseProbe::default();
221 // SAFETY: Test code: `count_release` only touches the probe, which outlives every copy
222 // of the error (all are dropped before the asserts below and before `probe` goes).
223 let err = unsafe { Error::local_callback_with_release("ValueError: bad", probe.opaque(), count_release) };
224 let copy = err.clone();
225 let wrapped = crate::consumer::internals::ConsumerUtils::maybe_wrap_as_kafka_error_with_msg(
226 err,
227 "User rebalance callback throws an error",
228 );
229 let wrapped_copy = wrapped.clone();
230 match wrapped.source() {
231 Some(Error::LocalCallback(e)) => assert_eq!(e.opaque(), probe.opaque()),
232 other => panic!("unexpected cause {other:?}"),
233 }
234 drop(wrapped);
235 assert_eq!(probe.count(), 0);
236 drop(copy);
237 assert_eq!(probe.count(), 0);
238 drop(wrapped_copy);
239 assert_eq!(probe.count(), 1);
240 }
241
242 /// The release runs on whatever thread drops the last copy.
243 #[test]
244 fn owned_opaque_is_released_on_the_dropping_thread() {
245 let probe = ReleaseProbe::default();
246 // SAFETY: Test code: `count_release` only touches the probe, which outlives the error:
247 // the thread that drops it is joined before the asserts and before `probe` goes.
248 let err = unsafe { LocalCallbackError::with_release("boom", probe.opaque(), count_release) };
249 let dropper = thread::spawn(move || {
250 drop(err);
251 thread::current().id()
252 });
253 let dropper_id = dropper.join().unwrap();
254 assert_ne!(dropper_id, thread::current().id());
255 assert_eq!(probe.count(), 1);
256 assert_eq!(*probe.thread.lock().unwrap(), Some(dropper_id));
257 }
258
259 /// The unowned error (`new`, `Error::local_callback`) releases nothing:
260 /// dropping it leaves the pointee alone.
261 #[test]
262 fn borrowed_opaque_is_never_released() {
263 let probe = ReleaseProbe::default();
264 let err = Error::local_callback("boom", probe.opaque());
265 let copy = err.clone();
266 drop(err);
267 drop(copy);
268 drop(LocalCallbackError::new("boom", probe.opaque()));
269 assert_eq!(probe.count(), 0);
270 assert!(probe.thread.lock().unwrap().is_none());
271 }
272
273 #[test]
274 fn carries_message_and_opaque_unchanged() {
275 let mut target = 7u8;
276 let opaque = (&mut target as *mut u8).cast::<c_void>();
277 let err = LocalCallbackError::new("boom", opaque);
278 assert_eq!(err.message(), "boom");
279 assert_eq!(err.opaque(), opaque);
280 assert_eq!(err.clone().opaque(), opaque);
281 assert_eq!(err.to_string(), "LocalCallbackError: boom");
282 assert!(LocalCallbackError::new("null", ptr::null_mut()).opaque().is_null());
283 }
284
285 /// Outside the Kafka hierarchy, so the listener path wraps it with Java's
286 /// message and keeps it as the cause.
287 #[test]
288 fn listener_wrap_keeps_it_as_the_source() {
289 let mut target = 0u8;
290 let opaque = (&mut target as *mut u8).cast::<c_void>();
291 let err = Error::local_callback("ValueError: bad", opaque);
292 assert!(err.is_local_callback_error());
293 assert!(!err.is_kafka_error());
294 assert!(!err.is_api_error());
295 assert!(!err.is_retriable_error());
296 assert_eq!(err.message(), "ValueError: bad");
297
298 let wrapped = crate::consumer::internals::ConsumerUtils::maybe_wrap_as_kafka_error_with_msg(
299 err,
300 "User rebalance callback throws an error",
301 );
302 assert!(wrapped.is_kafka_error());
303 assert!(!wrapped.is_local_callback_error());
304 assert_eq!(wrapped.message(), "User rebalance callback throws an error");
305 let source = wrapped.source().expect("the foreign error is the cause");
306 assert!(source.is_local_callback_error());
307 match source {
308 Error::LocalCallback(e) => assert_eq!(e.opaque(), opaque),
309 other => panic!("unexpected cause {other:?}"),
310 }
311 }
312}