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::num::NonZeroUsize;
7use std::thread::available_parallelism;
8use std::{collections::BTreeMap, env};
9use utoipa::ToSchema;
10use uuid::Uuid;
11
12/// Configuration for reading data from Kafka topics with `InputTransport`.
13#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
14pub struct KafkaInputConfig {
15 /// Options passed directly to `rdkafka`.
16 ///
17 /// [`librdkafka` options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md)
18 /// used to configure the Kafka consumer.
19 ///
20 /// This input connector does not use consumer groups, so options related to
21 /// consumer groups are rejected, including:
22 ///
23 /// * `group.id`, if present, is ignored.
24 /// * `auto.offset.reset` (use `start_from` instead).
25 /// * "enable.auto.commit", if present, must be set to "false".
26 /// * "enable.auto.offset.store", if present, must be set to "false".
27 #[serde(flatten)]
28 pub kafka_options: BTreeMap<String, String>,
29
30 /// Topic to subscribe to.
31 pub topic: String,
32
33 /// The log level of the client.
34 ///
35 /// If not specified, the log level will be calculated based on the global
36 /// log level of the `log` crate.
37 pub log_level: Option<KafkaLogLevel>,
38
39 /// Maximum timeout in seconds to wait for the endpoint to join the Kafka
40 /// consumer group during initialization.
41 #[serde(default = "default_group_join_timeout_secs")]
42 pub group_join_timeout_secs: u32,
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 /// Where to begin reading the topic.
53 #[serde(default)]
54 pub start_from: KafkaStartFromConfig,
55
56 /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
57 pub region: Option<String>,
58
59 /// The list of Kafka partitions to read from.
60 ///
61 /// Only the specified partitions will be consumed. If this field is not set,
62 /// the connector will consume from all available partitions.
63 ///
64 /// If `start_from` is set to `offsets` and this field is provided, the
65 /// number of partitions must exactly match the number of offsets, and the
66 /// order of partitions must correspond to the order of offsets.
67 ///
68 /// If offsets are provided for all partitions, this field can be omitted.
69 pub partitions: Option<Vec<i32>>,
70
71 /// By default, if the input connector resumes from a checkpoint and the
72 /// data where it needs to resume has expired from the Kafka topic, the
73 /// input connector fails initialization and the pipeline will fail to start.
74 ///
75 /// Set this to true to change the behavior so that, if data is not
76 /// available on resume, the input connector starts from the earliest
77 /// offsets that are now available.
78 pub resume_earliest_if_data_expires: bool,
79}
80
81impl KafkaInputConfig {
82 // Returns the number of threads to use based on configuration, defaults,
83 // and system resources.
84 pub fn poller_threads(&self) -> usize {
85 let max_threads = available_parallelism().map_or(16, NonZeroUsize::get);
86 self.poller_threads.unwrap_or(3).clamp(1, max_threads)
87 }
88}
89
90impl<'de> Deserialize<'de> for KafkaInputConfig {
91 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
92 where
93 D: Deserializer<'de>,
94 {
95 let compat = compat::KafkaInputConfigCompat::deserialize(deserializer)?;
96 Self::try_from(compat).map_err(D::Error::custom)
97 }
98}
99
100/// Where to begin reading a Kafka topic.
101#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
102#[serde(rename_all = "snake_case")]
103pub enum KafkaStartFromConfig {
104 /// Start from the beginning of the topic.
105 Earliest,
106
107 /// Start from the current end of the topic.
108 ///
109 /// This will only read any data that is added to the topic after the
110 /// connector initializes.
111 #[default]
112 Latest,
113
114 /// Start from particular offsets in the topic.
115 ///
116 /// The number of offsets must match the number of partitions in the topic.
117 Offsets(Vec<i64>),
118}
119
120/// Kafka logging levels.
121#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ToSchema)]
122pub enum KafkaLogLevel {
123 #[serde(rename = "emerg")]
124 Emerg,
125 #[serde(rename = "alert")]
126 Alert,
127 #[serde(rename = "critical")]
128 Critical,
129 #[serde(rename = "error")]
130 Error,
131 #[serde(rename = "warning")]
132 Warning,
133 #[serde(rename = "notice")]
134 Notice,
135 #[serde(rename = "info")]
136 Info,
137 #[serde(rename = "debug")]
138 Debug,
139}
140
141/// On startup, the endpoint waits to join the consumer group.
142/// This constant defines the default wait timeout.
143pub const fn default_group_join_timeout_secs() -> u32 {
144 10
145}
146
147impl KafkaInputConfig {
148 /// Set `option` to `val`; return an error if `option` is set to a different
149 /// value.
150 #[allow(dead_code)]
151 fn enforce_option(&mut self, option: &str, val: &str) -> AnyResult<()> {
152 let option_val = self
153 .kafka_options
154 .entry(option.to_string())
155 .or_insert_with(|| val.to_string());
156 if option_val != val {
157 Err(AnyError::msg("cannot override '{option}' option: the Kafka transport adapter sets this option to '{val}'"))?;
158 }
159 Ok(())
160 }
161
162 /// Set `option` to `val`, if missing.
163 fn set_option_if_missing(&mut self, option: &str, val: &str) {
164 self.kafka_options
165 .entry(option.to_string())
166 .or_insert_with(|| val.to_string());
167 }
168
169 /// Validate configuration, set default option values required by this
170 /// adapter.
171 pub fn validate(&mut self) -> AnyResult<()> {
172 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
173
174 // These options will prevent librdkafka from automatically committing offsets
175 // of consumed messages to the broker, meaning that next time the
176 // connector is instantiated it will start reading from the offset
177 // specified in `auto.offset.reset`. We used to set these to
178 // `true`, which caused `rdkafka` to hang in some circumstances
179 // (https://github.com/confluentinc/librdkafka/issues/3954). Besides, the new behavior
180 // is probably more correct given that circuit state currently does not survive
181 // across pipeline restarts, so it makes sense to start feeding messages
182 // from the start rather than from the last offset consumed by the
183 // previous instance of the pipeline, whose state is lost. Once we add
184 // fault tolerance, we will likely use explicit commits, which also do
185 // not require these options.
186 //
187 // See https://docs.confluent.io/platform/current/clients/consumer.html#offset-management
188 //
189 // Note: we allow the user to override the options, so they can still enable
190 // auto commit if they know what they are doing, e.g., the secops demo
191 // requires the pipeline to commit its offset for the generator to know
192 // when to resume sending.
193 self.set_option_if_missing("enable.auto.commit", "false");
194 self.set_option_if_missing("enable.auto.offset.store", "false");
195
196 let group_id = format!("{}", Uuid::now_v7());
197 self.set_option_if_missing("group.id", &group_id);
198 self.set_option_if_missing("enable.partition.eof", "false");
199
200 // We link with openssl statically, which means that the default OPENSSLDIR location
201 // baked into openssl is not correct (see https://github.com/fede1024/rust-rdkafka/issues/594).
202 // We set the ssl.ca.location to "probe" so that librdkafka can find the CA certificates in a
203 // standard location (e.g., /etc/ssl/).
204 self.set_option_if_missing("ssl.ca.location", "probe");
205
206 // Enable client context `stats` callback so we can periodically check
207 // up on librdkafka memory usage.
208 self.set_option_if_missing("statistics.interval.ms", "10000");
209
210 if let (Some(partitions), KafkaStartFromConfig::Offsets(offsets)) =
211 (&self.partitions, &self.start_from)
212 {
213 if partitions.len() != offsets.len() {
214 anyhow::bail!("the number of partitions ('{partitions:?}') should be equal to the number of offsets '{offsets:?}' specified")
215 }
216 }
217
218 Ok(())
219 }
220}
221
222pub fn default_redpanda_server() -> String {
223 env::var("REDPANDA_BROKERS").unwrap_or_else(|_| "localhost".to_string())
224}
225
226const fn default_initialization_timeout_secs() -> u32 {
227 60
228}
229
230/// Kafka header value encoded as a UTF-8 string or a byte array.
231#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
232#[repr(transparent)]
233pub struct KafkaHeaderValue(pub Vec<u8>);
234
235/// Visitor for deserializing Kafka headers value.
236struct HeaderVisitor;
237
238impl<'de> Visitor<'de> for HeaderVisitor {
239 type Value = KafkaHeaderValue;
240
241 fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
242 formatter.write_str("a string (e.g., \"xyz\") or a byte array (e.g., '[1,2,3])")
243 }
244
245 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
246 where
247 E: Error,
248 {
249 Ok(KafkaHeaderValue(v.as_bytes().to_owned()))
250 }
251
252 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
253 where
254 E: Error,
255 {
256 Ok(KafkaHeaderValue(v.into_bytes()))
257 }
258
259 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
260 where
261 A: SeqAccess<'de>,
262 {
263 let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
264
265 while let Some(b) = seq.next_element()? {
266 result.push(b);
267 }
268
269 Ok(KafkaHeaderValue(result))
270 }
271}
272
273impl<'de> Deserialize<'de> for KafkaHeaderValue {
274 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
275 where
276 D: Deserializer<'de>,
277 {
278 deserializer.deserialize_any(HeaderVisitor)
279 }
280}
281
282#[cfg(test)]
283#[test]
284fn test_kafka_header_value_deserialize() {
285 assert_eq!(
286 serde_json::from_str::<KafkaHeaderValue>(r#""foobar""#).unwrap(),
287 KafkaHeaderValue(br#"foobar"#.to_vec())
288 );
289
290 assert_eq!(
291 serde_json::from_str::<KafkaHeaderValue>(r#"[1,2,3,4,5]"#).unwrap(),
292 KafkaHeaderValue(vec![1u8, 2, 3, 4, 5])
293 );
294
295 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"150"#).is_err());
296
297 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"{{"foo": "bar"}}"#).is_err());
298}
299
300/// Kafka message header.
301#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
302pub struct KafkaHeader {
303 pub key: String,
304 pub value: Option<KafkaHeaderValue>,
305}
306
307/// Configuration for writing data to a Kafka topic with `OutputTransport`.
308#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
309pub struct KafkaOutputConfig {
310 /// Options passed directly to `rdkafka`.
311 ///
312 /// See [`librdkafka` options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md)
313 /// used to configure the Kafka producer.
314 #[serde(flatten)]
315 pub kafka_options: BTreeMap<String, String>,
316
317 /// Topic to write to.
318 pub topic: String,
319
320 /// Kafka headers to be added to each message produced by this connector.
321 #[serde(default)]
322 pub headers: Vec<KafkaHeader>,
323
324 /// The log level of the client.
325 ///
326 /// If not specified, the log level will be calculated based on the global
327 /// log level of the `log` crate.
328 pub log_level: Option<KafkaLogLevel>,
329
330 /// Maximum timeout in seconds to wait for the endpoint to connect to
331 /// a Kafka broker.
332 ///
333 /// Defaults to 60.
334 #[serde(default = "default_initialization_timeout_secs")]
335 pub initialization_timeout_secs: u32,
336
337 /// Optional configuration for fault tolerance.
338 pub fault_tolerance: Option<KafkaOutputFtConfig>,
339
340 /// If specified, this service is used to provide defaults for the Kafka options.
341 pub kafka_service: Option<String>,
342
343 /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
344 pub region: Option<String>,
345}
346
347/// Fault tolerance configuration for Kafka output connector.
348#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
349#[serde(default)]
350pub struct KafkaOutputFtConfig {
351 /// Options passed to `rdkafka` for consumers only, as documented at
352 /// [`librdkafka`
353 /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
354 ///
355 /// These options override `kafka_options` for consumers, and may be empty.
356 pub consumer_options: BTreeMap<String, String>,
357
358 /// Options passed to `rdkafka` for producers only, as documented at
359 /// [`librdkafka`
360 /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
361 ///
362 /// These options override `kafka_options` for producers, and may be empty.
363 pub producer_options: BTreeMap<String, String>,
364}
365
366impl KafkaOutputConfig {
367 #[allow(dead_code)]
368 /// Set `option` to `val`, if missing.
369 fn set_option_if_missing(&mut self, option: &str, val: &str) {
370 self.kafka_options
371 .entry(option.to_string())
372 .or_insert_with(|| val.to_string());
373 }
374
375 #[allow(dead_code)]
376 /// Validate configuration, set default option values required by this
377 /// adapter.
378 pub fn validate(&mut self) -> AnyResult<()> {
379 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
380
381 // We link with openssl statically, which means that the default OPENSSLDIR location
382 // baked into openssl is not correct (see https://github.com/fede1024/rust-rdkafka/issues/594).
383 // We set the ssl.ca.location to "probe" so that librdkafka can find the CA certificates in a
384 // standard location (e.g., /etc/ssl/).
385 self.set_option_if_missing("ssl.ca.location", "probe");
386
387 // Enable client context `stats` callback so we can periodically check
388 // up on librdkafka memory usage.
389 self.set_option_if_missing("statistics.interval.ms", "10000");
390
391 Ok(())
392 }
393}
394
395/// A set of updates to a SQL table or view.
396///
397/// The `sequence_number` field stores the offset of the chunk relative to the
398/// start of the stream and can be used to implement reliable delivery.
399/// The payload is stored in the `bin_data`, `text_data`, or `json_data` field
400/// depending on the data format used.
401#[derive(Deserialize, ToSchema)]
402pub struct Chunk {
403 pub sequence_number: u64,
404
405 // Exactly one of the following fields must be set.
406 // This should be an enum inlined with `#[serde(flatten)]`, but `utoipa`
407 // struggles to generate a schema for that.
408 /// Base64 encoded binary payload, e.g., bincode.
409 pub bin_data: Option<Vec<u8>>,
410
411 /// Text payload, e.g., CSV.
412 pub text_data: Option<String>,
413
414 /// JSON payload.
415 #[schema(value_type = Option<Object>)]
416 pub json_data: Option<JsonValue>,
417}
418
419mod compat {
420 use std::collections::BTreeMap;
421
422 use serde::Deserialize;
423
424 use crate::transport::kafka::{KafkaLogLevel, KafkaStartFromConfig};
425
426 #[derive(Deserialize)]
427 pub struct KafkaInputConfigCompat {
428 /// Current, long-standing configuration option.
429 log_level: Option<KafkaLogLevel>,
430
431 /// Current, long-standing configuration option.
432 #[serde(default = "super::default_group_join_timeout_secs")]
433 group_join_timeout_secs: u32,
434
435 /// Current configuration option.
436 poller_threads: Option<usize>,
437
438 /// Current configuration option, which changed type in an incompatible
439 /// way soon after it was introduced. No backward compatibility for the
440 /// initial form.
441 start_from: Option<KafkaStartFromConfig>,
442
443 /// Current configuration option that replaces the old `topics`
444 /// option. Currently mandatory.
445 topic: Option<String>,
446
447 /// Old form of `topic`. Currently accepted as a substitute as long as
448 /// it has exactly one element.
449 #[serde(default)]
450 topics: Vec<String>,
451
452 /// Legacy, now ignored.
453 fault_tolerance: Option<String>,
454
455 /// Legacy, now ignored.
456 kafka_service: Option<String>,
457
458 /// Options passed directly to `rdkafka`.
459 #[serde(flatten)]
460 kafka_options: BTreeMap<String, String>,
461
462 /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
463 region: Option<String>,
464
465 /// The Kafka partitions to read from.
466 partitions: Option<Vec<i32>>,
467
468 /// By default, if the input connector resumes from a checkpoint and the
469 /// data where it needs to resume has expired from the Kafka topic, the
470 /// input connector fails the pipeline.
471 ///
472 /// Set this to true to change the behavior so that, if data is not
473 /// available on resume, the input connector starts from the earliest
474 /// offsets that are now available.
475 #[serde(default)]
476 pub resume_earliest_if_data_expires: bool,
477 }
478
479 impl TryFrom<KafkaInputConfigCompat> for super::KafkaInputConfig {
480 type Error = String;
481
482 fn try_from(mut compat: KafkaInputConfigCompat) -> Result<Self, Self::Error> {
483 let (topic, start_from) = if !compat.topics.is_empty() {
484 // Legacy mode. Convert to modern form.
485 if compat.topic.is_some() {
486 return Err(
487 "Kafka input adapter may not have both (modern) `topic` and (legacy) `topics`."
488 .into(),
489 );
490 }
491 if compat.topics.len() != 1 {
492 return Err(format!(
493 "Kafka input adapter must have exactly one topic (not {}).",
494 compat.topics.len()
495 ));
496 }
497 let start_from = if let Some(start_from) = compat.start_from {
498 start_from
499 } else if let Some(auto_offset_reset) =
500 compat.kafka_options.get("auto.offset.reset")
501 {
502 match auto_offset_reset.as_str() {
503 "smallest" | "earliest" | "beginning" => KafkaStartFromConfig::Earliest,
504 "largest" | "latest" | "end" => KafkaStartFromConfig::Latest,
505 _ => return Err(format!("Unrecognized value {auto_offset_reset:?} for `auto.offset.reset` in Kafka legacy input adapter configuration")),
506 }
507 } else {
508 KafkaStartFromConfig::default()
509 };
510 (compat.topics.pop().unwrap(), start_from)
511 } else if let Some(topic) = compat.topic {
512 // Modern mode. Forbid legacy settings.
513 if compat.fault_tolerance.is_some() {
514 return Err("Kafka input adapter `fault_tolerance` setting is obsolete.".into());
515 }
516 if compat.kafka_service.is_some() {
517 return Err("Kafka input adapter `kafka_service` setting is obsolete.".into());
518 }
519 (topic, compat.start_from.unwrap_or_default())
520 } else {
521 return Err("Kafka input adapter is missing required `topic` setting.".into());
522 };
523
524 for key in compat.kafka_options.keys() {
525 if !key.contains('.')
526 && key != "debug"
527 && key != "enabled_events"
528 && key != "retries"
529 {
530 return Err(format!("Invalid Kafka input connector configuration key {key:?}: it is not valid for the input connector, nor does it contain `.` as librdkafka configuration options generally do (nor is it one of the few special exceptions to that rule)."));
531 }
532 }
533
534 Ok(Self {
535 topic,
536 kafka_options: compat.kafka_options,
537 log_level: compat.log_level,
538 group_join_timeout_secs: compat.group_join_timeout_secs,
539 poller_threads: compat.poller_threads,
540 start_from,
541 region: compat.region,
542 partitions: compat.partitions,
543 resume_earliest_if_data_expires: compat.resume_earliest_if_data_expires,
544 })
545 }
546 }
547}