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::num::NonZeroUsize;
7use std::thread::available_parallelism;
8use std::{collections::BTreeMap, env};
9use utoipa::ToSchema;
10use uuid::Uuid;
11
12/// Configuration for reading data from Kafka topics with `InputTransport`.
13#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
14pub struct KafkaInputConfig {
15 /// Options passed directly to `rdkafka`.
16 ///
17 /// [`librdkafka` options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md)
18 /// used to configure the Kafka consumer.
19 ///
20 /// This input connector does not use consumer groups, so options related to
21 /// consumer groups are rejected, including:
22 ///
23 /// * `group.id`, if present, is ignored.
24 /// * `auto.offset.reset` (use `start_from` instead).
25 /// * "enable.auto.commit", if present, must be set to "false".
26 /// * "enable.auto.offset.store", if present, must be set to "false".
27 #[serde(flatten)]
28 pub kafka_options: BTreeMap<String, String>,
29
30 /// Topic to subscribe to.
31 pub topic: String,
32
33 /// The log level of the client.
34 ///
35 /// If not specified, the log level will be calculated based on the global
36 /// log level of the `log` crate.
37 pub log_level: Option<KafkaLogLevel>,
38
39 /// Maximum timeout in seconds to wait for the endpoint to join the Kafka
40 /// consumer group during initialization.
41 #[serde(default = "default_group_join_timeout_secs")]
42 pub group_join_timeout_secs: u32,
43
44 /// Set to 1 or more to fix the number of threads used to poll
45 /// `rdkafka`. Multiple threads can increase performance with small Kafka
46 /// messages; for large messages, one thread is enough. In either case, too
47 /// many threads can harm performance. If unset, the default is 3, which
48 /// helps with small messages but will not harm performance with large
49 /// messagee
50 pub poller_threads: Option<usize>,
51
52 /// Where to begin reading the topic.
53 #[serde(default)]
54 pub start_from: KafkaStartFromConfig,
55
56 /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
57 pub region: Option<String>,
58
59 /// The list of Kafka partitions to read from.
60 ///
61 /// Only the specified partitions will be consumed. If this field is not set,
62 /// the connector will consume from all available partitions.
63 ///
64 /// If `start_from` is set to `offsets` and this field is provided, the
65 /// number of partitions must exactly match the number of offsets, and the
66 /// order of partitions must correspond to the order of offsets.
67 ///
68 /// If offsets are provided for all partitions, this field can be omitted.
69 pub partitions: Option<Vec<i32>>,
70}
71
72impl KafkaInputConfig {
73 // Returns the number of threads to use based on configuration, defaults,
74 // and system resources.
75 pub fn poller_threads(&self) -> usize {
76 let max_threads = available_parallelism().map_or(16, NonZeroUsize::get);
77 self.poller_threads.unwrap_or(3).clamp(1, max_threads)
78 }
79}
80
81impl<'de> Deserialize<'de> for KafkaInputConfig {
82 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
83 where
84 D: Deserializer<'de>,
85 {
86 let compat = compat::KafkaInputConfigCompat::deserialize(deserializer)?;
87 Self::try_from(compat).map_err(D::Error::custom)
88 }
89}
90
91/// Where to begin reading a Kafka topic.
92#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
93#[serde(rename_all = "snake_case")]
94pub enum KafkaStartFromConfig {
95 /// Start from the beginning of the topic.
96 Earliest,
97
98 /// Start from the current end of the topic.
99 ///
100 /// This will only read any data that is added to the topic after the
101 /// connector initializes.
102 #[default]
103 Latest,
104
105 /// Start from particular offsets in the topic.
106 ///
107 /// The number of offsets must match the number of partitions in the topic.
108 Offsets(Vec<i64>),
109}
110
111/// Kafka logging levels.
112#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ToSchema)]
113pub enum KafkaLogLevel {
114 #[serde(rename = "emerg")]
115 Emerg,
116 #[serde(rename = "alert")]
117 Alert,
118 #[serde(rename = "critical")]
119 Critical,
120 #[serde(rename = "error")]
121 Error,
122 #[serde(rename = "warning")]
123 Warning,
124 #[serde(rename = "notice")]
125 Notice,
126 #[serde(rename = "info")]
127 Info,
128 #[serde(rename = "debug")]
129 Debug,
130}
131
132/// On startup, the endpoint waits to join the consumer group.
133/// This constant defines the default wait timeout.
134pub const fn default_group_join_timeout_secs() -> u32 {
135 10
136}
137
138impl KafkaInputConfig {
139 /// Set `option` to `val`; return an error if `option` is set to a different
140 /// value.
141 #[allow(dead_code)]
142 fn enforce_option(&mut self, option: &str, val: &str) -> AnyResult<()> {
143 let option_val = self
144 .kafka_options
145 .entry(option.to_string())
146 .or_insert_with(|| val.to_string());
147 if option_val != val {
148 Err(AnyError::msg("cannot override '{option}' option: the Kafka transport adapter sets this option to '{val}'"))?;
149 }
150 Ok(())
151 }
152
153 /// Set `option` to `val`, if missing.
154 fn set_option_if_missing(&mut self, option: &str, val: &str) {
155 self.kafka_options
156 .entry(option.to_string())
157 .or_insert_with(|| val.to_string());
158 }
159
160 /// Validate configuration, set default option values required by this
161 /// adapter.
162 pub fn validate(&mut self) -> AnyResult<()> {
163 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
164
165 // These options will prevent librdkafka from automatically committing offsets
166 // of consumed messages to the broker, meaning that next time the
167 // connector is instantiated it will start reading from the offset
168 // specified in `auto.offset.reset`. We used to set these to
169 // `true`, which caused `rdkafka` to hang in some circumstances
170 // (https://github.com/confluentinc/librdkafka/issues/3954). Besides, the new behavior
171 // is probably more correct given that circuit state currently does not survive
172 // across pipeline restarts, so it makes sense to start feeding messages
173 // from the start rather than from the last offset consumed by the
174 // previous instance of the pipeline, whose state is lost. Once we add
175 // fault tolerance, we will likely use explicit commits, which also do
176 // not require these options.
177 //
178 // See https://docs.confluent.io/platform/current/clients/consumer.html#offset-management
179 //
180 // Note: we allow the user to override the options, so they can still enable
181 // auto commit if they know what they are doing, e.g., the secops demo
182 // requires the pipeline to commit its offset for the generator to know
183 // when to resume sending.
184 self.set_option_if_missing("enable.auto.commit", "false");
185 self.set_option_if_missing("enable.auto.offset.store", "false");
186
187 let group_id = format!("{}", Uuid::now_v7());
188 self.set_option_if_missing("group.id", &group_id);
189 self.set_option_if_missing("enable.partition.eof", "false");
190
191 // We link with openssl statically, which means that the default OPENSSLDIR location
192 // baked into openssl is not correct (see https://github.com/fede1024/rust-rdkafka/issues/594).
193 // We set the ssl.ca.location to "probe" so that librdkafka can find the CA certificates in a
194 // standard location (e.g., /etc/ssl/).
195 self.set_option_if_missing("ssl.ca.location", "probe");
196
197 // Enable client context `stats` callback so we can periodically check
198 // up on librdkafka memory usage.
199 self.set_option_if_missing("statistics.interval.ms", "10000");
200
201 if let (Some(partitions), KafkaStartFromConfig::Offsets(offsets)) =
202 (&self.partitions, &self.start_from)
203 {
204 if partitions.len() != offsets.len() {
205 anyhow::bail!("the number of partitions ('{partitions:?}') should be equal to the number of offsets '{offsets:?}' specified")
206 }
207 }
208
209 Ok(())
210 }
211}
212
213pub fn default_redpanda_server() -> String {
214 env::var("REDPANDA_BROKERS").unwrap_or_else(|_| "localhost".to_string())
215}
216
217const fn default_initialization_timeout_secs() -> u32 {
218 60
219}
220
221/// Kafka header value encoded as a UTF-8 string or a byte array.
222#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
223#[repr(transparent)]
224pub struct KafkaHeaderValue(pub Vec<u8>);
225
226/// Visitor for deserializing Kafka headers value.
227struct HeaderVisitor;
228
229impl<'de> Visitor<'de> for HeaderVisitor {
230 type Value = KafkaHeaderValue;
231
232 fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
233 formatter.write_str("a string (e.g., \"xyz\") or a byte array (e.g., '[1,2,3])")
234 }
235
236 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
237 where
238 E: Error,
239 {
240 Ok(KafkaHeaderValue(v.as_bytes().to_owned()))
241 }
242
243 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
244 where
245 E: Error,
246 {
247 Ok(KafkaHeaderValue(v.into_bytes()))
248 }
249
250 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
251 where
252 A: SeqAccess<'de>,
253 {
254 let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
255
256 while let Some(b) = seq.next_element()? {
257 result.push(b);
258 }
259
260 Ok(KafkaHeaderValue(result))
261 }
262}
263
264impl<'de> Deserialize<'de> for KafkaHeaderValue {
265 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
266 where
267 D: Deserializer<'de>,
268 {
269 deserializer.deserialize_any(HeaderVisitor)
270 }
271}
272
273#[cfg(test)]
274#[test]
275fn test_kafka_header_value_deserialize() {
276 assert_eq!(
277 serde_json::from_str::<KafkaHeaderValue>(r#""foobar""#).unwrap(),
278 KafkaHeaderValue(br#"foobar"#.to_vec())
279 );
280
281 assert_eq!(
282 serde_json::from_str::<KafkaHeaderValue>(r#"[1,2,3,4,5]"#).unwrap(),
283 KafkaHeaderValue(vec![1u8, 2, 3, 4, 5])
284 );
285
286 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"150"#).is_err());
287
288 assert!(serde_json::from_str::<KafkaHeaderValue>(r#"{{"foo": "bar"}}"#).is_err());
289}
290
291/// Kafka message header.
292#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
293pub struct KafkaHeader {
294 pub key: String,
295 pub value: Option<KafkaHeaderValue>,
296}
297
298/// Configuration for writing data to a Kafka topic with `OutputTransport`.
299#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
300pub struct KafkaOutputConfig {
301 /// Options passed directly to `rdkafka`.
302 ///
303 /// See [`librdkafka` options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md)
304 /// used to configure the Kafka producer.
305 #[serde(flatten)]
306 pub kafka_options: BTreeMap<String, String>,
307
308 /// Topic to write to.
309 pub topic: String,
310
311 /// Kafka headers to be added to each message produced by this connector.
312 #[serde(default)]
313 pub headers: Vec<KafkaHeader>,
314
315 /// The log level of the client.
316 ///
317 /// If not specified, the log level will be calculated based on the global
318 /// log level of the `log` crate.
319 pub log_level: Option<KafkaLogLevel>,
320
321 /// Maximum timeout in seconds to wait for the endpoint to connect to
322 /// a Kafka broker.
323 ///
324 /// Defaults to 60.
325 #[serde(default = "default_initialization_timeout_secs")]
326 pub initialization_timeout_secs: u32,
327
328 /// Optional configuration for fault tolerance.
329 pub fault_tolerance: Option<KafkaOutputFtConfig>,
330
331 /// If specified, this service is used to provide defaults for the Kafka options.
332 pub kafka_service: Option<String>,
333
334 /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
335 pub region: Option<String>,
336}
337
338/// Fault tolerance configuration for Kafka output connector.
339#[derive(Debug, Clone, Default, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
340#[serde(default)]
341pub struct KafkaOutputFtConfig {
342 /// Options passed to `rdkafka` for consumers only, as documented at
343 /// [`librdkafka`
344 /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
345 ///
346 /// These options override `kafka_options` for consumers, and may be empty.
347 pub consumer_options: BTreeMap<String, String>,
348
349 /// Options passed to `rdkafka` for producers only, as documented at
350 /// [`librdkafka`
351 /// options](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
352 ///
353 /// These options override `kafka_options` for producers, and may be empty.
354 pub producer_options: BTreeMap<String, String>,
355}
356
357impl KafkaOutputConfig {
358 #[allow(dead_code)]
359 /// Set `option` to `val`, if missing.
360 fn set_option_if_missing(&mut self, option: &str, val: &str) {
361 self.kafka_options
362 .entry(option.to_string())
363 .or_insert_with(|| val.to_string());
364 }
365
366 #[allow(dead_code)]
367 /// Validate configuration, set default option values required by this
368 /// adapter.
369 pub fn validate(&mut self) -> AnyResult<()> {
370 self.set_option_if_missing("bootstrap.servers", &default_redpanda_server());
371
372 // We link with openssl statically, which means that the default OPENSSLDIR location
373 // baked into openssl is not correct (see https://github.com/fede1024/rust-rdkafka/issues/594).
374 // We set the ssl.ca.location to "probe" so that librdkafka can find the CA certificates in a
375 // standard location (e.g., /etc/ssl/).
376 self.set_option_if_missing("ssl.ca.location", "probe");
377
378 // Enable client context `stats` callback so we can periodically check
379 // up on librdkafka memory usage.
380 self.set_option_if_missing("statistics.interval.ms", "10000");
381
382 Ok(())
383 }
384}
385
386/// A set of updates to a SQL table or view.
387///
388/// The `sequence_number` field stores the offset of the chunk relative to the
389/// start of the stream and can be used to implement reliable delivery.
390/// The payload is stored in the `bin_data`, `text_data`, or `json_data` field
391/// depending on the data format used.
392#[derive(Deserialize, ToSchema)]
393pub struct Chunk {
394 pub sequence_number: u64,
395
396 // Exactly one of the following fields must be set.
397 // This should be an enum inlined with `#[serde(flatten)]`, but `utoipa`
398 // struggles to generate a schema for that.
399 /// Base64 encoded binary payload, e.g., bincode.
400 pub bin_data: Option<Vec<u8>>,
401
402 /// Text payload, e.g., CSV.
403 pub text_data: Option<String>,
404
405 /// JSON payload.
406 #[schema(value_type = Option<Object>)]
407 pub json_data: Option<JsonValue>,
408}
409
410mod compat {
411 use std::collections::BTreeMap;
412
413 use serde::Deserialize;
414
415 use crate::transport::kafka::{KafkaLogLevel, KafkaStartFromConfig};
416
417 #[derive(Deserialize)]
418 pub struct KafkaInputConfigCompat {
419 /// Current, long-standing configuration option.
420 log_level: Option<KafkaLogLevel>,
421
422 /// Current, long-standing configuration option.
423 #[serde(default = "super::default_group_join_timeout_secs")]
424 group_join_timeout_secs: u32,
425
426 /// Current configuration option.
427 poller_threads: Option<usize>,
428
429 /// Current configuration option, which changed type in an incompatible
430 /// way soon after it was introduced. No backward compatibility for the
431 /// initial form.
432 start_from: Option<KafkaStartFromConfig>,
433
434 /// Current configuration option that replaces the old `topics`
435 /// option. Currently mandatory.
436 topic: Option<String>,
437
438 /// Old form of `topic`. Currently accepted as a substitute as long as
439 /// it has exactly one element.
440 #[serde(default)]
441 topics: Vec<String>,
442
443 /// Legacy, now ignored.
444 fault_tolerance: Option<String>,
445
446 /// Legacy, now ignored.
447 kafka_service: Option<String>,
448
449 /// Options passed directly to `rdkafka`.
450 #[serde(flatten)]
451 kafka_options: BTreeMap<String, String>,
452
453 /// The AWS region to use while connecting to AWS Managed Streaming for Kafka (MSK).
454 region: Option<String>,
455
456 /// The Kafka partitions to read from.
457 partitions: Option<Vec<i32>>,
458 }
459
460 impl TryFrom<KafkaInputConfigCompat> for super::KafkaInputConfig {
461 type Error = String;
462
463 fn try_from(mut compat: KafkaInputConfigCompat) -> Result<Self, Self::Error> {
464 let (topic, start_from) = if !compat.topics.is_empty() {
465 // Legacy mode. Convert to modern form.
466 if compat.topic.is_some() {
467 return Err(
468 "Kafka input adapter may not have both (modern) `topic` and (legacy) `topics`."
469 .into(),
470 );
471 }
472 if compat.topics.len() != 1 {
473 return Err(format!(
474 "Kafka input adapter must have exactly one topic (not {}).",
475 compat.topics.len()
476 ));
477 }
478 let start_from = if let Some(start_from) = compat.start_from {
479 start_from
480 } else if let Some(auto_offset_reset) =
481 compat.kafka_options.get("auto.offset.reset")
482 {
483 match auto_offset_reset.as_str() {
484 "smallest" | "earliest" | "beginning" => KafkaStartFromConfig::Earliest,
485 "largest" | "latest" | "end" => KafkaStartFromConfig::Latest,
486 _ => return Err(format!("Unrecognized value {auto_offset_reset:?} for `auto.offset.reset` in Kafka legacy input adapter configuration")),
487 }
488 } else {
489 KafkaStartFromConfig::default()
490 };
491 (compat.topics.pop().unwrap(), start_from)
492 } else if let Some(topic) = compat.topic {
493 // Modern mode. Forbid legacy settings.
494 if compat.fault_tolerance.is_some() {
495 return Err("Kafka input adapter `fault_tolerance` setting is obsolete.".into());
496 }
497 if compat.kafka_service.is_some() {
498 return Err("Kafka input adapter `kafka_service` setting is obsolete.".into());
499 }
500 (topic, compat.start_from.unwrap_or_default())
501 } else {
502 return Err("Kafka input adapter is missing required `topic` setting.".into());
503 };
504
505 for key in compat.kafka_options.keys() {
506 if !key.contains('.')
507 && key != "debug"
508 && key != "enabled_events"
509 && key != "retries"
510 {
511 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)."));
512 }
513 }
514
515 Ok(Self {
516 topic,
517 kafka_options: compat.kafka_options,
518 log_level: compat.log_level,
519 group_join_timeout_secs: compat.group_join_timeout_secs,
520 poller_threads: compat.poller_threads,
521 start_from,
522 region: compat.region,
523 partitions: compat.partitions,
524 })
525 }
526 }
527}