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