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