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