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 Ok(())
177 }
178}
179
180pub fn default_redpanda_server() -> String {
181 env::var("REDPANDA_BROKERS").unwrap_or_else(|_| "localhost".to_string())
182}
183
184const fn default_initialization_timeout_secs() -> u32 {
185 60
186}
187
188#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
190#[repr(transparent)]
191pub struct KafkaHeaderValue(pub Vec<u8>);
192
193struct HeaderVisitor;
195
196impl<'de> Visitor<'de> for HeaderVisitor {
197 type Value = KafkaHeaderValue;
198
199 fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
200 formatter.write_str("a string (e.g., \"xyz\") or a byte array (e.g., '[1,2,3])")
201 }
202
203 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
204 where
205 E: Error,
206 {
207 Ok(KafkaHeaderValue(v.as_bytes().to_owned()))
208 }
209
210 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
211 where
212 E: Error,
213 {
214 Ok(KafkaHeaderValue(v.into_bytes()))
215 }
216
217 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
218 where
219 A: SeqAccess<'de>,
220 {
221 let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
222
223 while let Some(b) = seq.next_element()? {
224 result.push(b);
225 }
226
227 Ok(KafkaHeaderValue(result))
228 }
229}
230
231impl<'de> Deserialize<'de> for KafkaHeaderValue {
232 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
233 where
234 D: Deserializer<'de>,
235 {
236 deserializer.deserialize_any(HeaderVisitor)
237 }
238}
239
240#[cfg(test)]
241#[test]
242fn test_kafka_header_value_deserialize() {
243 assert_eq!(
244 serde_json::from_str::<KafkaHeaderValue>(r#""foobar""#).unwrap(),
245 KafkaHeaderValue(br#"foobar"#.to_vec())
246 );
247
248 assert_eq!(
249 serde_json::from_str::<KafkaHeaderValue>(r#"[1,2,3,4,5]"#).unwrap(),
250 KafkaHeaderValue(vec![1u8, 2, 3, 4, 5])
251 );
252
253 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"150"#).is_err());
254
255 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"{{"foo": "bar"}}"#).is_err());
256}
257
258#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
260pub struct KafkaHeader {
261 pub key: String,
262 pub value: Option<KafkaHeaderValue>,
263}
264
265#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
267pub struct KafkaOutputConfig {
268 #[serde(flatten)]
273 pub kafka_options: BTreeMap<String, String>,
274
275 pub topic: String,
277
278 #[serde(default)]
280 pub headers: Vec<KafkaHeader>,
281
282 pub log_level: Option<KafkaLogLevel>,
287
288 #[serde(default = "default_initialization_timeout_secs")]
293 pub initialization_timeout_secs: u32,
294
295 pub fault_tolerance: Option<KafkaOutputFtConfig>,
297
298 pub kafka_service: Option<String>,
300}
301
302#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
304#[serde(default)]
305pub struct KafkaOutputFtConfig {
306 pub consumer_options: BTreeMap<String, String>,
312
313 pub producer_options: BTreeMap<String, String>,
319}
320
321impl KafkaOutputConfig {
322 #[allow(dead_code)]
323 fn set_option_if_missing(&mut self, option: &str, val: &str) {
325 self.kafka_options
326 .entry(option.to_string())
327 .or_insert_with(|| val.to_string());
328 }
329
330 #[allow(dead_code)]
331 pub fn validate(&mut self) -> AnyResult<()> {
334 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
335 Ok(())
336 }
337}
338
339#[derive(Deserialize, ToSchema)]
346pub struct Chunk {
347 pub sequence_number: u64,
348
349 pub bin_data: Option<Vec<u8>>,
354
355 pub text_data: Option<String>,
357
358 #[schema(value_type = Option<Object>)]
360 pub json_data: Option<JsonValue>,
361}
362
363mod compat {
364 use std::collections::BTreeMap;
365
366 use serde::Deserialize;
367
368 use crate::transport::kafka::{KafkaLogLevel, KafkaStartFromConfig};
369
370 #[derive(Deserialize)]
371 pub struct KafkaInputConfigCompat {
372 log_level: Option<KafkaLogLevel>,
374
375 #[serde(default = "super::default_group_join_timeout_secs")]
377 group_join_timeout_secs: u32,
378
379 poller_threads: Option<usize>,
381
382 start_from: Option<KafkaStartFromConfig>,
386
387 topic: Option<String>,
390
391 #[serde(default)]
394 topics: Vec<String>,
395
396 fault_tolerance: Option<String>,
398
399 kafka_service: Option<String>,
401
402 #[serde(flatten)]
404 kafka_options: BTreeMap<String, String>,
405 }
406
407 impl TryFrom<KafkaInputConfigCompat> for super::KafkaInputConfig {
408 type Error = String;
409
410 fn try_from(mut compat: KafkaInputConfigCompat) -> Result<Self, Self::Error> {
411 let (topic, start_from) = if !compat.topics.is_empty() {
412 if compat.topic.is_some() {
414 return Err(
415 "Kafka input adapter may not have both (modern) `topic` and (legacy) `topics`."
416 .into(),
417 );
418 }
419 if compat.topics.len() != 1 {
420 return Err(format!(
421 "Kafka input adapter must have exactly one topic (not {}).",
422 compat.topics.len()
423 ));
424 }
425 let start_from = if let Some(start_from) = compat.start_from {
426 start_from
427 } else if let Some(auto_offset_reset) =
428 compat.kafka_options.get("auto.offset.reset")
429 {
430 match auto_offset_reset.as_str() {
431 "smallest" | "earliest" | "beginning" => KafkaStartFromConfig::Earliest,
432 "largest" | "latest" | "end" => KafkaStartFromConfig::Latest,
433 _ => return Err(format!("Unrecognized value {auto_offset_reset:?} for `auto.offset.reset` in Kafka legacy input adapter configuration")),
434 }
435 } else {
436 KafkaStartFromConfig::default()
437 };
438 (compat.topics.pop().unwrap(), start_from)
439 } else if let Some(topic) = compat.topic {
440 if compat.fault_tolerance.is_some() {
442 return Err("Kafka input adapter `fault_tolerance` setting is obsolete.".into());
443 }
444 if compat.kafka_service.is_some() {
445 return Err("Kafka input adapter `kafka_service` setting is obsolete.".into());
446 }
447 (topic, compat.start_from.unwrap_or_default())
448 } else {
449 return Err("Kafka input adapter is missing required `topic` setting.".into());
450 };
451
452 for key in compat.kafka_options.keys() {
453 if !key.contains('.')
454 && key != "debug"
455 && key != "enabled_events"
456 && key != "retries"
457 {
458 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)."));
459 }
460 }
461
462 Ok(Self {
463 topic,
464 kafka_options: compat.kafka_options,
465 log_level: compat.log_level,
466 group_join_timeout_secs: compat.group_join_timeout_secs,
467 poller_threads: compat.poller_threads,
468 start_from,
469 })
470 }
471 }
472}