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