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        Ok(())
186    }
187}
188
189pub fn default_redpanda_server() -> String {
190    env::var("REDPANDA_BROKERS").unwrap_or_else(|_| "localhost".to_string())
191}
192
193const fn default_initialization_timeout_secs() -> u32 {
194    60
195}
196
197/// Kafka header value encoded as a UTF-8 string or a byte array.
198#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
199#[repr(transparent)]
200pub struct KafkaHeaderValue(pub Vec<u8>);
201
202/// Visitor for deserializing Kafka headers value.
203struct HeaderVisitor;
204
205impl<'de> Visitor<'de> for HeaderVisitor {
206    type Value = KafkaHeaderValue;
207
208    fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
209        formatter.write_str("a string (e.g., \"xyz\") or a byte array (e.g., '[1,2,3])")
210    }
211
212    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
213    where
214        E: Error,
215    {
216        Ok(KafkaHeaderValue(v.as_bytes().to_owned()))
217    }
218
219    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
220    where
221        E: Error,
222    {
223        Ok(KafkaHeaderValue(v.into_bytes()))
224    }
225
226    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
227    where
228        A: SeqAccess<'de>,
229    {
230        let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
231
232        while let Some(b) = seq.next_element()? {
233            result.push(b);
234        }
235
236        Ok(KafkaHeaderValue(result))
237    }
238}
239
240impl<'de> Deserialize<'de> for KafkaHeaderValue {
241    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
242    where
243        D: Deserializer<'de>,
244    {
245        deserializer.deserialize_any(HeaderVisitor)
246    }
247}
248
249#[cfg(test)]
250#[test]
251fn test_kafka_header_value_deserialize() {
252    assert_eq!(
253        serde_json::from_str::<KafkaHeaderValue>(r#""foobar""#).unwrap(),
254        KafkaHeaderValue(br#"foobar"#.to_vec())
255    );
256
257    assert_eq!(
258        serde_json::from_str::<KafkaHeaderValue>(r#"[1,2,3,4,5]"#).unwrap(),
259        KafkaHeaderValue(vec![1u8, 2, 3, 4, 5])
260    );
261
262    assert!(serde_json::from_str::<KafkaHeaderValue>(r#"150"#).is_err());
263
264    assert!(serde_json::from_str::<KafkaHeaderValue>(r#"{{"foo": "bar"}}"#).is_err());
265}
266
267/// Kafka message header.
268#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
269pub struct KafkaHeader {
270    pub key: String,
271    pub value: Option<KafkaHeaderValue>,
272}
273
274/// Configuration for writing data to a Kafka topic with `OutputTransport`.
275#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
276pub struct KafkaOutputConfig {
277    /// Options passed directly to `rdkafka`.
278    ///
279    /// See [`librdkafka` options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md)
280    /// used to configure the Kafka producer.
281    #[serde(flatten)]
282    pub kafka_options: BTreeMap<String, String>,
283
284    /// Topic to write to.
285    pub topic: String,
286
287    /// Kafka headers to be added to each message produced by this connector.
288    #[serde(default)]
289    pub headers: Vec<KafkaHeader>,
290
291    /// The log level of the client.
292    ///
293    /// If not specified, the log level will be calculated based on the global
294    /// log level of the `log` crate.
295    pub log_level: Option<KafkaLogLevel>,
296
297    /// Maximum timeout in seconds to wait for the endpoint to connect to
298    /// a Kafka broker.
299    ///
300    /// Defaults to 60.
301    #[serde(default = "default_initialization_timeout_secs")]
302    pub initialization_timeout_secs: u32,
303
304    /// Optional configuration for fault tolerance.
305    pub fault_tolerance: Option<KafkaOutputFtConfig>,
306
307    /// If specified, this service is used to provide defaults for the Kafka options.
308    pub kafka_service: Option<String>,
309
310    /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
311    pub region: Option<String>,
312}
313
314/// Fault tolerance configuration for Kafka output connector.
315#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
316#[serde(default)]
317pub struct KafkaOutputFtConfig {
318    /// Options passed to `rdkafka` for consumers only, as documented at
319    /// [`librdkafka`
320    /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
321    ///
322    /// These options override `kafka_options` for consumers, and may be empty.
323    pub consumer_options: BTreeMap<String, String>,
324
325    /// Options passed to `rdkafka` for producers only, as documented at
326    /// [`librdkafka`
327    /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
328    ///
329    /// These options override `kafka_options` for producers, and may be empty.
330    pub producer_options: BTreeMap<String, String>,
331}
332
333impl KafkaOutputConfig {
334    #[allow(dead_code)]
335    /// Set `option` to `val`, if missing.
336    fn set_option_if_missing(&mut self, option: &str, val: &str) {
337        self.kafka_options
338            .entry(option.to_string())
339            .or_insert_with(|| val.to_string());
340    }
341
342    #[allow(dead_code)]
343    /// Validate configuration, set default option values required by this
344    /// adapter.
345    pub fn validate(&mut self) -> AnyResult<()> {
346        self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
347
348        // We link with openssl statically, which means that the default OPENSSLDIR location
349        // baked into openssl is not correct (see https://github.com/fede1024/rust-rdkafka/issues/594).
350        // We set the ssl.ca.location to "probe" so that librdkafka can find the CA certificates in a
351        // standard location (e.g., /etc/ssl/).
352        self.set_option_if_missing("ssl.ca.location", "probe");
353
354        Ok(())
355    }
356}
357
358/// A set of updates to a SQL table or view.
359///
360/// The `sequence_number` field stores the offset of the chunk relative to the
361/// start of the stream and can be used to implement reliable delivery.
362/// The payload is stored in the `bin_data`, `text_data`, or `json_data` field
363/// depending on the data format used.
364#[derive(Deserialize, ToSchema)]
365pub struct Chunk {
366    pub sequence_number: u64,
367
368    // Exactly one of the following fields must be set.
369    // This should be an enum inlined with `#[serde(flatten)]`, but `utoipa`
370    // struggles to generate a schema for that.
371    /// Base64 encoded binary payload, e.g., bincode.
372    pub bin_data: Option<Vec<u8>>,
373
374    /// Text payload, e.g., CSV.
375    pub text_data: Option<String>,
376
377    /// JSON payload.
378    #[schema(value_type = Option<Object>)]
379    pub json_data: Option<JsonValue>,
380}
381
382mod compat {
383    use std::collections::BTreeMap;
384
385    use serde::Deserialize;
386
387    use crate::transport::kafka::{KafkaLogLevel, KafkaStartFromConfig};
388
389    #[derive(Deserialize)]
390    pub struct KafkaInputConfigCompat {
391        /// Current, long-standing configuration option.
392        log_level: Option<KafkaLogLevel>,
393
394        /// Current, long-standing configuration option.
395        #[serde(default = "super::default_group_join_timeout_secs")]
396        group_join_timeout_secs: u32,
397
398        /// Current configuration option.
399        poller_threads: Option<usize>,
400
401        /// Current configuration option, which changed type in an incompatible
402        /// way soon after it was introduced. No backward compatibility for the
403        /// initial form.
404        start_from: Option<KafkaStartFromConfig>,
405
406        /// Current configuration option that replaces the old `topics`
407        /// option. Currently mandatory.
408        topic: Option<String>,
409
410        /// Old form of `topic`. Currently accepted as a substitute as long as
411        /// it has exactly one element.
412        #[serde(default)]
413        topics: Vec<String>,
414
415        /// Legacy, now ignored.
416        fault_tolerance: Option<String>,
417
418        /// Legacy, now ignored.
419        kafka_service: Option<String>,
420
421        /// Options passed directly to `rdkafka`.
422        #[serde(flatten)]
423        kafka_options: BTreeMap<String, String>,
424
425        /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
426        region: Option<String>,
427    }
428
429    impl TryFrom<KafkaInputConfigCompat> for super::KafkaInputConfig {
430        type Error = String;
431
432        fn try_from(mut compat: KafkaInputConfigCompat) -> Result<Self, Self::Error> {
433            let (topic, start_from) = if !compat.topics.is_empty() {
434                // Legacy mode. Convert to modern form.
435                if compat.topic.is_some() {
436                    return Err(
437                        "Kafka input adapter may not have both (modern) `topic` and (legacy) `topics`."
438                            .into(),
439                    );
440                }
441                if compat.topics.len() != 1 {
442                    return Err(format!(
443                        "Kafka input adapter must have exactly one topic (not {}).",
444                        compat.topics.len()
445                    ));
446                }
447                let start_from = if let Some(start_from) = compat.start_from {
448                    start_from
449                } else if let Some(auto_offset_reset) =
450                    compat.kafka_options.get("auto.offset.reset")
451                {
452                    match auto_offset_reset.as_str() {
453                        "smallest" | "earliest" | "beginning" => KafkaStartFromConfig::Earliest,
454                        "largest" | "latest" | "end" => KafkaStartFromConfig::Latest,
455                        _ => return Err(format!("Unrecognized value {auto_offset_reset:?} for `auto.offset.reset` in Kafka legacy input adapter configuration")),
456                    }
457                } else {
458                    KafkaStartFromConfig::default()
459                };
460                (compat.topics.pop().unwrap(), start_from)
461            } else if let Some(topic) = compat.topic {
462                // Modern mode. Forbid legacy settings.
463                if compat.fault_tolerance.is_some() {
464                    return Err("Kafka input adapter `fault_tolerance` setting is obsolete.".into());
465                }
466                if compat.kafka_service.is_some() {
467                    return Err("Kafka input adapter `kafka_service` setting is obsolete.".into());
468                }
469                (topic, compat.start_from.unwrap_or_default())
470            } else {
471                return Err("Kafka input adapter is missing required `topic` setting.".into());
472            };
473
474            for key in compat.kafka_options.keys() {
475                if !key.contains('.')
476                    && key != "debug"
477                    && key != "enabled_events"
478                    && key != "retries"
479                {
480                    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)."));
481                }
482            }
483
484            Ok(Self {
485                topic,
486                kafka_options: compat.kafka_options,
487                log_level: compat.log_level,
488                group_join_timeout_secs: compat.group_join_timeout_secs,
489                poller_threads: compat.poller_threads,
490                start_from,
491                region: compat.region,
492            })
493        }
494    }
495}