Skip to main content

feldera_types/transport/
kafka.rs

1use anyhow::{Error as AnyError, Result as AnyResult, anyhow, bail};
2use regex::bytes::Regex;
3use serde::de::{Error, SeqAccess, Visitor};
4use serde::{Deserialize, Deserializer, Serialize};
5use serde_json::Value as JsonValue;
6use std::fmt::Formatter;
7use std::num::NonZeroUsize;
8use std::thread::available_parallelism;
9use std::{collections::BTreeMap, env};
10use utoipa::ToSchema;
11use uuid::Uuid;
12
13/// Configuration for reading data from Kafka topics with `InputTransport`.
14#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
15pub struct KafkaInputConfig {
16    /// Options passed directly to `rdkafka`.
17    ///
18    /// [`librdkafka` options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md)
19    /// used to configure the Kafka consumer.
20    ///
21    /// This input connector does not use consumer groups, so options related to
22    /// consumer groups are rejected, including:
23    ///
24    /// * `group.id`, if present, is ignored.
25    /// * `auto.offset.reset` (use `start_from` instead).
26    /// * "enable.auto.commit", if present, must be set to "false".
27    /// * "enable.auto.offset.store", if present, must be set to "false".
28    #[serde(flatten)]
29    pub kafka_options: BTreeMap<String, String>,
30
31    /// Topic to subscribe to.
32    pub topic: String,
33
34    /// The log level of the client.
35    ///
36    /// If not specified, the log level will be calculated based on the global
37    /// log level of the `log` crate.
38    pub log_level: Option<KafkaLogLevel>,
39
40    /// Maximum timeout in seconds to wait for the endpoint to join the Kafka
41    /// consumer group during initialization.
42    #[serde(default = "default_group_join_timeout_secs")]
43    pub group_join_timeout_secs: u32,
44
45    /// Set to 1 or more to fix the number of threads used to poll
46    /// `rdkafka`. Multiple threads can increase performance with small Kafka
47    /// messages; for large messages, one thread is enough. In either case, too
48    /// many threads can harm performance. If unset, the default is 3, which
49    /// helps with small messages but will not harm performance with large
50    /// messagee
51    pub poller_threads: Option<usize>,
52
53    /// Where to begin reading the topic.
54    #[serde(default, with = "crate::serde_via_value")]
55    pub start_from: KafkaStartFromConfig,
56
57    /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
58    pub region: Option<String>,
59
60    /// The list of Kafka partitions to read from.
61    ///
62    /// Only the specified partitions will be consumed. If this field is not set,
63    /// the connector will consume from all available partitions.
64    ///
65    /// If `start_from` is set to `offsets` and this field is provided, the
66    /// number of partitions must exactly match the number of offsets, and the
67    /// order of partitions must correspond to the order of offsets.
68    ///
69    /// If offsets are provided for all partitions, this field can be omitted.
70    pub partitions: Option<Vec<i32>>,
71
72    /// By default, if the input connector resumes from a checkpoint and the
73    /// data where it needs to resume has expired from the Kafka topic, the
74    /// input connector fails initialization and the pipeline will fail to start.
75    ///
76    /// Set this to true to change the behavior so that, if data is not
77    /// available on resume, the input connector starts from the earliest
78    /// offsets that are now available.
79    pub resume_earliest_if_data_expires: bool,
80
81    /// Whether to include Kafka headers in the record metadata.
82    ///
83    /// When `true`, Kafka message headers are available via the `CONNECTOR_METADATA()` function.
84    /// See <https://docs.feldera.com/connectors/sources/kafka#metadata> for details.
85    #[serde(default)]
86    pub include_headers: Option<bool>,
87
88    /// Whether to include Kafka message timestamp in the record metadata.
89    ///
90    /// When `true`, Kafka message timestamp is available via the `CONNECTOR_METADATA()` function.
91    /// See <https://docs.feldera.com/connectors/sources/kafka#metadata> for details.
92    #[serde(default)]
93    pub include_timestamp: Option<bool>,
94
95    /// Whether to include Kafka partition in the record metadata.
96    ///
97    /// When `true`, Kafka partition from which the message was read is available via the `CONNECTOR_METADATA()` function.
98    /// See <https://docs.feldera.com/connectors/sources/kafka#metadata> for details.
99    #[serde(default)]
100    pub include_partition: Option<bool>,
101
102    /// Whether to include Kafka message offset in the record metadata.
103    ///
104    /// When `true`, Kafka message offset is available via the `CONNECTOR_METADATA()` function.
105    /// See <https://docs.feldera.com/connectors/sources/kafka#metadata> for details.
106    #[serde(default)]
107    pub include_offset: Option<bool>,
108
109    /// Whether to include Kafka topic in the record metadata.
110    ///
111    /// When `true`, Kafka topic from which the message was read is available via the `CONNECTOR_METADATA()` function.
112    /// See <https://docs.feldera.com/connectors/sources/kafka#metadata> for details.
113    #[serde(default)]
114    pub include_topic: Option<bool>,
115
116    /// When lateness is enabled on a Feldera table, Feldera only produces
117    /// correct output if input arrives approximately in order within the bounds
118    /// of the lateness.  The Feldera Kafka input connector can reorder input
119    /// when there are multiple partitions:
120    ///
121    /// - If partitions start at different times, then reading all the
122    ///   partitions in parallel will naturally consume data out of order.
123    ///
124    /// - Even if they start at the same time, partitions might contain events
125    ///   at different rates.
126    ///
127    /// - Even if the partitions start at the same time and have the same number
128    ///   of events per unit time, if partitions are spread across brokers,
129    ///   different brokers may fetch data at different rates.
130    ///
131    /// - Even if all of the partitions are on a single broker, one cannot
132    ///   expect all of the partitions to naturally remain exactly in sync
133    ///   forever.
134    ///
135    /// Setting this option to `true` addresses the issue by synchronizing
136    /// ingestion across partitions, ingesting records in order of their Kafka
137    /// event timestamps.
138    ///
139    /// Pitfalls of this solution include:
140    ///
141    /// - Kafka event timestamps are not necessarily monotonically increasing
142    ///   even within a single partition.  If timestamps jump backward beyond
143    ///   the lateness, then this can also cause correctness problems.
144    ///
145    ///   (This can be avoided by keeping clocks on Kafka producers and brokers
146    ///   synchronized.)
147    ///
148    /// - If an event with a timestamp far in the future is added to a
149    ///   partition, that event, and all those that follow it, will never be
150    ///   processed.
151    ///
152    /// - If one or a few partitions have timestamps far behind the others, only
153    ///   those partitions will be processed until all the old events are
154    ///   processed.  (This is the flip side of the previous pitfall.)
155    ///
156    /// - One or more empty partitions will prevent any data from being
157    ///   processed at all, because there is no way to know the timestamp for
158    ///   the first event that will be added to that partition.
159    ///
160    /// - In a topic with `N` nonempty partitions, at least `N - 1` events will
161    ///   always be left unprocessed (one in each of `N - 1` partitions), because
162    ///   there is no way to know the timestamp for the next event to be added to
163    ///   the partition whose events have been completely processed.
164    #[serde(default)]
165    pub synchronize_partitions: bool,
166
167    /// Drop incoming messages whose Kafka headers do not satisfy this filter.
168    ///
169    /// The filter is a boolean expression (`and`, `or`, `not`) over regular
170    /// expression tests on individual header values (see [`HeaderFilter`]).
171    /// Messages that do not satisfy the filter are dropped before parsing and
172    /// never reach the pipeline.  When absent (the default), all messages are
173    /// admitted.
174    ///
175    /// Filtering is independent of `include_headers`: it works whether or not
176    /// the matched headers are also surfaced to SQL via `CONNECTOR_METADATA()`.
177    #[serde(default, with = "crate::serde_via_value")]
178    pub header_filter: Option<HeaderFilter>,
179}
180
181impl KafkaInputConfig {
182    /// Returns a default [KafkaInputConfig] with the given `kafka_options` and
183    /// `topic`.  To be a usable configuration, `kafka_options` must contain at
184    /// least `bootstrap.servers`.
185    pub fn default(kafka_options: BTreeMap<String, String>, topic: impl Into<String>) -> Self {
186        Self {
187            kafka_options,
188            topic: topic.into(),
189            log_level: None,
190            group_join_timeout_secs: default_group_join_timeout_secs(),
191            poller_threads: None,
192            start_from: KafkaStartFromConfig::default(),
193            region: None,
194            partitions: None,
195            resume_earliest_if_data_expires: false,
196            include_headers: None,
197            include_timestamp: None,
198            include_partition: None,
199            include_offset: None,
200            include_topic: None,
201            synchronize_partitions: false,
202            header_filter: None,
203        }
204    }
205
206    // Returns the number of threads to use based on configuration, defaults,
207    // and system resources.
208    pub fn poller_threads(&self) -> usize {
209        let max_threads = available_parallelism().map_or(16, NonZeroUsize::get);
210        self.poller_threads.unwrap_or(3).clamp(1, max_threads)
211    }
212
213    pub fn metadata_requested(&self) -> bool {
214        self.include_topic == Some(true)
215            || self.include_timestamp == Some(true)
216            || self.include_partition == Some(true)
217            || self.include_offset == Some(true)
218            || self.include_headers == Some(true)
219    }
220}
221
222impl<'de> Deserialize<'de> for KafkaInputConfig {
223    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
224    where
225        D: Deserializer<'de>,
226    {
227        let compat = compat::KafkaInputConfigCompat::deserialize(deserializer)?;
228        Self::try_from(compat).map_err(D::Error::custom)
229    }
230}
231
232/// Maximum nesting depth of a [`HeaderFilter`], to bound recursion during
233/// compilation and evaluation.
234const MAX_HEADER_FILTER_DEPTH: usize = 64;
235
236/// A boolean filter over the headers of a Kafka message.
237///
238/// The Kafka input connector uses this to drop messages whose headers do not
239/// satisfy a predicate.  It is a tree of boolean operators (`and`, `or`, `not`)
240/// whose leaves are regular expression tests on individual header values.  It
241/// serializes as an externally tagged JSON object, for example:
242///
243/// ```json
244/// {
245///   "and": [
246///     { "header": { "name": "event-type", "pattern": "created|updated" } },
247///     { "not": { "header": { "name": "source", "pattern": "test-.*" } } }
248///   ]
249/// }
250/// ```
251///
252/// This admits a message only if it has an `event-type` header valued exactly
253/// `created` or `updated` and does not have a `source` header whose value
254/// starts with `test-`.
255#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
256#[serde(rename_all = "snake_case")]
257pub enum HeaderFilter {
258    /// Leaf test: matches when the message has a header named
259    /// [`HeaderMatch::name`] whose value matches [`HeaderMatch::pattern`].
260    Header(HeaderMatch),
261
262    /// Conjunction: matches when every nested filter matches.  Must have at
263    /// least one operand.
264    And(Vec<HeaderFilter>),
265
266    /// Disjunction: matches when at least one nested filter matches.  Must have
267    /// at least one operand.
268    Or(Vec<HeaderFilter>),
269
270    /// Negation: matches when the nested filter does not match.
271    Not(Box<HeaderFilter>),
272}
273
274/// A leaf of a [`HeaderFilter`]: a regular expression tested against the value
275/// of a named Kafka header.
276#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
277pub struct HeaderMatch {
278    /// Name of the header to test, matched exactly against the header key.
279    pub name: String,
280
281    /// Regular expression ([Rust `regex` crate
282    /// syntax](https://docs.rs/regex/latest/regex/#syntax)) tested against the
283    /// header value.
284    ///
285    /// The value is matched as raw bytes, so non-UTF-8 values and byte patterns
286    /// work.  The pattern must match the *entire* value: it is anchored
287    /// automatically, so `^`/`$` are unnecessary (though harmless).  A header
288    /// present with a null value is matched as an empty byte sequence; a header
289    /// that appears more than once matches if any of its values match.
290    pub pattern: String,
291}
292
293impl HeaderFilter {
294    /// Validate the filter without retaining the compiled form: rejects empty
295    /// `and`/`or`, nesting deeper than `MAX_HEADER_FILTER_DEPTH`, and invalid
296    /// leaf patterns.
297    pub fn validate(&self) -> AnyResult<()> {
298        self.compile().map(|_| ())
299    }
300
301    /// Compile into a [`CompiledHeaderFilter`] ready for evaluation, compiling
302    /// each leaf regular expression exactly once.  Returns an error for the same
303    /// conditions as [`HeaderFilter::validate`].
304    pub fn compile(&self) -> AnyResult<CompiledHeaderFilter> {
305        Ok(CompiledHeaderFilter(self.compile_node(1)?))
306    }
307
308    fn compile_node(&self, depth: usize) -> AnyResult<CompiledNode> {
309        if depth > MAX_HEADER_FILTER_DEPTH {
310            bail!("Kafka header filter is nested more than {MAX_HEADER_FILTER_DEPTH} levels deep");
311        }
312        match self {
313            HeaderFilter::Header(HeaderMatch { name, pattern }) => {
314                // Anchor to the whole value so the pattern matches the entire
315                // header value rather than a substring.  The non-capturing group
316                // keeps any top-level alternation inside `pattern` bounded.
317                let regex = Regex::new(&format!(r"\A(?:{pattern})\z")).map_err(|error| {
318                    anyhow!(
319                        "invalid regular expression {pattern:?} for Kafka header {name:?}: {error}"
320                    )
321                })?;
322                Ok(CompiledNode::Header {
323                    name: name.clone(),
324                    regex,
325                })
326            }
327            HeaderFilter::And(children) => {
328                if children.is_empty() {
329                    bail!("Kafka header filter 'and' must have at least one operand");
330                }
331                Ok(CompiledNode::And(Self::compile_children(children, depth)?))
332            }
333            HeaderFilter::Or(children) => {
334                if children.is_empty() {
335                    bail!("Kafka header filter 'or' must have at least one operand");
336                }
337                Ok(CompiledNode::Or(Self::compile_children(children, depth)?))
338            }
339            HeaderFilter::Not(child) => {
340                Ok(CompiledNode::Not(Box::new(child.compile_node(depth + 1)?)))
341            }
342        }
343    }
344
345    fn compile_children(children: &[HeaderFilter], depth: usize) -> AnyResult<Vec<CompiledNode>> {
346        children.iter().map(|c| c.compile_node(depth + 1)).collect()
347    }
348}
349
350/// A [`HeaderFilter`] compiled for evaluation.  Holds the leaf regular
351/// expressions compiled once so that matching a message allocates nothing.
352#[derive(Debug)]
353pub struct CompiledHeaderFilter(CompiledNode);
354
355#[derive(Debug)]
356enum CompiledNode {
357    Header { name: String, regex: Regex },
358    And(Vec<CompiledNode>),
359    Or(Vec<CompiledNode>),
360    Not(Box<CompiledNode>),
361}
362
363impl CompiledHeaderFilter {
364    /// Evaluate the filter against a message's headers.
365    ///
366    /// `headers` lists the message's `(key, value)` pairs in order.  A `None`
367    /// value denotes a header present with a null value and is matched as an
368    /// empty byte sequence.  Returns `true` if the message satisfies the filter
369    /// and should be admitted.
370    pub fn matches(&self, headers: &[(&str, Option<&[u8]>)]) -> bool {
371        self.0.matches(headers)
372    }
373}
374
375impl CompiledNode {
376    fn matches(&self, headers: &[(&str, Option<&[u8]>)]) -> bool {
377        match self {
378            CompiledNode::Header { name, regex } => headers
379                .iter()
380                .any(|&(key, value)| key == name.as_str() && regex.is_match(value.unwrap_or(b""))),
381            CompiledNode::And(children) => children.iter().all(|c| c.matches(headers)),
382            CompiledNode::Or(children) => children.iter().any(|c| c.matches(headers)),
383            CompiledNode::Not(child) => !child.matches(headers),
384        }
385    }
386}
387
388/// Where to begin reading a Kafka topic.
389#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
390#[serde(rename_all = "snake_case")]
391pub enum KafkaStartFromConfig {
392    /// Start from the beginning of the topic.
393    Earliest,
394
395    /// Start from the current end of the topic.
396    ///
397    /// This will only read any data that is added to the topic after the
398    /// connector initializes.
399    #[default]
400    Latest,
401
402    /// Start from particular offsets in the topic.
403    ///
404    /// The number of offsets must match the number of partitions in the topic.
405    Offsets(Vec<i64>),
406
407    /// Start from a particular timestamp in the topic.
408    ///
409    /// Kafka timestamps are in milliseconds since the epoch.
410    Timestamp(i64),
411}
412
413/// Kafka logging levels.
414#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ToSchema)]
415pub enum KafkaLogLevel {
416    #[serde(rename = "emerg")]
417    Emerg,
418    #[serde(rename = "alert")]
419    Alert,
420    #[serde(rename = "critical")]
421    Critical,
422    #[serde(rename = "error")]
423    Error,
424    #[serde(rename = "warning")]
425    Warning,
426    #[serde(rename = "notice")]
427    Notice,
428    #[serde(rename = "info")]
429    Info,
430    #[serde(rename = "debug")]
431    Debug,
432}
433
434/// On startup, the endpoint waits to join the consumer group.
435/// This constant defines the default wait timeout.
436pub const fn default_group_join_timeout_secs() -> u32 {
437    10
438}
439
440impl KafkaInputConfig {
441    /// Set `option` to `val`; return an error if `option` is set to a different
442    /// value.
443    #[allow(dead_code)]
444    fn enforce_option(&mut self, option: &str, val: &str) -> AnyResult<()> {
445        let option_val = self
446            .kafka_options
447            .entry(option.to_string())
448            .or_insert_with(|| val.to_string());
449        if option_val != val {
450            Err(AnyError::msg(
451                "cannot override '{option}' option: the Kafka transport adapter sets this option to '{val}'",
452            ))?;
453        }
454        Ok(())
455    }
456
457    /// Set `option` to `val`, if missing.
458    fn set_option_if_missing(&mut self, option: &str, val: &str) {
459        self.kafka_options
460            .entry(option.to_string())
461            .or_insert_with(|| val.to_string());
462    }
463
464    /// Validate configuration, set default option values required by this
465    /// adapter.
466    pub fn validate(&mut self) -> AnyResult<()> {
467        self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
468
469        // These options will prevent librdkafka from automatically committing offsets
470        // of consumed messages to the broker, meaning that next time the
471        // connector is instantiated it will start reading from the offset
472        // specified in `auto.offset.reset`.  We used to set these to
473        // `true`, which caused `rdkafka` to hang in some circumstances
474        // (https://github.com/confluentinc/librdkafka/issues/3954).  Besides, the new behavior
475        // is probably more correct given that circuit state currently does not survive
476        // across pipeline restarts, so it makes sense to start feeding messages
477        // from the start rather than from the last offset consumed by the
478        // previous instance of the pipeline, whose state is lost.  Once we add
479        // fault tolerance, we will likely use explicit commits, which also do
480        // not require these options.
481        //
482        // See https://docs.confluent.io/platform/current/clients/consumer.html#offset-management
483        //
484        // Note: we allow the user to override the options, so they can still enable
485        // auto commit if they know what they are doing, e.g., the secops demo
486        // requires the pipeline to commit its offset for the generator to know
487        // when to resume sending.
488        self.set_option_if_missing("enable.auto.commit", "false");
489        self.set_option_if_missing("enable.auto.offset.store", "false");
490
491        let group_id = format!("{}", Uuid::now_v7());
492        self.set_option_if_missing("group.id", &group_id);
493        self.set_option_if_missing("enable.partition.eof", "false");
494
495        // We link with openssl statically, which means that the default OPENSSLDIR location
496        // baked into openssl is not correct (see https://github.com/fede1024/rust-rdkafka/issues/594).
497        // We set the ssl.ca.location to "probe" so that librdkafka can find the CA certificates in a
498        // standard location (e.g., /etc/ssl/).
499        self.set_option_if_missing("ssl.ca.location", "probe");
500
501        // Enable client context `stats` callback so we can periodically check
502        // up on librdkafka memory usage.
503        self.set_option_if_missing("statistics.interval.ms", "10000");
504
505        if let (Some(partitions), KafkaStartFromConfig::Offsets(offsets)) =
506            (&self.partitions, &self.start_from)
507            && partitions.len() != offsets.len()
508        {
509            anyhow::bail!(
510                "the number of partitions ('{partitions:?}') should be equal to the number of offsets '{offsets:?}' specified"
511            )
512        }
513
514        // Reject malformed filters (empty `and`/`or`, excessive nesting, or an
515        // invalid regular expression) at configuration time rather than when the
516        // connector starts.
517        if let Some(header_filter) = &self.header_filter {
518            header_filter.validate()?;
519        }
520
521        Ok(())
522    }
523}
524
525pub fn default_redpanda_server() -> String {
526    env::var("REDPANDA_BROKERS").unwrap_or_else(|_| "localhost".to_string())
527}
528
529const fn default_initialization_timeout_secs() -> u32 {
530    60
531}
532
533/// Kafka header value encoded as a UTF-8 string or a byte array.
534#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
535#[repr(transparent)]
536pub struct KafkaHeaderValue(pub Vec<u8>);
537
538/// Visitor for deserializing Kafka headers value.
539struct HeaderVisitor;
540
541impl<'de> Visitor<'de> for HeaderVisitor {
542    type Value = KafkaHeaderValue;
543
544    fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
545        formatter.write_str("a string (e.g., \"xyz\") or a byte array (e.g., '[1,2,3])")
546    }
547
548    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
549    where
550        E: Error,
551    {
552        Ok(KafkaHeaderValue(v.as_bytes().to_owned()))
553    }
554
555    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
556    where
557        E: Error,
558    {
559        Ok(KafkaHeaderValue(v.into_bytes()))
560    }
561
562    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
563    where
564        A: SeqAccess<'de>,
565    {
566        let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
567
568        while let Some(b) = seq.next_element()? {
569            result.push(b);
570        }
571
572        Ok(KafkaHeaderValue(result))
573    }
574}
575
576impl<'de> Deserialize<'de> for KafkaHeaderValue {
577    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
578    where
579        D: Deserializer<'de>,
580    {
581        deserializer.deserialize_any(HeaderVisitor)
582    }
583}
584
585#[cfg(test)]
586#[test]
587fn test_kafka_header_value_deserialize() {
588    assert_eq!(
589        serde_json::from_str::<KafkaHeaderValue>(r#""foobar""#).unwrap(),
590        KafkaHeaderValue(br#"foobar"#.to_vec())
591    );
592
593    assert_eq!(
594        serde_json::from_str::<KafkaHeaderValue>(r#"[1,2,3,4,5]"#).unwrap(),
595        KafkaHeaderValue(vec![1u8, 2, 3, 4, 5])
596    );
597
598    assert!(serde_json::from_str::<KafkaHeaderValue>(r#"150"#).is_err());
599
600    assert!(serde_json::from_str::<KafkaHeaderValue>(r#"{{"foo": "bar"}}"#).is_err());
601}
602
603/// Kafka message header.
604#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
605pub struct KafkaHeader {
606    pub key: String,
607    pub value: Option<KafkaHeaderValue>,
608}
609
610/// Configuration for writing data to a Kafka topic with `OutputTransport`.
611#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
612pub struct KafkaOutputConfig {
613    /// Options passed directly to `rdkafka`.
614    ///
615    /// See [`librdkafka` options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md)
616    /// used to configure the Kafka producer.
617    #[serde(flatten)]
618    pub kafka_options: BTreeMap<String, String>,
619
620    /// Topic to write to.
621    pub topic: String,
622
623    /// Kafka headers to be added to each message produced by this connector.
624    #[serde(default)]
625    pub headers: Vec<KafkaHeader>,
626
627    /// The log level of the client.
628    ///
629    /// If not specified, the log level will be calculated based on the global
630    /// log level of the `log` crate.
631    pub log_level: Option<KafkaLogLevel>,
632
633    /// Maximum timeout in seconds to wait for the endpoint to connect to
634    /// a Kafka broker.
635    ///
636    /// Defaults to 60.
637    #[serde(default = "default_initialization_timeout_secs")]
638    pub initialization_timeout_secs: u32,
639
640    /// Optional configuration for fault tolerance.
641    pub fault_tolerance: Option<KafkaOutputFtConfig>,
642
643    /// If specified, this service is used to provide defaults for the Kafka options.
644    pub kafka_service: Option<String>,
645
646    /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
647    pub region: Option<String>,
648}
649
650/// Fault tolerance configuration for Kafka output connector.
651#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
652#[serde(default)]
653pub struct KafkaOutputFtConfig {
654    /// Options passed to `rdkafka` for consumers only, as documented at
655    /// [`librdkafka`
656    /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
657    ///
658    /// These options override `kafka_options` for consumers, and may be empty.
659    pub consumer_options: BTreeMap<String, String>,
660
661    /// Options passed to `rdkafka` for producers only, as documented at
662    /// [`librdkafka`
663    /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
664    ///
665    /// These options override `kafka_options` for producers, and may be empty.
666    pub producer_options: BTreeMap<String, String>,
667}
668
669impl KafkaOutputConfig {
670    #[allow(dead_code)]
671    /// Set `option` to `val`, if missing.
672    fn set_option_if_missing(&mut self, option: &str, val: &str) {
673        self.kafka_options
674            .entry(option.to_string())
675            .or_insert_with(|| val.to_string());
676    }
677
678    #[allow(dead_code)]
679    /// Validate configuration, set default option values required by this
680    /// adapter.
681    pub fn validate(&mut self) -> AnyResult<()> {
682        self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
683
684        // We link with openssl statically, which means that the default OPENSSLDIR location
685        // baked into openssl is not correct (see https://github.com/fede1024/rust-rdkafka/issues/594).
686        // We set the ssl.ca.location to "probe" so that librdkafka can find the CA certificates in a
687        // standard location (e.g., /etc/ssl/).
688        self.set_option_if_missing("ssl.ca.location", "probe");
689
690        // Enable client context `stats` callback so we can periodically check
691        // up on librdkafka memory usage.
692        self.set_option_if_missing("statistics.interval.ms", "10000");
693
694        Ok(())
695    }
696}
697
698/// A set of updates to a SQL table or view.
699///
700/// The `sequence_number` field stores the offset of the chunk relative to the
701/// start of the stream and can be used to implement reliable delivery.
702/// The payload is stored in the `bin_data`, `text_data`, or `json_data` field
703/// depending on the data format used.
704#[derive(Deserialize, ToSchema)]
705pub struct Chunk {
706    pub sequence_number: u64,
707
708    // Exactly one of the following fields must be set.
709    // This should be an enum inlined with `#[serde(flatten)]`, but `utoipa`
710    // struggles to generate a schema for that.
711    /// Base64 encoded binary payload, e.g., bincode.
712    pub bin_data: Option<Vec<u8>>,
713
714    /// Text payload, e.g., CSV.
715    pub text_data: Option<String>,
716
717    /// JSON payload.
718    #[schema(value_type = Option<Object>)]
719    pub json_data: Option<JsonValue>,
720}
721
722mod compat {
723    use std::collections::BTreeMap;
724
725    use serde::Deserialize;
726
727    use crate::transport::kafka::{KafkaLogLevel, KafkaStartFromConfig};
728
729    #[derive(Deserialize)]
730    pub struct KafkaInputConfigCompat {
731        /// Current, long-standing configuration option.
732        log_level: Option<KafkaLogLevel>,
733
734        /// Current, long-standing configuration option.
735        #[serde(default = "super::default_group_join_timeout_secs")]
736        group_join_timeout_secs: u32,
737
738        /// Current configuration option.
739        poller_threads: Option<usize>,
740
741        /// Current configuration option, which changed type in an incompatible
742        /// way soon after it was introduced. No backward compatibility for the
743        /// initial form.
744        #[serde(default, with = "crate::serde_via_value")]
745        start_from: Option<KafkaStartFromConfig>,
746
747        /// Current configuration option that replaces the old `topics`
748        /// option. Currently mandatory.
749        topic: Option<String>,
750
751        /// Old form of `topic`. Currently accepted as a substitute as long as
752        /// it has exactly one element.
753        #[serde(default)]
754        topics: Vec<String>,
755
756        /// Legacy, now ignored.
757        fault_tolerance: Option<String>,
758
759        /// Legacy, now ignored.
760        kafka_service: Option<String>,
761
762        /// Options passed directly to `rdkafka`.
763        #[serde(flatten)]
764        kafka_options: BTreeMap<String, String>,
765
766        /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
767        region: Option<String>,
768
769        /// The Kafka partitions to read from.
770        partitions: Option<Vec<i32>>,
771
772        /// By default, if the input connector resumes from a checkpoint and the
773        /// data where it needs to resume has expired from the Kafka topic, the
774        /// input connector fails the pipeline.
775        ///
776        /// Set this to true to change the behavior so that, if data is not
777        /// available on resume, the input connector starts from the earliest
778        /// offsets that are now available.
779        #[serde(default)]
780        pub resume_earliest_if_data_expires: bool,
781
782        include_headers: Option<bool>,
783        include_timestamp: Option<bool>,
784        include_partition: Option<bool>,
785        include_offset: Option<bool>,
786        include_topic: Option<bool>,
787        #[serde(default)]
788        synchronize_partitions: bool,
789        #[serde(default, with = "crate::serde_via_value")]
790        header_filter: Option<super::HeaderFilter>,
791    }
792
793    impl TryFrom<KafkaInputConfigCompat> for super::KafkaInputConfig {
794        type Error = String;
795
796        fn try_from(mut compat: KafkaInputConfigCompat) -> Result<Self, Self::Error> {
797            let (topic, start_from) = if !compat.topics.is_empty() {
798                // Legacy mode. Convert to modern form.
799                if compat.topic.is_some() {
800                    return Err(
801                        "Kafka input adapter may not have both (modern) `topic` and (legacy) `topics`."
802                            .into(),
803                    );
804                }
805                if compat.topics.len() != 1 {
806                    return Err(format!(
807                        "Kafka input adapter must have exactly one topic (not {}).",
808                        compat.topics.len()
809                    ));
810                }
811                let start_from = if let Some(start_from) = compat.start_from {
812                    start_from
813                } else if let Some(auto_offset_reset) =
814                    compat.kafka_options.get("auto.offset.reset")
815                {
816                    match auto_offset_reset.as_str() {
817                        "smallest" | "earliest" | "beginning" => KafkaStartFromConfig::Earliest,
818                        "largest" | "latest" | "end" => KafkaStartFromConfig::Latest,
819                        _ => {
820                            return Err(format!(
821                                "Unrecognized value {auto_offset_reset:?} for `auto.offset.reset` in Kafka legacy input adapter configuration"
822                            ));
823                        }
824                    }
825                } else {
826                    KafkaStartFromConfig::default()
827                };
828                (compat.topics.pop().unwrap(), start_from)
829            } else if let Some(topic) = compat.topic {
830                // Modern mode. Forbid legacy settings.
831                if compat.fault_tolerance.is_some() {
832                    return Err("Kafka input adapter `fault_tolerance` setting is obsolete.".into());
833                }
834                if compat.kafka_service.is_some() {
835                    return Err("Kafka input adapter `kafka_service` setting is obsolete.".into());
836                }
837                (topic, compat.start_from.unwrap_or_default())
838            } else {
839                return Err("Kafka input adapter is missing required `topic` setting.".into());
840            };
841
842            for key in compat.kafka_options.keys() {
843                if !key.contains('.')
844                    && key != "debug"
845                    && key != "enabled_events"
846                    && key != "retries"
847                {
848                    return Err(format!(
849                        "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)."
850                    ));
851                }
852            }
853
854            Ok(Self {
855                topic,
856                kafka_options: compat.kafka_options,
857                log_level: compat.log_level,
858                group_join_timeout_secs: compat.group_join_timeout_secs,
859                poller_threads: compat.poller_threads,
860                start_from,
861                region: compat.region,
862                partitions: compat.partitions,
863                resume_earliest_if_data_expires: compat.resume_earliest_if_data_expires,
864                include_headers: compat.include_headers,
865                include_timestamp: compat.include_timestamp,
866                include_partition: compat.include_partition,
867                include_offset: compat.include_offset,
868                include_topic: compat.include_topic,
869                synchronize_partitions: compat.synchronize_partitions,
870                header_filter: compat.header_filter,
871            })
872        }
873    }
874}
875
876#[cfg(test)]
877mod header_filter_tests {
878    use super::{HeaderFilter, KafkaInputConfig, MAX_HEADER_FILTER_DEPTH};
879    use std::collections::BTreeMap;
880
881    /// Compile the filter described by `json` and evaluate it against `headers`.
882    fn admits(json: &str, headers: &[(&str, Option<&[u8]>)]) -> bool {
883        let filter: HeaderFilter = serde_json::from_str(json).unwrap();
884        filter.compile().unwrap().matches(headers)
885    }
886
887    #[test]
888    fn leaf_matches_whole_value() {
889        let f = r#"{"header": {"name": "type", "pattern": "created|updated"}}"#;
890        assert!(admits(f, &[("type", Some(&b"created"[..]))]));
891        assert!(admits(f, &[("type", Some(&b"updated"[..]))]));
892
893        // Patterns are anchored to the whole value: a substring must not match.
894        assert!(!admits(f, &[("type", Some(&b"created-x"[..]))]));
895        assert!(!admits(f, &[("type", Some(&b"x-created"[..]))]));
896
897        // Wrong value, wrong header name, and missing header all fail a leaf.
898        assert!(!admits(f, &[("type", Some(&b"deleted"[..]))]));
899        assert!(!admits(f, &[("other", Some(&b"created"[..]))]));
900        assert!(!admits(f, &[]));
901    }
902
903    #[test]
904    fn null_value_is_empty_bytes() {
905        let empty = r#"{"header": {"name": "h", "pattern": ""}}"#;
906        let nonempty = r#"{"header": {"name": "h", "pattern": ".+"}}"#;
907
908        // A header with a null value matches an empty pattern but not `.+`.
909        assert!(admits(empty, &[("h", None)]));
910        assert!(!admits(nonempty, &[("h", None)]));
911        assert!(admits(empty, &[("h", Some(&b""[..]))]));
912    }
913
914    #[test]
915    fn duplicate_header_any_value_matches() {
916        let f = r#"{"header": {"name": "k", "pattern": "b"}}"#;
917        assert!(admits(f, &[("k", Some(&b"a"[..])), ("k", Some(&b"b"[..]))]));
918        assert!(!admits(
919            f,
920            &[("k", Some(&b"a"[..])), ("k", Some(&b"c"[..]))]
921        ));
922    }
923
924    #[test]
925    fn non_utf8_value_bytes() {
926        // A single-byte match against a non-UTF-8 value must work without panic.
927        let f = r#"{"header": {"name": "b", "pattern": "(?s-u:.)"}}"#;
928        assert!(admits(f, &[("b", Some(&[0xffu8][..]))]));
929        // Anchoring still applies: two bytes do not match a single-byte pattern.
930        assert!(!admits(f, &[("b", Some(&[0xffu8, 0xfe][..]))]));
931    }
932
933    #[test]
934    fn boolean_combinations() {
935        // A AND (B OR C).
936        let f = r#"{"and": [
937            {"header": {"name": "a", "pattern": "1"}},
938            {"or": [
939                {"header": {"name": "b", "pattern": "1"}},
940                {"header": {"name": "c", "pattern": "1"}}
941            ]}
942        ]}"#;
943        assert!(admits(f, &[("a", Some(&b"1"[..])), ("b", Some(&b"1"[..]))]));
944        assert!(admits(f, &[("a", Some(&b"1"[..])), ("c", Some(&b"1"[..]))]));
945        assert!(!admits(f, &[("a", Some(&b"1"[..]))])); // neither b nor c
946        assert!(!admits(f, &[("b", Some(&b"1"[..]))])); // missing a
947    }
948
949    #[test]
950    fn not_over_leaf() {
951        let f = r#"{"not": {"header": {"name": "env", "pattern": "prod"}}}"#;
952        assert!(!admits(f, &[("env", Some(&b"prod"[..]))])); // matching -> dropped
953        assert!(admits(f, &[("env", Some(&b"dev"[..]))])); // non-matching -> admitted
954        assert!(admits(f, &[])); // absent header -> admitted
955    }
956
957    #[test]
958    fn de_morgan_equivalence() {
959        let lhs = r#"{"not": {"and": [
960            {"header": {"name": "a", "pattern": "1"}},
961            {"header": {"name": "b", "pattern": "1"}}
962        ]}}"#;
963        let rhs = r#"{"or": [
964            {"not": {"header": {"name": "a", "pattern": "1"}}},
965            {"not": {"header": {"name": "b", "pattern": "1"}}}
966        ]}"#;
967        let l = serde_json::from_str::<HeaderFilter>(lhs)
968            .unwrap()
969            .compile()
970            .unwrap();
971        let r = serde_json::from_str::<HeaderFilter>(rhs)
972            .unwrap()
973            .compile()
974            .unwrap();
975        for a in [None, Some(&b"1"[..])] {
976            for b in [None, Some(&b"1"[..])] {
977                let mut headers: Vec<(&str, Option<&[u8]>)> = Vec::new();
978                if let Some(v) = a {
979                    headers.push(("a", Some(v)));
980                }
981                if let Some(v) = b {
982                    headers.push(("b", Some(v)));
983                }
984                assert_eq!(
985                    l.matches(&headers),
986                    r.matches(&headers),
987                    "headers={headers:?}"
988                );
989            }
990        }
991    }
992
993    #[test]
994    fn rejects_empty_combinators() {
995        for json in [r#"{"and": []}"#, r#"{"or": []}"#] {
996            let filter: HeaderFilter = serde_json::from_str(json).unwrap();
997            assert!(filter.validate().is_err(), "expected {json} to be rejected");
998        }
999    }
1000
1001    #[test]
1002    fn rejects_deep_nesting() {
1003        // Wrap a leaf in `not` more times than the depth limit allows.
1004        let mut json = String::from(r#"{"header": {"name": "x", "pattern": "y"}}"#);
1005        for _ in 0..MAX_HEADER_FILTER_DEPTH + 5 {
1006            json = format!(r#"{{"not": {json}}}"#);
1007        }
1008        let filter: HeaderFilter = serde_json::from_str(&json).unwrap();
1009        assert!(filter.validate().is_err());
1010    }
1011
1012    #[test]
1013    fn rejects_invalid_regex() {
1014        let filter: HeaderFilter =
1015            serde_json::from_str(r#"{"header": {"name": "x", "pattern": "("}}"#).unwrap();
1016        assert!(filter.validate().is_err());
1017    }
1018
1019    #[test]
1020    fn serde_round_trip_external_tagging() {
1021        let json = r#"{"and":[{"header":{"name":"t","pattern":"a|b"}},{"not":{"header":{"name":"s","pattern":"x"}}}]}"#;
1022        let filter: HeaderFilter = serde_json::from_str(json).unwrap();
1023        let reserialized = serde_json::to_string(&filter).unwrap();
1024        assert_eq!(reserialized, json);
1025    }
1026
1027    #[test]
1028    fn config_validate_rejects_bad_filter() {
1029        let mut config = KafkaInputConfig::default(BTreeMap::new(), "topic");
1030        config.header_filter = Some(serde_json::from_str(r#"{"or": []}"#).unwrap());
1031        assert!(config.validate().is_err());
1032    }
1033
1034    #[test]
1035    fn config_deserializes_header_filter() {
1036        // Exercises the compat deserialization path for the new field.
1037        let config: KafkaInputConfig = serde_json::from_value(serde_json::json!({
1038            "topic": "t",
1039            "bootstrap.servers": "localhost:9092",
1040            "header_filter": {"header": {"name": "k", "pattern": "v"}}
1041        }))
1042        .unwrap();
1043        assert!(config.header_filter.is_some());
1044    }
1045
1046    #[test]
1047    fn config_with_header_filter_serializes_to_yaml() {
1048        // Regression: the pipeline config is serialized to YAML when a pipeline
1049        // is provisioned. `HeaderFilter` is a nested enum, which `serde_yaml`
1050        // cannot serialize directly; `serde_via_value` keeps this working.
1051        // Without it, the pipeline runner panics and the pipeline is stuck
1052        // provisioning.
1053        let mut config = KafkaInputConfig::default(
1054            BTreeMap::from([(
1055                "bootstrap.servers".to_string(),
1056                "localhost:9092".to_string(),
1057            )]),
1058            "topic",
1059        );
1060        config.header_filter = Some(
1061            serde_json::from_str(
1062                r#"{"and":[{"header":{"name":"a","pattern":"b"}},{"not":{"header":{"name":"c","pattern":"d"}}}]}"#,
1063            )
1064            .unwrap(),
1065        );
1066
1067        // Must not error (this is what panicked in the pipeline runner).
1068        let yaml = serde_yaml::to_string(&config).expect("serialize config to YAML");
1069
1070        // And the config round-trips back through YAML.
1071        let reparsed: KafkaInputConfig = serde_yaml::from_str(&yaml).unwrap();
1072        assert_eq!(reparsed.header_filter, config.header_filter);
1073    }
1074}