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