feldera_types/transport/kafka.rs
1use anyhow::{Error as AnyError, Result as AnyResult};
2use serde::de::{Error, SeqAccess, Visitor};
3use serde::{Deserialize, Deserializer, Serialize};
4use serde_json::Value as JsonValue;
5use std::fmt::Formatter;
6use std::{collections::BTreeMap, env};
7use utoipa::ToSchema;
8use uuid::Uuid;
9
10/// Configuration for reading data from Kafka topics with `InputTransport`.
11#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
12pub struct KafkaInputConfig {
13 /// Options passed directly to `rdkafka`.
14 ///
15 /// [`librdkafka` options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md)
16 /// used to configure the Kafka consumer. Not all options are valid with
17 /// this Kafka adapter:
18 ///
19 /// * "enable.auto.commit", if present, must be set to "false",
20 /// * "enable.auto.offset.store", if present, must be set to "false"
21 #[serde(flatten)]
22 pub kafka_options: BTreeMap<String, String>,
23
24 /// List of topics to subscribe to.
25 pub topics: Vec<String>,
26
27 /// The log level of the client.
28 ///
29 /// If not specified, the log level will be calculated based on the global
30 /// log level of the `log` crate.
31 pub log_level: Option<KafkaLogLevel>,
32
33 /// Maximum timeout in seconds to wait for the endpoint to join the Kafka
34 /// consumer group during initialization.
35 #[serde(default = "default_group_join_timeout_secs")]
36 pub group_join_timeout_secs: u32,
37
38 /// Deprecated.
39 pub fault_tolerance: Option<String>,
40
41 /// Deprecated.
42 pub kafka_service: Option<String>,
43
44 /// Set to 1 or more to fix the number of threads used to poll
45 /// `rdkafka`. Multiple threads can increase performance with small Kafka
46 /// messages; for large messages, one thread is enough. In either case, too
47 /// many threads can harm performance. If unset, the default is 3, which
48 /// helps with small messages but will not harm performance with large
49 /// messagee
50 pub poller_threads: Option<usize>,
51
52 /// A list of offsets and partitions specifying where to begin reading individual input topics.
53 ///
54 /// When specified, this property must contain a list of JSON objects with the following fields:
55 /// - `topic`: The name of the Kafka topic.
56 /// - `partition`: The partition number within the topic.
57 /// - `offset`: The specific offset from which to start consuming messages.
58 #[serde(default)]
59 pub start_from: Vec<KafkaStartFromConfig>,
60}
61
62/// Configuration for starting from a specific offset in a Kafka topic partition.
63#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
64pub struct KafkaStartFromConfig {
65 /// The Kafka topic.
66 pub topic: String,
67
68 /// The parition within the topic.
69 pub partition: u32,
70
71 /// The offset in the specified partition to start reading from.
72 pub offset: u64,
73}
74
75/// Kafka logging levels.
76#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ToSchema)]
77pub enum KafkaLogLevel {
78 #[serde(rename = "emerg")]
79 Emerg,
80 #[serde(rename = "alert")]
81 Alert,
82 #[serde(rename = "critical")]
83 Critical,
84 #[serde(rename = "error")]
85 Error,
86 #[serde(rename = "warning")]
87 Warning,
88 #[serde(rename = "notice")]
89 Notice,
90 #[serde(rename = "info")]
91 Info,
92 #[serde(rename = "debug")]
93 Debug,
94}
95
96/// On startup, the endpoint waits to join the consumer group.
97/// This constant defines the default wait timeout.
98const fn default_group_join_timeout_secs() -> u32 {
99 10
100}
101
102impl KafkaInputConfig {
103 /// Set `option` to `val`; return an error if `option` is set to a different
104 /// value.
105 #[allow(dead_code)]
106 fn enforce_option(&mut self, option: &str, val: &str) -> AnyResult<()> {
107 let option_val = self
108 .kafka_options
109 .entry(option.to_string())
110 .or_insert_with(|| val.to_string());
111 if option_val != val {
112 Err(AnyError::msg("cannot override '{option}' option: the Kafka transport adapter sets this option to '{val}'"))?;
113 }
114 Ok(())
115 }
116
117 /// Set `option` to `val`, if missing.
118 fn set_option_if_missing(&mut self, option: &str, val: &str) {
119 self.kafka_options
120 .entry(option.to_string())
121 .or_insert_with(|| val.to_string());
122 }
123
124 /// Validate configuration, set default option values required by this
125 /// adapter.
126 pub fn validate(&mut self) -> AnyResult<()> {
127 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
128
129 // These options will prevent librdkafka from automatically committing offsets
130 // of consumed messages to the broker, meaning that next time the
131 // connector is instantiated it will start reading from the offset
132 // specified in `auto.offset.reset`. We used to set these to
133 // `true`, which caused `rdkafka` to hang in some circumstances
134 // (https://github.com/confluentinc/librdkafka/issues/3954). Besides, the new behavior
135 // is probably more correct given that circuit state currently does not survive
136 // across pipeline restarts, so it makes sense to start feeding messages
137 // from the start rather than from the last offset consumed by the
138 // previous instance of the pipeline, whose state is lost. Once we add
139 // fault tolerance, we will likely use explicit commits, which also do
140 // not require these options.
141 //
142 // See https://docs.confluent.io/platform/current/clients/consumer.html#offset-management
143 //
144 // Note: we allow the user to override the options, so they can still enable
145 // auto commit if they know what they are doing, e.g., the secops demo
146 // requires the pipeline to commit its offset for the generator to know
147 // when to resume sending.
148 self.set_option_if_missing("enable.auto.commit", "false");
149 self.set_option_if_missing("enable.auto.offset.store", "false");
150
151 let group_id = format!("{}", Uuid::now_v7());
152 self.set_option_if_missing("group.id", &group_id);
153 self.set_option_if_missing("enable.partition.eof", "false");
154
155 Ok(())
156 }
157}
158
159pub fn default_redpanda_server() -> String {
160 env::var("REDPANDA_BROKERS").unwrap_or_else(|_| "localhost".to_string())
161}
162
163const fn default_initialization_timeout_secs() -> u32 {
164 60
165}
166
167/// Kafka header value encoded as a UTF-8 string or a byte array.
168#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
169#[repr(transparent)]
170pub struct KafkaHeaderValue(pub Vec<u8>);
171
172/// Visitor for deserializing Kafka headers value.
173struct HeaderVisitor;
174
175impl<'de> Visitor<'de> for HeaderVisitor {
176 type Value = KafkaHeaderValue;
177
178 fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
179 formatter.write_str("a string (e.g., \"xyz\") or a byte array (e.g., '[1,2,3])")
180 }
181
182 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
183 where
184 E: Error,
185 {
186 Ok(KafkaHeaderValue(v.as_bytes().to_owned()))
187 }
188
189 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
190 where
191 E: Error,
192 {
193 Ok(KafkaHeaderValue(v.into_bytes()))
194 }
195
196 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
197 where
198 A: SeqAccess<'de>,
199 {
200 let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
201
202 while let Some(b) = seq.next_element()? {
203 result.push(b);
204 }
205
206 Ok(KafkaHeaderValue(result))
207 }
208}
209
210impl<'de> Deserialize<'de> for KafkaHeaderValue {
211 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
212 where
213 D: Deserializer<'de>,
214 {
215 deserializer.deserialize_any(HeaderVisitor)
216 }
217}
218
219#[cfg(test)]
220#[test]
221fn test_kafka_header_value_deserialize() {
222 assert_eq!(
223 serde_json::from_str::<KafkaHeaderValue>(r#""foobar""#).unwrap(),
224 KafkaHeaderValue(br#"foobar"#.to_vec())
225 );
226
227 assert_eq!(
228 serde_json::from_str::<KafkaHeaderValue>(r#"[1,2,3,4,5]"#).unwrap(),
229 KafkaHeaderValue(vec![1u8, 2, 3, 4, 5])
230 );
231
232 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"150"#).is_err());
233
234 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"{{"foo": "bar"}}"#).is_err());
235}
236
237/// Kafka message header.
238#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
239pub struct KafkaHeader {
240 pub key: String,
241 pub value: Option<KafkaHeaderValue>,
242}
243
244/// Configuration for writing data to a Kafka topic with `OutputTransport`.
245#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
246pub struct KafkaOutputConfig {
247 /// Options passed directly to `rdkafka`.
248 ///
249 /// See [`librdkafka` options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md)
250 /// used to configure the Kafka producer.
251 #[serde(flatten)]
252 pub kafka_options: BTreeMap<String, String>,
253
254 /// Topic to write to.
255 pub topic: String,
256
257 /// Kafka headers to be added to each message produced by this connector.
258 #[serde(default)]
259 pub headers: Vec<KafkaHeader>,
260
261 /// The log level of the client.
262 ///
263 /// If not specified, the log level will be calculated based on the global
264 /// log level of the `log` crate.
265 pub log_level: Option<KafkaLogLevel>,
266
267 /// Maximum timeout in seconds to wait for the endpoint to connect to
268 /// a Kafka broker.
269 ///
270 /// Defaults to 60.
271 #[serde(default = "default_initialization_timeout_secs")]
272 pub initialization_timeout_secs: u32,
273
274 /// Optional configuration for fault tolerance.
275 pub fault_tolerance: Option<KafkaOutputFtConfig>,
276
277 /// If specified, this service is used to provide defaults for the Kafka options.
278 pub kafka_service: Option<String>,
279}
280
281/// Fault tolerance configuration for Kafka output connector.
282#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
283#[serde(default)]
284pub struct KafkaOutputFtConfig {
285 /// Options passed to `rdkafka` for consumers only, as documented at
286 /// [`librdkafka`
287 /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
288 ///
289 /// These options override `kafka_options` for consumers, and may be empty.
290 pub consumer_options: BTreeMap<String, String>,
291
292 /// Options passed to `rdkafka` for producers only, as documented at
293 /// [`librdkafka`
294 /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
295 ///
296 /// These options override `kafka_options` for producers, and may be empty.
297 pub producer_options: BTreeMap<String, String>,
298}
299
300impl KafkaOutputConfig {
301 #[allow(dead_code)]
302 /// Set `option` to `val`, if missing.
303 fn set_option_if_missing(&mut self, option: &str, val: &str) {
304 self.kafka_options
305 .entry(option.to_string())
306 .or_insert_with(|| val.to_string());
307 }
308
309 #[allow(dead_code)]
310 /// Validate configuration, set default option values required by this
311 /// adapter.
312 pub fn validate(&mut self) -> AnyResult<()> {
313 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
314 Ok(())
315 }
316}
317
318/// A set of updates to a SQL table or view.
319///
320/// The `sequence_number` field stores the offset of the chunk relative to the
321/// start of the stream and can be used to implement reliable delivery.
322/// The payload is stored in the `bin_data`, `text_data`, or `json_data` field
323/// depending on the data format used.
324#[derive(Deserialize, ToSchema)]
325pub struct Chunk {
326 pub sequence_number: u64,
327
328 // Exactly one of the following fields must be set.
329 // This should be an enum inlined with `#[serde(flatten)]`, but `utoipa`
330 // struggles to generate a schema for that.
331 /// Base64 encoded binary payload, e.g., bincode.
332 pub bin_data: Option<Vec<u8>>,
333
334 /// Text payload, e.g., CSV.
335 pub text_data: Option<String>,
336
337 /// JSON payload.
338 #[schema(value_type = Option<Object>)]
339 pub json_data: Option<JsonValue>,
340}