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
use std::fmt::Debug;
use std::fmt::Display;
use std::future::Future;
use anyhow::Result;
use async_trait::async_trait;
use prost::DecodeError;
use rdkafka::config::FromClientConfig;
use rdkafka::config::FromClientConfigAndContext;
use rdkafka::consumer::{ConsumerContext, Rebalance};
use rdkafka::error::{KafkaError, KafkaResult};
use rdkafka::message::BorrowedMessage;
use rdkafka::{ClientConfig, ClientContext, Message, TopicPartitionList};
use thiserror::Error;
use tracing::{debug, error, info};
use super::KafkaConfig;
pub use rdkafka::consumer::{CommitMode, Consumer, DefaultConsumerContext, StreamConsumer};
impl KafkaConfig {
pub fn consumer_config<T>(&self, group_id: &str) -> T
where
T: FromClientConfig,
{
ClientConfig::new()
.set("group.id", group_id)
.set("bootstrap.servers", &self.brokers_csv)
.set("enable.partition.eof", "false")
.set(
"security.protocol",
self.security_protocol
.clone()
.unwrap_or_else(|| "ssl".to_string()),
)
.set("session.timeout.ms", "6000")
.set("enable.auto.commit", "false")
.set("auto.offset.reset", "earliest")
.create()
.expect("Consumer creation failed")
}
}
#[async_trait]
pub trait ConsumerExt<C = DefaultConsumerContext>: Consumer<C>
where
C: ConsumerContext,
{
async fn process_protobuf_and_commit<F, T, Fut, E>(
&self,
message: Result<BorrowedMessage<'_>, KafkaError>,
process_fn: F,
mode: CommitMode,
) -> Result<(), Error>
where
T: prost::Message + Default,
F: Fn(T) -> Fut + Send + Sync,
Fut: Future<Output = Result<(), E>> + Send + Sync,
E: Display,
{
let message = message?;
let decoded_message = decode_protobuf::<T>(&message)?;
process_fn(decoded_message)
.await
.map_err(|err| Error::ProcessError(err.to_string()))?;
self.commit_message(&message, mode)?;
Ok(())
}
}
impl<C: ConsumerContext, R> ConsumerExt<C> for StreamConsumer<C, R> {}
fn decode_protobuf<T>(message: &BorrowedMessage<'_>) -> Result<T, Error>
where
T: prost::Message + Default,
{
let payload = message.payload().ok_or_else(|| Error::EmptyPayload)?;
Ok(T::decode(payload)?)
}
#[derive(Error, Debug)]
pub enum Error {
#[error("kafka error: {0}")]
KafkaError(#[from] KafkaError),
#[error("decode error: {0}")]
DecodeError(#[from] DecodeError),
#[error("No messages available right now")]
EmptyPayload,
#[error("any error: {0}")]
ProcessError(String),
}
pub struct LoggingConsumerContext;
impl ClientContext for LoggingConsumerContext {}
impl ConsumerContext for LoggingConsumerContext {
fn pre_rebalance(&self, rebalance: &Rebalance) {
match rebalance {
Rebalance::Assign(tpl) => {
info!("pre rebalance: {:?}", tpl)
}
Rebalance::Revoke(tpl) => {
info!("pre rebalance all partitions are revoke: {:?}", tpl)
}
Rebalance::Error(e) => {
info!("pre rebalance error: {:?}", e)
}
}
}
fn post_rebalance(&self, rebalance: &Rebalance) {
match rebalance {
Rebalance::Assign(tpl) => {
info!("post rebalance: {:?}", tpl)
}
Rebalance::Revoke(tpl) => {
info!("post rebalance all partitions are revoke: {:?}", tpl)
}
Rebalance::Error(e) => {
info!("post rebalance error: {:?}", e)
}
}
}
fn commit_callback(&self, result: KafkaResult<()>, offsets: &TopicPartitionList) {
match result {
Ok(_) => debug!("committed: {:?}", offsets),
Err(e) => info!("committed error: {:?}", e),
}
}
}