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 Ok(())
186 }
187}
188
189pub fn default_redpanda_server() -> String {
190 env::var("REDPANDA_BROKERS").unwrap_or_else(|_| "localhost".to_string())
191}
192
193const fn default_initialization_timeout_secs() -> u32 {
194 60
195}
196
197#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
199#[repr(transparent)]
200pub struct KafkaHeaderValue(pub Vec<u8>);
201
202struct HeaderVisitor;
204
205impl<'de> Visitor<'de> for HeaderVisitor {
206 type Value = KafkaHeaderValue;
207
208 fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
209 formatter.write_str("a string (e.g., \"xyz\") or a byte array (e.g., '[1,2,3])")
210 }
211
212 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
213 where
214 E: Error,
215 {
216 Ok(KafkaHeaderValue(v.as_bytes().to_owned()))
217 }
218
219 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
220 where
221 E: Error,
222 {
223 Ok(KafkaHeaderValue(v.into_bytes()))
224 }
225
226 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
227 where
228 A: SeqAccess<'de>,
229 {
230 let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
231
232 while let Some(b) = seq.next_element()? {
233 result.push(b);
234 }
235
236 Ok(KafkaHeaderValue(result))
237 }
238}
239
240impl<'de> Deserialize<'de> for KafkaHeaderValue {
241 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
242 where
243 D: Deserializer<'de>,
244 {
245 deserializer.deserialize_any(HeaderVisitor)
246 }
247}
248
249#[cfg(test)]
250#[test]
251fn test_kafka_header_value_deserialize() {
252 assert_eq!(
253 serde_json::from_str::<KafkaHeaderValue>(r#""foobar""#).unwrap(),
254 KafkaHeaderValue(br#"foobar"#.to_vec())
255 );
256
257 assert_eq!(
258 serde_json::from_str::<KafkaHeaderValue>(r#"[1,2,3,4,5]"#).unwrap(),
259 KafkaHeaderValue(vec![1u8, 2, 3, 4, 5])
260 );
261
262 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"150"#).is_err());
263
264 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"{{"foo": "bar"}}"#).is_err());
265}
266
267#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
269pub struct KafkaHeader {
270 pub key: String,
271 pub value: Option<KafkaHeaderValue>,
272}
273
274#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
276pub struct KafkaOutputConfig {
277 #[serde(flatten)]
282 pub kafka_options: BTreeMap<String, String>,
283
284 pub topic: String,
286
287 #[serde(default)]
289 pub headers: Vec<KafkaHeader>,
290
291 pub log_level: Option<KafkaLogLevel>,
296
297 #[serde(default = "default_initialization_timeout_secs")]
302 pub initialization_timeout_secs: u32,
303
304 pub fault_tolerance: Option<KafkaOutputFtConfig>,
306
307 pub kafka_service: Option<String>,
309
310 pub region: Option<String>,
312}
313
314#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
316#[serde(default)]
317pub struct KafkaOutputFtConfig {
318 pub consumer_options: BTreeMap<String, String>,
324
325 pub producer_options: BTreeMap<String, String>,
331}
332
333impl KafkaOutputConfig {
334 #[allow(dead_code)]
335 fn set_option_if_missing(&mut self, option: &str, val: &str) {
337 self.kafka_options
338 .entry(option.to_string())
339 .or_insert_with(|| val.to_string());
340 }
341
342 #[allow(dead_code)]
343 pub fn validate(&mut self) -> AnyResult<()> {
346 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
347
348 self.set_option_if_missing("ssl.ca.location", "probe");
353
354 Ok(())
355 }
356}
357
358#[derive(Deserialize, ToSchema)]
365pub struct Chunk {
366 pub sequence_number: u64,
367
368 pub bin_data: Option<Vec<u8>>,
373
374 pub text_data: Option<String>,
376
377 #[schema(value_type = Option<Object>)]
379 pub json_data: Option<JsonValue>,
380}
381
382mod compat {
383 use std::collections::BTreeMap;
384
385 use serde::Deserialize;
386
387 use crate::transport::kafka::{KafkaLogLevel, KafkaStartFromConfig};
388
389 #[derive(Deserialize)]
390 pub struct KafkaInputConfigCompat {
391 log_level: Option<KafkaLogLevel>,
393
394 #[serde(default = "super::default_group_join_timeout_secs")]
396 group_join_timeout_secs: u32,
397
398 poller_threads: Option<usize>,
400
401 start_from: Option<KafkaStartFromConfig>,
405
406 topic: Option<String>,
409
410 #[serde(default)]
413 topics: Vec<String>,
414
415 fault_tolerance: Option<String>,
417
418 kafka_service: Option<String>,
420
421 #[serde(flatten)]
423 kafka_options: BTreeMap<String, String>,
424
425 region: Option<String>,
427 }
428
429 impl TryFrom<KafkaInputConfigCompat> for super::KafkaInputConfig {
430 type Error = String;
431
432 fn try_from(mut compat: KafkaInputConfigCompat) -> Result<Self, Self::Error> {
433 let (topic, start_from) = if !compat.topics.is_empty() {
434 if compat.topic.is_some() {
436 return Err(
437 "Kafka input adapter may not have both (modern) `topic` and (legacy) `topics`."
438 .into(),
439 );
440 }
441 if compat.topics.len() != 1 {
442 return Err(format!(
443 "Kafka input adapter must have exactly one topic (not {}).",
444 compat.topics.len()
445 ));
446 }
447 let start_from = if let Some(start_from) = compat.start_from {
448 start_from
449 } else if let Some(auto_offset_reset) =
450 compat.kafka_options.get("auto.offset.reset")
451 {
452 match auto_offset_reset.as_str() {
453 "smallest" | "earliest" | "beginning" => KafkaStartFromConfig::Earliest,
454 "largest" | "latest" | "end" => KafkaStartFromConfig::Latest,
455 _ => return Err(format!("Unrecognized value {auto_offset_reset:?} for `auto.offset.reset` in Kafka legacy input adapter configuration")),
456 }
457 } else {
458 KafkaStartFromConfig::default()
459 };
460 (compat.topics.pop().unwrap(), start_from)
461 } else if let Some(topic) = compat.topic {
462 if compat.fault_tolerance.is_some() {
464 return Err("Kafka input adapter `fault_tolerance` setting is obsolete.".into());
465 }
466 if compat.kafka_service.is_some() {
467 return Err("Kafka input adapter `kafka_service` setting is obsolete.".into());
468 }
469 (topic, compat.start_from.unwrap_or_default())
470 } else {
471 return Err("Kafka input adapter is missing required `topic` setting.".into());
472 };
473
474 for key in compat.kafka_options.keys() {
475 if !key.contains('.')
476 && key != "debug"
477 && key != "enabled_events"
478 && key != "retries"
479 {
480 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)."));
481 }
482 }
483
484 Ok(Self {
485 topic,
486 kafka_options: compat.kafka_options,
487 log_level: compat.log_level,
488 group_join_timeout_secs: compat.group_join_timeout_secs,
489 poller_threads: compat.poller_threads,
490 start_from,
491 region: compat.region,
492 })
493 }
494 }
495}