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