feldera_types/transport/
kafka.rs

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::{
7    collections::BTreeMap,
8    env,
9    time::{SystemTime, UNIX_EPOCH},
10};
11use utoipa::ToSchema;
12
13/// Configuration for reading data from Kafka topics with `InputTransport`.
14#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
15pub struct KafkaInputConfig {
16    /// Options passed directly to `rdkafka`.
17    ///
18    /// [`librdkafka` options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md)
19    /// used to configure the Kafka consumer.  Not all options are valid with
20    /// this Kafka adapter:
21    ///
22    /// * "enable.auto.commit", if present, must be set to "false",
23    /// * "enable.auto.offset.store", if present, must be set to "false"
24    #[serde(flatten)]
25    pub kafka_options: BTreeMap<String, String>,
26
27    /// List of topics to subscribe to.
28    pub topics: Vec<String>,
29
30    /// The log level of the client.
31    ///
32    /// If not specified, the log level will be calculated based on the global
33    /// log level of the `log` crate.
34    pub log_level: Option<KafkaLogLevel>,
35
36    /// Maximum timeout in seconds to wait for the endpoint to join the Kafka
37    /// consumer group during initialization.
38    #[serde(default = "default_group_join_timeout_secs")]
39    pub group_join_timeout_secs: u32,
40
41    /// Deprecated.
42    pub fault_tolerance: Option<String>,
43
44    /// Deprecated.
45    pub kafka_service: Option<String>,
46
47    /// Set to 1 or more to fix the number of threads used to poll
48    /// `rdkafka`. Multiple threads can increase performance with small Kafka
49    /// messages; for large messages, one thread is enough. In either case, too
50    /// many threads can harm performance. If unset, the default is 3, which
51    /// helps with small messages but will not harm performance with large
52    /// messagee
53    pub poller_threads: Option<usize>,
54}
55
56/// Kafka logging levels.
57#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ToSchema)]
58pub enum KafkaLogLevel {
59    #[serde(rename = "emerg")]
60    Emerg,
61    #[serde(rename = "alert")]
62    Alert,
63    #[serde(rename = "critical")]
64    Critical,
65    #[serde(rename = "error")]
66    Error,
67    #[serde(rename = "warning")]
68    Warning,
69    #[serde(rename = "notice")]
70    Notice,
71    #[serde(rename = "info")]
72    Info,
73    #[serde(rename = "debug")]
74    Debug,
75}
76
77/// On startup, the endpoint waits to join the consumer group.
78/// This constant defines the default wait timeout.
79const fn default_group_join_timeout_secs() -> u32 {
80    10
81}
82
83impl KafkaInputConfig {
84    /// Set `option` to `val`; return an error if `option` is set to a different
85    /// value.
86    #[allow(dead_code)]
87    fn enforce_option(&mut self, option: &str, val: &str) -> AnyResult<()> {
88        let option_val = self
89            .kafka_options
90            .entry(option.to_string())
91            .or_insert_with(|| val.to_string());
92        if option_val != val {
93            Err(AnyError::msg("cannot override '{option}' option: the Kafka transport adapter sets this option to '{val}'"))?;
94        }
95        Ok(())
96    }
97
98    /// Set `option` to `val`, if missing.
99    fn set_option_if_missing(&mut self, option: &str, val: &str) {
100        self.kafka_options
101            .entry(option.to_string())
102            .or_insert_with(|| val.to_string());
103    }
104
105    /// Validate configuration, set default option values required by this
106    /// adapter.
107    pub fn validate(&mut self) -> AnyResult<()> {
108        self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
109
110        // These options will prevent librdkafka from automatically committing offsets
111        // of consumed messages to the broker, meaning that next time the
112        // connector is instantiated it will start reading from the offset
113        // specified in `auto.offset.reset`.  We used to set these to
114        // `true`, which caused `rdkafka` to hang in some circumstances
115        // (https://github.com/confluentinc/librdkafka/issues/3954).  Besides, the new behavior
116        // is probably more correct given that circuit state currently does not survive
117        // across pipeline restarts, so it makes sense to start feeding messages
118        // from the start rather than from the last offset consumed by the
119        // previous instance of the pipeline, whose state is lost.  Once we add
120        // fault tolerance, we will likely use explicit commits, which also do
121        // not require these options.
122        //
123        // See https://docs.confluent.io/platform/current/clients/consumer.html#offset-management
124        //
125        // Note: we allow the user to override the options, so they can still enable
126        // auto commit if they know what they are doing, e.g., the secops demo
127        // requires the pipeline to commit its offset for the generator to know
128        // when to resume sending.
129        self.set_option_if_missing("enable.auto.commit", "false");
130        self.set_option_if_missing("enable.auto.offset.store", "false");
131
132        let group_id = format!(
133            "{}",
134            SystemTime::now()
135                .duration_since(UNIX_EPOCH)
136                .unwrap()
137                .as_millis()
138        );
139        self.set_option_if_missing("group.id", &group_id);
140        self.set_option_if_missing("enable.partition.eof", "false");
141
142        Ok(())
143    }
144}
145
146pub fn default_redpanda_server() -> String {
147    env::var("REDPANDA_BROKERS").unwrap_or_else(|_| "localhost".to_string())
148}
149
150const fn default_initialization_timeout_secs() -> u32 {
151    60
152}
153
154/// Kafka header value encoded as a UTF-8 string or a byte array.
155#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
156#[repr(transparent)]
157pub struct KafkaHeaderValue(pub Vec<u8>);
158
159/// Visitor for deserializing Kafka headers value.
160struct HeaderVisitor;
161
162impl<'de> Visitor<'de> for HeaderVisitor {
163    type Value = KafkaHeaderValue;
164
165    fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
166        formatter.write_str("a string (e.g., \"xyz\") or a byte array (e.g., '[1,2,3])")
167    }
168
169    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
170    where
171        E: Error,
172    {
173        Ok(KafkaHeaderValue(v.as_bytes().to_owned()))
174    }
175
176    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
177    where
178        E: Error,
179    {
180        Ok(KafkaHeaderValue(v.into_bytes()))
181    }
182
183    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
184    where
185        A: SeqAccess<'de>,
186    {
187        let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
188
189        while let Some(b) = seq.next_element()? {
190            result.push(b);
191        }
192
193        Ok(KafkaHeaderValue(result))
194    }
195}
196
197impl<'de> Deserialize<'de> for KafkaHeaderValue {
198    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
199    where
200        D: Deserializer<'de>,
201    {
202        deserializer.deserialize_any(HeaderVisitor)
203    }
204}
205
206#[cfg(test)]
207#[test]
208fn test_kafka_header_value_deserialize() {
209    assert_eq!(
210        serde_json::from_str::<KafkaHeaderValue>(r#""foobar""#).unwrap(),
211        KafkaHeaderValue(br#"foobar"#.to_vec())
212    );
213
214    assert_eq!(
215        serde_json::from_str::<KafkaHeaderValue>(r#"[1,2,3,4,5]"#).unwrap(),
216        KafkaHeaderValue(vec![1u8, 2, 3, 4, 5])
217    );
218
219    assert!(serde_json::from_str::<KafkaHeaderValue>(r#"150"#).is_err());
220
221    assert!(serde_json::from_str::<KafkaHeaderValue>(r#"{{"foo": "bar"}}"#).is_err());
222}
223
224/// Kafka message header.
225#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
226pub struct KafkaHeader {
227    pub key: String,
228    pub value: Option<KafkaHeaderValue>,
229}
230
231/// Configuration for writing data to a Kafka topic with `OutputTransport`.
232#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
233pub struct KafkaOutputConfig {
234    /// Options passed directly to `rdkafka`.
235    ///
236    /// See [`librdkafka` options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md)
237    /// used to configure the Kafka producer.
238    #[serde(flatten)]
239    pub kafka_options: BTreeMap<String, String>,
240
241    /// Topic to write to.
242    pub topic: String,
243
244    /// Kafka headers to be added to each message produced by this connector.
245    #[serde(default)]
246    pub headers: Vec<KafkaHeader>,
247
248    /// The log level of the client.
249    ///
250    /// If not specified, the log level will be calculated based on the global
251    /// log level of the `log` crate.
252    pub log_level: Option<KafkaLogLevel>,
253
254    /// Maximum timeout in seconds to wait for the endpoint to connect to
255    /// a Kafka broker.
256    ///
257    /// Defaults to 60.
258    #[serde(default = "default_initialization_timeout_secs")]
259    pub initialization_timeout_secs: u32,
260
261    /// Optional configuration for fault tolerance.
262    pub fault_tolerance: Option<KafkaOutputFtConfig>,
263
264    /// If specified, this service is used to provide defaults for the Kafka options.
265    pub kafka_service: Option<String>,
266}
267
268/// Fault tolerance configuration for Kafka output connector.
269#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
270#[serde(default)]
271pub struct KafkaOutputFtConfig {
272    /// Options passed to `rdkafka` for consumers only, as documented at
273    /// [`librdkafka`
274    /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
275    ///
276    /// These options override `kafka_options` for consumers, and may be empty.
277    pub consumer_options: BTreeMap<String, String>,
278
279    /// Options passed to `rdkafka` for producers only, as documented at
280    /// [`librdkafka`
281    /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
282    ///
283    /// These options override `kafka_options` for producers, and may be empty.
284    pub producer_options: BTreeMap<String, String>,
285}
286
287impl KafkaOutputConfig {
288    #[allow(dead_code)]
289    /// Set `option` to `val`, if missing.
290    fn set_option_if_missing(&mut self, option: &str, val: &str) {
291        self.kafka_options
292            .entry(option.to_string())
293            .or_insert_with(|| val.to_string());
294    }
295
296    #[allow(dead_code)]
297    /// Validate configuration, set default option values required by this
298    /// adapter.
299    pub fn validate(&mut self) -> AnyResult<()> {
300        self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
301        Ok(())
302    }
303}
304
305/// A set of updates to a SQL table or view.
306///
307/// The `sequence_number` field stores the offset of the chunk relative to the
308/// start of the stream and can be used to implement reliable delivery.
309/// The payload is stored in the `bin_data`, `text_data`, or `json_data` field
310/// depending on the data format used.
311#[derive(Deserialize, ToSchema)]
312pub struct Chunk {
313    pub sequence_number: u64,
314
315    // Exactly one of the following fields must be set.
316    // This should be an enum inlined with `#[serde(flatten)]`, but `utoipa`
317    // struggles to generate a schema for that.
318    /// Base64 encoded binary payload, e.g., bincode.
319    pub bin_data: Option<Vec<u8>>,
320
321    /// Text payload, e.g., CSV.
322    pub text_data: Option<String>,
323
324    /// JSON payload.
325    #[schema(value_type = Option<Object>)]
326    pub json_data: Option<JsonValue>,
327}