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