Skip to main content

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, with = "crate::serde_via_value")]
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    /// Whether to include Kafka headers in the record metadata.
81    ///
82    /// When `true`, Kafka message headers are available via the `CONNECTOR_METADATA()` function.
83    /// See <https://docs.feldera.com/connectors/sources/kafka#metadata> for details.
84    #[serde(default)]
85    pub include_headers: Option<bool>,
86
87    /// Whether to include Kafka message timestamp in the record metadata.
88    ///
89    /// When `true`, Kafka message timestamp is available via the `CONNECTOR_METADATA()` function.
90    /// See <https://docs.feldera.com/connectors/sources/kafka#metadata> for details.
91    #[serde(default)]
92    pub include_timestamp: Option<bool>,
93
94    /// Whether to include Kafka partition in the record metadata.
95    ///
96    /// When `true`, Kafka partition from which the message was read is available via the `CONNECTOR_METADATA()` function.
97    /// See <https://docs.feldera.com/connectors/sources/kafka#metadata> for details.
98    #[serde(default)]
99    pub include_partition: Option<bool>,
100
101    /// Whether to include Kafka message offset in the record metadata.
102    ///
103    /// When `true`, Kafka message offset is available via the `CONNECTOR_METADATA()` function.
104    /// See <https://docs.feldera.com/connectors/sources/kafka#metadata> for details.
105    #[serde(default)]
106    pub include_offset: Option<bool>,
107
108    /// Whether to include Kafka topic in the record metadata.
109    ///
110    /// When `true`, Kafka topic from which the message was read is available via the `CONNECTOR_METADATA()` function.
111    /// See <https://docs.feldera.com/connectors/sources/kafka#metadata> for details.
112    #[serde(default)]
113    pub include_topic: Option<bool>,
114
115    /// When lateness is enabled on a Feldera table, Feldera only produces
116    /// correct output if input arrives approximately in order within the bounds
117    /// of the lateness.  The Feldera Kafka input connector can reorder input
118    /// when there are multiple partitions:
119    ///
120    /// - If partitions start at different times, then reading all the
121    ///   partitions in parallel will naturally consume data out of order.
122    ///
123    /// - Even if they start at the same time, partitions might contain events
124    ///   at different rates.
125    ///
126    /// - Even if the partitions start at the same time and have the same number
127    ///   of events per unit time, if partitions are spread across brokers,
128    ///   different brokers may fetch data at different rates.
129    ///
130    /// - Even if all of the partitions are on a single broker, one cannot
131    ///   expect all of the partitions to naturally remain exactly in sync
132    ///   forever.
133    ///
134    /// Setting this option to `true` addresses the issue by synchronizing
135    /// ingestion across partitions, ingesting records in order of their Kafka
136    /// event timestamps.
137    ///
138    /// Pitfalls of this solution include:
139    ///
140    /// - Kafka event timestamps are not necessarily monotonically increasing
141    ///   even within a single partition.  If timestamps jump backward beyond
142    ///   the lateness, then this can also cause correctness problems.
143    ///
144    ///   (This can be avoided by keeping clocks on Kafka producers and brokers
145    ///   synchronized.)
146    ///
147    /// - If an event with a timestamp far in the future is added to a
148    ///   partition, that event, and all those that follow it, will never be
149    ///   processed.
150    ///
151    /// - If one or a few partitions have timestamps far behind the others, only
152    ///   those partitions will be processed until all the old events are
153    ///   processed.  (This is the flip side of the previous pitfall.)
154    ///
155    /// - One or more empty partitions will prevent any data from being
156    ///   processed at all, because there is no way to know the timestamp for
157    ///   the first event that will be added to that partition.
158    ///
159    /// - In a topic with `N` nonempty partitions, at least `N - 1` events will
160    ///   always be left unprocessed (one in each of `N - 1` partitions), because
161    ///   there is no way to know the timestamp for the next event to be added to
162    ///   the partition whose events have been completely processed.
163    #[serde(default)]
164    pub synchronize_partitions: bool,
165}
166
167impl KafkaInputConfig {
168    /// Returns a default [KafkaInputConfig] with the given `kafka_options` and
169    /// `topic`.  To be a usable configuration, `kafka_options` must contain at
170    /// least `bootstrap.servers`.
171    pub fn default(kafka_options: BTreeMap<String, String>, topic: impl Into<String>) -> Self {
172        Self {
173            kafka_options,
174            topic: topic.into(),
175            log_level: None,
176            group_join_timeout_secs: default_group_join_timeout_secs(),
177            poller_threads: None,
178            start_from: KafkaStartFromConfig::default(),
179            region: None,
180            partitions: None,
181            resume_earliest_if_data_expires: false,
182            include_headers: None,
183            include_timestamp: None,
184            include_partition: None,
185            include_offset: None,
186            include_topic: None,
187            synchronize_partitions: false,
188        }
189    }
190
191    // Returns the number of threads to use based on configuration, defaults,
192    // and system resources.
193    pub fn poller_threads(&self) -> usize {
194        let max_threads = available_parallelism().map_or(16, NonZeroUsize::get);
195        self.poller_threads.unwrap_or(3).clamp(1, max_threads)
196    }
197
198    pub fn metadata_requested(&self) -> bool {
199        self.include_topic == Some(true)
200            || self.include_timestamp == Some(true)
201            || self.include_partition == Some(true)
202            || self.include_offset == Some(true)
203            || self.include_headers == Some(true)
204    }
205}
206
207impl<'de> Deserialize<'de> for KafkaInputConfig {
208    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
209    where
210        D: Deserializer<'de>,
211    {
212        let compat = compat::KafkaInputConfigCompat::deserialize(deserializer)?;
213        Self::try_from(compat).map_err(D::Error::custom)
214    }
215}
216
217/// Where to begin reading a Kafka topic.
218#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
219#[serde(rename_all = "snake_case")]
220pub enum KafkaStartFromConfig {
221    /// Start from the beginning of the topic.
222    Earliest,
223
224    /// Start from the current end of the topic.
225    ///
226    /// This will only read any data that is added to the topic after the
227    /// connector initializes.
228    #[default]
229    Latest,
230
231    /// Start from particular offsets in the topic.
232    ///
233    /// The number of offsets must match the number of partitions in the topic.
234    Offsets(Vec<i64>),
235
236    /// Start from a particular timestamp in the topic.
237    ///
238    /// Kafka timestamps are in milliseconds since the epoch.
239    Timestamp(i64),
240}
241
242/// Kafka logging levels.
243#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ToSchema)]
244pub enum KafkaLogLevel {
245    #[serde(rename = "emerg")]
246    Emerg,
247    #[serde(rename = "alert")]
248    Alert,
249    #[serde(rename = "critical")]
250    Critical,
251    #[serde(rename = "error")]
252    Error,
253    #[serde(rename = "warning")]
254    Warning,
255    #[serde(rename = "notice")]
256    Notice,
257    #[serde(rename = "info")]
258    Info,
259    #[serde(rename = "debug")]
260    Debug,
261}
262
263/// On startup, the endpoint waits to join the consumer group.
264/// This constant defines the default wait timeout.
265pub const fn default_group_join_timeout_secs() -> u32 {
266    10
267}
268
269impl KafkaInputConfig {
270    /// Set `option` to `val`; return an error if `option` is set to a different
271    /// value.
272    #[allow(dead_code)]
273    fn enforce_option(&mut self, option: &str, val: &str) -> AnyResult<()> {
274        let option_val = self
275            .kafka_options
276            .entry(option.to_string())
277            .or_insert_with(|| val.to_string());
278        if option_val != val {
279            Err(AnyError::msg(
280                "cannot override '{option}' option: the Kafka transport adapter sets this option to '{val}'",
281            ))?;
282        }
283        Ok(())
284    }
285
286    /// Set `option` to `val`, if missing.
287    fn set_option_if_missing(&mut self, option: &str, val: &str) {
288        self.kafka_options
289            .entry(option.to_string())
290            .or_insert_with(|| val.to_string());
291    }
292
293    /// Validate configuration, set default option values required by this
294    /// adapter.
295    pub fn validate(&mut self) -> AnyResult<()> {
296        self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
297
298        // These options will prevent librdkafka from automatically committing offsets
299        // of consumed messages to the broker, meaning that next time the
300        // connector is instantiated it will start reading from the offset
301        // specified in `auto.offset.reset`.  We used to set these to
302        // `true`, which caused `rdkafka` to hang in some circumstances
303        // (https://github.com/confluentinc/librdkafka/issues/3954).  Besides, the new behavior
304        // is probably more correct given that circuit state currently does not survive
305        // across pipeline restarts, so it makes sense to start feeding messages
306        // from the start rather than from the last offset consumed by the
307        // previous instance of the pipeline, whose state is lost.  Once we add
308        // fault tolerance, we will likely use explicit commits, which also do
309        // not require these options.
310        //
311        // See https://docs.confluent.io/platform/current/clients/consumer.html#offset-management
312        //
313        // Note: we allow the user to override the options, so they can still enable
314        // auto commit if they know what they are doing, e.g., the secops demo
315        // requires the pipeline to commit its offset for the generator to know
316        // when to resume sending.
317        self.set_option_if_missing("enable.auto.commit", "false");
318        self.set_option_if_missing("enable.auto.offset.store", "false");
319
320        let group_id = format!("{}", Uuid::now_v7());
321        self.set_option_if_missing("group.id", &group_id);
322        self.set_option_if_missing("enable.partition.eof", "false");
323
324        // We link with openssl statically, which means that the default OPENSSLDIR location
325        // baked into openssl is not correct (see https://github.com/fede1024/rust-rdkafka/issues/594).
326        // We set the ssl.ca.location to "probe" so that librdkafka can find the CA certificates in a
327        // standard location (e.g., /etc/ssl/).
328        self.set_option_if_missing("ssl.ca.location", "probe");
329
330        // Enable client context `stats` callback so we can periodically check
331        // up on librdkafka memory usage.
332        self.set_option_if_missing("statistics.interval.ms", "10000");
333
334        if let (Some(partitions), KafkaStartFromConfig::Offsets(offsets)) =
335            (&self.partitions, &self.start_from)
336            && partitions.len() != offsets.len()
337        {
338            anyhow::bail!(
339                "the number of partitions ('{partitions:?}') should be equal to the number of offsets '{offsets:?}' specified"
340            )
341        }
342
343        Ok(())
344    }
345}
346
347pub fn default_redpanda_server() -> String {
348    env::var("REDPANDA_BROKERS").unwrap_or_else(|_| "localhost".to_string())
349}
350
351const fn default_initialization_timeout_secs() -> u32 {
352    60
353}
354
355/// Kafka header value encoded as a UTF-8 string or a byte array.
356#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
357#[repr(transparent)]
358pub struct KafkaHeaderValue(pub Vec<u8>);
359
360/// Visitor for deserializing Kafka headers value.
361struct HeaderVisitor;
362
363impl<'de> Visitor<'de> for HeaderVisitor {
364    type Value = KafkaHeaderValue;
365
366    fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
367        formatter.write_str("a string (e.g., \"xyz\") or a byte array (e.g., '[1,2,3])")
368    }
369
370    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
371    where
372        E: Error,
373    {
374        Ok(KafkaHeaderValue(v.as_bytes().to_owned()))
375    }
376
377    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
378    where
379        E: Error,
380    {
381        Ok(KafkaHeaderValue(v.into_bytes()))
382    }
383
384    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
385    where
386        A: SeqAccess<'de>,
387    {
388        let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
389
390        while let Some(b) = seq.next_element()? {
391            result.push(b);
392        }
393
394        Ok(KafkaHeaderValue(result))
395    }
396}
397
398impl<'de> Deserialize<'de> for KafkaHeaderValue {
399    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
400    where
401        D: Deserializer<'de>,
402    {
403        deserializer.deserialize_any(HeaderVisitor)
404    }
405}
406
407#[cfg(test)]
408#[test]
409fn test_kafka_header_value_deserialize() {
410    assert_eq!(
411        serde_json::from_str::<KafkaHeaderValue>(r#""foobar""#).unwrap(),
412        KafkaHeaderValue(br#"foobar"#.to_vec())
413    );
414
415    assert_eq!(
416        serde_json::from_str::<KafkaHeaderValue>(r#"[1,2,3,4,5]"#).unwrap(),
417        KafkaHeaderValue(vec![1u8, 2, 3, 4, 5])
418    );
419
420    assert!(serde_json::from_str::<KafkaHeaderValue>(r#"150"#).is_err());
421
422    assert!(serde_json::from_str::<KafkaHeaderValue>(r#"{{"foo": "bar"}}"#).is_err());
423}
424
425/// Kafka message header.
426#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
427pub struct KafkaHeader {
428    pub key: String,
429    pub value: Option<KafkaHeaderValue>,
430}
431
432/// Configuration for writing data to a Kafka topic with `OutputTransport`.
433#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
434pub struct KafkaOutputConfig {
435    /// Options passed directly to `rdkafka`.
436    ///
437    /// See [`librdkafka` options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md)
438    /// used to configure the Kafka producer.
439    #[serde(flatten)]
440    pub kafka_options: BTreeMap<String, String>,
441
442    /// Topic to write to.
443    pub topic: String,
444
445    /// Kafka headers to be added to each message produced by this connector.
446    #[serde(default)]
447    pub headers: Vec<KafkaHeader>,
448
449    /// The log level of the client.
450    ///
451    /// If not specified, the log level will be calculated based on the global
452    /// log level of the `log` crate.
453    pub log_level: Option<KafkaLogLevel>,
454
455    /// Maximum timeout in seconds to wait for the endpoint to connect to
456    /// a Kafka broker.
457    ///
458    /// Defaults to 60.
459    #[serde(default = "default_initialization_timeout_secs")]
460    pub initialization_timeout_secs: u32,
461
462    /// Optional configuration for fault tolerance.
463    pub fault_tolerance: Option<KafkaOutputFtConfig>,
464
465    /// If specified, this service is used to provide defaults for the Kafka options.
466    pub kafka_service: Option<String>,
467
468    /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
469    pub region: Option<String>,
470}
471
472/// Fault tolerance configuration for Kafka output connector.
473#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
474#[serde(default)]
475pub struct KafkaOutputFtConfig {
476    /// Options passed to `rdkafka` for consumers only, as documented at
477    /// [`librdkafka`
478    /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
479    ///
480    /// These options override `kafka_options` for consumers, and may be empty.
481    pub consumer_options: BTreeMap<String, String>,
482
483    /// Options passed to `rdkafka` for producers only, as documented at
484    /// [`librdkafka`
485    /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
486    ///
487    /// These options override `kafka_options` for producers, and may be empty.
488    pub producer_options: BTreeMap<String, String>,
489}
490
491impl KafkaOutputConfig {
492    #[allow(dead_code)]
493    /// Set `option` to `val`, if missing.
494    fn set_option_if_missing(&mut self, option: &str, val: &str) {
495        self.kafka_options
496            .entry(option.to_string())
497            .or_insert_with(|| val.to_string());
498    }
499
500    #[allow(dead_code)]
501    /// Validate configuration, set default option values required by this
502    /// adapter.
503    pub fn validate(&mut self) -> AnyResult<()> {
504        self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
505
506        // We link with openssl statically, which means that the default OPENSSLDIR location
507        // baked into openssl is not correct (see https://github.com/fede1024/rust-rdkafka/issues/594).
508        // We set the ssl.ca.location to "probe" so that librdkafka can find the CA certificates in a
509        // standard location (e.g., /etc/ssl/).
510        self.set_option_if_missing("ssl.ca.location", "probe");
511
512        // Enable client context `stats` callback so we can periodically check
513        // up on librdkafka memory usage.
514        self.set_option_if_missing("statistics.interval.ms", "10000");
515
516        Ok(())
517    }
518}
519
520/// A set of updates to a SQL table or view.
521///
522/// The `sequence_number` field stores the offset of the chunk relative to the
523/// start of the stream and can be used to implement reliable delivery.
524/// The payload is stored in the `bin_data`, `text_data`, or `json_data` field
525/// depending on the data format used.
526#[derive(Deserialize, ToSchema)]
527pub struct Chunk {
528    pub sequence_number: u64,
529
530    // Exactly one of the following fields must be set.
531    // This should be an enum inlined with `#[serde(flatten)]`, but `utoipa`
532    // struggles to generate a schema for that.
533    /// Base64 encoded binary payload, e.g., bincode.
534    pub bin_data: Option<Vec<u8>>,
535
536    /// Text payload, e.g., CSV.
537    pub text_data: Option<String>,
538
539    /// JSON payload.
540    #[schema(value_type = Option<Object>)]
541    pub json_data: Option<JsonValue>,
542}
543
544mod compat {
545    use std::collections::BTreeMap;
546
547    use serde::Deserialize;
548
549    use crate::transport::kafka::{KafkaLogLevel, KafkaStartFromConfig};
550
551    #[derive(Deserialize)]
552    pub struct KafkaInputConfigCompat {
553        /// Current, long-standing configuration option.
554        log_level: Option<KafkaLogLevel>,
555
556        /// Current, long-standing configuration option.
557        #[serde(default = "super::default_group_join_timeout_secs")]
558        group_join_timeout_secs: u32,
559
560        /// Current configuration option.
561        poller_threads: Option<usize>,
562
563        /// Current configuration option, which changed type in an incompatible
564        /// way soon after it was introduced. No backward compatibility for the
565        /// initial form.
566        #[serde(default, with = "crate::serde_via_value")]
567        start_from: Option<KafkaStartFromConfig>,
568
569        /// Current configuration option that replaces the old `topics`
570        /// option. Currently mandatory.
571        topic: Option<String>,
572
573        /// Old form of `topic`. Currently accepted as a substitute as long as
574        /// it has exactly one element.
575        #[serde(default)]
576        topics: Vec<String>,
577
578        /// Legacy, now ignored.
579        fault_tolerance: Option<String>,
580
581        /// Legacy, now ignored.
582        kafka_service: Option<String>,
583
584        /// Options passed directly to `rdkafka`.
585        #[serde(flatten)]
586        kafka_options: BTreeMap<String, String>,
587
588        /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
589        region: Option<String>,
590
591        /// The Kafka partitions to read from.
592        partitions: Option<Vec<i32>>,
593
594        /// By default, if the input connector resumes from a checkpoint and the
595        /// data where it needs to resume has expired from the Kafka topic, the
596        /// input connector fails the pipeline.
597        ///
598        /// Set this to true to change the behavior so that, if data is not
599        /// available on resume, the input connector starts from the earliest
600        /// offsets that are now available.
601        #[serde(default)]
602        pub resume_earliest_if_data_expires: bool,
603
604        include_headers: Option<bool>,
605        include_timestamp: Option<bool>,
606        include_partition: Option<bool>,
607        include_offset: Option<bool>,
608        include_topic: Option<bool>,
609        #[serde(default)]
610        synchronize_partitions: bool,
611    }
612
613    impl TryFrom<KafkaInputConfigCompat> for super::KafkaInputConfig {
614        type Error = String;
615
616        fn try_from(mut compat: KafkaInputConfigCompat) -> Result<Self, Self::Error> {
617            let (topic, start_from) = if !compat.topics.is_empty() {
618                // Legacy mode. Convert to modern form.
619                if compat.topic.is_some() {
620                    return Err(
621                        "Kafka input adapter may not have both (modern) `topic` and (legacy) `topics`."
622                            .into(),
623                    );
624                }
625                if compat.topics.len() != 1 {
626                    return Err(format!(
627                        "Kafka input adapter must have exactly one topic (not {}).",
628                        compat.topics.len()
629                    ));
630                }
631                let start_from = if let Some(start_from) = compat.start_from {
632                    start_from
633                } else if let Some(auto_offset_reset) =
634                    compat.kafka_options.get("auto.offset.reset")
635                {
636                    match auto_offset_reset.as_str() {
637                        "smallest" | "earliest" | "beginning" => KafkaStartFromConfig::Earliest,
638                        "largest" | "latest" | "end" => KafkaStartFromConfig::Latest,
639                        _ => {
640                            return Err(format!(
641                                "Unrecognized value {auto_offset_reset:?} for `auto.offset.reset` in Kafka legacy input adapter configuration"
642                            ));
643                        }
644                    }
645                } else {
646                    KafkaStartFromConfig::default()
647                };
648                (compat.topics.pop().unwrap(), start_from)
649            } else if let Some(topic) = compat.topic {
650                // Modern mode. Forbid legacy settings.
651                if compat.fault_tolerance.is_some() {
652                    return Err("Kafka input adapter `fault_tolerance` setting is obsolete.".into());
653                }
654                if compat.kafka_service.is_some() {
655                    return Err("Kafka input adapter `kafka_service` setting is obsolete.".into());
656                }
657                (topic, compat.start_from.unwrap_or_default())
658            } else {
659                return Err("Kafka input adapter is missing required `topic` setting.".into());
660            };
661
662            for key in compat.kafka_options.keys() {
663                if !key.contains('.')
664                    && key != "debug"
665                    && key != "enabled_events"
666                    && key != "retries"
667                {
668                    return Err(format!(
669                        "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)."
670                    ));
671                }
672            }
673
674            Ok(Self {
675                topic,
676                kafka_options: compat.kafka_options,
677                log_level: compat.log_level,
678                group_join_timeout_secs: compat.group_join_timeout_secs,
679                poller_threads: compat.poller_threads,
680                start_from,
681                region: compat.region,
682                partitions: compat.partitions,
683                resume_earliest_if_data_expires: compat.resume_earliest_if_data_expires,
684                include_headers: compat.include_headers,
685                include_timestamp: compat.include_timestamp,
686                include_partition: compat.include_partition,
687                include_offset: compat.include_offset,
688                include_topic: compat.include_topic,
689                synchronize_partitions: compat.synchronize_partitions,
690            })
691        }
692    }
693}