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