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