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
498fn default_group_join_timeout() -> String {
501 DEFAULT_GROUP_JOIN_TIMEOUT.to_string()
502}
503fn default_initialization_timeout() -> String {
504 DEFAULT_INITIALIZATION_TIMEOUT.to_string()
505}
506
507impl KafkaInputConfig {
508 pub fn group_join_timeout(&self) -> ConfigDuration {
511 self.group_join_timeout
512 .unwrap_or(DEFAULT_GROUP_JOIN_TIMEOUT)
513 }
514}
515
516impl KafkaOutputConfig {
517 pub fn initialization_timeout(&self) -> ConfigDuration {
520 self.initialization_timeout
521 .unwrap_or(DEFAULT_INITIALIZATION_TIMEOUT)
522 }
523}
524
525impl KafkaInputConfig {
526 #[allow(dead_code)]
529 fn enforce_option(&mut self, option: &str, val: &str) -> AnyResult<()> {
530 let option_val = self
531 .kafka_options
532 .entry(option.to_string())
533 .or_insert_with(|| val.to_string());
534 if option_val != val {
535 Err(AnyError::msg(
536 "cannot override '{option}' option: the Kafka transport adapter sets this option to '{val}'",
537 ))?;
538 }
539 Ok(())
540 }
541
542 fn set_option_if_missing(&mut self, option: &str, val: &str) {
544 self.kafka_options
545 .entry(option.to_string())
546 .or_insert_with(|| val.to_string());
547 }
548
549 pub fn validate(&mut self) -> AnyResult<()> {
552 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
553
554 self.set_option_if_missing("enable.auto.commit", "false");
574 self.set_option_if_missing("enable.auto.offset.store", "false");
575
576 let group_id = format!("{}", Uuid::now_v7());
577 self.set_option_if_missing("group.id", &group_id);
578 self.set_option_if_missing("enable.partition.eof", "false");
579
580 self.set_option_if_missing("ssl.ca.location", "probe");
585
586 self.set_option_if_missing("statistics.interval.ms", "10000");
589
590 if let (Some(partitions), KafkaStartFromConfig::Offsets(offsets)) =
591 (&self.partitions, &self.start_from)
592 && partitions.len() != offsets.len()
593 {
594 anyhow::bail!(
595 "the number of partitions ('{partitions:?}') should be equal to the number of offsets '{offsets:?}' specified"
596 )
597 }
598
599 if let Some(header_filter) = &self.header_filter {
603 header_filter.validate()?;
604 }
605
606 Ok(())
607 }
608}
609
610pub fn default_redpanda_server() -> String {
611 env::var("REDPANDA_BROKERS").unwrap_or_else(|_| "localhost".to_string())
612}
613
614#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
616#[repr(transparent)]
617pub struct KafkaHeaderValue(pub Vec<u8>);
618
619struct HeaderVisitor;
621
622impl<'de> Visitor<'de> for HeaderVisitor {
623 type Value = KafkaHeaderValue;
624
625 fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
626 formatter.write_str("a string (e.g., \"xyz\") or a byte array (e.g., '[1,2,3])")
627 }
628
629 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
630 where
631 E: Error,
632 {
633 Ok(KafkaHeaderValue(v.as_bytes().to_owned()))
634 }
635
636 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
637 where
638 E: Error,
639 {
640 Ok(KafkaHeaderValue(v.into_bytes()))
641 }
642
643 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
644 where
645 A: SeqAccess<'de>,
646 {
647 let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
648
649 while let Some(b) = seq.next_element()? {
650 result.push(b);
651 }
652
653 Ok(KafkaHeaderValue(result))
654 }
655}
656
657impl<'de> Deserialize<'de> for KafkaHeaderValue {
658 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
659 where
660 D: Deserializer<'de>,
661 {
662 deserializer.deserialize_any(HeaderVisitor)
663 }
664}
665
666#[cfg(test)]
667#[test]
668fn test_kafka_header_value_deserialize() {
669 assert_eq!(
670 serde_json::from_str::<KafkaHeaderValue>(r#""foobar""#).unwrap(),
671 KafkaHeaderValue(br#"foobar"#.to_vec())
672 );
673
674 assert_eq!(
675 serde_json::from_str::<KafkaHeaderValue>(r#"[1,2,3,4,5]"#).unwrap(),
676 KafkaHeaderValue(vec![1u8, 2, 3, 4, 5])
677 );
678
679 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"150"#).is_err());
680
681 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"{{"foo": "bar"}}"#).is_err());
682}
683
684#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
686pub struct KafkaHeader {
687 pub key: String,
688 pub value: Option<KafkaHeaderValue>,
689}
690
691#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
693pub struct KafkaOutputConfig {
694 #[serde(flatten)]
699 pub kafka_options: BTreeMap<String, String>,
700
701 pub topic: String,
703
704 #[serde(default)]
706 pub headers: Vec<KafkaHeader>,
707
708 pub log_level: Option<KafkaLogLevel>,
713
714 #[serde(
717 default,
718 alias = "initialization_timeout_secs",
719 deserialize_with = "duration_initialization_timeout",
720 skip_serializing_if = "Option::is_none"
721 )]
722 #[schema(value_type = Option<String>, default = default_initialization_timeout)]
723 pub initialization_timeout: Option<ConfigDuration>,
724
725 pub fault_tolerance: Option<KafkaOutputFtConfig>,
727
728 pub kafka_service: Option<String>,
730
731 pub region: Option<String>,
733
734 #[serde(skip_serializing_if = "Option::is_none")]
740 pub oauth_provider: Option<KafkaOauthProvider>,
741}
742
743#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
745#[serde(default)]
746pub struct KafkaOutputFtConfig {
747 pub consumer_options: BTreeMap<String, String>,
753
754 pub producer_options: BTreeMap<String, String>,
760}
761
762impl KafkaOutputConfig {
763 #[allow(dead_code)]
764 fn set_option_if_missing(&mut self, option: &str, val: &str) {
766 self.kafka_options
767 .entry(option.to_string())
768 .or_insert_with(|| val.to_string());
769 }
770
771 #[allow(dead_code)]
772 pub fn validate(&mut self) -> AnyResult<()> {
775 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
776
777 self.set_option_if_missing("ssl.ca.location", "probe");
782
783 self.set_option_if_missing("statistics.interval.ms", "10000");
786
787 Ok(())
788 }
789}
790
791#[derive(Deserialize, ToSchema)]
798pub struct Chunk {
799 pub sequence_number: u64,
800
801 pub bin_data: Option<Vec<u8>>,
806
807 pub text_data: Option<String>,
809
810 #[schema(value_type = Option<Object>)]
812 pub json_data: Option<JsonValue>,
813}
814
815mod compat {
816 use std::collections::BTreeMap;
817
818 use serde::Deserialize;
819
820 use crate::duration::ConfigDuration;
821 use crate::transport::kafka::{KafkaLogLevel, KafkaOauthProvider, KafkaStartFromConfig};
822
823 #[derive(Deserialize)]
824 pub struct KafkaInputConfigCompat {
825 log_level: Option<KafkaLogLevel>,
827
828 #[serde(
831 default,
832 alias = "group_join_timeout_secs",
833 deserialize_with = "super::duration_group_join_timeout"
834 )]
835 group_join_timeout: Option<ConfigDuration>,
836
837 poller_threads: Option<usize>,
839
840 #[serde(default, with = "crate::serde_via_value")]
844 start_from: Option<KafkaStartFromConfig>,
845
846 topic: Option<String>,
849
850 #[serde(default)]
853 topics: Vec<String>,
854
855 fault_tolerance: Option<String>,
857
858 kafka_service: Option<String>,
860
861 #[serde(flatten)]
863 kafka_options: BTreeMap<String, String>,
864
865 region: Option<String>,
867
868 oauth_provider: Option<KafkaOauthProvider>,
870
871 partitions: Option<Vec<i32>>,
873
874 #[serde(default)]
882 pub resume_earliest_if_data_expires: bool,
883
884 include_headers: Option<bool>,
885 include_timestamp: Option<bool>,
886 include_partition: Option<bool>,
887 include_offset: Option<bool>,
888 include_topic: Option<bool>,
889 #[serde(default)]
890 synchronize_partitions: bool,
891 #[serde(default, with = "crate::serde_via_value")]
892 header_filter: Option<super::HeaderFilter>,
893 }
894
895 impl TryFrom<KafkaInputConfigCompat> for super::KafkaInputConfig {
896 type Error = String;
897
898 fn try_from(mut compat: KafkaInputConfigCompat) -> Result<Self, Self::Error> {
899 let (topic, start_from) = if !compat.topics.is_empty() {
900 if compat.topic.is_some() {
902 return Err(
903 "Kafka input adapter may not have both (modern) `topic` and (legacy) `topics`."
904 .into(),
905 );
906 }
907 if compat.topics.len() != 1 {
908 return Err(format!(
909 "Kafka input adapter must have exactly one topic (not {}).",
910 compat.topics.len()
911 ));
912 }
913 let start_from = if let Some(start_from) = compat.start_from {
914 start_from
915 } else if let Some(auto_offset_reset) =
916 compat.kafka_options.get("auto.offset.reset")
917 {
918 match auto_offset_reset.as_str() {
919 "smallest" | "earliest" | "beginning" => KafkaStartFromConfig::Earliest,
920 "largest" | "latest" | "end" => KafkaStartFromConfig::Latest,
921 _ => {
922 return Err(format!(
923 "Unrecognized value {auto_offset_reset:?} for `auto.offset.reset` in Kafka legacy input adapter configuration"
924 ));
925 }
926 }
927 } else {
928 KafkaStartFromConfig::default()
929 };
930 (compat.topics.pop().unwrap(), start_from)
931 } else if let Some(topic) = compat.topic {
932 if compat.fault_tolerance.is_some() {
934 return Err("Kafka input adapter `fault_tolerance` setting is obsolete.".into());
935 }
936 if compat.kafka_service.is_some() {
937 return Err("Kafka input adapter `kafka_service` setting is obsolete.".into());
938 }
939 (topic, compat.start_from.unwrap_or_default())
940 } else {
941 return Err("Kafka input adapter is missing required `topic` setting.".into());
942 };
943
944 for key in compat.kafka_options.keys() {
945 if !key.contains('.')
946 && key != "debug"
947 && key != "enabled_events"
948 && key != "retries"
949 {
950 return Err(format!(
951 "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)."
952 ));
953 }
954 }
955
956 Ok(Self {
957 topic,
958 kafka_options: compat.kafka_options,
959 log_level: compat.log_level,
960 group_join_timeout: compat.group_join_timeout,
961 poller_threads: compat.poller_threads,
962 start_from,
963 region: compat.region,
964 oauth_provider: compat.oauth_provider,
965 partitions: compat.partitions,
966 resume_earliest_if_data_expires: compat.resume_earliest_if_data_expires,
967 include_headers: compat.include_headers,
968 include_timestamp: compat.include_timestamp,
969 include_partition: compat.include_partition,
970 include_offset: compat.include_offset,
971 include_topic: compat.include_topic,
972 synchronize_partitions: compat.synchronize_partitions,
973 header_filter: compat.header_filter,
974 })
975 }
976 }
977}
978
979#[cfg(test)]
980mod oauth_provider_tests {
981 use std::collections::BTreeMap;
982
983 use serde::Deserialize;
984
985 use super::{KafkaInputConfig, KafkaOauthProvider, KafkaOutputConfig};
986
987 #[test]
988 fn oauth_provider_is_optional() {
989 let config: KafkaInputConfig =
990 serde_json::from_str(r#"{"topic": "t", "bootstrap.servers": "localhost:9092"}"#)
991 .unwrap();
992 assert_eq!(config.oauth_provider, None);
993 }
994
995 #[test]
996 fn oauth_provider_gcp_round_trips() {
997 let config: KafkaInputConfig = serde_json::from_str(
998 r#"{"topic": "t", "bootstrap.servers": "localhost:9092", "oauth_provider": "gcp"}"#,
999 )
1000 .unwrap();
1001 assert_eq!(config.oauth_provider, Some(KafkaOauthProvider::Gcp));
1002 }
1003
1004 #[test]
1009 fn unset_oauth_provider_is_not_serialized() {
1010 let config = KafkaInputConfig::default(
1011 BTreeMap::from([("bootstrap.servers".into(), "localhost:9092".into())]),
1012 "t",
1013 );
1014 let json = serde_json::to_value(&config).unwrap();
1015 assert!(!json.as_object().unwrap().contains_key("oauth_provider"));
1016
1017 let output_config = KafkaOutputConfig {
1018 kafka_options: BTreeMap::from([("bootstrap.servers".into(), "localhost:9092".into())]),
1019 topic: "t".into(),
1020 headers: Vec::new(),
1021 log_level: None,
1022 initialization_timeout: None,
1023 fault_tolerance: None,
1024 kafka_service: None,
1025 region: None,
1026 oauth_provider: None,
1027 };
1028 let json = serde_json::to_value(&output_config).unwrap();
1029 assert!(!json.as_object().unwrap().contains_key("oauth_provider"));
1030 }
1031
1032 #[test]
1033 fn set_oauth_provider_is_serialized() {
1034 let mut config = KafkaInputConfig::default(
1035 BTreeMap::from([("bootstrap.servers".into(), "localhost:9092".into())]),
1036 "t",
1037 );
1038 config.oauth_provider = Some(KafkaOauthProvider::Gcp);
1039 let json = serde_json::to_value(&config).unwrap();
1040 assert_eq!(json["oauth_provider"], serde_json::json!("gcp"));
1041 }
1042
1043 #[test]
1047 fn old_runtime_rejects_null_oauth_provider() {
1048 #[derive(Deserialize)]
1049 struct OldRuntimeConfig {
1050 #[serde(flatten)]
1051 #[allow(dead_code)]
1052 kafka_options: BTreeMap<String, String>,
1053 #[allow(dead_code)]
1054 topic: String,
1055 }
1056
1057 assert!(
1058 serde_json::from_str::<OldRuntimeConfig>(r#"{"topic": "t", "oauth_provider": null}"#)
1059 .is_err()
1060 );
1061 assert!(serde_json::from_str::<OldRuntimeConfig>(r#"{"topic": "t"}"#).is_ok());
1062 }
1063
1064 #[test]
1065 fn legacy_region_only_config_still_deserializes() {
1066 let config: KafkaInputConfig = serde_json::from_str(
1070 r#"{"topic": "t", "bootstrap.servers": "localhost:9092", "region": "us-east-1"}"#,
1071 )
1072 .unwrap();
1073 assert_eq!(config.region, Some("us-east-1".to_string()));
1074 assert_eq!(config.oauth_provider, None);
1075 }
1076}
1077
1078#[cfg(test)]
1079mod header_filter_tests {
1080 use super::{HeaderFilter, KafkaInputConfig, MAX_HEADER_FILTER_DEPTH};
1081 use std::collections::BTreeMap;
1082
1083 fn admits(json: &str, headers: &[(&str, Option<&[u8]>)]) -> bool {
1085 let filter: HeaderFilter = serde_json::from_str(json).unwrap();
1086 filter.compile().unwrap().matches(headers)
1087 }
1088
1089 #[test]
1090 fn leaf_matches_whole_value() {
1091 let f = r#"{"header": {"name": "type", "pattern": "created|updated"}}"#;
1092 assert!(admits(f, &[("type", Some(&b"created"[..]))]));
1093 assert!(admits(f, &[("type", Some(&b"updated"[..]))]));
1094
1095 assert!(!admits(f, &[("type", Some(&b"created-x"[..]))]));
1097 assert!(!admits(f, &[("type", Some(&b"x-created"[..]))]));
1098
1099 assert!(!admits(f, &[("type", Some(&b"deleted"[..]))]));
1101 assert!(!admits(f, &[("other", Some(&b"created"[..]))]));
1102 assert!(!admits(f, &[]));
1103 }
1104
1105 #[test]
1106 fn null_value_is_empty_bytes() {
1107 let empty = r#"{"header": {"name": "h", "pattern": ""}}"#;
1108 let nonempty = r#"{"header": {"name": "h", "pattern": ".+"}}"#;
1109
1110 assert!(admits(empty, &[("h", None)]));
1112 assert!(!admits(nonempty, &[("h", None)]));
1113 assert!(admits(empty, &[("h", Some(&b""[..]))]));
1114 }
1115
1116 #[test]
1117 fn duplicate_header_any_value_matches() {
1118 let f = r#"{"header": {"name": "k", "pattern": "b"}}"#;
1119 assert!(admits(f, &[("k", Some(&b"a"[..])), ("k", Some(&b"b"[..]))]));
1120 assert!(!admits(
1121 f,
1122 &[("k", Some(&b"a"[..])), ("k", Some(&b"c"[..]))]
1123 ));
1124 }
1125
1126 #[test]
1127 fn non_utf8_value_bytes() {
1128 let f = r#"{"header": {"name": "b", "pattern": "(?s-u:.)"}}"#;
1130 assert!(admits(f, &[("b", Some(&[0xffu8][..]))]));
1131 assert!(!admits(f, &[("b", Some(&[0xffu8, 0xfe][..]))]));
1133 }
1134
1135 #[test]
1136 fn boolean_combinations() {
1137 let f = r#"{"and": [
1139 {"header": {"name": "a", "pattern": "1"}},
1140 {"or": [
1141 {"header": {"name": "b", "pattern": "1"}},
1142 {"header": {"name": "c", "pattern": "1"}}
1143 ]}
1144 ]}"#;
1145 assert!(admits(f, &[("a", Some(&b"1"[..])), ("b", Some(&b"1"[..]))]));
1146 assert!(admits(f, &[("a", Some(&b"1"[..])), ("c", Some(&b"1"[..]))]));
1147 assert!(!admits(f, &[("a", Some(&b"1"[..]))])); assert!(!admits(f, &[("b", Some(&b"1"[..]))])); }
1150
1151 #[test]
1152 fn not_over_leaf() {
1153 let f = r#"{"not": {"header": {"name": "env", "pattern": "prod"}}}"#;
1154 assert!(!admits(f, &[("env", Some(&b"prod"[..]))])); assert!(admits(f, &[("env", Some(&b"dev"[..]))])); assert!(admits(f, &[])); }
1158
1159 #[test]
1160 fn de_morgan_equivalence() {
1161 let lhs = r#"{"not": {"and": [
1162 {"header": {"name": "a", "pattern": "1"}},
1163 {"header": {"name": "b", "pattern": "1"}}
1164 ]}}"#;
1165 let rhs = r#"{"or": [
1166 {"not": {"header": {"name": "a", "pattern": "1"}}},
1167 {"not": {"header": {"name": "b", "pattern": "1"}}}
1168 ]}"#;
1169 let l = serde_json::from_str::<HeaderFilter>(lhs)
1170 .unwrap()
1171 .compile()
1172 .unwrap();
1173 let r = serde_json::from_str::<HeaderFilter>(rhs)
1174 .unwrap()
1175 .compile()
1176 .unwrap();
1177 for a in [None, Some(&b"1"[..])] {
1178 for b in [None, Some(&b"1"[..])] {
1179 let mut headers: Vec<(&str, Option<&[u8]>)> = Vec::new();
1180 if let Some(v) = a {
1181 headers.push(("a", Some(v)));
1182 }
1183 if let Some(v) = b {
1184 headers.push(("b", Some(v)));
1185 }
1186 assert_eq!(
1187 l.matches(&headers),
1188 r.matches(&headers),
1189 "headers={headers:?}"
1190 );
1191 }
1192 }
1193 }
1194
1195 #[test]
1196 fn rejects_empty_combinators() {
1197 for json in [r#"{"and": []}"#, r#"{"or": []}"#] {
1198 let filter: HeaderFilter = serde_json::from_str(json).unwrap();
1199 assert!(filter.validate().is_err(), "expected {json} to be rejected");
1200 }
1201 }
1202
1203 #[test]
1204 fn rejects_deep_nesting() {
1205 let mut json = String::from(r#"{"header": {"name": "x", "pattern": "y"}}"#);
1207 for _ in 0..MAX_HEADER_FILTER_DEPTH + 5 {
1208 json = format!(r#"{{"not": {json}}}"#);
1209 }
1210 let filter: HeaderFilter = serde_json::from_str(&json).unwrap();
1211 assert!(filter.validate().is_err());
1212 }
1213
1214 #[test]
1215 fn rejects_invalid_regex() {
1216 let filter: HeaderFilter =
1217 serde_json::from_str(r#"{"header": {"name": "x", "pattern": "("}}"#).unwrap();
1218 assert!(filter.validate().is_err());
1219 }
1220
1221 #[test]
1222 fn serde_round_trip_external_tagging() {
1223 let json = r#"{"and":[{"header":{"name":"t","pattern":"a|b"}},{"not":{"header":{"name":"s","pattern":"x"}}}]}"#;
1224 let filter: HeaderFilter = serde_json::from_str(json).unwrap();
1225 let reserialized = serde_json::to_string(&filter).unwrap();
1226 assert_eq!(reserialized, json);
1227 }
1228
1229 #[test]
1230 fn config_validate_rejects_bad_filter() {
1231 let mut config = KafkaInputConfig::default(BTreeMap::new(), "topic");
1232 config.header_filter = Some(serde_json::from_str(r#"{"or": []}"#).unwrap());
1233 assert!(config.validate().is_err());
1234 }
1235
1236 #[test]
1237 fn config_deserializes_header_filter() {
1238 let config: KafkaInputConfig = serde_json::from_value(serde_json::json!({
1240 "topic": "t",
1241 "bootstrap.servers": "localhost:9092",
1242 "header_filter": {"header": {"name": "k", "pattern": "v"}}
1243 }))
1244 .unwrap();
1245 assert!(config.header_filter.is_some());
1246 }
1247}
1248
1249#[cfg(test)]
1250mod timeout_tests {
1251 use super::*;
1252
1253 fn config_json(fields: &str) -> String {
1256 let separator = if fields.is_empty() { "" } else { ", " };
1257 format!(r#"{{"topic": "test_topic"{separator}{fields}}}"#)
1258 }
1259
1260 #[test]
1263 fn group_join_timeout_accepts_both_spellings() {
1264 for (fields, expected) in [
1265 ("", DEFAULT_GROUP_JOIN_TIMEOUT),
1266 (
1267 r#""group_join_timeout": "1500ms""#,
1268 ConfigDuration::from_millis(1500),
1269 ),
1270 (
1271 r#""group_join_timeout_secs": 25"#,
1272 ConfigDuration::from_secs(25),
1273 ),
1274 ] {
1275 let json = config_json(fields);
1276 let config: KafkaInputConfig = serde_json::from_str(&json).unwrap();
1277 assert_eq!(config.group_join_timeout(), expected, "parsing {json}");
1278 }
1279
1280 let json = config_json(r#""group_join_timeout": "1500ms", "group_join_timeout_secs": 25"#);
1282 let error = serde_json::from_str::<KafkaInputConfig>(&json)
1283 .unwrap_err()
1284 .to_string();
1285 assert!(
1286 error.contains("duplicate field `group_join_timeout`"),
1287 "{error}"
1288 );
1289 }
1290
1291 #[test]
1293 fn initialization_timeout_accepts_both_spellings() {
1294 for (fields, expected) in [
1295 ("", DEFAULT_INITIALIZATION_TIMEOUT),
1296 (
1297 r#""initialization_timeout": "2m""#,
1298 ConfigDuration::from_secs(120),
1299 ),
1300 (
1301 r#""initialization_timeout_secs": 15"#,
1302 ConfigDuration::from_secs(15),
1303 ),
1304 ] {
1305 let json = config_json(fields);
1306 let config: KafkaOutputConfig = serde_json::from_str(&json).unwrap();
1307 assert_eq!(config.initialization_timeout(), expected, "parsing {json}");
1308 }
1309 }
1310}