1use anyhow::{Error as AnyError, Result as AnyResult, anyhow, bail};
2use regex::bytes::Regex;
3use serde::de::{Error, SeqAccess, Visitor};
4use serde::{Deserialize, Deserializer, Serialize};
5use serde_json::Value as JsonValue;
6use std::fmt::Formatter;
7use std::num::NonZeroUsize;
8use std::thread::available_parallelism;
9use std::{collections::BTreeMap, env};
10use utoipa::ToSchema;
11use uuid::Uuid;
12
13use crate::{
14 duration::{ConfigDuration, LegacyUnit},
15 duration_setting,
16};
17
18duration_setting!(
19 duration_group_join_timeout,
20 "group_join_timeout",
21 LegacyUnit::Secs
22);
23duration_setting!(
24 duration_initialization_timeout,
25 "initialization_timeout",
26 LegacyUnit::Secs
27);
28
29#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
31pub struct KafkaInputConfig {
32 #[serde(flatten)]
45 pub kafka_options: BTreeMap<String, String>,
46
47 pub topic: String,
49
50 pub log_level: Option<KafkaLogLevel>,
55
56 #[serde(
60 default,
61 alias = "group_join_timeout_secs",
62 deserialize_with = "duration_group_join_timeout",
63 skip_serializing_if = "Option::is_none"
64 )]
65 #[schema(value_type = Option<String>, default = default_group_join_timeout)]
66 pub group_join_timeout: Option<ConfigDuration>,
67
68 pub poller_threads: Option<usize>,
75
76 #[serde(default, with = "crate::serde_via_value")]
78 pub start_from: KafkaStartFromConfig,
79
80 pub region: Option<String>,
82
83 #[serde(skip_serializing_if = "Option::is_none")]
90 pub oauth_provider: Option<KafkaOauthProvider>,
91
92 pub partitions: Option<Vec<i32>>,
103
104 pub resume_earliest_if_data_expires: bool,
112
113 #[serde(default)]
118 pub include_headers: Option<bool>,
119
120 #[serde(default)]
125 pub include_timestamp: Option<bool>,
126
127 #[serde(default)]
132 pub include_partition: Option<bool>,
133
134 #[serde(default)]
139 pub include_offset: Option<bool>,
140
141 #[serde(default)]
146 pub include_topic: Option<bool>,
147
148 #[serde(default)]
197 pub synchronize_partitions: bool,
198
199 #[serde(default, with = "crate::serde_via_value")]
210 pub header_filter: Option<HeaderFilter>,
211}
212
213impl KafkaInputConfig {
214 pub fn default(kafka_options: BTreeMap<String, String>, topic: impl Into<String>) -> Self {
218 Self {
219 kafka_options,
220 topic: topic.into(),
221 log_level: None,
222 group_join_timeout: None,
223 poller_threads: None,
224 start_from: KafkaStartFromConfig::default(),
225 region: None,
226 oauth_provider: None,
227 partitions: None,
228 resume_earliest_if_data_expires: false,
229 include_headers: None,
230 include_timestamp: None,
231 include_partition: None,
232 include_offset: None,
233 include_topic: None,
234 synchronize_partitions: false,
235 header_filter: None,
236 }
237 }
238
239 pub fn poller_threads(&self) -> usize {
242 let max_threads = available_parallelism().map_or(16, NonZeroUsize::get);
243 self.poller_threads.unwrap_or(3).clamp(1, max_threads)
244 }
245
246 pub fn metadata_requested(&self) -> bool {
247 self.include_topic == Some(true)
248 || self.include_timestamp == Some(true)
249 || self.include_partition == Some(true)
250 || self.include_offset == Some(true)
251 || self.include_headers == Some(true)
252 }
253}
254
255impl<'de> Deserialize<'de> for KafkaInputConfig {
256 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
257 where
258 D: Deserializer<'de>,
259 {
260 let compat = compat::KafkaInputConfigCompat::deserialize(deserializer)?;
261 Self::try_from(compat).map_err(D::Error::custom)
262 }
263}
264
265const MAX_HEADER_FILTER_DEPTH: usize = 64;
268
269#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
289#[serde(rename_all = "snake_case")]
290pub enum HeaderFilter {
291 Header(HeaderMatch),
294
295 And(Vec<HeaderFilter>),
298
299 Or(Vec<HeaderFilter>),
302
303 Not(Box<HeaderFilter>),
305}
306
307#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
310pub struct HeaderMatch {
311 pub name: String,
313
314 pub pattern: String,
324}
325
326impl HeaderFilter {
327 pub fn validate(&self) -> AnyResult<()> {
331 self.compile().map(|_| ())
332 }
333
334 pub fn compile(&self) -> AnyResult<CompiledHeaderFilter> {
338 Ok(CompiledHeaderFilter(self.compile_node(1)?))
339 }
340
341 fn compile_node(&self, depth: usize) -> AnyResult<CompiledNode> {
342 if depth > MAX_HEADER_FILTER_DEPTH {
343 bail!("Kafka header filter is nested more than {MAX_HEADER_FILTER_DEPTH} levels deep");
344 }
345 match self {
346 HeaderFilter::Header(HeaderMatch { name, pattern }) => {
347 let regex = Regex::new(&format!(r"\A(?:{pattern})\z")).map_err(|error| {
351 anyhow!(
352 "invalid regular expression {pattern:?} for Kafka header {name:?}: {error}"
353 )
354 })?;
355 Ok(CompiledNode::Header {
356 name: name.clone(),
357 regex,
358 })
359 }
360 HeaderFilter::And(children) => {
361 if children.is_empty() {
362 bail!("Kafka header filter 'and' must have at least one operand");
363 }
364 Ok(CompiledNode::And(Self::compile_children(children, depth)?))
365 }
366 HeaderFilter::Or(children) => {
367 if children.is_empty() {
368 bail!("Kafka header filter 'or' must have at least one operand");
369 }
370 Ok(CompiledNode::Or(Self::compile_children(children, depth)?))
371 }
372 HeaderFilter::Not(child) => {
373 Ok(CompiledNode::Not(Box::new(child.compile_node(depth + 1)?)))
374 }
375 }
376 }
377
378 fn compile_children(children: &[HeaderFilter], depth: usize) -> AnyResult<Vec<CompiledNode>> {
379 children.iter().map(|c| c.compile_node(depth + 1)).collect()
380 }
381}
382
383#[derive(Debug)]
386pub struct CompiledHeaderFilter(CompiledNode);
387
388#[derive(Debug)]
389enum CompiledNode {
390 Header { name: String, regex: Regex },
391 And(Vec<CompiledNode>),
392 Or(Vec<CompiledNode>),
393 Not(Box<CompiledNode>),
394}
395
396impl CompiledHeaderFilter {
397 pub fn matches(&self, headers: &[(&str, Option<&[u8]>)]) -> bool {
404 self.0.matches(headers)
405 }
406}
407
408impl CompiledNode {
409 fn matches(&self, headers: &[(&str, Option<&[u8]>)]) -> bool {
410 match self {
411 CompiledNode::Header { name, regex } => headers
412 .iter()
413 .any(|&(key, value)| key == name.as_str() && regex.is_match(value.unwrap_or(b""))),
414 CompiledNode::And(children) => children.iter().all(|c| c.matches(headers)),
415 CompiledNode::Or(children) => children.iter().any(|c| c.matches(headers)),
416 CompiledNode::Not(child) => !child.matches(headers),
417 }
418 }
419}
420
421#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
423#[serde(rename_all = "snake_case")]
424pub enum KafkaStartFromConfig {
425 Earliest,
427
428 #[default]
433 Latest,
434
435 Offsets(Vec<i64>),
439
440 Timestamp(i64),
444}
445
446#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ToSchema)]
448pub enum KafkaLogLevel {
449 #[serde(rename = "emerg")]
450 Emerg,
451 #[serde(rename = "alert")]
452 Alert,
453 #[serde(rename = "critical")]
454 Critical,
455 #[serde(rename = "error")]
456 Error,
457 #[serde(rename = "warning")]
458 Warning,
459 #[serde(rename = "notice")]
460 Notice,
461 #[serde(rename = "info")]
462 Info,
463 #[serde(rename = "debug")]
464 Debug,
465}
466
467#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
470#[serde(rename_all = "snake_case")]
471pub enum KafkaOauthProvider {
472 #[default]
478 Aws,
479
480 Gcp,
489}
490
491pub const DEFAULT_GROUP_JOIN_TIMEOUT: ConfigDuration = ConfigDuration::from_secs(10);
494
495pub const DEFAULT_INITIALIZATION_TIMEOUT: ConfigDuration = ConfigDuration::from_secs(60);
497
498const DEFAULT_QUEUED_MAX_MESSAGES_KBYTES: u64 = 4096;
500
501const MIN_DEFAULT_FETCH_MAX_BYTES: u64 = 52_428_800;
503
504const DEFAULT_FETCH_QUEUE_BACKOFF_MS: u64 = 10;
506
507fn default_group_join_timeout() -> String {
510 DEFAULT_GROUP_JOIN_TIMEOUT.to_string()
511}
512fn default_initialization_timeout() -> String {
513 DEFAULT_INITIALIZATION_TIMEOUT.to_string()
514}
515
516impl KafkaInputConfig {
517 pub fn group_join_timeout(&self) -> ConfigDuration {
520 self.group_join_timeout
521 .unwrap_or(DEFAULT_GROUP_JOIN_TIMEOUT)
522 }
523}
524
525impl KafkaOutputConfig {
526 pub fn initialization_timeout(&self) -> ConfigDuration {
529 self.initialization_timeout
530 .unwrap_or(DEFAULT_INITIALIZATION_TIMEOUT)
531 }
532}
533
534impl KafkaInputConfig {
535 #[allow(dead_code)]
538 fn enforce_option(&mut self, option: &str, val: &str) -> AnyResult<()> {
539 let option_val = self
540 .kafka_options
541 .entry(option.to_string())
542 .or_insert_with(|| val.to_string());
543 if option_val != val {
544 Err(AnyError::msg(
545 "cannot override '{option}' option: the Kafka transport adapter sets this option to '{val}'",
546 ))?;
547 }
548 Ok(())
549 }
550
551 fn set_option_if_missing(&mut self, option: &str, val: &str) {
553 self.kafka_options
554 .entry(option.to_string())
555 .or_insert_with(|| val.to_string());
556 }
557
558 pub fn validate(&mut self) -> AnyResult<()> {
561 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
562
563 self.set_option_if_missing("enable.auto.commit", "false");
583 self.set_option_if_missing("enable.auto.offset.store", "false");
584
585 let group_id = format!("{}", Uuid::now_v7());
586 self.set_option_if_missing("group.id", &group_id);
587 self.set_option_if_missing("enable.partition.eof", "false");
588
589 self.set_option_if_missing("ssl.ca.location", "probe");
594
595 self.set_option_if_missing("statistics.interval.ms", "10000");
598
599 if !self
601 .kafka_options
602 .contains_key("queued.max.messages.kbytes")
603 {
604 self.kafka_options.insert(
605 "queued.max.messages.kbytes".into(),
606 DEFAULT_QUEUED_MAX_MESSAGES_KBYTES.to_string(),
607 );
608 let message_max_bytes = match self.kafka_options.get("message.max.bytes") {
611 None => Some(0),
612 Some(value) => value.parse::<u64>().ok(),
613 };
614 if let Some(message_max_bytes) = message_max_bytes {
615 let fetch_max_bytes = message_max_bytes
616 .max(MIN_DEFAULT_FETCH_MAX_BYTES)
617 .to_string();
618 self.set_option_if_missing("fetch.max.bytes", &fetch_max_bytes);
619 }
620 }
621 self.set_option_if_missing(
623 "fetch.queue.backoff.ms",
624 &DEFAULT_FETCH_QUEUE_BACKOFF_MS.to_string(),
625 );
626
627 if let (Some(partitions), KafkaStartFromConfig::Offsets(offsets)) =
628 (&self.partitions, &self.start_from)
629 && partitions.len() != offsets.len()
630 {
631 anyhow::bail!(
632 "the number of partitions ('{partitions:?}') should be equal to the number of offsets '{offsets:?}' specified"
633 )
634 }
635
636 if let Some(header_filter) = &self.header_filter {
640 header_filter.validate()?;
641 }
642
643 Ok(())
644 }
645}
646
647pub fn default_redpanda_server() -> String {
648 env::var("REDPANDA_BROKERS").unwrap_or_else(|_| "localhost".to_string())
649}
650
651#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
653#[repr(transparent)]
654pub struct KafkaHeaderValue(pub Vec<u8>);
655
656struct HeaderVisitor;
658
659impl<'de> Visitor<'de> for HeaderVisitor {
660 type Value = KafkaHeaderValue;
661
662 fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
663 formatter.write_str("a string (e.g., \"xyz\") or a byte array (e.g., '[1,2,3])")
664 }
665
666 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
667 where
668 E: Error,
669 {
670 Ok(KafkaHeaderValue(v.as_bytes().to_owned()))
671 }
672
673 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
674 where
675 E: Error,
676 {
677 Ok(KafkaHeaderValue(v.into_bytes()))
678 }
679
680 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
681 where
682 A: SeqAccess<'de>,
683 {
684 let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
685
686 while let Some(b) = seq.next_element()? {
687 result.push(b);
688 }
689
690 Ok(KafkaHeaderValue(result))
691 }
692}
693
694impl<'de> Deserialize<'de> for KafkaHeaderValue {
695 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
696 where
697 D: Deserializer<'de>,
698 {
699 deserializer.deserialize_any(HeaderVisitor)
700 }
701}
702
703#[cfg(test)]
704#[test]
705fn test_kafka_header_value_deserialize() {
706 assert_eq!(
707 serde_json::from_str::<KafkaHeaderValue>(r#""foobar""#).unwrap(),
708 KafkaHeaderValue(br#"foobar"#.to_vec())
709 );
710
711 assert_eq!(
712 serde_json::from_str::<KafkaHeaderValue>(r#"[1,2,3,4,5]"#).unwrap(),
713 KafkaHeaderValue(vec![1u8, 2, 3, 4, 5])
714 );
715
716 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"150"#).is_err());
717
718 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"{{"foo": "bar"}}"#).is_err());
719}
720
721#[cfg(test)]
722#[test]
723fn test_prefetch_limit_default_and_override() {
724 let mut config = KafkaInputConfig::default(BTreeMap::new(), "t");
725 config.validate().unwrap();
726 assert_eq!(config.kafka_options["queued.max.messages.kbytes"], "4096");
727 assert_eq!(config.kafka_options["fetch.max.bytes"], "52428800");
728 assert_eq!(config.kafka_options["fetch.queue.backoff.ms"], "10");
729
730 let options = BTreeMap::from([("message.max.bytes".into(), "104857600".into())]);
731 let mut config = KafkaInputConfig::default(options, "t");
732 config.validate().unwrap();
733 assert_eq!(config.kafka_options["fetch.max.bytes"], "104857600");
734
735 let options = BTreeMap::from([("message.max.bytes".into(), "1000".into())]);
736 let mut config = KafkaInputConfig::default(options, "t");
737 config.validate().unwrap();
738 assert_eq!(config.kafka_options["fetch.max.bytes"], "52428800");
739
740 let options = BTreeMap::from([("message.max.bytes".into(), "0x6400000".into())]);
742 let mut config = KafkaInputConfig::default(options, "t");
743 config.validate().unwrap();
744 assert!(!config.kafka_options.contains_key("fetch.max.bytes"));
745
746 let options = BTreeMap::from([("queued.max.messages.kbytes".into(), "65536".into())]);
748 let mut config = KafkaInputConfig::default(options, "t");
749 config.validate().unwrap();
750 assert_eq!(config.kafka_options["queued.max.messages.kbytes"], "65536");
751 assert!(!config.kafka_options.contains_key("fetch.max.bytes"));
752 assert_eq!(config.kafka_options["fetch.queue.backoff.ms"], "10");
753
754 let options = BTreeMap::from([
755 ("fetch.max.bytes".into(), "1000000".into()),
756 ("fetch.queue.backoff.ms".into(), "500".into()),
757 ]);
758 let mut config = KafkaInputConfig::default(options, "t");
759 config.validate().unwrap();
760 assert_eq!(config.kafka_options["fetch.max.bytes"], "1000000");
761 assert_eq!(config.kafka_options["fetch.queue.backoff.ms"], "500");
762}
763
764#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
766pub struct KafkaHeader {
767 pub key: String,
768 pub value: Option<KafkaHeaderValue>,
769}
770
771#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
773pub struct KafkaOutputConfig {
774 #[serde(flatten)]
779 pub kafka_options: BTreeMap<String, String>,
780
781 pub topic: String,
783
784 #[serde(default)]
786 pub headers: Vec<KafkaHeader>,
787
788 pub log_level: Option<KafkaLogLevel>,
793
794 #[serde(
797 default,
798 alias = "initialization_timeout_secs",
799 deserialize_with = "duration_initialization_timeout",
800 skip_serializing_if = "Option::is_none"
801 )]
802 #[schema(value_type = Option<String>, default = default_initialization_timeout)]
803 pub initialization_timeout: Option<ConfigDuration>,
804
805 pub fault_tolerance: Option<KafkaOutputFtConfig>,
807
808 pub kafka_service: Option<String>,
810
811 pub region: Option<String>,
813
814 #[serde(skip_serializing_if = "Option::is_none")]
820 pub oauth_provider: Option<KafkaOauthProvider>,
821}
822
823#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
825#[serde(default)]
826pub struct KafkaOutputFtConfig {
827 pub consumer_options: BTreeMap<String, String>,
833
834 pub producer_options: BTreeMap<String, String>,
840}
841
842impl KafkaOutputConfig {
843 #[allow(dead_code)]
844 fn set_option_if_missing(&mut self, option: &str, val: &str) {
846 self.kafka_options
847 .entry(option.to_string())
848 .or_insert_with(|| val.to_string());
849 }
850
851 #[allow(dead_code)]
852 pub fn validate(&mut self) -> AnyResult<()> {
855 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
856
857 self.set_option_if_missing("ssl.ca.location", "probe");
862
863 self.set_option_if_missing("statistics.interval.ms", "10000");
866
867 Ok(())
868 }
869}
870
871#[derive(Deserialize, ToSchema)]
878pub struct Chunk {
879 pub sequence_number: u64,
880
881 pub bin_data: Option<Vec<u8>>,
886
887 pub text_data: Option<String>,
889
890 #[schema(value_type = Option<Object>)]
892 pub json_data: Option<JsonValue>,
893}
894
895mod compat {
896 use std::collections::BTreeMap;
897
898 use serde::Deserialize;
899
900 use crate::duration::ConfigDuration;
901 use crate::transport::kafka::{KafkaLogLevel, KafkaOauthProvider, KafkaStartFromConfig};
902
903 #[derive(Deserialize)]
904 pub struct KafkaInputConfigCompat {
905 log_level: Option<KafkaLogLevel>,
907
908 #[serde(
911 default,
912 alias = "group_join_timeout_secs",
913 deserialize_with = "super::duration_group_join_timeout"
914 )]
915 group_join_timeout: Option<ConfigDuration>,
916
917 poller_threads: Option<usize>,
919
920 #[serde(default, with = "crate::serde_via_value")]
924 start_from: Option<KafkaStartFromConfig>,
925
926 topic: Option<String>,
929
930 #[serde(default)]
933 topics: Vec<String>,
934
935 fault_tolerance: Option<String>,
937
938 kafka_service: Option<String>,
940
941 #[serde(flatten)]
943 kafka_options: BTreeMap<String, String>,
944
945 region: Option<String>,
947
948 oauth_provider: Option<KafkaOauthProvider>,
950
951 partitions: Option<Vec<i32>>,
953
954 #[serde(default)]
962 pub resume_earliest_if_data_expires: bool,
963
964 include_headers: Option<bool>,
965 include_timestamp: Option<bool>,
966 include_partition: Option<bool>,
967 include_offset: Option<bool>,
968 include_topic: Option<bool>,
969 #[serde(default)]
970 synchronize_partitions: bool,
971 #[serde(default, with = "crate::serde_via_value")]
972 header_filter: Option<super::HeaderFilter>,
973 }
974
975 impl TryFrom<KafkaInputConfigCompat> for super::KafkaInputConfig {
976 type Error = String;
977
978 fn try_from(mut compat: KafkaInputConfigCompat) -> Result<Self, Self::Error> {
979 let (topic, start_from) = if !compat.topics.is_empty() {
980 if compat.topic.is_some() {
982 return Err(
983 "Kafka input adapter may not have both (modern) `topic` and (legacy) `topics`."
984 .into(),
985 );
986 }
987 if compat.topics.len() != 1 {
988 return Err(format!(
989 "Kafka input adapter must have exactly one topic (not {}).",
990 compat.topics.len()
991 ));
992 }
993 let start_from = if let Some(start_from) = compat.start_from {
994 start_from
995 } else if let Some(auto_offset_reset) =
996 compat.kafka_options.get("auto.offset.reset")
997 {
998 match auto_offset_reset.as_str() {
999 "smallest" | "earliest" | "beginning" => KafkaStartFromConfig::Earliest,
1000 "largest" | "latest" | "end" => KafkaStartFromConfig::Latest,
1001 _ => {
1002 return Err(format!(
1003 "Unrecognized value {auto_offset_reset:?} for `auto.offset.reset` in Kafka legacy input adapter configuration"
1004 ));
1005 }
1006 }
1007 } else {
1008 KafkaStartFromConfig::default()
1009 };
1010 (compat.topics.pop().unwrap(), start_from)
1011 } else if let Some(topic) = compat.topic {
1012 if compat.fault_tolerance.is_some() {
1014 return Err("Kafka input adapter `fault_tolerance` setting is obsolete.".into());
1015 }
1016 if compat.kafka_service.is_some() {
1017 return Err("Kafka input adapter `kafka_service` setting is obsolete.".into());
1018 }
1019 (topic, compat.start_from.unwrap_or_default())
1020 } else {
1021 return Err("Kafka input adapter is missing required `topic` setting.".into());
1022 };
1023
1024 for key in compat.kafka_options.keys() {
1025 if !key.contains('.')
1026 && key != "debug"
1027 && key != "enabled_events"
1028 && key != "retries"
1029 {
1030 return Err(format!(
1031 "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)."
1032 ));
1033 }
1034 }
1035
1036 Ok(Self {
1037 topic,
1038 kafka_options: compat.kafka_options,
1039 log_level: compat.log_level,
1040 group_join_timeout: compat.group_join_timeout,
1041 poller_threads: compat.poller_threads,
1042 start_from,
1043 region: compat.region,
1044 oauth_provider: compat.oauth_provider,
1045 partitions: compat.partitions,
1046 resume_earliest_if_data_expires: compat.resume_earliest_if_data_expires,
1047 include_headers: compat.include_headers,
1048 include_timestamp: compat.include_timestamp,
1049 include_partition: compat.include_partition,
1050 include_offset: compat.include_offset,
1051 include_topic: compat.include_topic,
1052 synchronize_partitions: compat.synchronize_partitions,
1053 header_filter: compat.header_filter,
1054 })
1055 }
1056 }
1057}
1058
1059#[cfg(test)]
1060mod oauth_provider_tests {
1061 use std::collections::BTreeMap;
1062
1063 use serde::Deserialize;
1064
1065 use super::{KafkaInputConfig, KafkaOauthProvider, KafkaOutputConfig};
1066
1067 #[test]
1068 fn oauth_provider_is_optional() {
1069 let config: KafkaInputConfig =
1070 serde_json::from_str(r#"{"topic": "t", "bootstrap.servers": "localhost:9092"}"#)
1071 .unwrap();
1072 assert_eq!(config.oauth_provider, None);
1073 }
1074
1075 #[test]
1076 fn oauth_provider_gcp_round_trips() {
1077 let config: KafkaInputConfig = serde_json::from_str(
1078 r#"{"topic": "t", "bootstrap.servers": "localhost:9092", "oauth_provider": "gcp"}"#,
1079 )
1080 .unwrap();
1081 assert_eq!(config.oauth_provider, Some(KafkaOauthProvider::Gcp));
1082 }
1083
1084 #[test]
1089 fn unset_oauth_provider_is_not_serialized() {
1090 let config = KafkaInputConfig::default(
1091 BTreeMap::from([("bootstrap.servers".into(), "localhost:9092".into())]),
1092 "t",
1093 );
1094 let json = serde_json::to_value(&config).unwrap();
1095 assert!(!json.as_object().unwrap().contains_key("oauth_provider"));
1096
1097 let output_config = KafkaOutputConfig {
1098 kafka_options: BTreeMap::from([("bootstrap.servers".into(), "localhost:9092".into())]),
1099 topic: "t".into(),
1100 headers: Vec::new(),
1101 log_level: None,
1102 initialization_timeout: None,
1103 fault_tolerance: None,
1104 kafka_service: None,
1105 region: None,
1106 oauth_provider: None,
1107 };
1108 let json = serde_json::to_value(&output_config).unwrap();
1109 assert!(!json.as_object().unwrap().contains_key("oauth_provider"));
1110 }
1111
1112 #[test]
1113 fn set_oauth_provider_is_serialized() {
1114 let mut config = KafkaInputConfig::default(
1115 BTreeMap::from([("bootstrap.servers".into(), "localhost:9092".into())]),
1116 "t",
1117 );
1118 config.oauth_provider = Some(KafkaOauthProvider::Gcp);
1119 let json = serde_json::to_value(&config).unwrap();
1120 assert_eq!(json["oauth_provider"], serde_json::json!("gcp"));
1121 }
1122
1123 #[test]
1127 fn old_runtime_rejects_null_oauth_provider() {
1128 #[derive(Deserialize)]
1129 struct OldRuntimeConfig {
1130 #[serde(flatten)]
1131 #[allow(dead_code)]
1132 kafka_options: BTreeMap<String, String>,
1133 #[allow(dead_code)]
1134 topic: String,
1135 }
1136
1137 assert!(
1138 serde_json::from_str::<OldRuntimeConfig>(r#"{"topic": "t", "oauth_provider": null}"#)
1139 .is_err()
1140 );
1141 assert!(serde_json::from_str::<OldRuntimeConfig>(r#"{"topic": "t"}"#).is_ok());
1142 }
1143
1144 #[test]
1145 fn legacy_region_only_config_still_deserializes() {
1146 let config: KafkaInputConfig = serde_json::from_str(
1150 r#"{"topic": "t", "bootstrap.servers": "localhost:9092", "region": "us-east-1"}"#,
1151 )
1152 .unwrap();
1153 assert_eq!(config.region, Some("us-east-1".to_string()));
1154 assert_eq!(config.oauth_provider, None);
1155 }
1156}
1157
1158#[cfg(test)]
1159mod header_filter_tests {
1160 use super::{HeaderFilter, KafkaInputConfig, MAX_HEADER_FILTER_DEPTH};
1161 use std::collections::BTreeMap;
1162
1163 fn admits(json: &str, headers: &[(&str, Option<&[u8]>)]) -> bool {
1165 let filter: HeaderFilter = serde_json::from_str(json).unwrap();
1166 filter.compile().unwrap().matches(headers)
1167 }
1168
1169 #[test]
1170 fn leaf_matches_whole_value() {
1171 let f = r#"{"header": {"name": "type", "pattern": "created|updated"}}"#;
1172 assert!(admits(f, &[("type", Some(&b"created"[..]))]));
1173 assert!(admits(f, &[("type", Some(&b"updated"[..]))]));
1174
1175 assert!(!admits(f, &[("type", Some(&b"created-x"[..]))]));
1177 assert!(!admits(f, &[("type", Some(&b"x-created"[..]))]));
1178
1179 assert!(!admits(f, &[("type", Some(&b"deleted"[..]))]));
1181 assert!(!admits(f, &[("other", Some(&b"created"[..]))]));
1182 assert!(!admits(f, &[]));
1183 }
1184
1185 #[test]
1186 fn null_value_is_empty_bytes() {
1187 let empty = r#"{"header": {"name": "h", "pattern": ""}}"#;
1188 let nonempty = r#"{"header": {"name": "h", "pattern": ".+"}}"#;
1189
1190 assert!(admits(empty, &[("h", None)]));
1192 assert!(!admits(nonempty, &[("h", None)]));
1193 assert!(admits(empty, &[("h", Some(&b""[..]))]));
1194 }
1195
1196 #[test]
1197 fn duplicate_header_any_value_matches() {
1198 let f = r#"{"header": {"name": "k", "pattern": "b"}}"#;
1199 assert!(admits(f, &[("k", Some(&b"a"[..])), ("k", Some(&b"b"[..]))]));
1200 assert!(!admits(
1201 f,
1202 &[("k", Some(&b"a"[..])), ("k", Some(&b"c"[..]))]
1203 ));
1204 }
1205
1206 #[test]
1207 fn non_utf8_value_bytes() {
1208 let f = r#"{"header": {"name": "b", "pattern": "(?s-u:.)"}}"#;
1210 assert!(admits(f, &[("b", Some(&[0xffu8][..]))]));
1211 assert!(!admits(f, &[("b", Some(&[0xffu8, 0xfe][..]))]));
1213 }
1214
1215 #[test]
1216 fn boolean_combinations() {
1217 let f = r#"{"and": [
1219 {"header": {"name": "a", "pattern": "1"}},
1220 {"or": [
1221 {"header": {"name": "b", "pattern": "1"}},
1222 {"header": {"name": "c", "pattern": "1"}}
1223 ]}
1224 ]}"#;
1225 assert!(admits(f, &[("a", Some(&b"1"[..])), ("b", Some(&b"1"[..]))]));
1226 assert!(admits(f, &[("a", Some(&b"1"[..])), ("c", Some(&b"1"[..]))]));
1227 assert!(!admits(f, &[("a", Some(&b"1"[..]))])); assert!(!admits(f, &[("b", Some(&b"1"[..]))])); }
1230
1231 #[test]
1232 fn not_over_leaf() {
1233 let f = r#"{"not": {"header": {"name": "env", "pattern": "prod"}}}"#;
1234 assert!(!admits(f, &[("env", Some(&b"prod"[..]))])); assert!(admits(f, &[("env", Some(&b"dev"[..]))])); assert!(admits(f, &[])); }
1238
1239 #[test]
1240 fn de_morgan_equivalence() {
1241 let lhs = r#"{"not": {"and": [
1242 {"header": {"name": "a", "pattern": "1"}},
1243 {"header": {"name": "b", "pattern": "1"}}
1244 ]}}"#;
1245 let rhs = r#"{"or": [
1246 {"not": {"header": {"name": "a", "pattern": "1"}}},
1247 {"not": {"header": {"name": "b", "pattern": "1"}}}
1248 ]}"#;
1249 let l = serde_json::from_str::<HeaderFilter>(lhs)
1250 .unwrap()
1251 .compile()
1252 .unwrap();
1253 let r = serde_json::from_str::<HeaderFilter>(rhs)
1254 .unwrap()
1255 .compile()
1256 .unwrap();
1257 for a in [None, Some(&b"1"[..])] {
1258 for b in [None, Some(&b"1"[..])] {
1259 let mut headers: Vec<(&str, Option<&[u8]>)> = Vec::new();
1260 if let Some(v) = a {
1261 headers.push(("a", Some(v)));
1262 }
1263 if let Some(v) = b {
1264 headers.push(("b", Some(v)));
1265 }
1266 assert_eq!(
1267 l.matches(&headers),
1268 r.matches(&headers),
1269 "headers={headers:?}"
1270 );
1271 }
1272 }
1273 }
1274
1275 #[test]
1276 fn rejects_empty_combinators() {
1277 for json in [r#"{"and": []}"#, r#"{"or": []}"#] {
1278 let filter: HeaderFilter = serde_json::from_str(json).unwrap();
1279 assert!(filter.validate().is_err(), "expected {json} to be rejected");
1280 }
1281 }
1282
1283 #[test]
1284 fn rejects_deep_nesting() {
1285 let mut json = String::from(r#"{"header": {"name": "x", "pattern": "y"}}"#);
1287 for _ in 0..MAX_HEADER_FILTER_DEPTH + 5 {
1288 json = format!(r#"{{"not": {json}}}"#);
1289 }
1290 let filter: HeaderFilter = serde_json::from_str(&json).unwrap();
1291 assert!(filter.validate().is_err());
1292 }
1293
1294 #[test]
1295 fn rejects_invalid_regex() {
1296 let filter: HeaderFilter =
1297 serde_json::from_str(r#"{"header": {"name": "x", "pattern": "("}}"#).unwrap();
1298 assert!(filter.validate().is_err());
1299 }
1300
1301 #[test]
1302 fn serde_round_trip_external_tagging() {
1303 let json = r#"{"and":[{"header":{"name":"t","pattern":"a|b"}},{"not":{"header":{"name":"s","pattern":"x"}}}]}"#;
1304 let filter: HeaderFilter = serde_json::from_str(json).unwrap();
1305 let reserialized = serde_json::to_string(&filter).unwrap();
1306 assert_eq!(reserialized, json);
1307 }
1308
1309 #[test]
1310 fn config_validate_rejects_bad_filter() {
1311 let mut config = KafkaInputConfig::default(BTreeMap::new(), "topic");
1312 config.header_filter = Some(serde_json::from_str(r#"{"or": []}"#).unwrap());
1313 assert!(config.validate().is_err());
1314 }
1315
1316 #[test]
1317 fn config_deserializes_header_filter() {
1318 let config: KafkaInputConfig = serde_json::from_value(serde_json::json!({
1320 "topic": "t",
1321 "bootstrap.servers": "localhost:9092",
1322 "header_filter": {"header": {"name": "k", "pattern": "v"}}
1323 }))
1324 .unwrap();
1325 assert!(config.header_filter.is_some());
1326 }
1327}
1328
1329#[cfg(test)]
1330mod timeout_tests {
1331 use super::*;
1332
1333 fn config_json(fields: &str) -> String {
1336 let separator = if fields.is_empty() { "" } else { ", " };
1337 format!(r#"{{"topic": "test_topic"{separator}{fields}}}"#)
1338 }
1339
1340 #[test]
1343 fn group_join_timeout_accepts_both_spellings() {
1344 for (fields, expected) in [
1345 ("", DEFAULT_GROUP_JOIN_TIMEOUT),
1346 (
1347 r#""group_join_timeout": "1500ms""#,
1348 ConfigDuration::from_millis(1500),
1349 ),
1350 (
1351 r#""group_join_timeout_secs": 25"#,
1352 ConfigDuration::from_secs(25),
1353 ),
1354 ] {
1355 let json = config_json(fields);
1356 let config: KafkaInputConfig = serde_json::from_str(&json).unwrap();
1357 assert_eq!(config.group_join_timeout(), expected, "parsing {json}");
1358 }
1359
1360 let json = config_json(r#""group_join_timeout": "1500ms", "group_join_timeout_secs": 25"#);
1362 let error = serde_json::from_str::<KafkaInputConfig>(&json)
1363 .unwrap_err()
1364 .to_string();
1365 assert!(
1366 error.contains("duplicate field `group_join_timeout`"),
1367 "{error}"
1368 );
1369 }
1370
1371 #[test]
1373 fn initialization_timeout_accepts_both_spellings() {
1374 for (fields, expected) in [
1375 ("", DEFAULT_INITIALIZATION_TIMEOUT),
1376 (
1377 r#""initialization_timeout": "2m""#,
1378 ConfigDuration::from_secs(120),
1379 ),
1380 (
1381 r#""initialization_timeout_secs": 15"#,
1382 ConfigDuration::from_secs(15),
1383 ),
1384 ] {
1385 let json = config_json(fields);
1386 let config: KafkaOutputConfig = serde_json::from_str(&json).unwrap();
1387 assert_eq!(config.initialization_timeout(), expected, "parsing {json}");
1388 }
1389 }
1390}