use anyhow::{Error as AnyError, Result as AnyResult};
use serde::de::{Error, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value as JsonValue;
use std::fmt::Formatter;
use std::{
collections::BTreeMap,
env,
time::{SystemTime, UNIX_EPOCH},
};
use utoipa::ToSchema;
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct KafkaInputConfig {
#[serde(flatten)]
pub kafka_options: BTreeMap<String, String>,
pub topics: Vec<String>,
pub log_level: Option<KafkaLogLevel>,
#[serde(default = "default_group_join_timeout_secs")]
pub group_join_timeout_secs: u32,
pub fault_tolerance: Option<KafkaInputFtConfig>,
pub kafka_service: Option<String>,
pub poller_threads: Option<usize>,
}
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct KafkaInputFtConfig {
#[serde(default)]
pub consumer_options: BTreeMap<String, String>,
#[serde(default)]
pub producer_options: BTreeMap<String, String>,
pub index_suffix: Option<String>,
#[serde(default)]
pub create_missing_index: Option<bool>,
pub max_step_bytes: Option<u64>,
pub max_step_messages: Option<u64>,
}
#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ToSchema)]
pub enum KafkaLogLevel {
#[serde(rename = "emerg")]
Emerg,
#[serde(rename = "alert")]
Alert,
#[serde(rename = "critical")]
Critical,
#[serde(rename = "error")]
Error,
#[serde(rename = "warning")]
Warning,
#[serde(rename = "notice")]
Notice,
#[serde(rename = "info")]
Info,
#[serde(rename = "debug")]
Debug,
}
const fn default_group_join_timeout_secs() -> u32 {
10
}
impl KafkaInputConfig {
#[allow(dead_code)]
fn enforce_option(&mut self, option: &str, val: &str) -> AnyResult<()> {
let option_val = self
.kafka_options
.entry(option.to_string())
.or_insert_with(|| val.to_string());
if option_val != val {
Err(AnyError::msg("cannot override '{option}' option: the Kafka transport adapter sets this option to '{val}'"))?;
}
Ok(())
}
fn set_option_if_missing(&mut self, option: &str, val: &str) {
self.kafka_options
.entry(option.to_string())
.or_insert_with(|| val.to_string());
}
pub fn validate(&mut self) -> AnyResult<()> {
self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
self.set_option_if_missing("enable.auto.commit", "false");
self.set_option_if_missing("enable.auto.offset.store", "false");
let group_id = format!(
"{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis()
);
self.set_option_if_missing("group.id", &group_id);
self.set_option_if_missing("enable.partition.eof", "false");
Ok(())
}
}
pub fn default_redpanda_server() -> String {
env::var("REDPANDA_BROKERS").unwrap_or_else(|_| "localhost".to_string())
}
const fn default_max_inflight_messages() -> u32 {
1000
}
const fn default_initialization_timeout_secs() -> u32 {
60
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
#[repr(transparent)]
pub struct KafkaHeaderValue(pub Vec<u8>);
struct HeaderVisitor;
impl<'de> Visitor<'de> for HeaderVisitor {
type Value = KafkaHeaderValue;
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
formatter.write_str("a string (e.g., \"xyz\") or a byte array (e.g., '[1,2,3])")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(KafkaHeaderValue(v.as_bytes().to_owned()))
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
Ok(KafkaHeaderValue(v.into_bytes()))
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
while let Some(b) = seq.next_element()? {
result.push(b);
}
Ok(KafkaHeaderValue(result))
}
}
impl<'de> Deserialize<'de> for KafkaHeaderValue {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(HeaderVisitor)
}
}
#[cfg(test)]
#[test]
fn test_kafka_header_value_deserialize() {
assert_eq!(
serde_json::from_str::<KafkaHeaderValue>(r#""foobar""#).unwrap(),
KafkaHeaderValue(br#"foobar"#.to_vec())
);
assert_eq!(
serde_json::from_str::<KafkaHeaderValue>(r#"[1,2,3,4,5]"#).unwrap(),
KafkaHeaderValue(vec![1u8, 2, 3, 4, 5])
);
assert!(serde_json::from_str::<KafkaHeaderValue>(r#"150"#).is_err());
assert!(serde_json::from_str::<KafkaHeaderValue>(r#"{{"foo": "bar"}}"#).is_err());
}
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct KafkaHeader {
pub key: String,
pub value: Option<KafkaHeaderValue>,
}
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct KafkaOutputConfig {
#[serde(flatten)]
pub kafka_options: BTreeMap<String, String>,
pub topic: String,
#[serde(default)]
pub headers: Vec<KafkaHeader>,
pub log_level: Option<KafkaLogLevel>,
#[serde(default = "default_max_inflight_messages")]
pub max_inflight_messages: u32,
#[serde(default = "default_initialization_timeout_secs")]
pub initialization_timeout_secs: u32,
pub fault_tolerance: Option<KafkaOutputFtConfig>,
pub kafka_service: Option<String>,
}
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct KafkaOutputFtConfig {
#[serde(default)]
pub consumer_options: BTreeMap<String, String>,
#[serde(default)]
pub producer_options: BTreeMap<String, String>,
}
impl KafkaOutputConfig {
#[allow(dead_code)]
fn set_option_if_missing(&mut self, option: &str, val: &str) {
self.kafka_options
.entry(option.to_string())
.or_insert_with(|| val.to_string());
}
#[allow(dead_code)]
pub fn validate(&mut self) -> AnyResult<()> {
self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
Ok(())
}
}
#[derive(Deserialize, ToSchema)]
pub struct Chunk {
pub sequence_number: u64,
pub bin_data: Option<Vec<u8>>,
pub text_data: Option<String>,
#[schema(value_type = Option<Object>)]
pub json_data: Option<JsonValue>,
}