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#[derive(Clone, Eq, PartialEq, Serialize, ToSchema)]
32pub struct KafkaInputConfig {
33 #[serde(flatten)]
46 pub kafka_options: BTreeMap<String, String>,
47
48 pub topic: String,
50
51 pub log_level: Option<KafkaLogLevel>,
56
57 #[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 pub poller_threads: Option<usize>,
76
77 #[serde(default, with = "crate::serde_via_value")]
79 pub start_from: KafkaStartFromConfig,
80
81 pub region: Option<String>,
83
84 #[serde(skip_serializing_if = "Option::is_none")]
91 pub oauth_provider: Option<KafkaOauthProvider>,
92
93 pub partitions: Option<Vec<i32>>,
104
105 pub resume_earliest_if_data_expires: bool,
113
114 #[serde(default)]
119 pub include_headers: Option<bool>,
120
121 #[serde(default)]
126 pub include_timestamp: Option<bool>,
127
128 #[serde(default)]
133 pub include_partition: Option<bool>,
134
135 #[serde(default)]
140 pub include_offset: Option<bool>,
141
142 #[serde(default)]
147 pub include_topic: Option<bool>,
148
149 #[serde(default)]
198 pub synchronize_partitions: bool,
199
200 #[serde(default, with = "crate::serde_via_value")]
211 pub header_filter: Option<HeaderFilter>,
212}
213
214impl KafkaInputConfig {
215 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 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
266const MAX_HEADER_FILTER_DEPTH: usize = 64;
269
270#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
290#[serde(rename_all = "snake_case")]
291pub enum HeaderFilter {
292 Header(HeaderMatch),
295
296 And(Vec<HeaderFilter>),
299
300 Or(Vec<HeaderFilter>),
303
304 Not(Box<HeaderFilter>),
306}
307
308#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
311pub struct HeaderMatch {
312 pub name: String,
314
315 pub pattern: String,
325}
326
327impl HeaderFilter {
328 pub fn validate(&self) -> AnyResult<()> {
332 self.compile().map(|_| ())
333 }
334
335 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 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#[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 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#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
424#[serde(rename_all = "snake_case")]
425pub enum KafkaStartFromConfig {
426 Earliest,
428
429 #[default]
434 Latest,
435
436 Offsets(Vec<i64>),
440
441 Timestamp(i64),
445}
446
447#[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#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
471#[serde(rename_all = "snake_case")]
472pub enum KafkaOauthProvider {
473 #[default]
479 Aws,
480
481 Gcp,
490}
491
492pub const DEFAULT_GROUP_JOIN_TIMEOUT: ConfigDuration = ConfigDuration::from_secs(10);
495
496pub const DEFAULT_INITIALIZATION_TIMEOUT: ConfigDuration = ConfigDuration::from_secs(60);
498
499const DEFAULT_QUEUED_MAX_MESSAGES_KBYTES: u64 = 4096;
501
502const MIN_DEFAULT_FETCH_MAX_BYTES: u64 = 52_428_800;
504
505const DEFAULT_FETCH_QUEUE_BACKOFF_MS: u64 = 10;
507
508fn 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 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 pub fn initialization_timeout(&self) -> ConfigDuration {
530 self.initialization_timeout
531 .unwrap_or(DEFAULT_INITIALIZATION_TIMEOUT)
532 }
533}
534
535impl KafkaInputConfig {
536 #[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 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 pub fn validate(&mut self) -> AnyResult<()> {
562 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
563
564 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 self.set_option_if_missing("ssl.ca.location", "probe");
595
596 self.set_option_if_missing("statistics.interval.ms", "10000");
599
600 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 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 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 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#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
654#[repr(transparent)]
655pub struct KafkaHeaderValue(pub Vec<u8>);
656
657struct 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
704fn 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 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 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#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
814pub struct KafkaHeader {
815 pub key: String,
816 pub value: Option<KafkaHeaderValue>,
817}
818
819#[derive(Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
821pub struct KafkaOutputConfig {
822 #[serde(flatten)]
827 pub kafka_options: BTreeMap<String, String>,
828
829 pub topic: String,
831
832 #[serde(default)]
834 pub headers: Vec<KafkaHeader>,
835
836 pub log_level: Option<KafkaLogLevel>,
841
842 #[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 pub fault_tolerance: Option<KafkaOutputFtConfig>,
855
856 pub kafka_service: Option<String>,
858
859 pub region: Option<String>,
861
862 #[serde(skip_serializing_if = "Option::is_none")]
868 pub oauth_provider: Option<KafkaOauthProvider>,
869}
870
871#[derive(Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
873#[serde(default)]
874pub struct KafkaOutputFtConfig {
875 pub consumer_options: BTreeMap<String, String>,
881
882 pub producer_options: BTreeMap<String, String>,
888}
889
890impl KafkaOutputConfig {
891 #[allow(dead_code)]
892 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 pub fn validate(&mut self) -> AnyResult<()> {
903 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
904
905 self.set_option_if_missing("ssl.ca.location", "probe");
910
911 self.set_option_if_missing("statistics.interval.ms", "10000");
914
915 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#[derive(Deserialize, ToSchema)]
936pub struct Chunk {
937 pub sequence_number: u64,
938
939 pub bin_data: Option<Vec<u8>>,
944
945 pub text_data: Option<String>,
947
948 #[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 log_level: Option<KafkaLogLevel>,
965
966 #[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 poller_threads: Option<usize>,
977
978 #[serde(default, with = "crate::serde_via_value")]
982 start_from: Option<KafkaStartFromConfig>,
983
984 topic: Option<String>,
987
988 #[serde(default)]
991 topics: Vec<String>,
992
993 fault_tolerance: Option<String>,
995
996 kafka_service: Option<String>,
998
999 #[serde(flatten)]
1001 kafka_options: BTreeMap<String, String>,
1002
1003 region: Option<String>,
1005
1006 oauth_provider: Option<KafkaOauthProvider>,
1008
1009 partitions: Option<Vec<i32>>,
1011
1012 #[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 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 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
1117fn 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 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 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 #[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 #[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 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 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 assert!(!admits(f, &[("type", Some(&b"created-x"[..]))]));
1331 assert!(!admits(f, &[("type", Some(&b"x-created"[..]))]));
1332
1333 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 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 let f = r#"{"header": {"name": "b", "pattern": "(?s-u:.)"}}"#;
1364 assert!(admits(f, &[("b", Some(&[0xffu8][..]))]));
1365 assert!(!admits(f, &[("b", Some(&[0xffu8, 0xfe][..]))]));
1367 }
1368
1369 #[test]
1370 fn boolean_combinations() {
1371 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"[..]))])); assert!(!admits(f, &[("b", Some(&b"1"[..]))])); }
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"[..]))])); assert!(admits(f, &[("env", Some(&b"dev"[..]))])); assert!(admits(f, &[])); }
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 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 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 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 #[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 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 #[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 #[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 #[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}