1use anyhow::{Error as AnyError, Result as AnyResult};
2use serde::de::{Error, SeqAccess, Visitor};
3use serde::{Deserialize, Deserializer, Serialize};
4use serde_json::Value as JsonValue;
5use std::fmt::Formatter;
6use std::num::NonZeroUsize;
7use std::thread::available_parallelism;
8use std::{collections::BTreeMap, env};
9use utoipa::ToSchema;
10use uuid::Uuid;
11
12#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
14pub struct KafkaInputConfig {
15 #[serde(flatten)]
28 pub kafka_options: BTreeMap<String, String>,
29
30 pub topic: String,
32
33 pub log_level: Option<KafkaLogLevel>,
38
39 #[serde(default = "default_group_join_timeout_secs")]
42 pub group_join_timeout_secs: u32,
43
44 pub poller_threads: Option<usize>,
51
52 #[serde(default)]
54 pub start_from: KafkaStartFromConfig,
55
56 pub region: Option<String>,
58}
59
60impl KafkaInputConfig {
61 pub fn poller_threads(&self) -> usize {
64 let max_threads = available_parallelism().map_or(16, NonZeroUsize::get);
65 self.poller_threads.unwrap_or(3).clamp(1, max_threads)
66 }
67}
68
69impl<'de> Deserialize<'de> for KafkaInputConfig {
70 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
71 where
72 D: Deserializer<'de>,
73 {
74 let compat = compat::KafkaInputConfigCompat::deserialize(deserializer)?;
75 Self::try_from(compat).map_err(D::Error::custom)
76 }
77}
78
79#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
81#[serde(rename_all = "snake_case")]
82pub enum KafkaStartFromConfig {
83 Earliest,
85
86 #[default]
91 Latest,
92
93 Offsets(Vec<i64>),
97}
98
99#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ToSchema)]
101pub enum KafkaLogLevel {
102 #[serde(rename = "emerg")]
103 Emerg,
104 #[serde(rename = "alert")]
105 Alert,
106 #[serde(rename = "critical")]
107 Critical,
108 #[serde(rename = "error")]
109 Error,
110 #[serde(rename = "warning")]
111 Warning,
112 #[serde(rename = "notice")]
113 Notice,
114 #[serde(rename = "info")]
115 Info,
116 #[serde(rename = "debug")]
117 Debug,
118}
119
120pub const fn default_group_join_timeout_secs() -> u32 {
123 10
124}
125
126impl KafkaInputConfig {
127 #[allow(dead_code)]
130 fn enforce_option(&mut self, option: &str, val: &str) -> AnyResult<()> {
131 let option_val = self
132 .kafka_options
133 .entry(option.to_string())
134 .or_insert_with(|| val.to_string());
135 if option_val != val {
136 Err(AnyError::msg("cannot override '{option}' option: the Kafka transport adapter sets this option to '{val}'"))?;
137 }
138 Ok(())
139 }
140
141 fn set_option_if_missing(&mut self, option: &str, val: &str) {
143 self.kafka_options
144 .entry(option.to_string())
145 .or_insert_with(|| val.to_string());
146 }
147
148 pub fn validate(&mut self) -> AnyResult<()> {
151 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
152
153 self.set_option_if_missing("enable.auto.commit", "false");
173 self.set_option_if_missing("enable.auto.offset.store", "false");
174
175 let group_id = format!("{}", Uuid::now_v7());
176 self.set_option_if_missing("group.id", &group_id);
177 self.set_option_if_missing("enable.partition.eof", "false");
178
179 self.set_option_if_missing("ssl.ca.location", "probe");
184
185 self.set_option_if_missing("statistics.interval.ms", "10000");
188
189 Ok(())
190 }
191}
192
193pub fn default_redpanda_server() -> String {
194 env::var("REDPANDA_BROKERS").unwrap_or_else(|_| "localhost".to_string())
195}
196
197const fn default_initialization_timeout_secs() -> u32 {
198 60
199}
200
201#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
203#[repr(transparent)]
204pub struct KafkaHeaderValue(pub Vec<u8>);
205
206struct HeaderVisitor;
208
209impl<'de> Visitor<'de> for HeaderVisitor {
210 type Value = KafkaHeaderValue;
211
212 fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
213 formatter.write_str("a string (e.g., \"xyz\") or a byte array (e.g., '[1,2,3])")
214 }
215
216 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
217 where
218 E: Error,
219 {
220 Ok(KafkaHeaderValue(v.as_bytes().to_owned()))
221 }
222
223 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
224 where
225 E: Error,
226 {
227 Ok(KafkaHeaderValue(v.into_bytes()))
228 }
229
230 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
231 where
232 A: SeqAccess<'de>,
233 {
234 let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
235
236 while let Some(b) = seq.next_element()? {
237 result.push(b);
238 }
239
240 Ok(KafkaHeaderValue(result))
241 }
242}
243
244impl<'de> Deserialize<'de> for KafkaHeaderValue {
245 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
246 where
247 D: Deserializer<'de>,
248 {
249 deserializer.deserialize_any(HeaderVisitor)
250 }
251}
252
253#[cfg(test)]
254#[test]
255fn test_kafka_header_value_deserialize() {
256 assert_eq!(
257 serde_json::from_str::<KafkaHeaderValue>(r#""foobar""#).unwrap(),
258 KafkaHeaderValue(br#"foobar"#.to_vec())
259 );
260
261 assert_eq!(
262 serde_json::from_str::<KafkaHeaderValue>(r#"[1,2,3,4,5]"#).unwrap(),
263 KafkaHeaderValue(vec![1u8, 2, 3, 4, 5])
264 );
265
266 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"150"#).is_err());
267
268 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"{{"foo": "bar"}}"#).is_err());
269}
270
271#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
273pub struct KafkaHeader {
274 pub key: String,
275 pub value: Option<KafkaHeaderValue>,
276}
277
278#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
280pub struct KafkaOutputConfig {
281 #[serde(flatten)]
286 pub kafka_options: BTreeMap<String, String>,
287
288 pub topic: String,
290
291 #[serde(default)]
293 pub headers: Vec<KafkaHeader>,
294
295 pub log_level: Option<KafkaLogLevel>,
300
301 #[serde(default = "default_initialization_timeout_secs")]
306 pub initialization_timeout_secs: u32,
307
308 pub fault_tolerance: Option<KafkaOutputFtConfig>,
310
311 pub kafka_service: Option<String>,
313
314 pub region: Option<String>,
316}
317
318#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
320#[serde(default)]
321pub struct KafkaOutputFtConfig {
322 pub consumer_options: BTreeMap<String, String>,
328
329 pub producer_options: BTreeMap<String, String>,
335}
336
337impl KafkaOutputConfig {
338 #[allow(dead_code)]
339 fn set_option_if_missing(&mut self, option: &str, val: &str) {
341 self.kafka_options
342 .entry(option.to_string())
343 .or_insert_with(|| val.to_string());
344 }
345
346 #[allow(dead_code)]
347 pub fn validate(&mut self) -> AnyResult<()> {
350 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
351
352 self.set_option_if_missing("ssl.ca.location", "probe");
357
358 self.set_option_if_missing("statistics.interval.ms", "10000");
361
362 Ok(())
363 }
364}
365
366#[derive(Deserialize, ToSchema)]
373pub struct Chunk {
374 pub sequence_number: u64,
375
376 pub bin_data: Option<Vec<u8>>,
381
382 pub text_data: Option<String>,
384
385 #[schema(value_type = Option<Object>)]
387 pub json_data: Option<JsonValue>,
388}
389
390mod compat {
391 use std::collections::BTreeMap;
392
393 use serde::Deserialize;
394
395 use crate::transport::kafka::{KafkaLogLevel, KafkaStartFromConfig};
396
397 #[derive(Deserialize)]
398 pub struct KafkaInputConfigCompat {
399 log_level: Option<KafkaLogLevel>,
401
402 #[serde(default = "super::default_group_join_timeout_secs")]
404 group_join_timeout_secs: u32,
405
406 poller_threads: Option<usize>,
408
409 start_from: Option<KafkaStartFromConfig>,
413
414 topic: Option<String>,
417
418 #[serde(default)]
421 topics: Vec<String>,
422
423 fault_tolerance: Option<String>,
425
426 kafka_service: Option<String>,
428
429 #[serde(flatten)]
431 kafka_options: BTreeMap<String, String>,
432
433 region: Option<String>,
435 }
436
437 impl TryFrom<KafkaInputConfigCompat> for super::KafkaInputConfig {
438 type Error = String;
439
440 fn try_from(mut compat: KafkaInputConfigCompat) -> Result<Self, Self::Error> {
441 let (topic, start_from) = if !compat.topics.is_empty() {
442 if compat.topic.is_some() {
444 return Err(
445 "Kafka input adapter may not have both (modern) `topic` and (legacy) `topics`."
446 .into(),
447 );
448 }
449 if compat.topics.len() != 1 {
450 return Err(format!(
451 "Kafka input adapter must have exactly one topic (not {}).",
452 compat.topics.len()
453 ));
454 }
455 let start_from = if let Some(start_from) = compat.start_from {
456 start_from
457 } else if let Some(auto_offset_reset) =
458 compat.kafka_options.get("auto.offset.reset")
459 {
460 match auto_offset_reset.as_str() {
461 "smallest" | "earliest" | "beginning" => KafkaStartFromConfig::Earliest,
462 "largest" | "latest" | "end" => KafkaStartFromConfig::Latest,
463 _ => return Err(format!("Unrecognized value {auto_offset_reset:?} for `auto.offset.reset` in Kafka legacy input adapter configuration")),
464 }
465 } else {
466 KafkaStartFromConfig::default()
467 };
468 (compat.topics.pop().unwrap(), start_from)
469 } else if let Some(topic) = compat.topic {
470 if compat.fault_tolerance.is_some() {
472 return Err("Kafka input adapter `fault_tolerance` setting is obsolete.".into());
473 }
474 if compat.kafka_service.is_some() {
475 return Err("Kafka input adapter `kafka_service` setting is obsolete.".into());
476 }
477 (topic, compat.start_from.unwrap_or_default())
478 } else {
479 return Err("Kafka input adapter is missing required `topic` setting.".into());
480 };
481
482 for key in compat.kafka_options.keys() {
483 if !key.contains('.')
484 && key != "debug"
485 && key != "enabled_events"
486 && key != "retries"
487 {
488 return Err(format!("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)."));
489 }
490 }
491
492 Ok(Self {
493 topic,
494 kafka_options: compat.kafka_options,
495 log_level: compat.log_level,
496 group_join_timeout_secs: compat.group_join_timeout_secs,
497 poller_threads: compat.poller_threads,
498 start_from,
499 region: compat.region,
500 })
501 }
502 }
503}