1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
use rdsys::rd_kafka_vtype_t::*;
use rdsys::types::*;
use rdsys;
use client::{Client, Context};
use config::{ClientConfig, FromClientConfig, FromClientConfigAndContext};
use error::{KafkaError, KafkaResult, IsError};
use message::{BorrowedMessage, ToBytes};
use std::ffi::CString;
use std::os::raw::c_void;
use std::mem;
use std::ptr;
use std::sync::Arc;
pub use message::DeliveryResult;
pub trait ProducerContext: Context {
type DeliveryContext: Send + Sync;
fn delivery(&self, delivery_result: &DeliveryResult, delivery_context: Self::DeliveryContext);
}
#[derive(Clone)]
pub struct EmptyProducerContext;
impl Context for EmptyProducerContext {}
impl ProducerContext for EmptyProducerContext {
type DeliveryContext = ();
fn delivery(&self, _: &DeliveryResult, _: Self::DeliveryContext) {}
}
unsafe extern "C" fn delivery_cb<C: ProducerContext>(
_client: *mut RDKafka,
msg: *const RDKafkaMessage,
_opaque: *mut c_void,
) {
let producer_context = Box::from_raw(_opaque as *mut C);
let delivery_context = Box::from_raw((*msg)._private as *mut C::DeliveryContext);
let owner = 42u8;
let delivery_result = BorrowedMessage::from_dr_callback(msg as *mut RDKafkaMessage, &owner);
trace!("Delivery event received: {:?}", delivery_result);
(*producer_context).delivery(&delivery_result, (*delivery_context));
mem::forget(producer_context);
match delivery_result {
Ok(message) => mem::forget(message),
Err((_, message)) => mem::forget(message),
}
}
impl FromClientConfig for BaseProducer<EmptyProducerContext> {
fn from_config(config: &ClientConfig) -> KafkaResult<BaseProducer<EmptyProducerContext>> {
BaseProducer::from_config_and_context(config, EmptyProducerContext)
}
}
impl<C: ProducerContext> FromClientConfigAndContext<C> for BaseProducer<C> {
fn from_config_and_context(config: &ClientConfig, context: C) -> KafkaResult<BaseProducer<C>> {
let native_config = config.create_native_config()?;
unsafe { rdsys::rd_kafka_conf_set_dr_msg_cb(native_config.ptr(), Some(delivery_cb::<C>)) };
let client = Client::new(config, native_config, RDKafkaType::RD_KAFKA_PRODUCER, context)?;
Ok(BaseProducer::from_client(client))
}
}
pub struct BaseProducer<C: ProducerContext> {
client_arc: Arc<Client<C>>,
}
impl<C: ProducerContext> BaseProducer<C> {
fn from_client(client: Client<C>) -> BaseProducer<C> {
BaseProducer { client_arc: Arc::new(client) }
}
pub fn poll(&self, timeout_ms: i32) -> i32 {
unsafe { rdsys::rd_kafka_poll(self.native_ptr(), timeout_ms) }
}
fn native_ptr(&self) -> *mut RDKafka {
self.client_arc.native_ptr()
}
pub fn send_copy<P, K>(
&self,
topic_name: &str,
partition: Option<i32>,
payload: Option<&P>,
key: Option<&K>,
delivery_context: Option<Box<C::DeliveryContext>>,
timestamp: Option<i64>,
) -> KafkaResult<()>
where K: ToBytes + ?Sized,
P: ToBytes + ?Sized {
let (payload_ptr, payload_len) = match payload.map(P::to_bytes) {
None => (ptr::null_mut(), 0),
Some(p) => (p.as_ptr() as *mut c_void, p.len()),
};
let (key_ptr, key_len) = match key.map(K::to_bytes) {
None => (ptr::null_mut(), 0),
Some(k) => (k.as_ptr() as *mut c_void, k.len()),
};
let delivery_context_ptr = match delivery_context {
Some(context) => Box::into_raw(context) as *mut c_void,
None => ptr::null_mut(),
};
let topic_name_c = CString::new(topic_name.to_owned())?;
let produce_error = unsafe {
rdsys::rd_kafka_producev(
self.native_ptr(),
RD_KAFKA_VTYPE_TOPIC, topic_name_c.as_ptr(),
RD_KAFKA_VTYPE_PARTITION, partition.unwrap_or(-1),
RD_KAFKA_VTYPE_MSGFLAGS, rdsys::RD_KAFKA_MSG_F_COPY as i32,
RD_KAFKA_VTYPE_VALUE, payload_ptr, payload_len,
RD_KAFKA_VTYPE_KEY, key_ptr, key_len,
RD_KAFKA_VTYPE_OPAQUE, delivery_context_ptr,
RD_KAFKA_VTYPE_TIMESTAMP, timestamp.unwrap_or(0),
RD_KAFKA_VTYPE_END
)
};
if produce_error.is_error() {
if !delivery_context_ptr.is_null() {
unsafe { Box::from_raw(delivery_context_ptr as *mut C::DeliveryContext) };
}
Err(KafkaError::MessageProduction(produce_error.into()))
} else {
Ok(())
}
}
pub fn flush(&self, timeout_ms: i32) {
unsafe { rdsys::rd_kafka_flush(self.native_ptr(), timeout_ms) };
}
pub fn in_flight_count(&self) -> i32 {
unsafe { rdsys::rd_kafka_outq_len(self.native_ptr()) }
}
}
impl<C: ProducerContext> Clone for BaseProducer<C> {
fn clone(&self) -> BaseProducer<C> {
BaseProducer { client_arc: self.client_arc.clone() }
}
}
#[cfg(test)]
mod tests {
use super::*;
use config::ClientConfig;
#[test]
fn test_base_producer_clone() {
let producer = ClientConfig::new().create::<BaseProducer<_>>().unwrap();
let _producer_clone = producer.clone();
}
}