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.connector == "mysql" {
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    }
324    Ok(source.into())
325}
326
327fn snapshot_marker(event: &ChangeEvent) -> &'static str {
328    if event
329        .source
330        .attributes
331        .get("rustium.snapshot.kind")
332        .and_then(serde_json::Value::as_str)
333        == Some("incremental")
334    {
335        "incremental"
336    } else if event.source.snapshot {
337        "true"
338    } else {
339        "false"
340    }
341}
342
343fn json_source_schema(event: &ChangeEvent) -> serde_json::Value {
344    let mut properties = serde_json::Map::from_iter([
345        ("version".into(), serde_json::json!({"type": "string"})),
346        ("connector".into(), serde_json::json!({"type": "string"})),
347        ("name".into(), serde_json::json!({"type": "string"})),
348        (
349            "ts_ms".into(),
350            serde_json::json!({"type": ["integer", "null"]}),
351        ),
352        ("snapshot".into(), serde_json::json!({"type": "string"})),
353        ("db".into(), serde_json::json!({"type": "string"})),
354        (
355            "schema".into(),
356            serde_json::json!({"type": ["string", "null"]}),
357        ),
358        (
359            "table".into(),
360            serde_json::json!({"type": ["string", "null"]}),
361        ),
362    ]);
363    let mut required = vec![
364        "version",
365        "connector",
366        "name",
367        "ts_ms",
368        "snapshot",
369        "db",
370        "schema",
371        "table",
372    ];
373    let connector_fields: Vec<(&str, serde_json::Value)> = match &event.position {
374        SourcePosition::Postgres(_) => vec![
375            ("sequence", serde_json::json!({"type": "string"})),
376            ("txId", serde_json::json!({"type": ["integer", "null"]})),
377            ("lsn", serde_json::json!({"type": "integer"})),
378            ("xmin", serde_json::json!({"type": ["integer", "null"]})),
379        ],
380        SourcePosition::MySql(_) => vec![
381            ("server_id", serde_json::json!({"type": "integer"})),
382            ("gtid", serde_json::json!({"type": ["string", "null"]})),
383            ("file", serde_json::json!({"type": "string"})),
384            ("pos", serde_json::json!({"type": "integer"})),
385            ("row", serde_json::json!({"type": "integer"})),
386            ("thread", serde_json::json!({"type": ["integer", "null"]})),
387            ("query", serde_json::json!({"type": ["string", "null"]})),
388        ],
389        SourcePosition::SqlServer(_) => vec![
390            ("change_lsn", serde_json::json!({"type": "string"})),
391            ("commit_lsn", serde_json::json!({"type": "string"})),
392            ("event_serial_no", serde_json::json!({"type": "integer"})),
393        ],
394    };
395    for (name, schema) in connector_fields {
396        properties.insert(name.into(), schema);
397        required.push(name);
398    }
399    serde_json::json!({
400        "type": "object",
401        "additionalProperties": false,
402        "properties": properties,
403        "required": required,
404    })
405}
406
407fn event_key(row: &Row, event: &ChangeEvent, unavailable_value: &str) -> Option<serde_json::Value> {
408    let key_fields = event.schema.fields.iter().filter(|field| field.primary_key);
409    let mut key = serde_json::Map::new();
410    for field in key_fields {
411        if let Some(value) = row.get(&field.name) {
412            key.insert(field.name.clone(), value.to_json(unavailable_value));
413        }
414    }
415    (!key.is_empty()).then_some(key.into())
416}
417
418fn row_to_json(row: &Row, unavailable_value: &str) -> serde_json::Value {
419    row.iter()
420        .map(|(name, value)| (name.clone(), value.to_json(unavailable_value)))
421        .collect::<serde_json::Map<_, _>>()
422        .into()
423}
424
425fn logical_message_to_json(row: &Row, unavailable_value: &str) -> serde_json::Value {
426    row.iter()
427        .map(|(name, value)| {
428            let value = match value {
429                DataValue::Bytes(value) => STANDARD.encode(value).into(),
430                value => value.to_json(unavailable_value),
431            };
432            (name.clone(), value)
433        })
434        .collect::<serde_json::Map<_, _>>()
435        .into()
436}
437
438fn json_key_schema(
439    event: &ChangeEvent,
440    destination: &str,
441    config: &JsonEncoderConfig,
442) -> Result<WireSchema> {
443    let definition = if is_heartbeat(event) {
444        serde_json::json!({
445            "$schema": "http://json-schema.org/draft-07/schema#",
446            "title": format!("{}.HeartbeatKey", event.source.connector_name),
447            "type": "object",
448            "additionalProperties": false,
449            "properties": {"serverName": {"type": "string"}},
450            "required": ["serverName"],
451        })
452    } else {
453        let key_fields = event
454            .schema
455            .fields
456            .iter()
457            .filter(|field| field.primary_key)
458            .collect::<Vec<_>>();
459        let properties = key_fields
460            .iter()
461            .map(|field| {
462                (
463                    field.name.clone(),
464                    json_field_schema(field, &config.unavailable_value, true),
465                )
466            })
467            .collect::<serde_json::Map<_, _>>();
468        let required = key_fields
469            .iter()
470            .map(|field| field.name.clone())
471            .collect::<Vec<_>>();
472        serde_json::json!({
473            "$schema": "http://json-schema.org/draft-07/schema#",
474            "title": schema_title(event, "Key"),
475            "type": "object",
476            "additionalProperties": false,
477            "properties": properties,
478            "required": required,
479        })
480    };
481    wire_schema(format!("{destination}-key"), definition)
482}
483
484fn json_payload_schema(
485    event: &ChangeEvent,
486    destination: &str,
487    config: &JsonEncoderConfig,
488) -> Result<WireSchema> {
489    let source_schema = json_source_schema(event);
490    let definition = if is_heartbeat(event) {
491        serde_json::json!({
492            "$schema": "http://json-schema.org/draft-07/schema#",
493            "title": format!("{}.Heartbeat", event.source.connector_name),
494            "type": "object",
495            "additionalProperties": false,
496            "properties": {"ts_ms": {"type": "integer"}},
497            "required": ["ts_ms"],
498        })
499    } else if is_logical_decoding_message(event) {
500        let message_schema = json_row_schema(event, config);
501        serde_json::json!({
502            "$schema": "http://json-schema.org/draft-07/schema#",
503            "title": schema_title(event, "Envelope"),
504            "$comment": format!("Rustium EventSchema version {}", event.schema.version),
505            "type": "object",
506            "additionalProperties": false,
507            "properties": {
508                "source": source_schema.clone(),
509                "op": {"type": "string", "enum": ["m"]},
510                "ts_ms": {"type": "integer"},
511                "transaction": {
512                    "anyOf": [
513                        {"type": "null"},
514                        {
515                            "type": "object",
516                            "additionalProperties": false,
517                            "properties": {
518                                "id": {"type": "string"},
519                                "total_order": {"type": ["integer", "null"]},
520                                "data_collection_order": {"type": ["integer", "null"]}
521                            },
522                            "required": ["id", "total_order", "data_collection_order"]
523                        }
524                    ]
525                },
526                "message": message_schema
527            },
528            "required": ["source", "op", "ts_ms", "transaction", "message"]
529        })
530    } else {
531        let row_schema = json_row_schema(event, config);
532        serde_json::json!({
533            "$schema": "http://json-schema.org/draft-07/schema#",
534            "title": schema_title(event, "Envelope"),
535            "$comment": format!("Rustium EventSchema version {}", event.schema.version),
536            "type": "object",
537            "additionalProperties": false,
538            "properties": {
539                "before": {"anyOf": [{"type": "null"}, row_schema.clone()]},
540                "after": {"anyOf": [{"type": "null"}, row_schema]},
541                "source": source_schema,
542                "op": {"type": "string", "enum": ["r", "c", "u", "d", "t", "m"]},
543                "ts_ms": {"type": "integer"},
544                "transaction": {
545                    "anyOf": [
546                        {"type": "null"},
547                        {
548                            "type": "object",
549                            "additionalProperties": false,
550                            "properties": {
551                                "id": {"type": "string"},
552                                "total_order": {"type": ["integer", "null"]},
553                                "data_collection_order": {"type": ["integer", "null"]}
554                            },
555                            "required": ["id", "total_order", "data_collection_order"]
556                        }
557                    ]
558                }
559            },
560            "required": ["before", "after", "source", "op", "ts_ms", "transaction"]
561        })
562    };
563    wire_schema(format!("{destination}-value"), definition)
564}
565
566fn json_row_schema(event: &ChangeEvent, config: &JsonEncoderConfig) -> serde_json::Value {
567    let properties = event
568        .schema
569        .fields
570        .iter()
571        .map(|field| {
572            (
573                field.name.clone(),
574                json_field_schema(field, &config.unavailable_value, false),
575            )
576        })
577        .collect::<serde_json::Map<_, _>>();
578    serde_json::json!({
579        "title": schema_title(event, "Value"),
580        "type": "object",
581        "additionalProperties": false,
582        "properties": properties
583    })
584}
585
586fn json_field_schema(field: &FieldSchema, unavailable_value: &str, key: bool) -> serde_json::Value {
587    let mut variants = vec![json_base_type(&field.type_name)];
588    if !key {
589        variants.push(serde_json::json!({
590            "type": "string",
591            "const": unavailable_value
592        }));
593    }
594    if field.optional {
595        variants.push(serde_json::json!({"type": "null"}));
596    }
597    if variants.len() == 1 {
598        variants.remove(0)
599    } else {
600        serde_json::json!({"anyOf": variants})
601    }
602}
603
604fn json_base_type(type_name: &str) -> serde_json::Value {
605    let normalized = type_name.trim().to_ascii_lowercase();
606    if let Some(element) = normalized.strip_suffix("[]") {
607        return serde_json::json!({
608            "type": "array",
609            "items": json_base_type(element)
610        });
611    }
612    if normalized == "hstore" || normalized.starts_with("map") {
613        return serde_json::json!({
614            "type": "object",
615            "additionalProperties": {"type": ["string", "null"]}
616        });
617    }
618    if normalized == "json" || normalized == "jsonb" {
619        return serde_json::json!({});
620    }
621    if normalized == "bool" || normalized == "boolean" || normalized == "bit" {
622        return serde_json::json!({"type": "boolean"});
623    }
624    if normalized.contains("decimal")
625        || normalized.contains("numeric")
626        || normalized.contains("money")
627    {
628        return serde_json::json!({"type": "string"});
629    }
630    if [
631        "tinyint",
632        "smallint",
633        "mediumint",
634        "integer",
635        "bigint",
636        "serial",
637        "year",
638        "int2",
639        "int4",
640        "int8",
641    ]
642    .iter()
643    .any(|prefix| normalized.starts_with(prefix))
644        || normalized == "int"
645    {
646        return serde_json::json!({"type": "integer"});
647    }
648    if ["real", "float", "double"]
649        .iter()
650        .any(|prefix| normalized.starts_with(prefix))
651    {
652        return serde_json::json!({"type": ["number", "null"]});
653    }
654    serde_json::json!({"type": "string"})
655}
656
657fn schema_title(event: &ChangeEvent, suffix: &str) -> String {
658    let base = event
659        .schema
660        .name
661        .strip_suffix(".Envelope")
662        .unwrap_or(&event.schema.name);
663    format!("{base}.{suffix}")
664}
665
666fn wire_schema(subject: String, definition: serde_json::Value) -> Result<WireSchema> {
667    Ok(WireSchema {
668        subject,
669        schema_type: WireSchemaType::Json,
670        definition: serde_json::to_string(&definition)?,
671    })
672}
673
674const fn operation_code(operation: Operation) -> &'static str {
675    match operation {
676        Operation::Read => "r",
677        Operation::Create => "c",
678        Operation::Update => "u",
679        Operation::Delete => "d",
680        Operation::Truncate => "t",
681        Operation::Message => "m",
682    }
683}
684
685const fn operation_name(operation: Operation) -> &'static str {
686    match operation {
687        Operation::Read => "read",
688        Operation::Create => "create",
689        Operation::Update => "update",
690        Operation::Delete => "delete",
691        Operation::Truncate => "truncate",
692        Operation::Message => "message",
693    }
694}
695
696#[cfg(test)]
697mod tests {
698    use std::{fs, path::Path};
699
700    use chrono::{TimeZone, Utc};
701    use indexmap::indexmap;
702    use rustium_core::{
703        DataValue, EventId, EventSchema, FieldSchema, MySqlPosition, PostgresPosition,
704        SourceMetadata, SqlServerPosition, TransactionMetadata,
705    };
706
707    use super::*;
708
709    fn event() -> ChangeEvent {
710        ChangeEvent {
711            id: EventId("event-1".into()),
712            source: SourceMetadata {
713                connector: "postgresql".into(),
714                connector_name: "orders".into(),
715                database: "app".into(),
716                schema: Some("public".into()),
717                table: Some("customers".into()),
718                snapshot: false,
719                version: "0.1.0".into(),
720                attributes: BTreeMap::new(),
721            },
722            position: SourcePosition::Postgres(PostgresPosition {
723                lsn: 42,
724                commit_lsn: Some(44),
725                transaction_id: Some(7),
726                xmin: Some(9),
727                event_serial: 1,
728                snapshot: false,
729            }),
730            transaction: Some(TransactionMetadata {
731                id: "7".into(),
732                total_order: Some(1),
733                collection_order: Some(1),
734            }),
735            operation: Operation::Create,
736            before: None,
737            after: Some(indexmap! {
738                "id".into() => DataValue::Int64(1),
739                "name".into() => DataValue::String("Alice".into()),
740                "attributes".into() => DataValue::Map(BTreeMap::from([
741                    ("region".into(), DataValue::String("global".into())),
742                    ("optional".into(), DataValue::Null),
743                ])),
744            }),
745            schema: EventSchema {
746                name: "orders.app.public.customers.Envelope".into(),
747                version: 1,
748                fields: vec![
749                    FieldSchema {
750                        name: "id".into(),
751                        type_name: "int8".into(),
752                        optional: false,
753                        primary_key: true,
754                    },
755                    FieldSchema {
756                        name: "name".into(),
757                        type_name: "text".into(),
758                        optional: false,
759                        primary_key: false,
760                    },
761                    FieldSchema {
762                        name: "attributes".into(),
763                        type_name: "hstore".into(),
764                        optional: true,
765                        primary_key: false,
766                    },
767                ],
768            },
769            source_time: Some(
770                Utc.timestamp_millis_opt(1_700_000_000_123)
771                    .single()
772                    .unwrap(),
773            ),
774            observed_time: Utc
775                .timestamp_millis_opt(1_700_000_001_456)
776                .single()
777                .unwrap(),
778        }
779    }
780
781    fn logical_message_event() -> ChangeEvent {
782        let mut event = event();
783        event.source.connector = "postgresql".into();
784        event.source.schema = Some(String::new());
785        event.source.table = Some(String::new());
786        event
787            .source
788            .attributes
789            .insert("rustium.logical_decoding_message".into(), true.into());
790        event.position = SourcePosition::Postgres(PostgresPosition {
791            lsn: 64,
792            commit_lsn: Some(64),
793            transaction_id: None,
794            xmin: None,
795            event_serial: 1,
796            snapshot: false,
797        });
798        event.transaction = None;
799        event.operation = Operation::Message;
800        event.before = None;
801        event.after = Some(indexmap! {
802            "prefix".into() => DataValue::String("orders.created".into()),
803            "content".into() => DataValue::Bytes(b"payload".to_vec()),
804        });
805        event.schema = EventSchema {
806            name: "orders.Message".into(),
807            version: 1,
808            fields: vec![
809                FieldSchema {
810                    name: "prefix".into(),
811                    type_name: "text".into(),
812                    optional: true,
813                    primary_key: true,
814                },
815                FieldSchema {
816                    name: "content".into(),
817                    type_name: "bytea".into(),
818                    optional: true,
819                    primary_key: false,
820                },
821            ],
822        };
823        event
824    }
825
826    fn encoded_fixture(event: &ChangeEvent) -> serde_json::Value {
827        let encoded = DebeziumJsonEncoder::new(JsonEncoderConfig {
828            topic_prefix: "app".into(),
829            unavailable_value: "__unavailable".into(),
830            tombstones_on_delete: true,
831            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
832            heartbeat_topic_name: None,
833        })
834        .encode(event)
835        .unwrap();
836        serde_json::json!({
837            "destination": encoded.destination,
838            "key": serde_json::from_slice::<serde_json::Value>(encoded.key.as_ref().unwrap()).unwrap(),
839            "payload": serde_json::from_slice::<serde_json::Value>(encoded.payload.as_ref().unwrap()).unwrap(),
840        })
841    }
842
843    fn golden_fixture(path: &str) -> serde_json::Value {
844        serde_json::from_str(path).unwrap()
845    }
846
847    fn connector_events() -> [(&'static str, ChangeEvent); 3] {
848        let postgres = event();
849
850        let mut mysql = event();
851        mysql.source.connector = "mysql".into();
852        mysql.source.schema = None;
853        mysql.schema.name = "orders.app.customers.Envelope".into();
854        mysql.position = SourcePosition::MySql(MySqlPosition {
855            binlog_filename: "mysql-bin.000123".into(),
856            binlog_position: 4_567,
857            gtid_set: Some("24bc7850-2c16-11ef-8f32-0242ac120002:1-9".into()),
858            server_id: 184,
859            event_serial: 2,
860            snapshot: false,
861        });
862
863        let mut sqlserver = event();
864        sqlserver.source.connector = "sqlserver".into();
865        sqlserver.source.schema = Some("dbo".into());
866        sqlserver.schema.name = "orders.app.dbo.customers.Envelope".into();
867        sqlserver.position = SourcePosition::SqlServer(SqlServerPosition {
868            database: "app".into(),
869            commit_lsn: "0x0000002A000001000001".into(),
870            change_lsn: "0x0000002A000001000002".into(),
871            event_serial: 3,
872            snapshot: false,
873        });
874
875        [
876            ("postgresql", postgres),
877            ("mysql", mysql),
878            ("sqlserver", sqlserver),
879        ]
880    }
881
882    fn schema_fixture(event: &ChangeEvent) -> serde_json::Value {
883        let encoded = DebeziumJsonSchemaEncoder::new(JsonEncoderConfig {
884            topic_prefix: "app".into(),
885            unavailable_value: "__unavailable".into(),
886            tombstones_on_delete: true,
887            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
888            heartbeat_topic_name: None,
889        })
890        .encode(event)
891        .unwrap();
892        let key = encoded.key_schema.unwrap();
893        let value = encoded.payload_schema.unwrap();
894        serde_json::json!({
895            "destination": encoded.destination,
896            "key": {
897                "subject": key.subject,
898                "schema_type": format!("{:?}", key.schema_type),
899                "definition": serde_json::from_str::<serde_json::Value>(&key.definition).unwrap(),
900            },
901            "value": {
902                "subject": value.subject,
903                "schema_type": format!("{:?}", value.schema_type),
904                "definition": serde_json::from_str::<serde_json::Value>(&value.definition).unwrap(),
905            },
906        })
907    }
908
909    fn write_fixture(path: &Path, fixture: &serde_json::Value) {
910        fs::create_dir_all(path.parent().unwrap()).unwrap();
911        let mut contents = serde_json::to_string_pretty(fixture).unwrap();
912        contents.push('\n');
913        fs::write(path, contents).unwrap();
914    }
915
916    #[test]
917    fn matches_debezium_json_golden_fixtures_for_prioritized_connectors() {
918        let [(_, postgres), (_, mysql), (_, sqlserver)] = connector_events();
919        assert_eq!(
920            encoded_fixture(&postgres),
921            golden_fixture(include_str!(
922                "../tests/fixtures/debezium-postgresql-create.json"
923            ))
924        );
925
926        assert_eq!(
927            encoded_fixture(&mysql),
928            golden_fixture(include_str!("../tests/fixtures/debezium-mysql-create.json"))
929        );
930
931        assert_eq!(
932            encoded_fixture(&sqlserver),
933            golden_fixture(include_str!(
934                "../tests/fixtures/debezium-sqlserver-create.json"
935            ))
936        );
937    }
938
939    #[test]
940    fn matches_json_schema_golden_fixtures_for_prioritized_connectors() {
941        let [(_, postgres), (_, mysql), (_, sqlserver)] = connector_events();
942        assert_eq!(
943            schema_fixture(&postgres),
944            golden_fixture(include_str!(
945                "../tests/fixtures/schema-postgresql-create.json"
946            ))
947        );
948        assert_eq!(
949            schema_fixture(&mysql),
950            golden_fixture(include_str!("../tests/fixtures/schema-mysql-create.json"))
951        );
952        assert_eq!(
953            schema_fixture(&sqlserver),
954            golden_fixture(include_str!(
955                "../tests/fixtures/schema-sqlserver-create.json"
956            ))
957        );
958    }
959
960    #[test]
961    #[ignore = "regenerates checked-in JSON Schema golden fixtures"]
962    fn regenerate_json_schema_golden_fixtures() {
963        let fixture_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
964        for (connector, event) in connector_events() {
965            write_fixture(
966                &fixture_dir.join(format!("schema-{connector}-create.json")),
967                &schema_fixture(&event),
968            );
969        }
970    }
971
972    #[test]
973    fn emits_debezium_envelope_and_key() {
974        let encoded = DebeziumJsonEncoder::new(JsonEncoderConfig {
975            topic_prefix: "app".into(),
976            unavailable_value: "__unavailable".into(),
977            tombstones_on_delete: true,
978            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
979            heartbeat_topic_name: None,
980        })
981        .encode(&event())
982        .unwrap();
983        let value: serde_json::Value =
984            serde_json::from_slice(encoded.payload.as_ref().unwrap()).unwrap();
985        assert_eq!(encoded.destination, "app.app.public.customers");
986        assert_eq!(value["op"], "c");
987        assert_eq!(value["after"]["name"], "Alice");
988        assert_eq!(value["after"]["attributes"]["region"], "global");
989        assert!(value["after"]["attributes"]["optional"].is_null());
990        assert_eq!(value["source"]["xmin"], 9);
991        assert!(encoded.key.is_some());
992    }
993
994    #[test]
995    fn emits_postgresql_logical_decoding_message_contracts() {
996        let config = JsonEncoderConfig {
997            topic_prefix: "app".into(),
998            unavailable_value: "__unavailable".into(),
999            tombstones_on_delete: true,
1000            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
1001            heartbeat_topic_name: None,
1002        };
1003        let event = logical_message_event();
1004        let encoded = DebeziumJsonEncoder::new(config.clone())
1005            .encode(&event)
1006            .unwrap();
1007        assert_eq!(encoded.destination, "app.message");
1008        assert_eq!(
1009            serde_json::from_slice::<serde_json::Value>(encoded.key.as_ref().unwrap()).unwrap(),
1010            serde_json::json!({"prefix": "orders.created"})
1011        );
1012        let payload =
1013            serde_json::from_slice::<serde_json::Value>(encoded.payload.as_ref().unwrap()).unwrap();
1014        assert_eq!(payload["op"], "m");
1015        assert_eq!(payload["source"]["schema"], "");
1016        assert_eq!(payload["source"]["table"], "");
1017        assert_eq!(payload["message"]["prefix"], "orders.created");
1018        assert_eq!(payload["message"]["content"], "cGF5bG9hZA==");
1019        assert!(payload.get("before").is_none());
1020        assert!(payload.get("after").is_none());
1021
1022        let schema_encoded = DebeziumJsonSchemaEncoder::new(config)
1023            .encode(&event)
1024            .unwrap();
1025        let definition: serde_json::Value =
1026            serde_json::from_str(&schema_encoded.payload_schema.unwrap().definition).unwrap();
1027        assert!(definition["properties"]["message"].is_object());
1028        assert!(definition["properties"].get("before").is_none());
1029        assert_eq!(schema_encoded.destination, "app.message");
1030    }
1031
1032    #[test]
1033    fn emits_incremental_snapshot_marker() {
1034        let mut event = event();
1035        event.operation = Operation::Read;
1036        event.source.snapshot = true;
1037        event
1038            .source
1039            .attributes
1040            .insert("rustium.snapshot.kind".into(), "incremental".into());
1041        let encoded = DebeziumJsonEncoder::new(JsonEncoderConfig {
1042            topic_prefix: "app".into(),
1043            unavailable_value: "__unavailable".into(),
1044            tombstones_on_delete: true,
1045            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
1046            heartbeat_topic_name: None,
1047        })
1048        .encode(&event)
1049        .unwrap();
1050        let value: serde_json::Value =
1051            serde_json::from_slice(encoded.payload.as_ref().unwrap()).unwrap();
1052        assert_eq!(value["op"], "r");
1053        assert_eq!(value["source"]["snapshot"], "incremental");
1054    }
1055
1056    #[test]
1057    fn emits_delete_envelope_and_null_tombstone() {
1058        let mut event = event();
1059        event.operation = Operation::Delete;
1060        event.before = event.after.take();
1061
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_batch(&event)
1070        .unwrap();
1071
1072        assert_eq!(encoded.len(), 2);
1073        assert_eq!(encoded[0].destination, encoded[1].destination);
1074        assert_eq!(encoded[0].key, encoded[1].key);
1075        assert!(encoded[0].payload.is_some());
1076        assert!(encoded[1].payload.is_none());
1077        assert_ne!(encoded[0].id, encoded[1].id);
1078        assert_eq!(
1079            encoded[1].headers.get("rustium.record.type"),
1080            Some(&"tombstone".into())
1081        );
1082    }
1083
1084    #[test]
1085    fn can_disable_delete_tombstones() {
1086        let mut event = event();
1087        event.operation = Operation::Delete;
1088        event.before = event.after.take();
1089
1090        let encoded = DebeziumJsonEncoder::new(JsonEncoderConfig {
1091            topic_prefix: "app".into(),
1092            unavailable_value: "__unavailable".into(),
1093            tombstones_on_delete: false,
1094            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
1095            heartbeat_topic_name: None,
1096        })
1097        .encode_batch(&event)
1098        .unwrap();
1099
1100        assert_eq!(encoded.len(), 1);
1101        assert!(encoded[0].payload.is_some());
1102    }
1103
1104    #[test]
1105    fn emits_debezium_heartbeat_key_topic_and_value() {
1106        let mut event = event();
1107        event.operation = Operation::Message;
1108        event.before = None;
1109        event.after = None;
1110        event.source.table = None;
1111        event.source.schema = None;
1112        event
1113            .source
1114            .attributes
1115            .insert("rustium.heartbeat".into(), true.into());
1116
1117        let encoded = DebeziumJsonEncoder::new(JsonEncoderConfig {
1118            topic_prefix: "inventory".into(),
1119            unavailable_value: "__unavailable".into(),
1120            tombstones_on_delete: true,
1121            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
1122            heartbeat_topic_name: None,
1123        })
1124        .encode(&event)
1125        .unwrap();
1126
1127        let key: serde_json::Value = serde_json::from_slice(encoded.key.as_ref().unwrap()).unwrap();
1128        let payload: serde_json::Value =
1129            serde_json::from_slice(encoded.payload.as_ref().unwrap()).unwrap();
1130        assert_eq!(encoded.destination, "__debezium-heartbeat.inventory");
1131        assert_eq!(key, serde_json::json!({"serverName": "orders"}));
1132        assert_eq!(payload["ts_ms"], event.observed_time.timestamp_millis());
1133        assert_eq!(
1134            encoded
1135                .headers
1136                .get("rustium.record.type")
1137                .map(String::as_str),
1138            Some("heartbeat")
1139        );
1140
1141        let overridden = DebeziumJsonEncoder::new(JsonEncoderConfig {
1142            topic_prefix: "inventory".into(),
1143            unavailable_value: "__unavailable".into(),
1144            tombstones_on_delete: true,
1145            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
1146            heartbeat_topic_name: Some("shared-heartbeat".into()),
1147        })
1148        .encode(&event)
1149        .unwrap();
1150        assert_eq!(overridden.destination, "shared-heartbeat");
1151    }
1152
1153    #[test]
1154    fn emits_json_schema_registry_descriptors_and_tombstones() {
1155        let encoder = DebeziumJsonSchemaEncoder::new(JsonEncoderConfig {
1156            topic_prefix: "app".into(),
1157            unavailable_value: "__unavailable".into(),
1158            tombstones_on_delete: true,
1159            heartbeat_topics_prefix: "__debezium-heartbeat".into(),
1160            heartbeat_topic_name: None,
1161        });
1162        let encoded = encoder.encode(&event()).unwrap();
1163        let key_schema = encoded.key_schema.as_ref().unwrap();
1164        let payload_schema = encoded.payload_schema.as_ref().unwrap();
1165        assert_eq!(key_schema.subject, "app.app.public.customers-key");
1166        assert_eq!(payload_schema.subject, "app.app.public.customers-value");
1167        assert_eq!(key_schema.schema_type, WireSchemaType::Json);
1168        let key: serde_json::Value = serde_json::from_str(&key_schema.definition).unwrap();
1169        let payload: serde_json::Value = serde_json::from_str(&payload_schema.definition).unwrap();
1170        assert_eq!(key["required"], serde_json::json!(["id"]));
1171        assert_eq!(key["properties"]["id"]["type"], "integer");
1172        assert_eq!(
1173            payload["properties"]["after"]["anyOf"][1]["properties"]["attributes"]["anyOf"][0]["type"],
1174            "object"
1175        );
1176
1177        let mut changed = event();
1178        changed.schema.version = 2;
1179        let changed = encoder.encode(&changed).unwrap();
1180        assert_ne!(
1181            payload_schema.definition,
1182            changed.payload_schema.unwrap().definition
1183        );
1184
1185        let mut deleted = event();
1186        deleted.operation = Operation::Delete;
1187        deleted.before = deleted.after.take();
1188        let deleted = encoder.encode_batch(&deleted).unwrap();
1189        assert_eq!(deleted.len(), 2);
1190        assert_eq!(deleted[0].key_schema, deleted[1].key_schema);
1191        assert!(deleted[0].payload_schema.is_some());
1192        assert!(deleted[1].payload_schema.is_none());
1193    }
1194}