Skip to main content

rustium_format_json/
lib.rs

1//! JSON encoders for Rustium's native and Debezium compatibility modes.
2
3use std::collections::BTreeMap;
4
5use base64::{Engine as _, engine::general_purpose::STANDARD};
6use bytes::Bytes;
7use rustium_core::{
8    ChangeEvent, DataValue, EncodedEvent, Error, EventEncoder, FieldSchema, Operation, Result, Row,
9    SourcePosition, WireSchema, WireSchemaType,
10};
11
12#[derive(Debug, Clone)]
13pub struct JsonEncoderConfig {
14    pub topic_prefix: String,
15    pub unavailable_value: String,
16    pub tombstones_on_delete: bool,
17    pub heartbeat_topics_prefix: String,
18    pub heartbeat_topic_name: Option<String>,
19}
20
21pub struct RustiumJsonEncoder {
22    config: JsonEncoderConfig,
23}
24
25impl RustiumJsonEncoder {
26    #[must_use]
27    pub fn new(config: JsonEncoderConfig) -> Self {
28        Self { config }
29    }
30}
31
32impl EventEncoder for RustiumJsonEncoder {
33    fn content_type(&self) -> &'static str {
34        "application/vnd.rustium.change+json;version=1"
35    }
36
37    fn encode(&self, event: &ChangeEvent) -> Result<EncodedEvent> {
38        let payload = serde_json::json!({
39            "specversion": "1.0",
40            "id": event.id.0,
41            "source": event.source,
42            "position": event.position,
43            "transaction": event.transaction,
44            "op": operation_name(event.operation),
45            "before": event.before.as_ref().map(|row| row_to_json(row, &self.config.unavailable_value)),
46            "after": event.after.as_ref().map(|row| row_to_json(row, &self.config.unavailable_value)),
47            "schema": event.schema,
48            "source_time": event.source_time,
49            "observed_time": event.observed_time,
50        });
51        build_encoded(event, &self.config, payload)
52    }
53}
54
55pub struct DebeziumJsonEncoder {
56    config: JsonEncoderConfig,
57}
58
59impl DebeziumJsonEncoder {
60    #[must_use]
61    pub fn new(config: JsonEncoderConfig) -> Self {
62        Self { config }
63    }
64}
65
66pub struct DebeziumJsonSchemaEncoder {
67    inner: DebeziumJsonEncoder,
68}
69
70impl DebeziumJsonSchemaEncoder {
71    #[must_use]
72    pub fn new(config: JsonEncoderConfig) -> Self {
73        Self {
74            inner: DebeziumJsonEncoder::new(config),
75        }
76    }
77
78    fn attach_schemas(&self, event: &ChangeEvent, records: &mut [EncodedEvent]) -> Result<()> {
79        let Some(first) = records.first() else {
80            return Ok(());
81        };
82        let key_schema = first
83            .key
84            .is_some()
85            .then(|| json_key_schema(event, &first.destination, &self.inner.config))
86            .transpose()?;
87        let payload_schema = json_payload_schema(event, &first.destination, &self.inner.config)?;
88        for record in records {
89            if record.key.is_some() {
90                record.key_schema.clone_from(&key_schema);
91            }
92            if record.payload.is_some() {
93                record.payload_schema = Some(payload_schema.clone());
94            }
95            record.headers.insert(
96                "rustium.content.type".into(),
97                "application/json; framing=confluent-schema-registry".into(),
98            );
99        }
100        Ok(())
101    }
102}
103
104impl EventEncoder for DebeziumJsonSchemaEncoder {
105    fn content_type(&self) -> &'static str {
106        "application/json; framing=confluent-schema-registry"
107    }
108
109    fn encode(&self, event: &ChangeEvent) -> Result<EncodedEvent> {
110        let mut records = vec![self.inner.encode(event)?];
111        self.attach_schemas(event, &mut records)?;
112        Ok(records.remove(0))
113    }
114
115    fn encode_batch(&self, event: &ChangeEvent) -> Result<Vec<EncodedEvent>> {
116        let mut records = self.inner.encode_batch(event)?;
117        self.attach_schemas(event, &mut records)?;
118        Ok(records)
119    }
120}
121
122impl EventEncoder for DebeziumJsonEncoder {
123    fn content_type(&self) -> &'static str {
124        "application/json"
125    }
126
127    fn encode(&self, event: &ChangeEvent) -> Result<EncodedEvent> {
128        if is_heartbeat(event) {
129            return build_encoded(
130                event,
131                &self.config,
132                serde_json::json!({"ts_ms": event.observed_time.timestamp_millis()}),
133            );
134        }
135        let source_ts = event.source_time.map(|time| time.timestamp_millis());
136        let source = debezium_source(event, source_ts)?;
137        let transaction = event.transaction.as_ref().map(|transaction| {
138            serde_json::json!({
139                "id": transaction.id,
140                "total_order": transaction.total_order,
141                "data_collection_order": transaction.collection_order,
142            })
143        });
144        let payload = if is_logical_decoding_message(event) {
145            let message = event.after.as_ref().ok_or_else(|| {
146                Error::Encoding("PostgreSQL logical decoding message has no content".into())
147            })?;
148            serde_json::json!({
149                "source": source,
150                "op": operation_code(event.operation),
151                "ts_ms": event.observed_time.timestamp_millis(),
152                "transaction": transaction,
153                "message": logical_message_to_json(message, &self.config.unavailable_value),
154            })
155        } else {
156            serde_json::json!({
157                "before": event.before.as_ref().map(|row| row_to_json(row, &self.config.unavailable_value)),
158                "after": event.after.as_ref().map(|row| row_to_json(row, &self.config.unavailable_value)),
159                "source": source,
160                "op": operation_code(event.operation),
161                "ts_ms": event.observed_time.timestamp_millis(),
162                "transaction": transaction,
163            })
164        };
165        build_encoded(event, &self.config, payload)
166    }
167
168    fn encode_batch(&self, event: &ChangeEvent) -> Result<Vec<EncodedEvent>> {
169        let encoded = self.encode(event)?;
170        if event.operation != Operation::Delete || !self.config.tombstones_on_delete {
171            return Ok(vec![encoded]);
172        }
173
174        let tombstone_id = event.id.derived("debezium-tombstone");
175        let mut tombstone = EncodedEvent {
176            id: tombstone_id.clone(),
177            destination: encoded.destination.clone(),
178            key: encoded.key.clone(),
179            key_schema: encoded.key_schema.clone(),
180            payload: None,
181            payload_schema: None,
182            headers: encoded.headers.clone(),
183        };
184        tombstone
185            .headers
186            .insert("rustium.event.id".into(), tombstone_id.0);
187        tombstone
188            .headers
189            .insert("rustium.record.type".into(), "tombstone".into());
190        Ok(vec![encoded, tombstone])
191    }
192}
193
194fn build_encoded(
195    event: &ChangeEvent,
196    config: &JsonEncoderConfig,
197    payload: serde_json::Value,
198) -> Result<EncodedEvent> {
199    let heartbeat = is_heartbeat(event);
200    let logical_message = is_logical_decoding_message(event);
201    let destination = if heartbeat {
202        config.heartbeat_topic_name.clone().unwrap_or_else(|| {
203            format!("{}.{}", config.heartbeat_topics_prefix, config.topic_prefix)
204        })
205    } else if logical_message {
206        format!("{}.message", config.topic_prefix)
207    } else {
208        let table = event
209            .source
210            .table
211            .as_deref()
212            .ok_or_else(|| Error::Encoding("event has no source table".into()))?;
213        if event.source.schema.is_none() {
214            format!(
215                "{}.{}.{}",
216                config.topic_prefix, event.source.database, table
217            )
218        } else {
219            let schema = event
220                .source
221                .schema
222                .as_deref()
223                .ok_or_else(|| Error::Encoding("event has no source schema".into()))?;
224            format!(
225                "{}.{}.{}.{}",
226                config.topic_prefix, event.source.database, schema, table
227            )
228        }
229    };
230    let key = if heartbeat {
231        Some(Bytes::from(serde_json::to_vec(&serde_json::json!({
232            "serverName": event.source.connector_name,
233        }))?))
234    } else {
235        event
236            .after
237            .as_ref()
238            .or(event.before.as_ref())
239            .and_then(|row| event_key(row, event, &config.unavailable_value))
240            .map(|value| Bytes::from(serde_json::to_vec(&value).expect("JSON key cannot fail")))
241    };
242    let mut headers = BTreeMap::new();
243    headers.insert("rustium.event.id".into(), event.id.0.clone());
244    headers.insert("rustium.content.type".into(), "application/json".into());
245    if heartbeat {
246        headers.insert("rustium.record.type".into(), "heartbeat".into());
247    } else if logical_message {
248        headers.insert(
249            "rustium.record.type".into(),
250            "logical-decoding-message".into(),
251        );
252    }
253    Ok(EncodedEvent {
254        id: event.id.clone(),
255        destination,
256        key,
257        key_schema: None,
258        payload: Some(Bytes::from(serde_json::to_vec(&payload)?)),
259        payload_schema: None,
260        headers,
261    })
262}
263
264fn is_heartbeat(event: &ChangeEvent) -> bool {
265    event
266        .source
267        .attributes
268        .get("rustium.heartbeat")
269        .is_some_and(|value| value == &serde_json::Value::Bool(true))
270}
271
272fn is_logical_decoding_message(event: &ChangeEvent) -> bool {
273    event
274        .source
275        .attributes
276        .get("rustium.logical_decoding_message")
277        .is_some_and(|value| value == &serde_json::Value::Bool(true))
278}
279
280fn debezium_source(event: &ChangeEvent, source_ts: Option<i64>) -> Result<serde_json::Value> {
281    let common = serde_json::json!({
282        "version": event.source.version,
283        "connector": event.source.connector,
284        "name": event.source.connector_name,
285        "ts_ms": source_ts,
286        "snapshot": snapshot_marker(event),
287        "db": event.source.database,
288        "schema": event.source.schema,
289        "table": event.source.table,
290    });
291    let mut source = common
292        .as_object()
293        .cloned()
294        .ok_or_else(|| Error::Encoding("source metadata is not an object".into()))?;
295    match &event.position {
296        SourcePosition::Postgres(position) => {
297            source.insert(
298                "sequence".into(),
299                serde_json::to_string(&[
300                    position.commit_lsn.unwrap_or(position.lsn).to_string(),
301                    position.lsn.to_string(),
302                ])?
303                .into(),
304            );
305            source.insert("txId".into(), position.transaction_id.into());
306            source.insert("lsn".into(), position.lsn.into());
307            source.insert("xmin".into(), position.xmin.into());
308        }
309        SourcePosition::MySql(position) => {
310            source.insert("server_id".into(), position.server_id.into());
311            source.insert("gtid".into(), position.gtid_set.clone().into());
312            source.insert("file".into(), position.binlog_filename.clone().into());
313            source.insert("pos".into(), position.binlog_position.into());
314            source.insert("row".into(), position.event_serial.into());
315            source.insert("thread".into(), serde_json::Value::Null);
316            source.insert("query".into(), serde_json::Value::Null);
317        }
318        SourcePosition::SqlServer(position) => {
319            source.insert("change_lsn".into(), position.change_lsn.clone().into());
320            source.insert("commit_lsn".into(), position.commit_lsn.clone().into());
321            source.insert("event_serial_no".into(), position.event_serial.into());
322        }
323        SourcePosition::Oracle(position) => {
324            source.insert("scn".into(), position.scn.into());
325            source.insert("commit_scn".into(), position.commit_scn.into());
326            source.insert("txId".into(), position.transaction_id.clone().into());
327            source.insert("rs_id".into(), position.rs_id.clone().into());
328            source.insert("ssn".into(), position.ssn.into());
329            source.insert("event_serial_no".into(), position.event_serial.into());
330        }
331        SourcePosition::MongoDb(position) => {
332            source.insert("resume_token".into(), position.resume_token.clone().into());
333            source.insert(
334                "cluster_time_seconds".into(),
335                position.cluster_time_seconds.map(u64::from).into(),
336            );
337            source.insert(
338                "cluster_time_increment".into(),
339                position.cluster_time_increment.map(u64::from).into(),
340            );
341            source.insert("event_serial_no".into(), position.event_serial.into());
342        }
343        SourcePosition::Debezium(position) => {
344            source.insert(
345                "source_offset".into(),
346                serde_json::to_string(&position.source)?.into(),
347            );
348            source.insert("record_id".into(), position.record_id.clone().into());
349            source.insert("event_serial_no".into(), position.event_serial.into());
350        }
351    }
352    Ok(source.into())
353}
354
355fn snapshot_marker(event: &ChangeEvent) -> &'static str {
356    if event
357        .source
358        .attributes
359        .get("rustium.snapshot.kind")
360        .and_then(serde_json::Value::as_str)
361        == Some("incremental")
362    {
363        "incremental"
364    } else if event.source.snapshot {
365        "true"
366    } else {
367        "false"
368    }
369}
370
371fn json_source_schema(event: &ChangeEvent) -> serde_json::Value {
372    let mut properties = serde_json::Map::from_iter([
373        ("version".into(), serde_json::json!({"type": "string"})),
374        ("connector".into(), serde_json::json!({"type": "string"})),
375        ("name".into(), serde_json::json!({"type": "string"})),
376        (
377            "ts_ms".into(),
378            serde_json::json!({"type": ["integer", "null"]}),
379        ),
380        ("snapshot".into(), serde_json::json!({"type": "string"})),
381        ("db".into(), serde_json::json!({"type": "string"})),
382        (
383            "schema".into(),
384            serde_json::json!({"type": ["string", "null"]}),
385        ),
386        (
387            "table".into(),
388            serde_json::json!({"type": ["string", "null"]}),
389        ),
390    ]);
391    let mut required = vec![
392        "version",
393        "connector",
394        "name",
395        "ts_ms",
396        "snapshot",
397        "db",
398        "schema",
399        "table",
400    ];
401    let connector_fields: Vec<(&str, serde_json::Value)> = match &event.position {
402        SourcePosition::Postgres(_) => vec![
403            ("sequence", serde_json::json!({"type": "string"})),
404            ("txId", serde_json::json!({"type": ["integer", "null"]})),
405            ("lsn", serde_json::json!({"type": "integer"})),
406            ("xmin", serde_json::json!({"type": ["integer", "null"]})),
407        ],
408        SourcePosition::MySql(_) => vec![
409            ("server_id", serde_json::json!({"type": "integer"})),
410            ("gtid", serde_json::json!({"type": ["string", "null"]})),
411            ("file", serde_json::json!({"type": "string"})),
412            ("pos", serde_json::json!({"type": "integer"})),
413            ("row", serde_json::json!({"type": "integer"})),
414            ("thread", serde_json::json!({"type": ["integer", "null"]})),
415            ("query", serde_json::json!({"type": ["string", "null"]})),
416        ],
417        SourcePosition::SqlServer(_) => vec![
418            ("change_lsn", serde_json::json!({"type": "string"})),
419            ("commit_lsn", serde_json::json!({"type": "string"})),
420            ("event_serial_no", serde_json::json!({"type": "integer"})),
421        ],
422        SourcePosition::Oracle(_) => vec![
423            ("scn", serde_json::json!({"type": "integer"})),
424            (
425                "commit_scn",
426                serde_json::json!({"type": ["integer", "null"]}),
427            ),
428            ("txId", serde_json::json!({"type": ["string", "null"]})),
429            ("rs_id", serde_json::json!({"type": ["string", "null"]})),
430            ("ssn", serde_json::json!({"type": ["integer", "null"]})),
431            ("event_serial_no", serde_json::json!({"type": "integer"})),
432        ],
433        SourcePosition::MongoDb(_) => vec![
434            (
435                "resume_token",
436                serde_json::json!({"type": ["string", "null"]}),
437            ),
438            (
439                "cluster_time_seconds",
440                serde_json::json!({"type": ["integer", "null"]}),
441            ),
442            (
443                "cluster_time_increment",
444                serde_json::json!({"type": ["integer", "null"]}),
445            ),
446            ("event_serial_no", serde_json::json!({"type": "integer"})),
447        ],
448        SourcePosition::Debezium(_) => vec![
449            ("source_offset", serde_json::json!({"type": "string"})),
450            ("record_id", serde_json::json!({"type": "string"})),
451            ("event_serial_no", serde_json::json!({"type": "integer"})),
452        ],
453    };
454    for (name, schema) in connector_fields {
455        properties.insert(name.into(), schema);
456        required.push(name);
457    }
458    serde_json::json!({
459        "type": "object",
460        "additionalProperties": false,
461        "properties": properties,
462        "required": required,
463    })
464}
465
466fn event_key(row: &Row, event: &ChangeEvent, unavailable_value: &str) -> Option<serde_json::Value> {
467    let key_fields = event.schema.fields.iter().filter(|field| field.primary_key);
468    let mut key = serde_json::Map::new();
469    for field in key_fields {
470        if let Some(value) = row.get(&field.name) {
471            key.insert(field.name.clone(), value.to_json(unavailable_value));
472        }
473    }
474    (!key.is_empty()).then_some(key.into())
475}
476
477fn row_to_json(row: &Row, unavailable_value: &str) -> serde_json::Value {
478    row.iter()
479        .map(|(name, value)| (name.clone(), value.to_json(unavailable_value)))
480        .collect::<serde_json::Map<_, _>>()
481        .into()
482}
483
484fn logical_message_to_json(row: &Row, unavailable_value: &str) -> serde_json::Value {
485    row.iter()
486        .map(|(name, value)| {
487            let value = match value {
488                DataValue::Bytes(value) => STANDARD.encode(value).into(),
489                value => value.to_json(unavailable_value),
490            };
491            (name.clone(), value)
492        })
493        .collect::<serde_json::Map<_, _>>()
494        .into()
495}
496
497fn json_key_schema(
498    event: &ChangeEvent,
499    destination: &str,
500    config: &JsonEncoderConfig,
501) -> Result<WireSchema> {
502    let definition = if is_heartbeat(event) {
503        serde_json::json!({
504            "$schema": "http://json-schema.org/draft-07/schema#",
505            "title": format!("{}.HeartbeatKey", event.source.connector_name),
506            "type": "object",
507            "additionalProperties": false,
508            "properties": {"serverName": {"type": "string"}},
509            "required": ["serverName"],
510        })
511    } else {
512        let key_fields = event
513            .schema
514            .fields
515            .iter()
516            .filter(|field| field.primary_key)
517            .collect::<Vec<_>>();
518        let properties = key_fields
519            .iter()
520            .map(|field| {
521                (
522                    field.name.clone(),
523                    json_field_schema(field, &config.unavailable_value, true),
524                )
525            })
526            .collect::<serde_json::Map<_, _>>();
527        let required = key_fields
528            .iter()
529            .map(|field| field.name.clone())
530            .collect::<Vec<_>>();
531        serde_json::json!({
532            "$schema": "http://json-schema.org/draft-07/schema#",
533            "title": schema_title(event, "Key"),
534            "type": "object",
535            "additionalProperties": false,
536            "properties": properties,
537            "required": required,
538        })
539    };
540    wire_schema(format!("{destination}-key"), definition)
541}
542
543fn json_payload_schema(
544    event: &ChangeEvent,
545    destination: &str,
546    config: &JsonEncoderConfig,
547) -> Result<WireSchema> {
548    let source_schema = json_source_schema(event);
549    let definition = if is_heartbeat(event) {
550        serde_json::json!({
551            "$schema": "http://json-schema.org/draft-07/schema#",
552            "title": format!("{}.Heartbeat", event.source.connector_name),
553            "type": "object",
554            "additionalProperties": false,
555            "properties": {"ts_ms": {"type": "integer"}},
556            "required": ["ts_ms"],
557        })
558    } else if is_logical_decoding_message(event) {
559        let message_schema = json_row_schema(event, config);
560        serde_json::json!({
561            "$schema": "http://json-schema.org/draft-07/schema#",
562            "title": schema_title(event, "Envelope"),
563            "$comment": format!("Rustium EventSchema version {}", event.schema.version),
564            "type": "object",
565            "additionalProperties": false,
566            "properties": {
567                "source": source_schema.clone(),
568                "op": {"type": "string", "enum": ["m"]},
569                "ts_ms": {"type": "integer"},
570                "transaction": {
571                    "anyOf": [
572                        {"type": "null"},
573                        {
574                            "type": "object",
575                            "additionalProperties": false,
576                            "properties": {
577                                "id": {"type": "string"},
578                                "total_order": {"type": ["integer", "null"]},
579                                "data_collection_order": {"type": ["integer", "null"]}
580                            },
581                            "required": ["id", "total_order", "data_collection_order"]
582                        }
583                    ]
584                },
585                "message": message_schema
586            },
587            "required": ["source", "op", "ts_ms", "transaction", "message"]
588        })
589    } else {
590        let row_schema = json_row_schema(event, config);
591        serde_json::json!({
592            "$schema": "http://json-schema.org/draft-07/schema#",
593            "title": schema_title(event, "Envelope"),
594            "$comment": format!("Rustium EventSchema version {}", event.schema.version),
595            "type": "object",
596            "additionalProperties": false,
597            "properties": {
598                "before": {"anyOf": [{"type": "null"}, row_schema.clone()]},
599                "after": {"anyOf": [{"type": "null"}, row_schema]},
600                "source": source_schema,
601                "op": {"type": "string", "enum": ["r", "c", "u", "d", "t", "m"]},
602                "ts_ms": {"type": "integer"},
603                "transaction": {
604                    "anyOf": [
605                        {"type": "null"},
606                        {
607                            "type": "object",
608                            "additionalProperties": false,
609                            "properties": {
610                                "id": {"type": "string"},
611                                "total_order": {"type": ["integer", "null"]},
612                                "data_collection_order": {"type": ["integer", "null"]}
613                            },
614                            "required": ["id", "total_order", "data_collection_order"]
615                        }
616                    ]
617                }
618            },
619            "required": ["before", "after", "source", "op", "ts_ms", "transaction"]
620        })
621    };
622    wire_schema(format!("{destination}-value"), definition)
623}
624
625fn json_row_schema(event: &ChangeEvent, config: &JsonEncoderConfig) -> serde_json::Value {
626    let properties = event
627        .schema
628        .fields
629        .iter()
630        .map(|field| {
631            (
632                field.name.clone(),
633                json_field_schema(field, &config.unavailable_value, false),
634            )
635        })
636        .collect::<serde_json::Map<_, _>>();
637    serde_json::json!({
638        "title": schema_title(event, "Value"),
639        "type": "object",
640        "additionalProperties": false,
641        "properties": properties
642    })
643}
644
645fn json_field_schema(field: &FieldSchema, unavailable_value: &str, key: bool) -> serde_json::Value {
646    let mut variants = vec![json_base_type(&field.type_name)];
647    if !key {
648        variants.push(serde_json::json!({
649            "type": "string",
650            "const": unavailable_value
651        }));
652    }
653    if field.optional {
654        variants.push(serde_json::json!({"type": "null"}));
655    }
656    if variants.len() == 1 {
657        variants.remove(0)
658    } else {
659        serde_json::json!({"anyOf": variants})
660    }
661}
662
663fn json_base_type(type_name: &str) -> serde_json::Value {
664    let normalized = type_name.trim().to_ascii_lowercase();
665    if let Some(element) = normalized.strip_suffix("[]") {
666        return serde_json::json!({
667            "type": "array",
668            "items": json_base_type(element)
669        });
670    }
671    if normalized == "hstore" || normalized.starts_with("map") {
672        return serde_json::json!({
673            "type": "object",
674            "additionalProperties": {"type": ["string", "null"]}
675        });
676    }
677    if normalized == "json" || normalized == "jsonb" {
678        return serde_json::json!({});
679    }
680    if normalized == "bool" || normalized == "boolean" || normalized == "bit" {
681        return serde_json::json!({"type": "boolean"});
682    }
683    if normalized.contains("decimal")
684        || normalized.contains("numeric")
685        || normalized.contains("money")
686    {
687        return serde_json::json!({"type": "string"});
688    }
689    if [
690        "tinyint",
691        "smallint",
692        "mediumint",
693        "integer",
694        "bigint",
695        "serial",
696        "year",
697        "int2",
698        "int4",
699        "int8",
700    ]
701    .iter()
702    .any(|prefix| normalized.starts_with(prefix))
703        || normalized == "int"
704    {
705        return serde_json::json!({"type": "integer"});
706    }
707    if ["real", "float", "double"]
708        .iter()
709        .any(|prefix| normalized.starts_with(prefix))
710    {
711        return serde_json::json!({"type": ["number", "null"]});
712    }
713    serde_json::json!({"type": "string"})
714}
715
716fn schema_title(event: &ChangeEvent, suffix: &str) -> String {
717    let base = event
718        .schema
719        .name
720        .strip_suffix(".Envelope")
721        .unwrap_or(&event.schema.name);
722    format!("{base}.{suffix}")
723}
724
725fn wire_schema(subject: String, definition: serde_json::Value) -> Result<WireSchema> {
726    Ok(WireSchema {
727        subject,
728        schema_type: WireSchemaType::Json,
729        definition: serde_json::to_string(&definition)?,
730    })
731}
732
733const fn operation_code(operation: Operation) -> &'static str {
734    match operation {
735        Operation::Read => "r",
736        Operation::Create => "c",
737        Operation::Update => "u",
738        Operation::Delete => "d",
739        Operation::Truncate => "t",
740        Operation::Message => "m",
741    }
742}
743
744const fn operation_name(operation: Operation) -> &'static str {
745    match operation {
746        Operation::Read => "read",
747        Operation::Create => "create",
748        Operation::Update => "update",
749        Operation::Delete => "delete",
750        Operation::Truncate => "truncate",
751        Operation::Message => "message",
752    }
753}
754
755#[cfg(test)]
756mod tests {
757    use std::{fs, path::Path};
758
759    use chrono::{TimeZone, Utc};
760    use indexmap::indexmap;
761    use rustium_core::{
762        DataValue, DebeziumPosition, EventId, EventSchema, FieldSchema, MySqlPosition,
763        PostgresPosition, SourceMetadata, SqlServerPosition, TransactionMetadata,
764    };
765
766    use super::*;
767
768    fn event() -> ChangeEvent {
769        ChangeEvent {
770            id: EventId("event-1".into()),
771            source: SourceMetadata {
772                connector: "postgresql".into(),
773                connector_name: "orders".into(),
774                database: "app".into(),
775                schema: Some("public".into()),
776                table: Some("customers".into()),
777                snapshot: false,
778                version: "0.1.0".into(),
779                attributes: BTreeMap::new(),
780            },
781            position: SourcePosition::Postgres(PostgresPosition {
782                lsn: 42,
783                commit_lsn: Some(44),
784                transaction_id: Some(7),
785                xmin: Some(9),
786                event_serial: 1,
787                snapshot: false,
788            }),
789            transaction: Some(TransactionMetadata {
790                id: "7".into(),
791                total_order: Some(1),
792                collection_order: Some(1),
793            }),
794            operation: Operation::Create,
795            before: None,
796            after: Some(indexmap! {
797                "id".into() => DataValue::Int64(1),
798                "name".into() => DataValue::String("Alice".into()),
799                "attributes".into() => DataValue::Map(BTreeMap::from([
800                    ("region".into(), DataValue::String("global".into())),
801                    ("optional".into(), DataValue::Null),
802                ])),
803            }),
804            schema: EventSchema {
805                name: "orders.app.public.customers.Envelope".into(),
806                version: 1,
807                fields: vec![
808                    FieldSchema {
809                        name: "id".into(),
810                        type_name: "int8".into(),
811                        optional: false,
812                        primary_key: true,
813                    },
814                    FieldSchema {
815                        name: "name".into(),
816                        type_name: "text".into(),
817                        optional: false,
818                        primary_key: false,
819                    },
820                    FieldSchema {
821                        name: "attributes".into(),
822                        type_name: "hstore".into(),
823                        optional: true,
824                        primary_key: false,
825                    },
826                ],
827            },
828            source_time: Some(
829                Utc.timestamp_millis_opt(1_700_000_000_123)
830                    .single()
831                    .unwrap(),
832            ),
833            observed_time: Utc
834                .timestamp_millis_opt(1_700_000_001_456)
835                .single()
836                .unwrap(),
837        }
838    }
839
840    fn logical_message_event() -> ChangeEvent {
841        let mut event = event();
842        event.source.connector = "postgresql".into();
843        event.source.schema = Some(String::new());
844        event.source.table = Some(String::new());
845        event
846            .source
847            .attributes
848            .insert("rustium.logical_decoding_message".into(), true.into());
849        event.position = SourcePosition::Postgres(PostgresPosition {
850            lsn: 64,
851            commit_lsn: Some(64),
852            transaction_id: None,
853            xmin: None,
854            event_serial: 1,
855            snapshot: false,
856        });
857        event.transaction = None;
858        event.operation = Operation::Message;
859        event.before = None;
860        event.after = Some(indexmap! {
861            "prefix".into() => DataValue::String("orders.created".into()),
862            "content".into() => DataValue::Bytes(b"payload".to_vec()),
863        });
864        event.schema = EventSchema {
865            name: "orders.Message".into(),
866            version: 1,
867            fields: vec![
868                FieldSchema {
869                    name: "prefix".into(),
870                    type_name: "text".into(),
871                    optional: true,
872                    primary_key: true,
873                },
874                FieldSchema {
875                    name: "content".into(),
876                    type_name: "bytea".into(),
877                    optional: true,
878                    primary_key: false,
879                },
880            ],
881        };
882        event
883    }
884
885    fn encoded_fixture(event: &ChangeEvent) -> serde_json::Value {
886        let encoded = DebeziumJsonEncoder::new(JsonEncoderConfig {
887            topic_prefix: "app".into(),
888            unavailable_value: "__unavailable".into(),
889            tombstones_on_delete: true,
890            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
891            heartbeat_topic_name: None,
892        })
893        .encode(event)
894        .unwrap();
895        serde_json::json!({
896            "destination": encoded.destination,
897            "key": serde_json::from_slice::<serde_json::Value>(encoded.key.as_ref().unwrap()).unwrap(),
898            "payload": serde_json::from_slice::<serde_json::Value>(encoded.payload.as_ref().unwrap()).unwrap(),
899        })
900    }
901
902    fn golden_fixture(path: &str) -> serde_json::Value {
903        serde_json::from_str(path).unwrap()
904    }
905
906    fn connector_events() -> [(&'static str, ChangeEvent); 3] {
907        let postgres = event();
908
909        let mut mysql = event();
910        mysql.source.connector = "mysql".into();
911        mysql.source.schema = None;
912        mysql.schema.name = "orders.app.customers.Envelope".into();
913        mysql.position = SourcePosition::MySql(MySqlPosition {
914            binlog_filename: "mysql-bin.000123".into(),
915            binlog_position: 4_567,
916            gtid_set: Some("24bc7850-2c16-11ef-8f32-0242ac120002:1-9".into()),
917            server_id: 184,
918            event_serial: 2,
919            snapshot: false,
920        });
921
922        let mut sqlserver = event();
923        sqlserver.source.connector = "sqlserver".into();
924        sqlserver.source.schema = Some("dbo".into());
925        sqlserver.schema.name = "orders.app.dbo.customers.Envelope".into();
926        sqlserver.position = SourcePosition::SqlServer(SqlServerPosition {
927            database: "app".into(),
928            commit_lsn: "0x0000002A000001000001".into(),
929            change_lsn: "0x0000002A000001000002".into(),
930            event_serial: 3,
931            snapshot: false,
932        });
933
934        [
935            ("postgresql", postgres),
936            ("mysql", mysql),
937            ("sqlserver", sqlserver),
938        ]
939    }
940
941    #[test]
942    fn encodes_bridge_offsets_and_routes_sources_without_relational_schemas() {
943        let mut bridge = event();
944        bridge.source.connector = "spanner".into();
945        bridge.source.database = "inventory".into();
946        bridge.source.schema = None;
947        bridge.source.table = Some("Users".into());
948        bridge.position = SourcePosition::Debezium(DebeziumPosition {
949            connector: "spanner".into(),
950            source: BTreeMap::from([
951                ("partition_token".into(), "partition-1".into()),
952                ("sequence".into(), "7".into()),
953            ]),
954            record_id: "record-7".into(),
955            event_serial: 7,
956            snapshot: false,
957        });
958        let fixture = encoded_fixture(&bridge);
959        assert_eq!(fixture["destination"], "app.inventory.Users");
960        assert_eq!(fixture["payload"]["source"]["record_id"], "record-7");
961        let offset: serde_json::Value = serde_json::from_str(
962            fixture["payload"]["source"]["source_offset"]
963                .as_str()
964                .unwrap(),
965        )
966        .unwrap();
967        assert_eq!(offset["partition_token"], "partition-1");
968    }
969
970    fn schema_fixture(event: &ChangeEvent) -> serde_json::Value {
971        let encoded = DebeziumJsonSchemaEncoder::new(JsonEncoderConfig {
972            topic_prefix: "app".into(),
973            unavailable_value: "__unavailable".into(),
974            tombstones_on_delete: true,
975            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
976            heartbeat_topic_name: None,
977        })
978        .encode(event)
979        .unwrap();
980        let key = encoded.key_schema.unwrap();
981        let value = encoded.payload_schema.unwrap();
982        serde_json::json!({
983            "destination": encoded.destination,
984            "key": {
985                "subject": key.subject,
986                "schema_type": format!("{:?}", key.schema_type),
987                "definition": serde_json::from_str::<serde_json::Value>(&key.definition).unwrap(),
988            },
989            "value": {
990                "subject": value.subject,
991                "schema_type": format!("{:?}", value.schema_type),
992                "definition": serde_json::from_str::<serde_json::Value>(&value.definition).unwrap(),
993            },
994        })
995    }
996
997    fn write_fixture(path: &Path, fixture: &serde_json::Value) {
998        fs::create_dir_all(path.parent().unwrap()).unwrap();
999        let mut contents = serde_json::to_string_pretty(fixture).unwrap();
1000        contents.push('\n');
1001        fs::write(path, contents).unwrap();
1002    }
1003
1004    #[test]
1005    fn matches_debezium_json_golden_fixtures_for_prioritized_connectors() {
1006        let [(_, postgres), (_, mysql), (_, sqlserver)] = connector_events();
1007        assert_eq!(
1008            encoded_fixture(&postgres),
1009            golden_fixture(include_str!(
1010                "../tests/fixtures/debezium-postgresql-create.json"
1011            ))
1012        );
1013
1014        assert_eq!(
1015            encoded_fixture(&mysql),
1016            golden_fixture(include_str!("../tests/fixtures/debezium-mysql-create.json"))
1017        );
1018
1019        assert_eq!(
1020            encoded_fixture(&sqlserver),
1021            golden_fixture(include_str!(
1022                "../tests/fixtures/debezium-sqlserver-create.json"
1023            ))
1024        );
1025    }
1026
1027    #[test]
1028    fn matches_json_schema_golden_fixtures_for_prioritized_connectors() {
1029        let [(_, postgres), (_, mysql), (_, sqlserver)] = connector_events();
1030        assert_eq!(
1031            schema_fixture(&postgres),
1032            golden_fixture(include_str!(
1033                "../tests/fixtures/schema-postgresql-create.json"
1034            ))
1035        );
1036        assert_eq!(
1037            schema_fixture(&mysql),
1038            golden_fixture(include_str!("../tests/fixtures/schema-mysql-create.json"))
1039        );
1040        assert_eq!(
1041            schema_fixture(&sqlserver),
1042            golden_fixture(include_str!(
1043                "../tests/fixtures/schema-sqlserver-create.json"
1044            ))
1045        );
1046    }
1047
1048    #[test]
1049    #[ignore = "regenerates checked-in JSON Schema golden fixtures"]
1050    fn regenerate_json_schema_golden_fixtures() {
1051        let fixture_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
1052        for (connector, event) in connector_events() {
1053            write_fixture(
1054                &fixture_dir.join(format!("schema-{connector}-create.json")),
1055                &schema_fixture(&event),
1056            );
1057        }
1058    }
1059
1060    #[test]
1061    fn emits_debezium_envelope_and_key() {
1062        let encoded = DebeziumJsonEncoder::new(JsonEncoderConfig {
1063            topic_prefix: "app".into(),
1064            unavailable_value: "__unavailable".into(),
1065            tombstones_on_delete: true,
1066            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
1067            heartbeat_topic_name: None,
1068        })
1069        .encode(&event())
1070        .unwrap();
1071        let value: serde_json::Value =
1072            serde_json::from_slice(encoded.payload.as_ref().unwrap()).unwrap();
1073        assert_eq!(encoded.destination, "app.app.public.customers");
1074        assert_eq!(value["op"], "c");
1075        assert_eq!(value["after"]["name"], "Alice");
1076        assert_eq!(value["after"]["attributes"]["region"], "global");
1077        assert!(value["after"]["attributes"]["optional"].is_null());
1078        assert_eq!(value["source"]["xmin"], 9);
1079        assert!(encoded.key.is_some());
1080    }
1081
1082    #[test]
1083    fn emits_postgresql_logical_decoding_message_contracts() {
1084        let config = JsonEncoderConfig {
1085            topic_prefix: "app".into(),
1086            unavailable_value: "__unavailable".into(),
1087            tombstones_on_delete: true,
1088            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
1089            heartbeat_topic_name: None,
1090        };
1091        let event = logical_message_event();
1092        let encoded = DebeziumJsonEncoder::new(config.clone())
1093            .encode(&event)
1094            .unwrap();
1095        assert_eq!(encoded.destination, "app.message");
1096        assert_eq!(
1097            serde_json::from_slice::<serde_json::Value>(encoded.key.as_ref().unwrap()).unwrap(),
1098            serde_json::json!({"prefix": "orders.created"})
1099        );
1100        let payload =
1101            serde_json::from_slice::<serde_json::Value>(encoded.payload.as_ref().unwrap()).unwrap();
1102        assert_eq!(payload["op"], "m");
1103        assert_eq!(payload["source"]["schema"], "");
1104        assert_eq!(payload["source"]["table"], "");
1105        assert_eq!(payload["message"]["prefix"], "orders.created");
1106        assert_eq!(payload["message"]["content"], "cGF5bG9hZA==");
1107        assert!(payload.get("before").is_none());
1108        assert!(payload.get("after").is_none());
1109
1110        let schema_encoded = DebeziumJsonSchemaEncoder::new(config)
1111            .encode(&event)
1112            .unwrap();
1113        let definition: serde_json::Value =
1114            serde_json::from_str(&schema_encoded.payload_schema.unwrap().definition).unwrap();
1115        assert!(definition["properties"]["message"].is_object());
1116        assert!(definition["properties"].get("before").is_none());
1117        assert_eq!(schema_encoded.destination, "app.message");
1118    }
1119
1120    #[test]
1121    fn emits_incremental_snapshot_marker() {
1122        let mut event = event();
1123        event.operation = Operation::Read;
1124        event.source.snapshot = true;
1125        event
1126            .source
1127            .attributes
1128            .insert("rustium.snapshot.kind".into(), "incremental".into());
1129        let encoded = DebeziumJsonEncoder::new(JsonEncoderConfig {
1130            topic_prefix: "app".into(),
1131            unavailable_value: "__unavailable".into(),
1132            tombstones_on_delete: true,
1133            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
1134            heartbeat_topic_name: None,
1135        })
1136        .encode(&event)
1137        .unwrap();
1138        let value: serde_json::Value =
1139            serde_json::from_slice(encoded.payload.as_ref().unwrap()).unwrap();
1140        assert_eq!(value["op"], "r");
1141        assert_eq!(value["source"]["snapshot"], "incremental");
1142    }
1143
1144    #[test]
1145    fn emits_delete_envelope_and_null_tombstone() {
1146        let mut event = event();
1147        event.operation = Operation::Delete;
1148        event.before = event.after.take();
1149
1150        let encoded = DebeziumJsonEncoder::new(JsonEncoderConfig {
1151            topic_prefix: "app".into(),
1152            unavailable_value: "__unavailable".into(),
1153            tombstones_on_delete: true,
1154            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
1155            heartbeat_topic_name: None,
1156        })
1157        .encode_batch(&event)
1158        .unwrap();
1159
1160        assert_eq!(encoded.len(), 2);
1161        assert_eq!(encoded[0].destination, encoded[1].destination);
1162        assert_eq!(encoded[0].key, encoded[1].key);
1163        assert!(encoded[0].payload.is_some());
1164        assert!(encoded[1].payload.is_none());
1165        assert_ne!(encoded[0].id, encoded[1].id);
1166        assert_eq!(
1167            encoded[1].headers.get("rustium.record.type"),
1168            Some(&"tombstone".into())
1169        );
1170    }
1171
1172    #[test]
1173    fn can_disable_delete_tombstones() {
1174        let mut event = event();
1175        event.operation = Operation::Delete;
1176        event.before = event.after.take();
1177
1178        let encoded = DebeziumJsonEncoder::new(JsonEncoderConfig {
1179            topic_prefix: "app".into(),
1180            unavailable_value: "__unavailable".into(),
1181            tombstones_on_delete: false,
1182            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
1183            heartbeat_topic_name: None,
1184        })
1185        .encode_batch(&event)
1186        .unwrap();
1187
1188        assert_eq!(encoded.len(), 1);
1189        assert!(encoded[0].payload.is_some());
1190    }
1191
1192    #[test]
1193    fn emits_debezium_heartbeat_key_topic_and_value() {
1194        let mut event = event();
1195        event.operation = Operation::Message;
1196        event.before = None;
1197        event.after = None;
1198        event.source.table = None;
1199        event.source.schema = None;
1200        event
1201            .source
1202            .attributes
1203            .insert("rustium.heartbeat".into(), true.into());
1204
1205        let encoded = DebeziumJsonEncoder::new(JsonEncoderConfig {
1206            topic_prefix: "inventory".into(),
1207            unavailable_value: "__unavailable".into(),
1208            tombstones_on_delete: true,
1209            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
1210            heartbeat_topic_name: None,
1211        })
1212        .encode(&event)
1213        .unwrap();
1214
1215        let key: serde_json::Value = serde_json::from_slice(encoded.key.as_ref().unwrap()).unwrap();
1216        let payload: serde_json::Value =
1217            serde_json::from_slice(encoded.payload.as_ref().unwrap()).unwrap();
1218        assert_eq!(encoded.destination, "__debezium-heartbeat.inventory");
1219        assert_eq!(key, serde_json::json!({"serverName": "orders"}));
1220        assert_eq!(payload["ts_ms"], event.observed_time.timestamp_millis());
1221        assert_eq!(
1222            encoded
1223                .headers
1224                .get("rustium.record.type")
1225                .map(String::as_str),
1226            Some("heartbeat")
1227        );
1228
1229        let overridden = DebeziumJsonEncoder::new(JsonEncoderConfig {
1230            topic_prefix: "inventory".into(),
1231            unavailable_value: "__unavailable".into(),
1232            tombstones_on_delete: true,
1233            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
1234            heartbeat_topic_name: Some("shared-heartbeat".into()),
1235        })
1236        .encode(&event)
1237        .unwrap();
1238        assert_eq!(overridden.destination, "shared-heartbeat");
1239    }
1240
1241    #[test]
1242    fn emits_json_schema_registry_descriptors_and_tombstones() {
1243        let encoder = DebeziumJsonSchemaEncoder::new(JsonEncoderConfig {
1244            topic_prefix: "app".into(),
1245            unavailable_value: "__unavailable".into(),
1246            tombstones_on_delete: true,
1247            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
1248            heartbeat_topic_name: None,
1249        });
1250        let encoded = encoder.encode(&event()).unwrap();
1251        let key_schema = encoded.key_schema.as_ref().unwrap();
1252        let payload_schema = encoded.payload_schema.as_ref().unwrap();
1253        assert_eq!(key_schema.subject, "app.app.public.customers-key");
1254        assert_eq!(payload_schema.subject, "app.app.public.customers-value");
1255        assert_eq!(key_schema.schema_type, WireSchemaType::Json);
1256        let key: serde_json::Value = serde_json::from_str(&key_schema.definition).unwrap();
1257        let payload: serde_json::Value = serde_json::from_str(&payload_schema.definition).unwrap();
1258        assert_eq!(key["required"], serde_json::json!(["id"]));
1259        assert_eq!(key["properties"]["id"]["type"], "integer");
1260        assert_eq!(
1261            payload["properties"]["after"]["anyOf"][1]["properties"]["attributes"]["anyOf"][0]["type"],
1262            "object"
1263        );
1264
1265        let mut changed = event();
1266        changed.schema.version = 2;
1267        let changed = encoder.encode(&changed).unwrap();
1268        assert_ne!(
1269            payload_schema.definition,
1270            changed.payload_schema.unwrap().definition
1271        );
1272
1273        let mut deleted = event();
1274        deleted.operation = Operation::Delete;
1275        deleted.before = deleted.after.take();
1276        let deleted = encoder.encode_batch(&deleted).unwrap();
1277        assert_eq!(deleted.len(), 2);
1278        assert_eq!(deleted[0].key_schema, deleted[1].key_schema);
1279        assert!(deleted[0].payload_schema.is_some());
1280        assert!(deleted[1].payload_schema.is_none());
1281    }
1282}