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 /// Optional name of the field that holds the operation of each record.
172 ///
173 /// The field must be a `string` or `enum` with one of these values:
174 /// - `"I"`: insert
175 /// - `"U"`: upsert
176 /// - `"D"`: delete
177 ///
178 /// If not set, every record is an insert.
179 /// Only works with the `raw` update format.
180 pub cdc_field: Option<String>,
181
182 /// Schema registry configuration.
183 #[serde(flatten)]
184 pub registry_config: AvroSchemaRegistryConfig,
185}
186
187/// Subject name strategies used in registering key and value schemas
188/// with the schema registry.
189#[derive(Clone, Serialize, Deserialize, Debug, ToSchema)]
190pub enum SubjectNameStrategy {
191 /// The subject name is derived directly from the Kafka topic name.
192 ///
193 /// For update formats with both key and value components, use subject names
194 /// `{topic_name}-key` and `{topic_name}-value` for key and value schemas respectively.
195 /// For update formats without a key (e.g., `raw`), publish value schema
196 /// under the subject name `{topic_name}`.
197 ///
198 /// Only applicable when using Kafka as a transport.
199 #[serde(rename = "topic_name")]
200 TopicName,
201
202 /// The name of the SQL relation that the schema is derived from is used as the subject name:
203 /// * the SQL view name for the message value schema.
204 /// * the SQL index name for the message key schema.
205 #[serde(rename = "record_name")]
206 RecordName,
207
208 /// Combines both the topic name and the record name to form the subject.
209 ///
210 /// For update formats with both key and value components, use subject names
211 /// `{topic_name}-{record_name}-key` and `{topic_name}-{record_name}-value` for
212 /// key and value schemas respectively.
213 /// For update formats without a key (e.g., `raw`), publish value schema
214 /// under the subject name `{topic_name}-{record_name}`.
215 ///
216 /// `{record_name}` is the name of the SQL view or index that this connector
217 /// is attached to.
218 ///
219 /// Only applicable when using Kafka as a transport.
220 #[serde(rename = "topic_record_name")]
221 TopicRecordName,
222}
223
224/// Determines how the message key is generated when the Avro encoder is configured
225/// in the `raw` mode.
226#[derive(Clone, Serialize, Deserialize, Debug, ToSchema, PartialEq, Eq)]
227pub enum AvroEncoderKeyMode {
228 /// Produce messages without a key.
229 #[serde(rename = "none")]
230 None,
231
232 /// Uses the unique key columns of the view as the message key.
233 ///
234 /// This setting is supported when the output connector is configured with the `index` property.
235 /// It utilizes the values of the index columns specified in the associated `CREATE INDEX` statement
236 /// as the Avro message key.
237 ///
238 /// A separate Avro schema will be created and registered in the schema registry
239 /// for the key component of the message.
240 #[serde(rename = "key_fields")]
241 KeyFields,
242}
243
244/// Avro output format configuration.
245#[derive(Clone, Serialize, Deserialize, Debug, ToSchema)]
246#[serde(deny_unknown_fields)]
247pub struct AvroEncoderConfig {
248 /// Format used to encode data change events in this stream.
249 ///
250 /// The default value is `raw`.
251 #[serde(default)]
252 pub update_format: AvroUpdateFormat,
253
254 /// Determines how the message key is generated when the Avro encoder is configured
255 /// in the `raw` mode.
256 ///
257 /// The default is `key_fields` when the `index` property of the connector is configured and `none` otherwise.
258 pub key_mode: Option<AvroEncoderKeyMode>,
259
260 /// Avro schema used to encode output records.
261 ///
262 /// When specified, the encoder will use this schema; otherwise it will automatically
263 /// generate an Avro schema based on the SQL view definition.
264 ///
265 /// Specified as a string containing schema definition in JSON format.
266 /// This schema must match precisely the SQL view definition, modulo
267 /// nullability of columns.
268 pub schema: Option<String>,
269
270 /// Optional name of the field used for Change Data Capture (CDC) annotations.
271 ///
272 /// Use this setting with data sinks that expect operation type
273 /// (insert, delete, or update) encoded as a column in the Avro record, such
274 /// as the [Iceberg Sink Kafka Connector](https://docs.feldera.com/connectors/sinks/iceberg).
275 ///
276 /// When set (e.g., `"cdc_field": "op"`), the specified field will be added to each record
277 /// to indicate the type of change:
278 /// - `"I"` for insert operations
279 /// - `"U"` for upserts
280 /// - `"D"` for deletions
281 ///
282 /// If not set, CDC metadata will not be included in the records.
283 /// Only works with the `raw` update format.
284 pub cdc_field: Option<String>,
285
286 /// Avro namespace for the generated Avro schemas.
287 pub namespace: Option<String>,
288
289 /// Subject name strategy used to publish Avro schemas used by the connector
290 /// in the schema registry.
291 ///
292 /// When this property is not specified, the connector chooses subject name strategy automatically:
293 /// * `topic_name` for `confluent_jdbc` update format
294 /// * `record_name` for `raw` update format
295 pub subject_name_strategy: Option<SubjectNameStrategy>,
296
297 /// Set to `true` if serialized messages should only contain raw data
298 /// without the header carrying schema ID.
299 /// `False` by default.
300 ///
301 /// See <https://docs.confluent.io/platform/current/schema-registry/fundamentals/serdes-develop/index.html#wire-format>
302 #[serde(default)]
303 pub skip_schema_id: bool,
304
305 /// Schema registry configuration.
306 ///
307 /// When configured, the connector will push the Avro schema, whether it is specified as part of
308 /// connector configuration or generated automatically, to the schema registry and use the schema id
309 /// assigned by the registry in the
310 #[serde(flatten)]
311 pub registry_config: AvroSchemaRegistryConfig,
312
313 /// The number of threads to use during encoding.
314 ///
315 /// Avro encoder supports encoding multiple records in parallel. This configuration specifies
316 /// the number of threads to run in parallel.
317 /// Default: 4
318 #[serde(default = "default_encoder_threads")]
319 pub threads: usize,
320}
321
322impl Default for AvroEncoderConfig {
323 fn default() -> Self {
324 Self {
325 update_format: Default::default(),
326 key_mode: Default::default(),
327 schema: Default::default(),
328 cdc_field: Default::default(),
329 namespace: Default::default(),
330 subject_name_strategy: Default::default(),
331 skip_schema_id: Default::default(),
332 registry_config: Default::default(),
333 threads: default_encoder_threads(),
334 }
335 }
336}
337
338fn default_encoder_threads() -> usize {
339 4
340}
341
342#[cfg(test)]
343mod tests {
344 use super::*;
345
346 /// The schema registry timeout has no default of its own: with neither
347 /// field set the accessor yields `None`, which leaves the HTTP client's own
348 /// timeout in place. Both spellings reach one field, so writing both is
349 /// rejected as a duplicate.
350 #[test]
351 fn registry_timeout_accepts_both_spellings() {
352 for (json, expected) in [
353 (r#"{}"#, None),
354 (
355 r#"{"registry_timeout": "100ms"}"#,
356 Some(ConfigDuration::from_millis(100)),
357 ),
358 (
359 r#"{"registry_timeout_secs": 10}"#,
360 Some(ConfigDuration::from_secs(10)),
361 ),
362 ] {
363 let config: AvroSchemaRegistryConfig = serde_json::from_str(json).unwrap();
364 assert_eq!(config.registry_timeout, expected, "parsing {json}");
365 }
366
367 // Both spellings reach one field, so writing both is a duplicate.
368 let error = serde_json::from_str::<AvroSchemaRegistryConfig>(
369 r#"{"registry_timeout": "100ms", "registry_timeout_secs": 10}"#,
370 )
371 .unwrap_err()
372 .to_string();
373 assert!(
374 error.contains("duplicate field `registry_timeout`"),
375 "{error}"
376 );
377 }
378}