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
57impl KafkaInputConfig {
58 pub fn poller_threads(&self) -> usize {
61 let max_threads = available_parallelism().map_or(16, NonZeroUsize::get);
62 self.poller_threads.unwrap_or(3).clamp(1, max_threads)
63 }
64}
65
66impl<'de> Deserialize<'de> for KafkaInputConfig {
67 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
68 where
69 D: Deserializer<'de>,
70 {
71 let compat = compat::KafkaInputConfigCompat::deserialize(deserializer)?;
72 Self::try_from(compat).map_err(D::Error::custom)
73 }
74}
75
76#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
78#[serde(rename_all = "snake_case")]
79pub enum KafkaStartFromConfig {
80 Earliest,
82
83 #[default]
88 Latest,
89
90 Offsets(Vec<i64>),
94}
95
96#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ToSchema)]
98pub enum KafkaLogLevel {
99 #[serde(rename = "emerg")]
100 Emerg,
101 #[serde(rename = "alert")]
102 Alert,
103 #[serde(rename = "critical")]
104 Critical,
105 #[serde(rename = "error")]
106 Error,
107 #[serde(rename = "warning")]
108 Warning,
109 #[serde(rename = "notice")]
110 Notice,
111 #[serde(rename = "info")]
112 Info,
113 #[serde(rename = "debug")]
114 Debug,
115}
116
117pub const fn default_group_join_timeout_secs() -> u32 {
120 10
121}
122
123impl KafkaInputConfig {
124 #[allow(dead_code)]
127 fn enforce_option(&mut self, option: &str, val: &str) -> AnyResult<()> {
128 let option_val = self
129 .kafka_options
130 .entry(option.to_string())
131 .or_insert_with(|| val.to_string());
132 if option_val != val {
133 Err(AnyError::msg("cannot override '{option}' option: the Kafka transport adapter sets this option to '{val}'"))?;
134 }
135 Ok(())
136 }
137
138 fn set_option_if_missing(&mut self, option: &str, val: &str) {
140 self.kafka_options
141 .entry(option.to_string())
142 .or_insert_with(|| val.to_string());
143 }
144
145 pub fn validate(&mut self) -> AnyResult<()> {
148 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
149
150 self.set_option_if_missing("enable.auto.commit", "false");
170 self.set_option_if_missing("enable.auto.offset.store", "false");
171
172 let group_id = format!("{}", Uuid::now_v7());
173 self.set_option_if_missing("group.id", &group_id);
174 self.set_option_if_missing("enable.partition.eof", "false");
175
176 self.set_option_if_missing("ssl.ca.location", "probe");
181
182 Ok(())
183 }
184}
185
186pub fn default_redpanda_server() -> String {
187 env::var("REDPANDA_BROKERS").unwrap_or_else(|_| "localhost".to_string())
188}
189
190const fn default_initialization_timeout_secs() -> u32 {
191 60
192}
193
194#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
196#[repr(transparent)]
197pub struct KafkaHeaderValue(pub Vec<u8>);
198
199struct HeaderVisitor;
201
202impl<'de> Visitor<'de> for HeaderVisitor {
203 type Value = KafkaHeaderValue;
204
205 fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
206 formatter.write_str("a string (e.g., \"xyz\") or a byte array (e.g., '[1,2,3])")
207 }
208
209 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
210 where
211 E: Error,
212 {
213 Ok(KafkaHeaderValue(v.as_bytes().to_owned()))
214 }
215
216 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
217 where
218 E: Error,
219 {
220 Ok(KafkaHeaderValue(v.into_bytes()))
221 }
222
223 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
224 where
225 A: SeqAccess<'de>,
226 {
227 let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
228
229 while let Some(b) = seq.next_element()? {
230 result.push(b);
231 }
232
233 Ok(KafkaHeaderValue(result))
234 }
235}
236
237impl<'de> Deserialize<'de> for KafkaHeaderValue {
238 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
239 where
240 D: Deserializer<'de>,
241 {
242 deserializer.deserialize_any(HeaderVisitor)
243 }
244}
245
246#[cfg(test)]
247#[test]
248fn test_kafka_header_value_deserialize() {
249 assert_eq!(
250 serde_json::from_str::<KafkaHeaderValue>(r#""foobar""#).unwrap(),
251 KafkaHeaderValue(br#"foobar"#.to_vec())
252 );
253
254 assert_eq!(
255 serde_json::from_str::<KafkaHeaderValue>(r#"[1,2,3,4,5]"#).unwrap(),
256 KafkaHeaderValue(vec![1u8, 2, 3, 4, 5])
257 );
258
259 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"150"#).is_err());
260
261 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"{{"foo": "bar"}}"#).is_err());
262}
263
264#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
266pub struct KafkaHeader {
267 pub key: String,
268 pub value: Option<KafkaHeaderValue>,
269}
270
271#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
273pub struct KafkaOutputConfig {
274 #[serde(flatten)]
279 pub kafka_options: BTreeMap<String, String>,
280
281 pub topic: String,
283
284 #[serde(default)]
286 pub headers: Vec<KafkaHeader>,
287
288 pub log_level: Option<KafkaLogLevel>,
293
294 #[serde(default = "default_initialization_timeout_secs")]
299 pub initialization_timeout_secs: u32,
300
301 pub fault_tolerance: Option<KafkaOutputFtConfig>,
303
304 pub kafka_service: Option<String>,
306}
307
308#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
310#[serde(default)]
311pub struct KafkaOutputFtConfig {
312 pub consumer_options: BTreeMap<String, String>,
318
319 pub producer_options: BTreeMap<String, String>,
325}
326
327impl KafkaOutputConfig {
328 #[allow(dead_code)]
329 fn set_option_if_missing(&mut self, option: &str, val: &str) {
331 self.kafka_options
332 .entry(option.to_string())
333 .or_insert_with(|| val.to_string());
334 }
335
336 #[allow(dead_code)]
337 pub fn validate(&mut self) -> AnyResult<()> {
340 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
341
342 self.set_option_if_missing("ssl.ca.location", "probe");
347
348 Ok(())
349 }
350}
351
352#[derive(Deserialize, ToSchema)]
359pub struct Chunk {
360 pub sequence_number: u64,
361
362 pub bin_data: Option<Vec<u8>>,
367
368 pub text_data: Option<String>,
370
371 #[schema(value_type = Option<Object>)]
373 pub json_data: Option<JsonValue>,
374}
375
376mod compat {
377 use std::collections::BTreeMap;
378
379 use serde::Deserialize;
380
381 use crate::transport::kafka::{KafkaLogLevel, KafkaStartFromConfig};
382
383 #[derive(Deserialize)]
384 pub struct KafkaInputConfigCompat {
385 log_level: Option<KafkaLogLevel>,
387
388 #[serde(default = "super::default_group_join_timeout_secs")]
390 group_join_timeout_secs: u32,
391
392 poller_threads: Option<usize>,
394
395 start_from: Option<KafkaStartFromConfig>,
399
400 topic: Option<String>,
403
404 #[serde(default)]
407 topics: Vec<String>,
408
409 fault_tolerance: Option<String>,
411
412 kafka_service: Option<String>,
414
415 #[serde(flatten)]
417 kafka_options: BTreeMap<String, String>,
418 }
419
420 impl TryFrom<KafkaInputConfigCompat> for super::KafkaInputConfig {
421 type Error = String;
422
423 fn try_from(mut compat: KafkaInputConfigCompat) -> Result<Self, Self::Error> {
424 let (topic, start_from) = if !compat.topics.is_empty() {
425 if compat.topic.is_some() {
427 return Err(
428 "Kafka input adapter may not have both (modern) `topic` and (legacy) `topics`."
429 .into(),
430 );
431 }
432 if compat.topics.len() != 1 {
433 return Err(format!(
434 "Kafka input adapter must have exactly one topic (not {}).",
435 compat.topics.len()
436 ));
437 }
438 let start_from = if let Some(start_from) = compat.start_from {
439 start_from
440 } else if let Some(auto_offset_reset) =
441 compat.kafka_options.get("auto.offset.reset")
442 {
443 match auto_offset_reset.as_str() {
444 "smallest" | "earliest" | "beginning" => KafkaStartFromConfig::Earliest,
445 "largest" | "latest" | "end" => KafkaStartFromConfig::Latest,
446 _ => return Err(format!("Unrecognized value {auto_offset_reset:?} for `auto.offset.reset` in Kafka legacy input adapter configuration")),
447 }
448 } else {
449 KafkaStartFromConfig::default()
450 };
451 (compat.topics.pop().unwrap(), start_from)
452 } else if let Some(topic) = compat.topic {
453 if compat.fault_tolerance.is_some() {
455 return Err("Kafka input adapter `fault_tolerance` setting is obsolete.".into());
456 }
457 if compat.kafka_service.is_some() {
458 return Err("Kafka input adapter `kafka_service` setting is obsolete.".into());
459 }
460 (topic, compat.start_from.unwrap_or_default())
461 } else {
462 return Err("Kafka input adapter is missing required `topic` setting.".into());
463 };
464
465 for key in compat.kafka_options.keys() {
466 if !key.contains('.')
467 && key != "debug"
468 && key != "enabled_events"
469 && key != "retries"
470 {
471 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)."));
472 }
473 }
474
475 Ok(Self {
476 topic,
477 kafka_options: compat.kafka_options,
478 log_level: compat.log_level,
479 group_join_timeout_secs: compat.group_join_timeout_secs,
480 poller_threads: compat.poller_threads,
481 start_from,
482 })
483 }
484 }
485}