Skip to main content

confluent_kafka/producer/
callback.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//! Producer callback interface.
16//!
17//! Translated from `org.apache.kafka.clients.producer.Callback`.
18
19use crate::common::Error;
20use crate::producer::RecordMetadata;
21
22/// A callback interface that the user can implement to allow code to execute
23/// when the request is complete. This callback will generally execute in the
24/// background I/O task so it should be fast.
25///
26/// # Translation notes
27///
28/// [`callback::new`](new) builds one from a closure, invoked exactly once.
29#[doc(alias = "org.apache.kafka.clients.producer.Callback")]
30pub trait Callback: Send + Sync {
31    /// A callback method the user can implement to provide asynchronous
32    /// handling of request completion. This method will be called when the
33    /// record sent to the server has been acknowledged. When `error` is not
34    /// `None` in the callback, `metadata` will contain the special -1 value for
35    /// all fields. If the topic partition cannot be chosen, a -1 value will be
36    /// assigned.
37    ///
38    /// # Arguments
39    ///
40    /// - `metadata` - The metadata for the record that was sent (i.e. the
41    ///   partition and offset). An empty metadata with -1 value for all fields
42    ///   will be returned if an error occurred.
43    /// - `error` - The error raised during processing of this record. `None` if
44    ///   no error occurred. Possible errors include:
45    ///
46    ///   Non-retriable errors (fatal, the message will never be sent):
47    ///   `InvalidTopicError`, `OffsetMetadataTooLargeError`,
48    ///   `RecordBatchTooLargeError`, `RecordTooLargeError`,
49    ///   `UnknownServerError`, `UnknownProducerIdError`,
50    ///   `InvalidProducerEpochError`, `AuthenticationError`,
51    ///   `AuthorizationError`.
52    ///
53    ///   Retriable errors (transient, may be covered by increasing
54    ///   `retries`): `CorruptRecordError`, `InvalidMetadataError`,
55    ///   `NotEnoughReplicasAfterAppendError`, `NotEnoughReplicasError`,
56    ///   `OffsetOutOfRangeError`, `TimeoutError`,
57    ///   `UnknownTopicOrPartitionError`, `ProducerBufferExhaustedError`.
58    #[doc(alias = "org.apache.kafka.clients.producer.Callback#onCompletion")]
59    fn on_completion(self: Box<Self>, metadata: Option<&RecordMetadata>, error: Option<&Error>);
60}
61
62impl<F> Callback for F
63where
64    F: FnOnce(Option<&RecordMetadata>, Option<&Error>) + Send + Sync,
65{
66    fn on_completion(self: Box<Self>, metadata: Option<&RecordMetadata>, error: Option<&Error>) {
67        (*self)(metadata, error)
68    }
69}
70
71/// Returns a [`Callback`] that calls `function`, standing in for a Java lambda
72/// implementing `Callback`: `function` is
73/// [`on_completion`](Callback::on_completion), and every other method keeps
74/// its default. A method Java adds later as an overload of `onCompletion` gets
75/// its own factory, `with_<parameter>`, taking a function of that overload's
76/// shape. The closure's parameter types are inferred:
77///
78/// ```
79/// use confluent_kafka::producer::{callback, Callback};
80///
81/// let callback: Box<dyn Callback> = Box::new(callback::new(|metadata, error| {
82///     if let Some(error) = error {
83///         eprintln!("send failed: {error}");
84///     } else if let Some(metadata) = metadata {
85///         println!("sent at offset {}", metadata.offset());
86///     }
87/// }));
88/// # callback.on_completion(None, None);
89/// ```
90///
91/// Every `FnOnce(Option<&RecordMetadata>, Option<&Error>) + Send + Sync` also
92/// implements `Callback` directly, but then the closure's parameter types must
93/// be written out: Rust infers a closure's signature only from an `Fn` bound,
94/// not from a trait it gets through a blanket impl.
95///
96/// # Arguments
97///
98/// - `function` - the body of [`on_completion`](Callback::on_completion),
99///   called once with the record's metadata and error.
100// stands in for a Java lambda implementing `Callback` (CLAUDE.md ยง3)
101#[doc(alias = "rust-only")]
102pub fn new<F>(function: F) -> impl Callback
103where
104    F: FnOnce(Option<&RecordMetadata>, Option<&Error>) + Send + Sync,
105{
106    struct FunctionCallback<F>(F);
107
108    impl<F> Callback for FunctionCallback<F>
109    where
110        F: FnOnce(Option<&RecordMetadata>, Option<&Error>) + Send + Sync,
111    {
112        fn on_completion(self: Box<Self>, metadata: Option<&RecordMetadata>, error: Option<&Error>) {
113            (self.0)(metadata, error)
114        }
115    }
116
117    FunctionCallback(function)
118}
119
120#[cfg(test)]
121mod tests {
122    use std::sync::{Arc, Mutex};
123
124    use super::*;
125    use crate::common::TopicPartition;
126
127    #[test]
128    fn new_calls_the_function_with_the_completion_arguments() {
129        let seen: Arc<Mutex<Option<(i64, bool)>>> = Arc::new(Mutex::new(None));
130        let sink = Arc::clone(&seen);
131        let callback: Box<dyn Callback> = Box::new(new(move |metadata, error| {
132            *sink.lock().unwrap() = Some((metadata.map_or(-2, RecordMetadata::offset), error.is_some()));
133        }));
134        let metadata = RecordMetadata::new(TopicPartition::new("t", 0), 7, 0, 0, 0, 0);
135        callback.on_completion(Some(&metadata), None);
136        assert_eq!(*seen.lock().unwrap(), Some((7, false)));
137    }
138
139    #[test]
140    fn new_passes_the_error() {
141        let seen = Arc::new(Mutex::new(None));
142        let sink = Arc::clone(&seen);
143        let callback: Box<dyn Callback> = Box::new(new(move |metadata, error: Option<&Error>| {
144            *sink.lock().unwrap() = Some((metadata.is_some(), error.map(ToString::to_string)));
145        }));
146        callback.on_completion(None, Some(&Error::local_illegal_state("boom")));
147        let (has_metadata, error) = seen.lock().unwrap().take().unwrap();
148        assert!(!has_metadata);
149        assert!(error.unwrap().contains("boom"));
150    }
151}