Skip to main content

feldera_types/format/
avro.rs

1use crate::display_url::{HiddenValues, REDACTED, url_without_credentials};
2use serde::{Deserialize, Serialize};
3use std::{collections::HashMap, fmt::Display};
4use utoipa::ToSchema;
5
6use crate::{
7    duration::{ConfigDuration, LegacyUnit},
8    duration_setting,
9};
10
11duration_setting!(
12    duration_registry_timeout,
13    "registry_timeout",
14    LegacyUnit::Secs
15);
16
17/// Supported Avro data change event formats.
18#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, ToSchema, Default)]
19pub enum AvroUpdateFormat {
20    /// Raw encoding.
21    ///
22    /// Each message in the stream represents a single-record update: an insert, upsert, or delete.
23    ///
24    /// ### Input Connectors
25    /// Raw Avro encoding can be used for insert and upsert operations, but not deletes.
26    /// - The message value contains the record to be inserted or updated.
27    /// - The message key and headers are ignored.
28    ///
29    /// ### Output Connectors
30    /// The raw format supports inserts, upserts, and deletes.
31    /// - The message value contains the record to be inserted or deleted.
32    /// - The operation type is specified in the `op` message header field, which can be
33    ///   `insert`, `update`, or `delete`.
34    /// - The message key can optionally store the primary key (see the `key_mode` property).
35    #[serde(rename = "raw")]
36    #[default]
37    Raw,
38
39    /// Debezium data change event format.
40    ///
41    /// ### Temporal types
42    ///
43    /// Debezium encodes temporal columns with a `connect.name` annotation
44    /// rather than a native Avro logical type. The input connector recognizes
45    /// these annotations and converts each value into the matching Feldera
46    /// column type:
47    ///
48    /// | `connect.name`                          | wire encoding                     | Feldera column |
49    /// |-----------------------------------------|-----------------------------------|----------------|
50    /// | `io.debezium.time.Date`                 | `int` days since epoch            | `DATE`         |
51    /// | `io.debezium.time.Time`                 | `int` milliseconds since midnight | `TIME`         |
52    /// | `io.debezium.time.MicroTime`            | `long` microseconds since midnight| `TIME`         |
53    /// | `io.debezium.time.NanoTime`             | `long` nanoseconds since midnight | `TIME`         |
54    /// | `io.debezium.time.ZonedTime`            | ISO-8601 `string`                 | `TIME`         |
55    /// | `io.debezium.time.Timestamp`            | `long` milliseconds since epoch   | `TIMESTAMP`    |
56    /// | `io.debezium.time.MicroTimestamp`       | `long` microseconds since epoch   | `TIMESTAMP`    |
57    /// | `io.debezium.time.NanoTimestamp`        | `long` nanoseconds since epoch    | `TIMESTAMP`    |
58    /// | `io.debezium.time.ZonedTimestamp`       | ISO-8601 `string`                 | `TIMESTAMP`    |
59    ///
60    /// Any timestamp type populates either a `TIMESTAMP` or a `TIMESTAMP WITH
61    /// TIME ZONE` column; the connector stores the same instant (microseconds
62    /// since the Unix epoch) in both cases.
63    ///
64    /// The `org.apache.kafka.connect.data.{Date,Time,Timestamp}` types emitted
65    /// with `time.precision.mode=connect` are also supported.
66    ///
67    /// `io.debezium.data.VariableScaleDecimal` (used for `NUMERIC`/`DECIMAL`
68    /// columns without a fixed scale, encoded as a `{scale, value}` record) is
69    /// parsed into a `DECIMAL` column.
70    #[serde(rename = "debezium")]
71    Debezium,
72
73    /// Confluent JDBC connector change event format.
74    #[serde(rename = "confluent_jdbc")]
75    ConfluentJdbc,
76}
77
78impl Display for AvroUpdateFormat {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        match self {
81            Self::Raw => f.write_str("raw"),
82            Self::Debezium => f.write_str("debezium"),
83            Self::ConfluentJdbc => f.write_str("confluent_jdbc"),
84        }
85    }
86}
87
88/// Schema registry configuration.
89#[derive(Clone, Serialize, Deserialize, Default, ToSchema)]
90pub struct AvroSchemaRegistryConfig {
91    /// List of schema registry URLs.
92    ///
93    /// * **Input connector**: When non-empty, the connector retrieves Avro
94    ///   message schemas from the registry.
95    ///
96    /// * **Output connector**: When non-empty, the connector will
97    ///   post the schema to the registry and embed the schema id returned
98    ///   by the registry in Avro messages.  Otherwise, schema id 0 is used.
99    #[serde(default)]
100    pub registry_urls: Vec<String>,
101
102    /// Custom headers that will be added to every call to the schema registry.
103    ///
104    /// This property is only applicable to output connectors.
105    ///
106    /// Requires `registry_urls` to be set.
107    #[serde(default)]
108    pub registry_headers: HashMap<String, String>,
109
110    /// Proxy that will be used to access the schema registry.
111    ///
112    /// Requires `registry_urls` to be set.
113    pub registry_proxy: Option<String>,
114
115    /// Timeout used to connect to the registry, for example `10s`.
116    ///
117    /// Requires `registry_urls` to be set. Unset leaves the HTTP client's own
118    /// timeout in place.
119    #[serde(
120        default,
121        alias = "registry_timeout_secs",
122        deserialize_with = "duration_registry_timeout",
123        skip_serializing_if = "Option::is_none"
124    )]
125    #[schema(value_type = Option<String>)]
126    pub registry_timeout: Option<ConfigDuration>,
127
128    /// Username used to authenticate with the registry.
129    ///
130    /// Requires `registry_urls` to be set. This option is mutually exclusive with
131    /// token-based authentication (see `registry_authorization_token`).
132    pub registry_username: Option<String>,
133
134    /// Password used to authenticate with the registry.
135    ///
136    /// Requires `registry_urls` to be set.
137    pub registry_password: Option<String>,
138
139    /// Token used to authenticate with the registry.
140    ///
141    /// Requires `registry_urls` to be set. This option is mutually exclusive with
142    /// password-based authentication (see `registry_username` and `registry_password`).
143    pub registry_authorization_token: Option<String>,
144}
145
146/// Avro output format configuration.
147#[derive(Clone, Serialize, Deserialize, Debug, Default, ToSchema)]
148#[serde(deny_unknown_fields)]
149pub struct AvroParserConfig {
150    /// Format used to encode data change events in this stream.
151    ///
152    /// The default value is 'raw'.
153    #[serde(default)]
154    pub update_format: AvroUpdateFormat,
155
156    /// Avro schema used to encode all records in this stream, specified as a JSON-encoded string.
157    ///
158    /// When this property is set, the connector uses the provided schema instead of
159    /// retrieving the schema from the schema registry. This setting is mutually exclusive
160    /// with `registry_urls`.
161    pub schema: Option<String>,
162
163    /// `true` if serialized messages only contain raw data without the
164    /// header carrying schema ID.
165    ///
166    /// See <https://docs.confluent.io/platform/current/schema-registry/fundamentals/serdes-develop/index.html#wire-format>
167    ///
168    /// The default value is `false`.
169    #[serde(default)]
170    pub skip_schema_id: bool,
171
172    /// Optional name of the field that holds the operation of each record.
173    ///
174    /// The field must be a `string` or `enum` with one of these values:
175    /// - `"I"`: insert
176    /// - `"U"`: upsert
177    /// - `"D"`: delete
178    ///
179    /// If not set, every record is an insert.
180    /// Only works with the `raw` update format.
181    pub cdc_field: Option<String>,
182
183    /// Schema registry configuration.
184    #[serde(flatten)]
185    pub registry_config: AvroSchemaRegistryConfig,
186}
187
188/// Subject name strategies used in registering key and value schemas
189/// with the schema registry.
190#[derive(Clone, Serialize, Deserialize, Debug, ToSchema)]
191pub enum SubjectNameStrategy {
192    /// The subject name is derived directly from the Kafka topic name.
193    ///
194    /// For update formats with both key and value components, use subject names
195    /// `{topic_name}-key` and `{topic_name}-value` for key and value schemas respectively.
196    /// For update formats without a key (e.g., `raw`), publish value schema
197    /// under the subject name `{topic_name}`.
198    ///
199    /// Only applicable when using Kafka as a transport.
200    #[serde(rename = "topic_name")]
201    TopicName,
202
203    /// The name of the SQL relation that the schema is derived from is used as the subject name:
204    /// * the SQL view name for the message value schema.
205    /// * the SQL index name for the message key schema.
206    #[serde(rename = "record_name")]
207    RecordName,
208
209    /// Combines both the topic name and the record name to form the subject.
210    ///
211    /// For update formats with both key and value components, use subject names
212    /// `{topic_name}-{record_name}-key` and `{topic_name}-{record_name}-value` for
213    /// key and value schemas respectively.
214    /// For update formats without a key (e.g., `raw`), publish value schema
215    /// under the subject name `{topic_name}-{record_name}`.
216    ///
217    /// `{record_name}` is the name of the SQL view or index that this connector
218    /// is attached to.
219    ///
220    /// Only applicable when using Kafka as a transport.
221    #[serde(rename = "topic_record_name")]
222    TopicRecordName,
223}
224
225/// Determines how the message key is generated when the Avro encoder is configured
226/// in the `raw` mode.
227#[derive(Clone, Serialize, Deserialize, Debug, ToSchema, PartialEq, Eq)]
228pub enum AvroEncoderKeyMode {
229    /// Produce messages without a key.
230    #[serde(rename = "none")]
231    None,
232
233    /// Uses the unique key columns of the view as the message key.
234    ///
235    /// This setting is supported when the output connector is configured with the `index` property.
236    /// It utilizes the values of the index columns specified in the associated `CREATE INDEX` statement
237    /// as the Avro message key.
238    ///
239    /// A separate Avro schema will be created and registered in the schema registry
240    /// for the key component of the message.
241    #[serde(rename = "key_fields")]
242    KeyFields,
243}
244
245/// Avro output format configuration.
246#[derive(Clone, Serialize, Deserialize, Debug, ToSchema)]
247#[serde(deny_unknown_fields)]
248pub struct AvroEncoderConfig {
249    /// Format used to encode data change events in this stream.
250    ///
251    /// The default value is `raw`.
252    #[serde(default)]
253    pub update_format: AvroUpdateFormat,
254
255    /// Determines how the message key is generated when the Avro encoder is configured
256    /// in the `raw` mode.
257    ///
258    /// The default is `key_fields` when the `index` property of the connector is configured and `none` otherwise.
259    pub key_mode: Option<AvroEncoderKeyMode>,
260
261    /// Avro schema used to encode output records.
262    ///
263    /// When specified, the encoder will use this schema; otherwise it will automatically
264    /// generate an Avro schema based on the SQL view definition.
265    ///
266    /// Specified as a string containing schema definition in JSON format.
267    /// This schema must match precisely the SQL view definition, modulo
268    /// nullability of columns.
269    pub schema: Option<String>,
270
271    /// Optional name of the field used for Change Data Capture (CDC) annotations.
272    ///
273    /// Use this setting with data sinks that expect operation type
274    /// (insert, delete, or update) encoded as a column in the Avro record, such
275    /// as the [Iceberg Sink Kafka Connector](https://docs.feldera.com/connectors/sinks/iceberg).
276    ///
277    /// When set (e.g., `"cdc_field": "op"`), the specified field will be added to each record
278    /// to indicate the type of change:
279    /// - `"I"` for insert operations
280    /// - `"U"` for upserts
281    /// - `"D"` for deletions
282    ///
283    /// If not set, CDC metadata will not be included in the records.
284    /// Only works with the `raw` update format.
285    pub cdc_field: Option<String>,
286
287    /// Avro namespace for the generated Avro schemas.
288    pub namespace: Option<String>,
289
290    /// Subject name strategy used to publish Avro schemas used by the connector
291    /// in the schema registry.
292    ///
293    /// When this property is not specified, the connector chooses subject name strategy automatically:
294    /// * `topic_name` for `confluent_jdbc` update format
295    /// * `record_name` for `raw` update format
296    pub subject_name_strategy: Option<SubjectNameStrategy>,
297
298    /// Set to `true` if serialized messages should only contain raw data
299    /// without the header carrying schema ID.
300    /// `False` by default.
301    ///
302    /// See <https://docs.confluent.io/platform/current/schema-registry/fundamentals/serdes-develop/index.html#wire-format>
303    #[serde(default)]
304    pub skip_schema_id: bool,
305
306    /// Schema registry configuration.
307    ///
308    /// When configured, the connector will push the Avro schema, whether it is specified as part of
309    /// connector configuration or generated automatically, to the schema registry and use the schema id
310    /// assigned by the registry in the
311    #[serde(flatten)]
312    pub registry_config: AvroSchemaRegistryConfig,
313
314    /// The number of threads to use during encoding.
315    ///
316    /// Avro encoder supports encoding multiple records in parallel. This configuration specifies
317    /// the number of threads to run in parallel.
318    /// Default: 4
319    #[serde(default = "default_encoder_threads")]
320    pub threads: usize,
321}
322
323impl Default for AvroEncoderConfig {
324    fn default() -> Self {
325        Self {
326            update_format: Default::default(),
327            key_mode: Default::default(),
328            schema: Default::default(),
329            cdc_field: Default::default(),
330            namespace: Default::default(),
331            subject_name_strategy: Default::default(),
332            skip_schema_id: Default::default(),
333            registry_config: Default::default(),
334            threads: default_encoder_threads(),
335        }
336    }
337}
338
339fn default_encoder_threads() -> usize {
340    4
341}
342
343impl std::fmt::Debug for AvroSchemaRegistryConfig {
344    /// Shows the URLs without credentials, the headers with hidden values,
345    /// and the credential fields as present or absent.
346    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
347        // The pattern names every field without `..`: a new field breaks the
348        // build here until its display is decided.
349        let Self {
350            registry_urls,
351            registry_headers,
352            registry_proxy,
353            registry_timeout,
354            registry_username,
355            registry_password,
356            registry_authorization_token,
357        } = self;
358        let present = |value: &Option<String>| value.as_ref().map(|_| REDACTED);
359        let urls: Vec<String> = registry_urls
360            .iter()
361            .map(|url| url_without_credentials(url))
362            .collect();
363        let headers = HiddenValues(registry_headers.keys().map(String::as_str).collect());
364        f.debug_struct("AvroSchemaRegistryConfig")
365            .field("registry_urls", &urls)
366            .field("registry_headers", &headers)
367            .field(
368                "registry_proxy",
369                &registry_proxy.as_deref().map(url_without_credentials),
370            )
371            .field("registry_timeout", registry_timeout)
372            .field("registry_username", registry_username)
373            .field("registry_password", &present(registry_password))
374            .field(
375                "registry_authorization_token",
376                &present(registry_authorization_token),
377            )
378            .finish()
379    }
380}
381
382/// The registry fields shared by input/output Avro configs, inspected before
383/// typed parsing so a failure cannot bypass credential registration.
384pub(crate) fn visit_sensitive_config(
385    config: &serde_json::Value,
386    visit: &mut dyn FnMut(&str, &str),
387) {
388    for name in ["registry_password", "registry_authorization_token"] {
389        crate::sensitive::visit_optional(
390            name,
391            config.get(name).and_then(serde_json::Value::as_str),
392            visit,
393        );
394    }
395    if let Some(urls) = config
396        .get("registry_urls")
397        .and_then(serde_json::Value::as_array)
398    {
399        for (index, url) in urls.iter().enumerate() {
400            if let Some(url) = url.as_str() {
401                crate::sensitive::visit_url(&format!("registry_urls.{index}"), url, visit);
402            }
403        }
404    }
405    if let Some(proxy) = config
406        .get("registry_proxy")
407        .and_then(serde_json::Value::as_str)
408    {
409        crate::sensitive::visit_url("registry_proxy", proxy, visit);
410    }
411    if let Some(headers) = config
412        .get("registry_headers")
413        .and_then(serde_json::Value::as_object)
414    {
415        for (name, value) in headers {
416            if crate::sensitive::credential_header(name) {
417                crate::sensitive::visit_optional(
418                    &format!("registry_headers.{}", name.to_ascii_lowercase()),
419                    value.as_str(),
420                    visit,
421                );
422            }
423        }
424    }
425}
426
427#[cfg(test)]
428mod tests {
429    use super::*;
430
431    /// The Debug output of the registry config holds no credential.
432    #[test]
433    fn registry_debug_omits_credentials() {
434        let config = AvroSchemaRegistryConfig {
435            registry_urls: vec!["http://u:pw-url@registry:8081/v1".to_string()],
436            registry_headers: HashMap::from([(
437                "Authorization".to_string(),
438                "pw-header".to_string(),
439            )]),
440            registry_proxy: Some("http://u:pw-proxy@proxy:3128".to_string()),
441            registry_username: Some("u".to_string()),
442            registry_password: Some("pw-pass".to_string()),
443            registry_authorization_token: Some("pw-token".to_string()),
444            ..Default::default()
445        };
446        let text = format!("{config:?}");
447        for secret in ["pw-url", "pw-header", "pw-proxy", "pw-pass", "pw-token"] {
448            assert!(!text.contains(secret), "{secret} in Debug: {text}");
449        }
450        for name in [
451            "registry:8081/v1",
452            r#""Authorization": "[REDACTED]""#,
453            "proxy:3128",
454        ] {
455            assert!(text.contains(name), "{name} missing: {text}");
456        }
457    }
458
459    /// The schema registry timeout has no default of its own: with neither
460    /// field set the accessor yields `None`, which leaves the HTTP client's own
461    /// timeout in place.  Both spellings reach one field, so writing both is
462    /// rejected as a duplicate.
463    #[test]
464    fn registry_timeout_accepts_both_spellings() {
465        for (json, expected) in [
466            (r#"{}"#, None),
467            (
468                r#"{"registry_timeout": "100ms"}"#,
469                Some(ConfigDuration::from_millis(100)),
470            ),
471            (
472                r#"{"registry_timeout_secs": 10}"#,
473                Some(ConfigDuration::from_secs(10)),
474            ),
475        ] {
476            let config: AvroSchemaRegistryConfig = serde_json::from_str(json).unwrap();
477            assert_eq!(config.registry_timeout, expected, "parsing {json}");
478        }
479
480        // Both spellings reach one field, so writing both is a duplicate.
481        let error = serde_json::from_str::<AvroSchemaRegistryConfig>(
482            r#"{"registry_timeout": "100ms", "registry_timeout_secs": 10}"#,
483        )
484        .unwrap_err()
485        .to_string();
486        assert!(
487            error.contains("duplicate field `registry_timeout`"),
488            "{error}"
489        );
490    }
491}