Skip to main content

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    /// When this option is `true`, a `d` event is followed by a tombstone: a message with the
217    /// same key and a null value. Log compaction in Kafka uses tombstones to remove deleted keys.
218    ///
219    /// This option is only valid with an `index`. The default is `true`.
220    pub tombstones_on_delete: Option<bool>,
221}
222
223impl Default for JsonEncoderConfig {
224    fn default() -> Self {
225        Self {
226            update_format: JsonUpdateFormat::default(),
227            json_flavor: None,
228            buffer_size_records: 10_000,
229            array: false,
230            key_fields: None,
231            tombstones_on_delete: None,
232        }
233    }
234}
235
236/// A JSON formatter that writes floats with `ryu`, as `serde_json` 1.0.148
237/// and earlier did, so the JSON text of a float does not change with
238/// `serde_json` updates (1.0.149 writes `1e20` as `1e+20`).
239#[derive(Clone, Copy, Debug, Default)]
240pub struct JsonFloatFormatter;
241
242impl serde_json::ser::Formatter for JsonFloatFormatter {
243    // `serde_json` writes non-finite values as `null` without calling these.
244    fn write_f32<W: ?Sized + std::io::Write>(
245        &mut self,
246        writer: &mut W,
247        value: f32,
248    ) -> std::io::Result<()> {
249        writer.write_all(ryu::Buffer::new().format_finite(value).as_bytes())
250    }
251
252    fn write_f64<W: ?Sized + std::io::Write>(
253        &mut self,
254        writer: &mut W,
255        value: f64,
256    ) -> std::io::Result<()> {
257        writer.write_all(ryu::Buffer::new().format_finite(value).as_bytes())
258    }
259}
260
261/// A `serde_json` serializer that writes floats with [`JsonFloatFormatter`].
262pub fn json_serializer<W: std::io::Write>(
263    writer: W,
264) -> serde_json::Serializer<W, JsonFloatFormatter> {
265    serde_json::Serializer::with_formatter(writer, JsonFloatFormatter)
266}
267
268/// Like `serde_json::to_string`, with floats written by [`JsonFloatFormatter`].
269pub fn to_json_string<T: Serialize + ?Sized>(value: &T) -> serde_json::Result<String> {
270    let mut json = Vec::new();
271    value.serialize(&mut json_serializer(&mut json))?;
272    String::from_utf8(json).map_err(serde::ser::Error::custom)
273}
274
275#[cfg(test)]
276mod float_format_tests {
277    use super::to_json_string;
278
279    #[test]
280    fn floats_keep_their_json_text() {
281        let doubles = [1e20, -3.4e38, 1.5e-7, 123.25, 1e15, f64::NAN];
282        assert_eq!(
283            to_json_string(&doubles).unwrap(),
284            "[1e20,-3.4e38,1.5e-7,123.25,1000000000000000.0,null]"
285        );
286        assert_eq!(to_json_string(&3.4e38f32).unwrap(), "3.4e38");
287    }
288}