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
13use crate::{
14    duration::{ConfigDuration, LegacyUnit},
15    duration_setting,
16};
17
18duration_setting!(
19    duration_group_join_timeout,
20    "group_join_timeout",
21    LegacyUnit::Secs
22);
23duration_setting!(
24    duration_initialization_timeout,
25    "initialization_timeout",
26    LegacyUnit::Secs
27);
28
29/// Configuration for reading data from Kafka topics with `InputTransport`.
30#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
31pub struct KafkaInputConfig {
32    /// Options passed directly to `rdkafka`.
33    ///
34    /// [`librdkafka` options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md)
35    /// used to configure the Kafka consumer.
36    ///
37    /// This input connector does not use consumer groups, so options related to
38    /// consumer groups are rejected, including:
39    ///
40    /// * `group.id`, if present, is ignored.
41    /// * `auto.offset.reset` (use `start_from` instead).
42    /// * "enable.auto.commit", if present, must be set to "false".
43    /// * "enable.auto.offset.store", if present, must be set to "false".
44    #[serde(flatten)]
45    pub kafka_options: BTreeMap<String, String>,
46
47    /// Topic to subscribe to.
48    pub topic: String,
49
50    /// The log level of the client.
51    ///
52    /// If not specified, the log level will be calculated based on the global
53    /// log level of the `log` crate.
54    pub log_level: Option<KafkaLogLevel>,
55
56    /// Maximum time to wait for the endpoint to join the Kafka consumer group
57    /// during initialization, for example `10s`. Unset selects
58    /// the default, `DEFAULT_GROUP_JOIN_TIMEOUT`.
59    #[serde(
60        default,
61        alias = "group_join_timeout_secs",
62        deserialize_with = "duration_group_join_timeout",
63        skip_serializing_if = "Option::is_none"
64    )]
65    #[schema(value_type = Option<String>, default = default_group_join_timeout)]
66    pub group_join_timeout: Option<ConfigDuration>,
67
68    /// Set to 1 or more to fix the number of threads used to poll
69    /// `rdkafka`. Multiple threads can increase performance with small Kafka
70    /// messages; for large messages, one thread is enough. In either case, too
71    /// many threads can harm performance. If unset, the default is 3, which
72    /// helps with small messages but will not harm performance with large
73    /// messagee
74    pub poller_threads: Option<usize>,
75
76    /// Where to begin reading the topic.
77    #[serde(default, with = "crate::serde_via_value")]
78    pub start_from: KafkaStartFromConfig,
79
80    /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
81    pub region: Option<String>,
82
83    /// Identity provider used to mint SASL/OAUTHBEARER tokens.
84    ///
85    /// Skipped when serializing so that a manager that knows this field can
86    /// still drive an older runtime that does not: such a runtime folds the
87    /// unknown key into the flattened `kafka_options: BTreeMap<String, String>`
88    /// and rejects a null value.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub oauth_provider: Option<KafkaOauthProvider>,
91
92    /// The list of Kafka partitions to read from.
93    ///
94    /// Only the specified partitions will be consumed. If this field is not set,
95    /// the connector will consume from all available partitions.
96    ///
97    /// If `start_from` is set to `offsets` and this field is provided, the
98    /// number of partitions must exactly match the number of offsets, and the
99    /// order of partitions must correspond to the order of offsets.
100    ///
101    /// If offsets are provided for all partitions, this field can be omitted.
102    pub partitions: Option<Vec<i32>>,
103
104    /// By default, if the input connector resumes from a checkpoint and the
105    /// data where it needs to resume has expired from the Kafka topic, the
106    /// input connector fails initialization and the pipeline will fail to start.
107    ///
108    /// Set this to true to change the behavior so that, if data is not
109    /// available on resume, the input connector starts from the earliest
110    /// offsets that are now available.
111    pub resume_earliest_if_data_expires: bool,
112
113    /// Whether to include Kafka headers in the record metadata.
114    ///
115    /// When `true`, Kafka message headers are available via the `CONNECTOR_METADATA()` function.
116    /// See <https://docs.feldera.com/connectors/sources/kafka#metadata> for details.
117    #[serde(default)]
118    pub include_headers: Option<bool>,
119
120    /// Whether to include Kafka message timestamp in the record metadata.
121    ///
122    /// When `true`, Kafka message timestamp is available via the `CONNECTOR_METADATA()` function.
123    /// See <https://docs.feldera.com/connectors/sources/kafka#metadata> for details.
124    #[serde(default)]
125    pub include_timestamp: Option<bool>,
126
127    /// Whether to include Kafka partition in the record metadata.
128    ///
129    /// When `true`, Kafka partition from which the message was read is available via the `CONNECTOR_METADATA()` function.
130    /// See <https://docs.feldera.com/connectors/sources/kafka#metadata> for details.
131    #[serde(default)]
132    pub include_partition: Option<bool>,
133
134    /// Whether to include Kafka message offset in the record metadata.
135    ///
136    /// When `true`, Kafka message offset is available via the `CONNECTOR_METADATA()` function.
137    /// See <https://docs.feldera.com/connectors/sources/kafka#metadata> for details.
138    #[serde(default)]
139    pub include_offset: Option<bool>,
140
141    /// Whether to include Kafka topic in the record metadata.
142    ///
143    /// When `true`, Kafka topic from which the message was read is available via the `CONNECTOR_METADATA()` function.
144    /// See <https://docs.feldera.com/connectors/sources/kafka#metadata> for details.
145    #[serde(default)]
146    pub include_topic: Option<bool>,
147
148    /// When lateness is enabled on a Feldera table, Feldera only produces
149    /// correct output if input arrives approximately in order within the bounds
150    /// of the lateness.  The Feldera Kafka input connector can reorder input
151    /// when there are multiple partitions:
152    ///
153    /// - If partitions start at different times, then reading all the
154    ///   partitions in parallel will naturally consume data out of order.
155    ///
156    /// - Even if they start at the same time, partitions might contain events
157    ///   at different rates.
158    ///
159    /// - Even if the partitions start at the same time and have the same number
160    ///   of events per unit time, if partitions are spread across brokers,
161    ///   different brokers may fetch data at different rates.
162    ///
163    /// - Even if all of the partitions are on a single broker, one cannot
164    ///   expect all of the partitions to naturally remain exactly in sync
165    ///   forever.
166    ///
167    /// Setting this option to `true` addresses the issue by synchronizing
168    /// ingestion across partitions, ingesting records in order of their Kafka
169    /// event timestamps.
170    ///
171    /// Pitfalls of this solution include:
172    ///
173    /// - Kafka event timestamps are not necessarily monotonically increasing
174    ///   even within a single partition.  If timestamps jump backward beyond
175    ///   the lateness, then this can also cause correctness problems.
176    ///
177    ///   (This can be avoided by keeping clocks on Kafka producers and brokers
178    ///   synchronized.)
179    ///
180    /// - If an event with a timestamp far in the future is added to a
181    ///   partition, that event, and all those that follow it, will never be
182    ///   processed.
183    ///
184    /// - If one or a few partitions have timestamps far behind the others, only
185    ///   those partitions will be processed until all the old events are
186    ///   processed.  (This is the flip side of the previous pitfall.)
187    ///
188    /// - One or more empty partitions will prevent any data from being
189    ///   processed at all, because there is no way to know the timestamp for
190    ///   the first event that will be added to that partition.
191    ///
192    /// - In a topic with `N` nonempty partitions, at least `N - 1` events will
193    ///   always be left unprocessed (one in each of `N - 1` partitions), because
194    ///   there is no way to know the timestamp for the next event to be added to
195    ///   the partition whose events have been completely processed.
196    #[serde(default)]
197    pub synchronize_partitions: bool,
198
199    /// Drop incoming messages whose Kafka headers do not satisfy this filter.
200    ///
201    /// The filter is a boolean expression (`and`, `or`, `not`) over regular
202    /// expression tests on individual header values (see [`HeaderFilter`]).
203    /// Messages that do not satisfy the filter are dropped before parsing and
204    /// never reach the pipeline.  When absent (the default), all messages are
205    /// admitted.
206    ///
207    /// Filtering is independent of `include_headers`: it works whether or not
208    /// the matched headers are also surfaced to SQL via `CONNECTOR_METADATA()`.
209    #[serde(default, with = "crate::serde_via_value")]
210    pub header_filter: Option<HeaderFilter>,
211}
212
213impl KafkaInputConfig {
214    /// Returns a default [KafkaInputConfig] with the given `kafka_options` and
215    /// `topic`.  To be a usable configuration, `kafka_options` must contain at
216    /// least `bootstrap.servers`.
217    pub fn default(kafka_options: BTreeMap<String, String>, topic: impl Into<String>) -> Self {
218        Self {
219            kafka_options,
220            topic: topic.into(),
221            log_level: None,
222            group_join_timeout: None,
223            poller_threads: None,
224            start_from: KafkaStartFromConfig::default(),
225            region: None,
226            oauth_provider: None,
227            partitions: None,
228            resume_earliest_if_data_expires: false,
229            include_headers: None,
230            include_timestamp: None,
231            include_partition: None,
232            include_offset: None,
233            include_topic: None,
234            synchronize_partitions: false,
235            header_filter: None,
236        }
237    }
238
239    // Returns the number of threads to use based on configuration, defaults,
240    // and system resources.
241    pub fn poller_threads(&self) -> usize {
242        let max_threads = available_parallelism().map_or(16, NonZeroUsize::get);
243        self.poller_threads.unwrap_or(3).clamp(1, max_threads)
244    }
245
246    pub fn metadata_requested(&self) -> bool {
247        self.include_topic == Some(true)
248            || self.include_timestamp == Some(true)
249            || self.include_partition == Some(true)
250            || self.include_offset == Some(true)
251            || self.include_headers == Some(true)
252    }
253}
254
255impl<'de> Deserialize<'de> for KafkaInputConfig {
256    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
257    where
258        D: Deserializer<'de>,
259    {
260        let compat = compat::KafkaInputConfigCompat::deserialize(deserializer)?;
261        Self::try_from(compat).map_err(D::Error::custom)
262    }
263}
264
265/// Maximum nesting depth of a [`HeaderFilter`], to bound recursion during
266/// compilation and evaluation.
267const MAX_HEADER_FILTER_DEPTH: usize = 64;
268
269/// A boolean filter over the headers of a Kafka message.
270///
271/// The Kafka input connector uses this to drop messages whose headers do not
272/// satisfy a predicate.  It is a tree of boolean operators (`and`, `or`, `not`)
273/// whose leaves are regular expression tests on individual header values.  It
274/// serializes as an externally tagged JSON object, for example:
275///
276/// ```json
277/// {
278///   "and": [
279///     { "header": { "name": "event-type", "pattern": "created|updated" } },
280///     { "not": { "header": { "name": "source", "pattern": "test-.*" } } }
281///   ]
282/// }
283/// ```
284///
285/// This admits a message only if it has an `event-type` header valued exactly
286/// `created` or `updated` and does not have a `source` header whose value
287/// starts with `test-`.
288#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
289#[serde(rename_all = "snake_case")]
290pub enum HeaderFilter {
291    /// Leaf test: matches when the message has a header named
292    /// [`HeaderMatch::name`] whose value matches [`HeaderMatch::pattern`].
293    Header(HeaderMatch),
294
295    /// Conjunction: matches when every nested filter matches.  Must have at
296    /// least one operand.
297    And(Vec<HeaderFilter>),
298
299    /// Disjunction: matches when at least one nested filter matches.  Must have
300    /// at least one operand.
301    Or(Vec<HeaderFilter>),
302
303    /// Negation: matches when the nested filter does not match.
304    Not(Box<HeaderFilter>),
305}
306
307/// A leaf of a [`HeaderFilter`]: a regular expression tested against the value
308/// of a named Kafka header.
309#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
310pub struct HeaderMatch {
311    /// Name of the header to test, matched exactly against the header key.
312    pub name: String,
313
314    /// Regular expression ([Rust `regex` crate
315    /// syntax](https://docs.rs/regex/latest/regex/#syntax)) tested against the
316    /// header value.
317    ///
318    /// The value is matched as raw bytes, so non-UTF-8 values and byte patterns
319    /// work.  The pattern must match the *entire* value: it is anchored
320    /// automatically, so `^`/`$` are unnecessary (though harmless).  A header
321    /// present with a null value is matched as an empty byte sequence; a header
322    /// that appears more than once matches if any of its values match.
323    pub pattern: String,
324}
325
326impl HeaderFilter {
327    /// Validate the filter without retaining the compiled form: rejects empty
328    /// `and`/`or`, nesting deeper than `MAX_HEADER_FILTER_DEPTH`, and invalid
329    /// leaf patterns.
330    pub fn validate(&self) -> AnyResult<()> {
331        self.compile().map(|_| ())
332    }
333
334    /// Compile into a [`CompiledHeaderFilter`] ready for evaluation, compiling
335    /// each leaf regular expression exactly once.  Returns an error for the same
336    /// conditions as [`HeaderFilter::validate`].
337    pub fn compile(&self) -> AnyResult<CompiledHeaderFilter> {
338        Ok(CompiledHeaderFilter(self.compile_node(1)?))
339    }
340
341    fn compile_node(&self, depth: usize) -> AnyResult<CompiledNode> {
342        if depth > MAX_HEADER_FILTER_DEPTH {
343            bail!("Kafka header filter is nested more than {MAX_HEADER_FILTER_DEPTH} levels deep");
344        }
345        match self {
346            HeaderFilter::Header(HeaderMatch { name, pattern }) => {
347                // Anchor to the whole value so the pattern matches the entire
348                // header value rather than a substring.  The non-capturing group
349                // keeps any top-level alternation inside `pattern` bounded.
350                let regex = Regex::new(&format!(r"\A(?:{pattern})\z")).map_err(|error| {
351                    anyhow!(
352                        "invalid regular expression {pattern:?} for Kafka header {name:?}: {error}"
353                    )
354                })?;
355                Ok(CompiledNode::Header {
356                    name: name.clone(),
357                    regex,
358                })
359            }
360            HeaderFilter::And(children) => {
361                if children.is_empty() {
362                    bail!("Kafka header filter 'and' must have at least one operand");
363                }
364                Ok(CompiledNode::And(Self::compile_children(children, depth)?))
365            }
366            HeaderFilter::Or(children) => {
367                if children.is_empty() {
368                    bail!("Kafka header filter 'or' must have at least one operand");
369                }
370                Ok(CompiledNode::Or(Self::compile_children(children, depth)?))
371            }
372            HeaderFilter::Not(child) => {
373                Ok(CompiledNode::Not(Box::new(child.compile_node(depth + 1)?)))
374            }
375        }
376    }
377
378    fn compile_children(children: &[HeaderFilter], depth: usize) -> AnyResult<Vec<CompiledNode>> {
379        children.iter().map(|c| c.compile_node(depth + 1)).collect()
380    }
381}
382
383/// A [`HeaderFilter`] compiled for evaluation.  Holds the leaf regular
384/// expressions compiled once so that matching a message allocates nothing.
385#[derive(Debug)]
386pub struct CompiledHeaderFilter(CompiledNode);
387
388#[derive(Debug)]
389enum CompiledNode {
390    Header { name: String, regex: Regex },
391    And(Vec<CompiledNode>),
392    Or(Vec<CompiledNode>),
393    Not(Box<CompiledNode>),
394}
395
396impl CompiledHeaderFilter {
397    /// Evaluate the filter against a message's headers.
398    ///
399    /// `headers` lists the message's `(key, value)` pairs in order.  A `None`
400    /// value denotes a header present with a null value and is matched as an
401    /// empty byte sequence.  Returns `true` if the message satisfies the filter
402    /// and should be admitted.
403    pub fn matches(&self, headers: &[(&str, Option<&[u8]>)]) -> bool {
404        self.0.matches(headers)
405    }
406}
407
408impl CompiledNode {
409    fn matches(&self, headers: &[(&str, Option<&[u8]>)]) -> bool {
410        match self {
411            CompiledNode::Header { name, regex } => headers
412                .iter()
413                .any(|&(key, value)| key == name.as_str() && regex.is_match(value.unwrap_or(b""))),
414            CompiledNode::And(children) => children.iter().all(|c| c.matches(headers)),
415            CompiledNode::Or(children) => children.iter().any(|c| c.matches(headers)),
416            CompiledNode::Not(child) => !child.matches(headers),
417        }
418    }
419}
420
421/// Where to begin reading a Kafka topic.
422#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
423#[serde(rename_all = "snake_case")]
424pub enum KafkaStartFromConfig {
425    /// Start from the beginning of the topic.
426    Earliest,
427
428    /// Start from the current end of the topic.
429    ///
430    /// This will only read any data that is added to the topic after the
431    /// connector initializes.
432    #[default]
433    Latest,
434
435    /// Start from particular offsets in the topic.
436    ///
437    /// The number of offsets must match the number of partitions in the topic.
438    Offsets(Vec<i64>),
439
440    /// Start from a particular timestamp in the topic.
441    ///
442    /// Kafka timestamps are in milliseconds since the epoch.
443    Timestamp(i64),
444}
445
446/// Kafka logging levels.
447#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ToSchema)]
448pub enum KafkaLogLevel {
449    #[serde(rename = "emerg")]
450    Emerg,
451    #[serde(rename = "alert")]
452    Alert,
453    #[serde(rename = "critical")]
454    Critical,
455    #[serde(rename = "error")]
456    Error,
457    #[serde(rename = "warning")]
458    Warning,
459    #[serde(rename = "notice")]
460    Notice,
461    #[serde(rename = "info")]
462    Info,
463    #[serde(rename = "debug")]
464    Debug,
465}
466
467/// Identity provider used to mint SASL/OAUTHBEARER tokens for the Kafka
468/// broker.
469#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
470#[serde(rename_all = "snake_case")]
471pub enum KafkaOauthProvider {
472    /// Mint an AWS Signature V4 token to authenticate to AWS Managed
473    /// Streaming for Kafka (MSK).
474    ///
475    /// This is the default provider, for backward compatibility.  `region` must
476    /// be set, either directly or via the `AWS_REGION` environment variable.
477    #[default]
478    Aws,
479
480    /// Mint a Google OAuth2 access token to authenticate to GCP Managed
481    /// Service for Apache Kafka.
482    ///
483    /// The token is obtained from Application Default Credentials: a
484    /// service account key or user credentials file (as set up by, e.g.,
485    /// `gcloud auth application-default login`), or, failing that, the
486    /// GKE metadata server (which supplies credentials automatically when
487    /// Workload Identity is configured).
488    Gcp,
489}
490
491/// On startup, the endpoint waits to join the consumer group.
492/// This constant defines the default wait timeout.
493pub const DEFAULT_GROUP_JOIN_TIMEOUT: ConfigDuration = ConfigDuration::from_secs(10);
494
495/// Default time to wait for the endpoint to connect to a Kafka broker.
496pub const DEFAULT_INITIALIZATION_TIMEOUT: ConfigDuration = ConfigDuration::from_secs(60);
497
498/// Default `queued.max.messages.kbytes`, the prefetch limit for each partition.
499const DEFAULT_QUEUED_MAX_MESSAGES_KBYTES: u64 = 4096;
500
501/// Lowest default `fetch.max.bytes`, which is the librdkafka default.
502const MIN_DEFAULT_FETCH_MAX_BYTES: u64 = 52_428_800;
503
504/// Default `fetch.queue.backoff.ms`.
505const DEFAULT_FETCH_QUEUE_BACKOFF_MS: u64 = 10;
506
507// The defaults as the OpenAPI schema shows them, one function per
508// `#[schema(default = ...)]`.
509fn default_group_join_timeout() -> String {
510    DEFAULT_GROUP_JOIN_TIMEOUT.to_string()
511}
512fn default_initialization_timeout() -> String {
513    DEFAULT_INITIALIZATION_TIMEOUT.to_string()
514}
515
516impl KafkaInputConfig {
517    /// The consumer-group join timeout in effect, or
518    /// [`DEFAULT_GROUP_JOIN_TIMEOUT`].
519    pub fn group_join_timeout(&self) -> ConfigDuration {
520        self.group_join_timeout
521            .unwrap_or(DEFAULT_GROUP_JOIN_TIMEOUT)
522    }
523}
524
525impl KafkaOutputConfig {
526    /// The broker connection timeout in effect, or
527    /// [`DEFAULT_INITIALIZATION_TIMEOUT`].
528    pub fn initialization_timeout(&self) -> ConfigDuration {
529        self.initialization_timeout
530            .unwrap_or(DEFAULT_INITIALIZATION_TIMEOUT)
531    }
532}
533
534impl KafkaInputConfig {
535    /// Set `option` to `val`; return an error if `option` is set to a different
536    /// value.
537    #[allow(dead_code)]
538    fn enforce_option(&mut self, option: &str, val: &str) -> AnyResult<()> {
539        let option_val = self
540            .kafka_options
541            .entry(option.to_string())
542            .or_insert_with(|| val.to_string());
543        if option_val != val {
544            Err(AnyError::msg(
545                "cannot override '{option}' option: the Kafka transport adapter sets this option to '{val}'",
546            ))?;
547        }
548        Ok(())
549    }
550
551    /// Set `option` to `val`, if missing.
552    fn set_option_if_missing(&mut self, option: &str, val: &str) {
553        self.kafka_options
554            .entry(option.to_string())
555            .or_insert_with(|| val.to_string());
556    }
557
558    /// Validate configuration, set default option values required by this
559    /// adapter.
560    pub fn validate(&mut self) -> AnyResult<()> {
561        self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
562
563        // These options will prevent librdkafka from automatically committing offsets
564        // of consumed messages to the broker, meaning that next time the
565        // connector is instantiated it will start reading from the offset
566        // specified in `auto.offset.reset`.  We used to set these to
567        // `true`, which caused `rdkafka` to hang in some circumstances
568        // (https://github.com/confluentinc/librdkafka/issues/3954).  Besides, the new behavior
569        // is probably more correct given that circuit state currently does not survive
570        // across pipeline restarts, so it makes sense to start feeding messages
571        // from the start rather than from the last offset consumed by the
572        // previous instance of the pipeline, whose state is lost.  Once we add
573        // fault tolerance, we will likely use explicit commits, which also do
574        // not require these options.
575        //
576        // See https://docs.confluent.io/platform/current/clients/consumer.html#offset-management
577        //
578        // Note: we allow the user to override the options, so they can still enable
579        // auto commit if they know what they are doing, e.g., the secops demo
580        // requires the pipeline to commit its offset for the generator to know
581        // when to resume sending.
582        self.set_option_if_missing("enable.auto.commit", "false");
583        self.set_option_if_missing("enable.auto.offset.store", "false");
584
585        let group_id = format!("{}", Uuid::now_v7());
586        self.set_option_if_missing("group.id", &group_id);
587        self.set_option_if_missing("enable.partition.eof", "false");
588
589        // We link with openssl statically, which means that the default OPENSSLDIR location
590        // baked into openssl is not correct (see https://github.com/fede1024/rust-rdkafka/issues/594).
591        // We set the ssl.ca.location to "probe" so that librdkafka can find the CA certificates in a
592        // standard location (e.g., /etc/ssl/).
593        self.set_option_if_missing("ssl.ca.location", "probe");
594
595        // Enable client context `stats` callback so we can periodically check
596        // up on librdkafka memory usage.
597        self.set_option_if_missing("statistics.interval.ms", "10000");
598
599        // Prefetch is per partition (split queues), so 64 MB x many partitions can OOM.
600        if !self
601            .kafka_options
602            .contains_key("queued.max.messages.kbytes")
603        {
604            self.kafka_options.insert(
605                "queued.max.messages.kbytes".into(),
606                DEFAULT_QUEUED_MAX_MESSAGES_KBYTES.to_string(),
607            );
608            // Keep the fetch size librdkafka used before, which it would lower to 4 MB.
609            // If we cannot parse message.max.bytes (librdkafka also takes hex), librdkafka decides.
610            let message_max_bytes = match self.kafka_options.get("message.max.bytes") {
611                None => Some(0),
612                Some(value) => value.parse::<u64>().ok(),
613            };
614            if let Some(message_max_bytes) = message_max_bytes {
615                let fetch_max_bytes = message_max_bytes
616                    .max(MIN_DEFAULT_FETCH_MAX_BYTES)
617                    .to_string();
618                self.set_option_if_missing("fetch.max.bytes", &fetch_max_bytes);
619            }
620        }
621        // At the 1 s default, each message over queued.max.messages.kbytes waits 1 s.
622        self.set_option_if_missing(
623            "fetch.queue.backoff.ms",
624            &DEFAULT_FETCH_QUEUE_BACKOFF_MS.to_string(),
625        );
626
627        if let (Some(partitions), KafkaStartFromConfig::Offsets(offsets)) =
628            (&self.partitions, &self.start_from)
629            && partitions.len() != offsets.len()
630        {
631            anyhow::bail!(
632                "the number of partitions ('{partitions:?}') should be equal to the number of offsets '{offsets:?}' specified"
633            )
634        }
635
636        // Reject malformed filters (empty `and`/`or`, excessive nesting, or an
637        // invalid regular expression) at configuration time rather than when the
638        // connector starts.
639        if let Some(header_filter) = &self.header_filter {
640            header_filter.validate()?;
641        }
642
643        Ok(())
644    }
645}
646
647pub fn default_redpanda_server() -> String {
648    env::var("REDPANDA_BROKERS").unwrap_or_else(|_| "localhost".to_string())
649}
650
651/// Kafka header value encoded as a UTF-8 string or a byte array.
652#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
653#[repr(transparent)]
654pub struct KafkaHeaderValue(pub Vec<u8>);
655
656/// Visitor for deserializing Kafka headers value.
657struct HeaderVisitor;
658
659impl<'de> Visitor<'de> for HeaderVisitor {
660    type Value = KafkaHeaderValue;
661
662    fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
663        formatter.write_str("a string (e.g., \"xyz\") or a byte array (e.g., '[1,2,3])")
664    }
665
666    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
667    where
668        E: Error,
669    {
670        Ok(KafkaHeaderValue(v.as_bytes().to_owned()))
671    }
672
673    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
674    where
675        E: Error,
676    {
677        Ok(KafkaHeaderValue(v.into_bytes()))
678    }
679
680    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
681    where
682        A: SeqAccess<'de>,
683    {
684        let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
685
686        while let Some(b) = seq.next_element()? {
687            result.push(b);
688        }
689
690        Ok(KafkaHeaderValue(result))
691    }
692}
693
694impl<'de> Deserialize<'de> for KafkaHeaderValue {
695    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
696    where
697        D: Deserializer<'de>,
698    {
699        deserializer.deserialize_any(HeaderVisitor)
700    }
701}
702
703#[cfg(test)]
704#[test]
705fn test_kafka_header_value_deserialize() {
706    assert_eq!(
707        serde_json::from_str::<KafkaHeaderValue>(r#""foobar""#).unwrap(),
708        KafkaHeaderValue(br#"foobar"#.to_vec())
709    );
710
711    assert_eq!(
712        serde_json::from_str::<KafkaHeaderValue>(r#"[1,2,3,4,5]"#).unwrap(),
713        KafkaHeaderValue(vec![1u8, 2, 3, 4, 5])
714    );
715
716    assert!(serde_json::from_str::<KafkaHeaderValue>(r#"150"#).is_err());
717
718    assert!(serde_json::from_str::<KafkaHeaderValue>(r#"{{"foo": "bar"}}"#).is_err());
719}
720
721#[cfg(test)]
722#[test]
723fn test_prefetch_limit_default_and_override() {
724    let mut config = KafkaInputConfig::default(BTreeMap::new(), "t");
725    config.validate().unwrap();
726    assert_eq!(config.kafka_options["queued.max.messages.kbytes"], "4096");
727    assert_eq!(config.kafka_options["fetch.max.bytes"], "52428800");
728    assert_eq!(config.kafka_options["fetch.queue.backoff.ms"], "10");
729
730    let options = BTreeMap::from([("message.max.bytes".into(), "104857600".into())]);
731    let mut config = KafkaInputConfig::default(options, "t");
732    config.validate().unwrap();
733    assert_eq!(config.kafka_options["fetch.max.bytes"], "104857600");
734
735    let options = BTreeMap::from([("message.max.bytes".into(), "1000".into())]);
736    let mut config = KafkaInputConfig::default(options, "t");
737    config.validate().unwrap();
738    assert_eq!(config.kafka_options["fetch.max.bytes"], "52428800");
739
740    // librdkafka also takes hex, which we do not parse, so librdkafka picks the fetch size.
741    let options = BTreeMap::from([("message.max.bytes".into(), "0x6400000".into())]);
742    let mut config = KafkaInputConfig::default(options, "t");
743    config.validate().unwrap();
744    assert!(!config.kafka_options.contains_key("fetch.max.bytes"));
745
746    // A user prefetch limit leaves `fetch.max.bytes` to librdkafka, as before.
747    let options = BTreeMap::from([("queued.max.messages.kbytes".into(), "65536".into())]);
748    let mut config = KafkaInputConfig::default(options, "t");
749    config.validate().unwrap();
750    assert_eq!(config.kafka_options["queued.max.messages.kbytes"], "65536");
751    assert!(!config.kafka_options.contains_key("fetch.max.bytes"));
752    assert_eq!(config.kafka_options["fetch.queue.backoff.ms"], "10");
753
754    let options = BTreeMap::from([
755        ("fetch.max.bytes".into(), "1000000".into()),
756        ("fetch.queue.backoff.ms".into(), "500".into()),
757    ]);
758    let mut config = KafkaInputConfig::default(options, "t");
759    config.validate().unwrap();
760    assert_eq!(config.kafka_options["fetch.max.bytes"], "1000000");
761    assert_eq!(config.kafka_options["fetch.queue.backoff.ms"], "500");
762}
763
764/// Kafka message header.
765#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
766pub struct KafkaHeader {
767    pub key: String,
768    pub value: Option<KafkaHeaderValue>,
769}
770
771/// Configuration for writing data to a Kafka topic with `OutputTransport`.
772#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
773pub struct KafkaOutputConfig {
774    /// Options passed directly to `rdkafka`.
775    ///
776    /// See [`librdkafka` options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md)
777    /// used to configure the Kafka producer.
778    #[serde(flatten)]
779    pub kafka_options: BTreeMap<String, String>,
780
781    /// Topic to write to.
782    pub topic: String,
783
784    /// Kafka headers to be added to each message produced by this connector.
785    #[serde(default)]
786    pub headers: Vec<KafkaHeader>,
787
788    /// The log level of the client.
789    ///
790    /// If not specified, the log level will be calculated based on the global
791    /// log level of the `log` crate.
792    pub log_level: Option<KafkaLogLevel>,
793
794    /// Maximum time to wait for the endpoint to connect to a Kafka broker, for
795    /// example `60s`. Unset selects the default, `DEFAULT_INITIALIZATION_TIMEOUT`.
796    #[serde(
797        default,
798        alias = "initialization_timeout_secs",
799        deserialize_with = "duration_initialization_timeout",
800        skip_serializing_if = "Option::is_none"
801    )]
802    #[schema(value_type = Option<String>, default = default_initialization_timeout)]
803    pub initialization_timeout: Option<ConfigDuration>,
804
805    /// Optional configuration for fault tolerance.
806    pub fault_tolerance: Option<KafkaOutputFtConfig>,
807
808    /// If specified, this service is used to provide defaults for the Kafka options.
809    pub kafka_service: Option<String>,
810
811    /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
812    pub region: Option<String>,
813
814    /// Identity provider used to mint SASL/OAUTHBEARER tokens.  See
815    /// [`KafkaOauthProvider`].
816    ///
817    /// Skipped when serializing, for the same reason as in
818    /// [`KafkaInputConfig::oauth_provider`].
819    #[serde(skip_serializing_if = "Option::is_none")]
820    pub oauth_provider: Option<KafkaOauthProvider>,
821}
822
823/// Fault tolerance configuration for Kafka output connector.
824#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
825#[serde(default)]
826pub struct KafkaOutputFtConfig {
827    /// Options passed to `rdkafka` for consumers only, as documented at
828    /// [`librdkafka`
829    /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
830    ///
831    /// These options override `kafka_options` for consumers, and may be empty.
832    pub consumer_options: BTreeMap<String, String>,
833
834    /// Options passed to `rdkafka` for producers only, as documented at
835    /// [`librdkafka`
836    /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
837    ///
838    /// These options override `kafka_options` for producers, and may be empty.
839    pub producer_options: BTreeMap<String, String>,
840}
841
842impl KafkaOutputConfig {
843    #[allow(dead_code)]
844    /// Set `option` to `val`, if missing.
845    fn set_option_if_missing(&mut self, option: &str, val: &str) {
846        self.kafka_options
847            .entry(option.to_string())
848            .or_insert_with(|| val.to_string());
849    }
850
851    #[allow(dead_code)]
852    /// Validate configuration, set default option values required by this
853    /// adapter.
854    pub fn validate(&mut self) -> AnyResult<()> {
855        self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
856
857        // We link with openssl statically, which means that the default OPENSSLDIR location
858        // baked into openssl is not correct (see https://github.com/fede1024/rust-rdkafka/issues/594).
859        // We set the ssl.ca.location to "probe" so that librdkafka can find the CA certificates in a
860        // standard location (e.g., /etc/ssl/).
861        self.set_option_if_missing("ssl.ca.location", "probe");
862
863        // Enable client context `stats` callback so we can periodically check
864        // up on librdkafka memory usage.
865        self.set_option_if_missing("statistics.interval.ms", "10000");
866
867        // Retry delivery until it succeeds. librdkafka's default drops a
868        // message after 5 minutes of retries, and nothing but a non-fatal error
869        // tells that it did. With no bound the sink waits on a full producer
870        // queue, and the pipeline parks behind it, until the broker is back.
871        // Either spelling of the timeout restores a bound. Do not insert a
872        // conflicting alias: librdkafka applies both to the same option.
873        if !self.kafka_options.contains_key("delivery.timeout.ms") {
874            self.set_option_if_missing("message.timeout.ms", "0");
875        }
876
877        Ok(())
878    }
879}
880
881/// A set of updates to a SQL table or view.
882///
883/// The `sequence_number` field stores the offset of the chunk relative to the
884/// start of the stream and can be used to implement reliable delivery.
885/// The payload is stored in the `bin_data`, `text_data`, or `json_data` field
886/// depending on the data format used.
887#[derive(Deserialize, ToSchema)]
888pub struct Chunk {
889    pub sequence_number: u64,
890
891    // Exactly one of the following fields must be set.
892    // This should be an enum inlined with `#[serde(flatten)]`, but `utoipa`
893    // struggles to generate a schema for that.
894    /// Base64 encoded binary payload, e.g., bincode.
895    pub bin_data: Option<Vec<u8>>,
896
897    /// Text payload, e.g., CSV.
898    pub text_data: Option<String>,
899
900    /// JSON payload.
901    #[schema(value_type = Option<Object>)]
902    pub json_data: Option<JsonValue>,
903}
904
905mod compat {
906    use std::collections::BTreeMap;
907
908    use serde::Deserialize;
909
910    use crate::duration::ConfigDuration;
911    use crate::transport::kafka::{KafkaLogLevel, KafkaOauthProvider, KafkaStartFromConfig};
912
913    #[derive(Deserialize)]
914    pub struct KafkaInputConfigCompat {
915        /// Current, long-standing configuration option.
916        log_level: Option<KafkaLogLevel>,
917
918        /// Current, long-standing configuration option, which also accepts the
919        /// bare number of seconds its `group_join_timeout_secs` spelling took.
920        #[serde(
921            default,
922            alias = "group_join_timeout_secs",
923            deserialize_with = "super::duration_group_join_timeout"
924        )]
925        group_join_timeout: Option<ConfigDuration>,
926
927        /// Current configuration option.
928        poller_threads: Option<usize>,
929
930        /// Current configuration option, which changed type in an incompatible
931        /// way soon after it was introduced. No backward compatibility for the
932        /// initial form.
933        #[serde(default, with = "crate::serde_via_value")]
934        start_from: Option<KafkaStartFromConfig>,
935
936        /// Current configuration option that replaces the old `topics`
937        /// option. Currently mandatory.
938        topic: Option<String>,
939
940        /// Old form of `topic`. Currently accepted as a substitute as long as
941        /// it has exactly one element.
942        #[serde(default)]
943        topics: Vec<String>,
944
945        /// Legacy, now ignored.
946        fault_tolerance: Option<String>,
947
948        /// Legacy, now ignored.
949        kafka_service: Option<String>,
950
951        /// Options passed directly to `rdkafka`.
952        #[serde(flatten)]
953        kafka_options: BTreeMap<String, String>,
954
955        /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
956        region: Option<String>,
957
958        /// Identity provider used to mint SASL/OAUTHBEARER tokens.
959        oauth_provider: Option<KafkaOauthProvider>,
960
961        /// The Kafka partitions to read from.
962        partitions: Option<Vec<i32>>,
963
964        /// By default, if the input connector resumes from a checkpoint and the
965        /// data where it needs to resume has expired from the Kafka topic, the
966        /// input connector fails the pipeline.
967        ///
968        /// Set this to true to change the behavior so that, if data is not
969        /// available on resume, the input connector starts from the earliest
970        /// offsets that are now available.
971        #[serde(default)]
972        pub resume_earliest_if_data_expires: bool,
973
974        include_headers: Option<bool>,
975        include_timestamp: Option<bool>,
976        include_partition: Option<bool>,
977        include_offset: Option<bool>,
978        include_topic: Option<bool>,
979        #[serde(default)]
980        synchronize_partitions: bool,
981        #[serde(default, with = "crate::serde_via_value")]
982        header_filter: Option<super::HeaderFilter>,
983    }
984
985    impl TryFrom<KafkaInputConfigCompat> for super::KafkaInputConfig {
986        type Error = String;
987
988        fn try_from(mut compat: KafkaInputConfigCompat) -> Result<Self, Self::Error> {
989            let (topic, start_from) = if !compat.topics.is_empty() {
990                // Legacy mode. Convert to modern form.
991                if compat.topic.is_some() {
992                    return Err(
993                        "Kafka input adapter may not have both (modern) `topic` and (legacy) `topics`."
994                            .into(),
995                    );
996                }
997                if compat.topics.len() != 1 {
998                    return Err(format!(
999                        "Kafka input adapter must have exactly one topic (not {}).",
1000                        compat.topics.len()
1001                    ));
1002                }
1003                let start_from = if let Some(start_from) = compat.start_from {
1004                    start_from
1005                } else if let Some(auto_offset_reset) =
1006                    compat.kafka_options.get("auto.offset.reset")
1007                {
1008                    match auto_offset_reset.as_str() {
1009                        "smallest" | "earliest" | "beginning" => KafkaStartFromConfig::Earliest,
1010                        "largest" | "latest" | "end" => KafkaStartFromConfig::Latest,
1011                        _ => {
1012                            return Err(format!(
1013                                "Unrecognized value {auto_offset_reset:?} for `auto.offset.reset` in Kafka legacy input adapter configuration"
1014                            ));
1015                        }
1016                    }
1017                } else {
1018                    KafkaStartFromConfig::default()
1019                };
1020                (compat.topics.pop().unwrap(), start_from)
1021            } else if let Some(topic) = compat.topic {
1022                // Modern mode. Forbid legacy settings.
1023                if compat.fault_tolerance.is_some() {
1024                    return Err("Kafka input adapter `fault_tolerance` setting is obsolete.".into());
1025                }
1026                if compat.kafka_service.is_some() {
1027                    return Err("Kafka input adapter `kafka_service` setting is obsolete.".into());
1028                }
1029                (topic, compat.start_from.unwrap_or_default())
1030            } else {
1031                return Err("Kafka input adapter is missing required `topic` setting.".into());
1032            };
1033
1034            for key in compat.kafka_options.keys() {
1035                if !key.contains('.')
1036                    && key != "debug"
1037                    && key != "enabled_events"
1038                    && key != "retries"
1039                {
1040                    return Err(format!(
1041                        "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)."
1042                    ));
1043                }
1044            }
1045
1046            Ok(Self {
1047                topic,
1048                kafka_options: compat.kafka_options,
1049                log_level: compat.log_level,
1050                group_join_timeout: compat.group_join_timeout,
1051                poller_threads: compat.poller_threads,
1052                start_from,
1053                region: compat.region,
1054                oauth_provider: compat.oauth_provider,
1055                partitions: compat.partitions,
1056                resume_earliest_if_data_expires: compat.resume_earliest_if_data_expires,
1057                include_headers: compat.include_headers,
1058                include_timestamp: compat.include_timestamp,
1059                include_partition: compat.include_partition,
1060                include_offset: compat.include_offset,
1061                include_topic: compat.include_topic,
1062                synchronize_partitions: compat.synchronize_partitions,
1063                header_filter: compat.header_filter,
1064            })
1065        }
1066    }
1067}
1068
1069#[cfg(test)]
1070mod oauth_provider_tests {
1071    use std::collections::BTreeMap;
1072
1073    use serde::Deserialize;
1074
1075    use super::{KafkaInputConfig, KafkaOauthProvider, KafkaOutputConfig};
1076
1077    #[test]
1078    fn oauth_provider_is_optional() {
1079        let config: KafkaInputConfig =
1080            serde_json::from_str(r#"{"topic": "t", "bootstrap.servers": "localhost:9092"}"#)
1081                .unwrap();
1082        assert_eq!(config.oauth_provider, None);
1083    }
1084
1085    #[test]
1086    fn oauth_provider_gcp_round_trips() {
1087        let config: KafkaInputConfig = serde_json::from_str(
1088            r#"{"topic": "t", "bootstrap.servers": "localhost:9092", "oauth_provider": "gcp"}"#,
1089        )
1090        .unwrap();
1091        assert_eq!(config.oauth_provider, Some(KafkaOauthProvider::Gcp));
1092    }
1093
1094    /// A manager that knows `oauth_provider` must not send the key to a runtime
1095    /// that does not: an older runtime folds the unknown key into its flattened
1096    /// `kafka_options: BTreeMap<String, String>`, where a null value fails
1097    /// deserialization with a non-actionable error.
1098    #[test]
1099    fn unset_oauth_provider_is_not_serialized() {
1100        let config = KafkaInputConfig::default(
1101            BTreeMap::from([("bootstrap.servers".into(), "localhost:9092".into())]),
1102            "t",
1103        );
1104        let json = serde_json::to_value(&config).unwrap();
1105        assert!(!json.as_object().unwrap().contains_key("oauth_provider"));
1106
1107        let output_config = KafkaOutputConfig {
1108            kafka_options: BTreeMap::from([("bootstrap.servers".into(), "localhost:9092".into())]),
1109            topic: "t".into(),
1110            headers: Vec::new(),
1111            log_level: None,
1112            initialization_timeout: None,
1113            fault_tolerance: None,
1114            kafka_service: None,
1115            region: None,
1116            oauth_provider: None,
1117        };
1118        let json = serde_json::to_value(&output_config).unwrap();
1119        assert!(!json.as_object().unwrap().contains_key("oauth_provider"));
1120    }
1121
1122    #[test]
1123    fn set_oauth_provider_is_serialized() {
1124        let mut config = KafkaInputConfig::default(
1125            BTreeMap::from([("bootstrap.servers".into(), "localhost:9092".into())]),
1126            "t",
1127        );
1128        config.oauth_provider = Some(KafkaOauthProvider::Gcp);
1129        let json = serde_json::to_value(&config).unwrap();
1130        assert_eq!(json["oauth_provider"], serde_json::json!("gcp"));
1131    }
1132
1133    /// Demonstrates the failure that `skip_serializing_if` avoids: an old
1134    /// runtime, modeled here by a config whose unknown keys flatten into a
1135    /// string map, cannot deserialize `"oauth_provider": null`.
1136    #[test]
1137    fn old_runtime_rejects_null_oauth_provider() {
1138        #[derive(Deserialize)]
1139        struct OldRuntimeConfig {
1140            #[serde(flatten)]
1141            #[allow(dead_code)]
1142            kafka_options: BTreeMap<String, String>,
1143            #[allow(dead_code)]
1144            topic: String,
1145        }
1146
1147        assert!(
1148            serde_json::from_str::<OldRuntimeConfig>(r#"{"topic": "t", "oauth_provider": null}"#)
1149                .is_err()
1150        );
1151        assert!(serde_json::from_str::<OldRuntimeConfig>(r#"{"topic": "t"}"#).is_ok());
1152    }
1153
1154    #[test]
1155    fn legacy_region_only_config_still_deserializes() {
1156        // Configs written before `oauth_provider` existed set only `region`;
1157        // they must still deserialize, with `oauth_provider` defaulting to
1158        // `None` (interpreted as AWS by the adapter, for backward compatibility).
1159        let config: KafkaInputConfig = serde_json::from_str(
1160            r#"{"topic": "t", "bootstrap.servers": "localhost:9092", "region": "us-east-1"}"#,
1161        )
1162        .unwrap();
1163        assert_eq!(config.region, Some("us-east-1".to_string()));
1164        assert_eq!(config.oauth_provider, None);
1165    }
1166}
1167
1168#[cfg(test)]
1169mod header_filter_tests {
1170    use super::{HeaderFilter, KafkaInputConfig, MAX_HEADER_FILTER_DEPTH};
1171    use std::collections::BTreeMap;
1172
1173    /// Compile the filter described by `json` and evaluate it against `headers`.
1174    fn admits(json: &str, headers: &[(&str, Option<&[u8]>)]) -> bool {
1175        let filter: HeaderFilter = serde_json::from_str(json).unwrap();
1176        filter.compile().unwrap().matches(headers)
1177    }
1178
1179    #[test]
1180    fn leaf_matches_whole_value() {
1181        let f = r#"{"header": {"name": "type", "pattern": "created|updated"}}"#;
1182        assert!(admits(f, &[("type", Some(&b"created"[..]))]));
1183        assert!(admits(f, &[("type", Some(&b"updated"[..]))]));
1184
1185        // Patterns are anchored to the whole value: a substring must not match.
1186        assert!(!admits(f, &[("type", Some(&b"created-x"[..]))]));
1187        assert!(!admits(f, &[("type", Some(&b"x-created"[..]))]));
1188
1189        // Wrong value, wrong header name, and missing header all fail a leaf.
1190        assert!(!admits(f, &[("type", Some(&b"deleted"[..]))]));
1191        assert!(!admits(f, &[("other", Some(&b"created"[..]))]));
1192        assert!(!admits(f, &[]));
1193    }
1194
1195    #[test]
1196    fn null_value_is_empty_bytes() {
1197        let empty = r#"{"header": {"name": "h", "pattern": ""}}"#;
1198        let nonempty = r#"{"header": {"name": "h", "pattern": ".+"}}"#;
1199
1200        // A header with a null value matches an empty pattern but not `.+`.
1201        assert!(admits(empty, &[("h", None)]));
1202        assert!(!admits(nonempty, &[("h", None)]));
1203        assert!(admits(empty, &[("h", Some(&b""[..]))]));
1204    }
1205
1206    #[test]
1207    fn duplicate_header_any_value_matches() {
1208        let f = r#"{"header": {"name": "k", "pattern": "b"}}"#;
1209        assert!(admits(f, &[("k", Some(&b"a"[..])), ("k", Some(&b"b"[..]))]));
1210        assert!(!admits(
1211            f,
1212            &[("k", Some(&b"a"[..])), ("k", Some(&b"c"[..]))]
1213        ));
1214    }
1215
1216    #[test]
1217    fn non_utf8_value_bytes() {
1218        // A single-byte match against a non-UTF-8 value must work without panic.
1219        let f = r#"{"header": {"name": "b", "pattern": "(?s-u:.)"}}"#;
1220        assert!(admits(f, &[("b", Some(&[0xffu8][..]))]));
1221        // Anchoring still applies: two bytes do not match a single-byte pattern.
1222        assert!(!admits(f, &[("b", Some(&[0xffu8, 0xfe][..]))]));
1223    }
1224
1225    #[test]
1226    fn boolean_combinations() {
1227        // A AND (B OR C).
1228        let f = r#"{"and": [
1229            {"header": {"name": "a", "pattern": "1"}},
1230            {"or": [
1231                {"header": {"name": "b", "pattern": "1"}},
1232                {"header": {"name": "c", "pattern": "1"}}
1233            ]}
1234        ]}"#;
1235        assert!(admits(f, &[("a", Some(&b"1"[..])), ("b", Some(&b"1"[..]))]));
1236        assert!(admits(f, &[("a", Some(&b"1"[..])), ("c", Some(&b"1"[..]))]));
1237        assert!(!admits(f, &[("a", Some(&b"1"[..]))])); // neither b nor c
1238        assert!(!admits(f, &[("b", Some(&b"1"[..]))])); // missing a
1239    }
1240
1241    #[test]
1242    fn not_over_leaf() {
1243        let f = r#"{"not": {"header": {"name": "env", "pattern": "prod"}}}"#;
1244        assert!(!admits(f, &[("env", Some(&b"prod"[..]))])); // matching -> dropped
1245        assert!(admits(f, &[("env", Some(&b"dev"[..]))])); // non-matching -> admitted
1246        assert!(admits(f, &[])); // absent header -> admitted
1247    }
1248
1249    #[test]
1250    fn de_morgan_equivalence() {
1251        let lhs = r#"{"not": {"and": [
1252            {"header": {"name": "a", "pattern": "1"}},
1253            {"header": {"name": "b", "pattern": "1"}}
1254        ]}}"#;
1255        let rhs = r#"{"or": [
1256            {"not": {"header": {"name": "a", "pattern": "1"}}},
1257            {"not": {"header": {"name": "b", "pattern": "1"}}}
1258        ]}"#;
1259        let l = serde_json::from_str::<HeaderFilter>(lhs)
1260            .unwrap()
1261            .compile()
1262            .unwrap();
1263        let r = serde_json::from_str::<HeaderFilter>(rhs)
1264            .unwrap()
1265            .compile()
1266            .unwrap();
1267        for a in [None, Some(&b"1"[..])] {
1268            for b in [None, Some(&b"1"[..])] {
1269                let mut headers: Vec<(&str, Option<&[u8]>)> = Vec::new();
1270                if let Some(v) = a {
1271                    headers.push(("a", Some(v)));
1272                }
1273                if let Some(v) = b {
1274                    headers.push(("b", Some(v)));
1275                }
1276                assert_eq!(
1277                    l.matches(&headers),
1278                    r.matches(&headers),
1279                    "headers={headers:?}"
1280                );
1281            }
1282        }
1283    }
1284
1285    #[test]
1286    fn rejects_empty_combinators() {
1287        for json in [r#"{"and": []}"#, r#"{"or": []}"#] {
1288            let filter: HeaderFilter = serde_json::from_str(json).unwrap();
1289            assert!(filter.validate().is_err(), "expected {json} to be rejected");
1290        }
1291    }
1292
1293    #[test]
1294    fn rejects_deep_nesting() {
1295        // Wrap a leaf in `not` more times than the depth limit allows.
1296        let mut json = String::from(r#"{"header": {"name": "x", "pattern": "y"}}"#);
1297        for _ in 0..MAX_HEADER_FILTER_DEPTH + 5 {
1298            json = format!(r#"{{"not": {json}}}"#);
1299        }
1300        let filter: HeaderFilter = serde_json::from_str(&json).unwrap();
1301        assert!(filter.validate().is_err());
1302    }
1303
1304    #[test]
1305    fn rejects_invalid_regex() {
1306        let filter: HeaderFilter =
1307            serde_json::from_str(r#"{"header": {"name": "x", "pattern": "("}}"#).unwrap();
1308        assert!(filter.validate().is_err());
1309    }
1310
1311    #[test]
1312    fn serde_round_trip_external_tagging() {
1313        let json = r#"{"and":[{"header":{"name":"t","pattern":"a|b"}},{"not":{"header":{"name":"s","pattern":"x"}}}]}"#;
1314        let filter: HeaderFilter = serde_json::from_str(json).unwrap();
1315        let reserialized = serde_json::to_string(&filter).unwrap();
1316        assert_eq!(reserialized, json);
1317    }
1318
1319    #[test]
1320    fn config_validate_rejects_bad_filter() {
1321        let mut config = KafkaInputConfig::default(BTreeMap::new(), "topic");
1322        config.header_filter = Some(serde_json::from_str(r#"{"or": []}"#).unwrap());
1323        assert!(config.validate().is_err());
1324    }
1325
1326    #[test]
1327    fn config_deserializes_header_filter() {
1328        // Exercises the compat deserialization path for the new field.
1329        let config: KafkaInputConfig = serde_json::from_value(serde_json::json!({
1330            "topic": "t",
1331            "bootstrap.servers": "localhost:9092",
1332            "header_filter": {"header": {"name": "k", "pattern": "v"}}
1333        }))
1334        .unwrap();
1335        assert!(config.header_filter.is_some());
1336    }
1337}
1338
1339#[cfg(test)]
1340mod timeout_tests {
1341    use super::*;
1342
1343    /// Wraps the fields under test in the `topic` key both Kafka configs
1344    /// require.
1345    fn config_json(fields: &str) -> String {
1346        let separator = if fields.is_empty() { "" } else { ", " };
1347        format!(r#"{{"topic": "test_topic"{separator}{fields}}}"#)
1348    }
1349
1350    /// The consumer-group join timeout reads back from both spellings. They
1351    /// reach one field, so writing both is rejected as a duplicate.
1352    #[test]
1353    fn group_join_timeout_accepts_both_spellings() {
1354        for (fields, expected) in [
1355            ("", DEFAULT_GROUP_JOIN_TIMEOUT),
1356            (
1357                r#""group_join_timeout": "1500ms""#,
1358                ConfigDuration::from_millis(1500),
1359            ),
1360            (
1361                r#""group_join_timeout_secs": 25"#,
1362                ConfigDuration::from_secs(25),
1363            ),
1364        ] {
1365            let json = config_json(fields);
1366            let config: KafkaInputConfig = serde_json::from_str(&json).unwrap();
1367            assert_eq!(config.group_join_timeout(), expected, "parsing {json}");
1368        }
1369
1370        // Both spellings reach one field, so writing both is a duplicate.
1371        let json = config_json(r#""group_join_timeout": "1500ms", "group_join_timeout_secs": 25"#);
1372        let error = serde_json::from_str::<KafkaInputConfig>(&json)
1373            .unwrap_err()
1374            .to_string();
1375        assert!(
1376            error.contains("duplicate field `group_join_timeout`"),
1377            "{error}"
1378        );
1379    }
1380
1381    /// The output connector retries delivery without bound unless the user
1382    /// bounds it.
1383    #[test]
1384    fn output_message_timeout_defaults_to_unbounded() {
1385        let mut config: KafkaOutputConfig = serde_json::from_str(&config_json("")).unwrap();
1386        config.validate().unwrap();
1387        assert_eq!(
1388            config
1389                .kafka_options
1390                .get("message.timeout.ms")
1391                .map(String::as_str),
1392            Some("0")
1393        );
1394
1395        for option in ["message.timeout.ms", "delivery.timeout.ms"] {
1396            for value in ["0", "30000"] {
1397                let mut config: KafkaOutputConfig =
1398                    serde_json::from_str(&config_json(&format!(r#""{option}": "{value}""#)))
1399                        .unwrap();
1400                config.validate().unwrap();
1401                assert_eq!(config.kafka_options.get(option).unwrap(), value);
1402                let other = if option == "message.timeout.ms" {
1403                    "delivery.timeout.ms"
1404                } else {
1405                    "message.timeout.ms"
1406                };
1407                assert!(!config.kafka_options.contains_key(other));
1408            }
1409        }
1410    }
1411
1412    /// See [`group_join_timeout_accepts_both_spellings`].
1413    #[test]
1414    fn initialization_timeout_accepts_both_spellings() {
1415        for (fields, expected) in [
1416            ("", DEFAULT_INITIALIZATION_TIMEOUT),
1417            (
1418                r#""initialization_timeout": "2m""#,
1419                ConfigDuration::from_secs(120),
1420            ),
1421            (
1422                r#""initialization_timeout_secs": 15"#,
1423                ConfigDuration::from_secs(15),
1424            ),
1425        ] {
1426            let json = config_json(fields);
1427            let config: KafkaOutputConfig = serde_json::from_str(&json).unwrap();
1428            assert_eq!(config.initialization_timeout(), expected, "parsing {json}");
1429        }
1430    }
1431}