forked from vectordotdev/vector
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpulsar.rs
More file actions
448 lines (388 loc) · 13.6 KB
/
Copy pathpulsar.rs
File metadata and controls
448 lines (388 loc) · 13.6 KB
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use crate::{
buffers::Acker,
config::{log_schema, DataType, GenerateConfig, SinkConfig, SinkContext, SinkDescription},
event::Event,
internal_events::PulsarEncodeEventFailed,
sinks::util::encoding::{EncodingConfig, EncodingConfiguration},
};
use futures::{future::BoxFuture, ready, stream::FuturesUnordered, FutureExt, Sink, Stream};
use pulsar::{
message::proto, producer::SendFuture, proto::CommandSendReceipt, Authentication,
Error as PulsarError, Producer, Pulsar, TokioExecutor,
};
use serde::{Deserialize, Serialize};
use snafu::{ResultExt, Snafu};
use std::{
collections::HashSet,
pin::Pin,
task::{Context, Poll},
};
#[derive(Debug, Snafu)]
enum BuildError {
#[snafu(display("creating pulsar producer failed: {}", source))]
CreatePulsarSink { source: PulsarError },
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct PulsarSinkConfig {
// Deprecated name
#[serde(alias = "address")]
endpoint: String,
topic: String,
encoding: EncodingConfig<Encoding>,
auth: Option<AuthConfig>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct AuthConfig {
name: String, // "token"
token: String, // <jwt token>
}
#[derive(Clone, Copy, Debug, Derivative, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum Encoding {
Text,
Json,
Avro,
}
type PulsarProducer = Producer<TokioExecutor>;
type BoxedPulsarProducer = Box<PulsarProducer>;
enum PulsarSinkState {
None,
Ready(BoxedPulsarProducer),
Sending(BoxFuture<'static, (BoxedPulsarProducer, Result<SendFuture, PulsarError>)>),
}
struct PulsarSink {
encoding: EncodingConfig<Encoding>,
avro_schema: Option<avro_rs::Schema>,
state: PulsarSinkState,
in_flight:
FuturesUnordered<BoxFuture<'static, (usize, Result<CommandSendReceipt, PulsarError>)>>,
acker: Acker,
seq_head: usize,
seq_tail: usize,
pending_acks: HashSet<usize>,
}
inventory::submit! {
SinkDescription::new::<PulsarSinkConfig>("pulsar")
}
impl GenerateConfig for PulsarSinkConfig {
fn generate_config() -> toml::Value {
toml::Value::try_from(Self {
endpoint: "pulsar://127.0.0.1:6650".to_string(),
topic: "topic-1234".to_string(),
encoding: Encoding::Text.into(),
auth: None,
})
.unwrap()
}
}
#[async_trait::async_trait]
#[typetag::serde(name = "pulsar")]
impl SinkConfig for PulsarSinkConfig {
async fn build(
&self,
cx: SinkContext,
) -> crate::Result<(super::VectorSink, super::Healthcheck)> {
let producer = self
.create_pulsar_producer()
.await
.context(CreatePulsarSink)?;
let sink = PulsarSink::new(producer, self.encoding.clone(), cx.acker())?;
let producer = self
.create_pulsar_producer()
.await
.context(CreatePulsarSink)?;
let healthcheck = healthcheck(producer).boxed();
Ok((super::VectorSink::Sink(Box::new(sink)), healthcheck))
}
fn input_type(&self) -> DataType {
DataType::Log
}
fn sink_type(&self) -> &'static str {
"pulsar"
}
}
impl PulsarSinkConfig {
async fn create_pulsar_producer(&self) -> Result<PulsarProducer, PulsarError> {
let mut builder = Pulsar::builder(&self.endpoint, TokioExecutor);
if let Some(auth) = &self.auth {
builder = builder.with_auth(Authentication {
name: auth.name.clone(),
data: auth.token.as_bytes().to_vec(),
});
}
if let Some(avro_schema) = &self.encoding.schema() {
let pulsar = builder.build().await?;
pulsar
.producer()
.with_options(pulsar::producer::ProducerOptions {
schema: Some(proto::Schema {
schema_data: avro_schema.to_string().into_bytes(),
type_: proto::schema::Type::Avro as i32,
..Default::default()
}),
..Default::default()
})
.with_topic(&self.topic)
.build()
.await
} else {
let pulsar = builder.build().await?;
pulsar.producer().with_topic(&self.topic).build().await
}
}
}
async fn healthcheck(producer: PulsarProducer) -> crate::Result<()> {
producer.check_connection().await.map_err(Into::into)
}
impl PulsarSink {
fn new(
producer: PulsarProducer,
encoding: EncodingConfig<Encoding>,
acker: Acker,
) -> crate::Result<Self> {
let schema = match &encoding.codec() {
Encoding::Avro => {
if let Some(schema) = &encoding.schema() {
avro_rs::Schema::parse_str(schema).ok()
} else {
return Err(
"Avro requires a schema, specify a schema file with `encoding.schema`."
.into(),
);
}
}
_ => None,
};
Ok(Self {
encoding,
avro_schema: schema,
state: PulsarSinkState::Ready(Box::new(producer)),
in_flight: FuturesUnordered::new(),
acker,
seq_head: 0,
seq_tail: 0,
pending_acks: HashSet::new(),
})
}
fn poll_in_flight_prepare(&mut self, cx: &mut Context<'_>) -> Poll<()> {
if let PulsarSinkState::Sending(fut) = &mut self.state {
let (producer, result) = ready!(fut.as_mut().poll(cx));
let seqno = self.seq_head;
self.seq_head += 1;
self.state = PulsarSinkState::Ready(producer);
self.in_flight.push(Box::pin(async move {
let result = match result {
Ok(fut) => fut.await,
Err(error) => Err(error),
};
(seqno, result)
}));
}
Poll::Ready(())
}
}
impl Sink<Event> for PulsarSink {
type Error = ();
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
ready!(self.poll_in_flight_prepare(cx));
Poll::Ready(Ok(()))
}
fn start_send(mut self: Pin<&mut Self>, item: Event) -> Result<(), Self::Error> {
assert!(
matches!(self.state, PulsarSinkState::Ready(_)),
"Expected `poll_ready` to be called first."
);
let message = encode_event(item, &self.encoding, &self.avro_schema).map_err(|e| {
emit!(PulsarEncodeEventFailed {
error: &*e.to_string()
})
})?;
let mut producer = match std::mem::replace(&mut self.state, PulsarSinkState::None) {
PulsarSinkState::Ready(producer) => producer,
_ => unreachable!(),
};
let _ = std::mem::replace(
&mut self.state,
PulsarSinkState::Sending(Box::pin(async move {
let result = producer.send(message).await;
(producer, result)
})),
);
Ok(())
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
ready!(self.poll_in_flight_prepare(cx));
let this = Pin::into_inner(self);
while !this.in_flight.is_empty() {
match ready!(Pin::new(&mut this.in_flight).poll_next(cx)) {
Some((seqno, Ok(result))) => {
trace!(
message = "Pulsar sink produced message.",
message_id = ?result.message_id,
producer_id = %result.producer_id,
sequence_id = %result.sequence_id,
);
this.pending_acks.insert(seqno);
let mut num_to_ack = 0;
while this.pending_acks.remove(&this.seq_tail) {
num_to_ack += 1;
this.seq_tail += 1
}
this.acker.ack(num_to_ack);
}
Some((_, Err(error))) => {
error!(message = "Pulsar sink generated an error.", %error);
return Poll::Ready(Err(()));
}
None => break,
}
}
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.poll_flush(cx)
}
}
fn encode_event(
mut item: Event,
encoding: &EncodingConfig<Encoding>,
avro_schema: &Option<avro_rs::Schema>,
) -> crate::Result<Vec<u8>> {
encoding.apply_rules(&mut item);
let log = item.into_log();
Ok(match encoding.codec() {
Encoding::Json => serde_json::to_vec(&log)?,
Encoding::Text => log
.get(log_schema().message_key())
.map(|v| v.as_bytes().to_vec())
.unwrap_or_default(),
Encoding::Avro => {
let value = avro_rs::to_value(log)?;
let resolved_value =
avro_rs::types::Value::resolve(value, avro_schema.as_ref().unwrap())?;
avro_rs::to_avro_datum(
&avro_schema
.as_ref()
.expect("Avro encoding selected but no schema found. Please report this."),
resolved_value,
)?
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
#[test]
fn generate_config() {
crate::test_util::test_generate_config::<PulsarSinkConfig>();
}
#[test]
fn pulsar_event_json() {
let msg = "hello_world".to_owned();
let mut evt = Event::from(msg.clone());
evt.as_mut_log().insert("key", "value");
let result = encode_event(evt, &EncodingConfig::from(Encoding::Json), &None).unwrap();
let map: HashMap<String, String> = serde_json::from_slice(&result[..]).unwrap();
assert_eq!(msg, map[&log_schema().message_key().to_string()]);
}
#[test]
fn pulsar_event_text() {
let msg = "hello_world".to_owned();
let evt = Event::from(msg.clone());
let event = encode_event(evt, &EncodingConfig::from(Encoding::Text), &None).unwrap();
assert_eq!(&event[..], msg.as_bytes());
}
#[test]
fn pulsar_event_avro() {
let raw_schema = r#"
{
"type": "record",
"name": "Log",
"fields": [
{"name": "message","type": ["null","string"]}
]
}
"#;
let msg = "hello_world".to_owned();
let mut evt = Event::from(msg);
evt.as_mut_log().insert("key", "value");
let mut encoding = EncodingConfig::from(Encoding::Avro);
encoding.schema = Some(raw_schema.to_string());
let schema = avro_rs::Schema::parse_str(&raw_schema).unwrap();
let result = encode_event(evt.clone(), &encoding, &Some(schema.clone())).unwrap();
let value = avro_rs::to_value(evt.into_log()).unwrap();
let resolved_value = avro_rs::types::Value::resolve(value, &schema).unwrap();
let must_be = avro_rs::to_avro_datum(&schema, resolved_value).unwrap();
assert_eq!(result, must_be);
}
#[test]
fn pulsar_encode_event() {
let msg = "hello_world";
let mut evt = Event::from(msg);
evt.as_mut_log().insert("key", "value");
let event = encode_event(
evt,
&EncodingConfig {
codec: Encoding::Json,
schema: None,
only_fields: None,
except_fields: Some(vec!["key".into()]),
timestamp_format: None,
},
&None,
)
.unwrap();
let map: HashMap<String, String> = serde_json::from_slice(&event[..]).unwrap();
assert!(!map.contains_key("key"));
}
}
#[cfg(feature = "pulsar-integration-tests")]
#[cfg(test)]
mod integration_tests {
use super::*;
use crate::test_util::{random_lines_with_stream, random_string, trace_init};
use futures::StreamExt;
use pulsar::SubType;
#[tokio::test]
async fn pulsar_happy() {
trace_init();
let num_events = 1_000;
let (_input, events) = random_lines_with_stream(100, num_events);
let topic = format!("test-{}", random_string(10));
let cnf = PulsarSinkConfig {
endpoint: "pulsar://127.0.0.1:6650".to_owned(),
topic: topic.clone(),
encoding: Encoding::Text.into(),
auth: None,
};
let pulsar = Pulsar::<TokioExecutor>::builder(&cnf.endpoint, TokioExecutor)
.build()
.await
.unwrap();
let mut consumer = pulsar
.consumer()
.with_topic(&topic)
.with_consumer_name("VectorTestConsumer")
.with_subscription_type(SubType::Shared)
.with_subscription("VectorTestSub")
.build::<String>()
.await
.unwrap();
let (acker, ack_counter) = Acker::new_for_testing();
let producer = cnf.create_pulsar_producer().await.unwrap();
let sink = PulsarSink::new(producer, cnf.encoding, acker).unwrap();
events.map(Ok).forward(sink).await.unwrap();
assert_eq!(
ack_counter.load(std::sync::atomic::Ordering::Relaxed),
num_events
);
for _ in 0..num_events {
let msg = match consumer.next().await.unwrap() {
Ok(msg) => msg,
Err(error) => panic!("{:?}", error),
};
consumer.ack(&msg).await.unwrap();
}
}
}