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