Skip to main content

feldera_types/format/
avro.rs

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