feldera_types/format/json.rs
1use serde::{Deserialize, Serialize};
2use std::fmt::Display;
3use utoipa::ToSchema;
4
5/// JSON parser configuration.
6///
7/// Describes the shape of an input JSON stream.
8///
9/// # Examples
10///
11/// A configuration with `update_format="raw"` and `array=false`
12/// is used to parse a stream of JSON objects without any envelope
13/// that get inserted in the input table.
14///
15/// ```json
16/// {"b": false, "i": 100, "s": "foo"}
17/// {"b": true, "i": 5, "s": "bar"}
18/// ```
19///
20/// A configuration with `update_format="insert_delete"` and
21/// `array=false` is used to parse a stream of JSON data change events
22/// in the insert/delete format:
23///
24/// ```json
25/// {"delete": {"b": false, "i": 15, "s": ""}}
26/// {"insert": {"b": false, "i": 100, "s": "foo"}}
27/// ```
28///
29/// A configuration with `update_format="insert_delete"` and
30/// `array=true` is used to parse a stream of JSON arrays
31/// where each array contains multiple data change events in
32/// the insert/delete format.
33///
34/// ```json
35/// [{"insert": {"b": true, "i": 0}}, {"delete": {"b": false, "i": 100, "s": "foo"}}]
36/// ```
37#[derive(Clone, Debug, Default, Deserialize, Serialize, ToSchema)]
38#[serde(default)]
39pub struct JsonParserConfig {
40 /// JSON update format.
41 pub update_format: JsonUpdateFormat,
42
43 /// Specifies JSON encoding used for individual table records.
44 pub json_flavor: JsonFlavor,
45
46 /// Set to `true` if updates in this stream are packaged into JSON arrays.
47 ///
48 /// # Example
49 ///
50 /// ```json
51 /// [{"b": true, "i": 0},{"b": false, "i": 100, "s": "foo"}]
52 /// ```
53 pub array: bool,
54
55 /// Whether JSON elements can span multiple lines.
56 ///
57 /// This only affects JSON input.
58 pub lines: JsonLines,
59}
60
61/// Whether JSON values can span multiple lines.
62#[derive(Deserialize, Serialize, Clone, Debug, Default, PartialEq, Eq, ToSchema)]
63pub enum JsonLines {
64 /// JSON values may span multiple lines.
65 ///
66 /// This supports general-purpose JSON input.
67 #[default]
68 #[serde(rename = "multiple")]
69 Multiple,
70
71 /// A given JSON value never contains a new-line.
72 ///
73 /// Suitable for parsing [NDJSON](https://github.com/ndjson/ndjson-spec).
74 /// Lines are allowed to contain multiple JSON values. The parser ignores
75 /// empty lines.
76 #[serde(rename = "single")]
77 Single,
78}
79
80/// Supported JSON data change event formats.
81///
82/// Each element in a JSON-formatted input stream specifies
83/// an update to one or more records in an input table. We support
84/// several different ways to represent such updates.
85///
86/// ### `InsertDelete`
87///
88/// Each element in the input stream consists of an "insert" or "delete"
89/// command and a record to be inserted to or deleted from the input table.
90///
91/// ```json
92/// {"insert": {"column1": "hello, world!", "column2": 100}}
93/// ```
94///
95/// ### `Debezium`
96///
97/// Debezium CDC format. Refer to [Debezium input connector documentation](https://docs.feldera.com/connectors/sources/debezium) for details.
98///
99/// ### `Snowflake`
100///
101/// Uses flat structure so that fields can get parsed directly into SQL
102/// columns. Defines three metadata fields:
103///
104/// * `__action` - "insert" or "delete"
105/// * `__stream_id` - unique 64-bit ID of the output stream (records within
106/// a stream are totally ordered)
107/// * `__seq_number` - monotonically increasing sequence number relative to
108/// the start of the stream.
109///
110/// ```json
111/// {"PART":1,"VENDOR":2,"EFFECTIVE_SINCE":"2019-05-21","PRICE":"10000","__action":"insert","__stream_id":4523666124030717756,"__seq_number":1}
112/// ```
113///
114/// ### `Raw`
115///
116/// This format is suitable for insert-only streams (no deletions).
117/// Each element in the input stream contains a record without any
118/// additional envelope that gets inserted in the input table.
119#[derive(Deserialize, Serialize, Clone, Debug, Default, PartialEq, Eq, ToSchema)]
120pub enum JsonUpdateFormat {
121 #[default]
122 #[serde(rename = "insert_delete")]
123 InsertDelete,
124
125 #[serde(rename = "debezium")]
126 Debezium,
127
128 #[serde(rename = "snowflake")]
129 Snowflake,
130
131 #[serde(rename = "raw")]
132 Raw,
133
134 #[serde(rename = "redis")]
135 Redis,
136}
137
138impl Display for JsonUpdateFormat {
139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140 match self {
141 JsonUpdateFormat::InsertDelete => write!(f, "insert_delete"),
142 JsonUpdateFormat::Debezium => write!(f, "debezium"),
143 JsonUpdateFormat::Snowflake => write!(f, "snowflake"),
144 JsonUpdateFormat::Raw => write!(f, "raw"),
145 JsonUpdateFormat::Redis => write!(f, "redis"),
146 }
147 }
148}
149
150/// Specifies JSON encoding used of table records.
151#[derive(Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
152pub enum JsonFlavor {
153 /// Default encoding used by Feldera, documented
154 /// [here](https://docs.feldera.com/formats/json#types).
155 #[default]
156 #[serde(rename = "default")]
157 Default,
158 /// Debezium MySQL JSON produced by the default configuration of the
159 /// Debezium [Kafka Connect connector](https://debezium.io/documentation/reference/stable/connectors/mysql.html#mysql-data-types)
160 /// with `decimal.handling.mode` set to "string".
161 #[serde(rename = "debezium_mysql")]
162 DebeziumMySql,
163 /// Debezium Postgres JSON produced by the default configuration of the
164 /// Debezium [Kafka Connect connector](https://debezium.io/documentation/reference/stable/connectors/postgresql.html#postgresql-data-types)
165 /// with `decimal.handling.mode` set to "string".
166 #[serde(rename = "debezium_postgres")]
167 DebeziumPostgres,
168 /// JSON format accepted by Snowflake using default settings.
169 #[serde(rename = "snowflake")]
170 Snowflake,
171 /// JSON format accepted by the Kafka Connect `JsonConverter` class.
172 #[serde(rename = "kafka_connect_json_converter")]
173 KafkaConnectJsonConverter,
174 #[serde(rename = "pandas")]
175 Pandas,
176 /// JSON format used to represent blockchain data.
177 /// Uses Base58 encoding for binary data such as Bitcoin addresses.
178 #[serde(rename = "blockchain")]
179 Blockchain,
180 /// JSON format with "0x"-prefixed hexadecimal encoding for binary data.
181 #[serde(rename = "c_hex")]
182 CHex,
183 /// Parquet to-json format.
184 /// (For internal use only)
185 #[serde(skip)]
186 ParquetConverter,
187 /// Used by the clock input connector.
188 ClockInput,
189 /// Datagen format.
190 /// (For internal use only)
191 #[serde(rename = "datagen")]
192 Datagen,
193 /// Postgres format.
194 /// (For internal use only)
195 #[serde(rename = "postgres")]
196 Postgres,
197}
198
199#[derive(Deserialize, Serialize, ToSchema)]
200#[serde(default)]
201pub struct JsonEncoderConfig {
202 pub update_format: JsonUpdateFormat,
203 pub json_flavor: Option<JsonFlavor>,
204 pub buffer_size_records: usize,
205 pub array: bool,
206
207 /// When this option is set, only the listed fields appear in the Debezium message key.
208 ///
209 /// This option is useful when writing to a table with primary keys.
210 /// For such tables, Debezium expects the message key to contain only
211 /// the primary key columns.
212 ///
213 /// This option is only valid with the `debezium` update format.
214 pub key_fields: Option<Vec<String>>,
215}
216
217impl Default for JsonEncoderConfig {
218 fn default() -> Self {
219 Self {
220 update_format: JsonUpdateFormat::default(),
221 json_flavor: None,
222 buffer_size_records: 10_000,
223 array: false,
224 key_fields: None,
225 }
226 }
227}
228
229/// A JSON formatter that writes floats with `ryu`, as `serde_json` 1.0.148
230/// and earlier did, so the JSON text of a float does not change with
231/// `serde_json` updates (1.0.149 writes `1e20` as `1e+20`).
232#[derive(Clone, Copy, Debug, Default)]
233pub struct JsonFloatFormatter;
234
235impl serde_json::ser::Formatter for JsonFloatFormatter {
236 // `serde_json` writes non-finite values as `null` without calling these.
237 fn write_f32<W: ?Sized + std::io::Write>(
238 &mut self,
239 writer: &mut W,
240 value: f32,
241 ) -> std::io::Result<()> {
242 writer.write_all(ryu::Buffer::new().format_finite(value).as_bytes())
243 }
244
245 fn write_f64<W: ?Sized + std::io::Write>(
246 &mut self,
247 writer: &mut W,
248 value: f64,
249 ) -> std::io::Result<()> {
250 writer.write_all(ryu::Buffer::new().format_finite(value).as_bytes())
251 }
252}
253
254/// A `serde_json` serializer that writes floats with [`JsonFloatFormatter`].
255pub fn json_serializer<W: std::io::Write>(
256 writer: W,
257) -> serde_json::Serializer<W, JsonFloatFormatter> {
258 serde_json::Serializer::with_formatter(writer, JsonFloatFormatter)
259}
260
261/// Like `serde_json::to_string`, with floats written by [`JsonFloatFormatter`].
262pub fn to_json_string<T: Serialize + ?Sized>(value: &T) -> serde_json::Result<String> {
263 let mut json = Vec::new();
264 value.serialize(&mut json_serializer(&mut json))?;
265 String::from_utf8(json).map_err(serde::ser::Error::custom)
266}
267
268#[cfg(test)]
269mod float_format_tests {
270 use super::to_json_string;
271
272 #[test]
273 fn floats_keep_their_json_text() {
274 let doubles = [1e20, -3.4e38, 1.5e-7, 123.25, 1e15, f64::NAN];
275 assert_eq!(
276 to_json_string(&doubles).unwrap(),
277 "[1e20,-3.4e38,1.5e-7,123.25,1000000000000000.0,null]"
278 );
279 assert_eq!(to_json_string(&3.4e38f32).unwrap(), "3.4e38");
280 }
281}