1use std::collections::BTreeMap;
2
3use bytes::Bytes;
4use chrono::{DateTime, Utc};
5use indexmap::IndexMap;
6use serde::{Deserialize, Serialize};
7use sha2::{Digest, Sha256};
8use uuid::Uuid;
9
10pub type Row = IndexMap<String, DataValue>;
11
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub struct ConnectorStateEnvelope {
14 pub format: String,
15 pub version: u32,
16 pub payload: serde_json::Value,
17}
18
19impl ConnectorStateEnvelope {
20 #[must_use]
21 pub fn new(format: impl Into<String>, version: u32, payload: serde_json::Value) -> Self {
22 Self {
23 format: format.into(),
24 version,
25 payload,
26 }
27 }
28}
29
30#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
31#[serde(tag = "type", content = "value", rename_all = "snake_case")]
32pub enum DataValue {
33 Null,
34 Boolean(bool),
35 Int32(i32),
36 Int64(i64),
37 UInt64(u64),
38 Float64(f64),
39 Decimal(String),
40 String(String),
41 Bytes(Vec<u8>),
42 Date(String),
43 Time(String),
44 Timestamp(String),
45 Uuid(Uuid),
46 Json(serde_json::Value),
47 Array(Vec<DataValue>),
48 Map(BTreeMap<String, DataValue>),
49 Unavailable,
50}
51
52impl DataValue {
53 #[must_use]
54 pub fn to_json(&self, unavailable_value: &str) -> serde_json::Value {
55 match self {
56 Self::Null => serde_json::Value::Null,
57 Self::Boolean(value) => (*value).into(),
58 Self::Int32(value) => (*value).into(),
59 Self::Int64(value) => (*value).into(),
60 Self::UInt64(value) => (*value).into(),
61 Self::Float64(value) => serde_json::Number::from_f64(*value)
62 .map_or(serde_json::Value::Null, serde_json::Value::Number),
63 Self::Decimal(value)
64 | Self::String(value)
65 | Self::Date(value)
66 | Self::Time(value)
67 | Self::Timestamp(value) => value.clone().into(),
68 Self::Bytes(value) => hex::encode(value).into(),
69 Self::Uuid(value) => value.to_string().into(),
70 Self::Json(value) => value.clone(),
71 Self::Array(values) => values
72 .iter()
73 .map(|value| value.to_json(unavailable_value))
74 .collect::<Vec<_>>()
75 .into(),
76 Self::Map(values) => values
77 .iter()
78 .map(|(key, value)| (key.clone(), value.to_json(unavailable_value)))
79 .collect::<serde_json::Map<_, _>>()
80 .into(),
81 Self::Unavailable => unavailable_value.into(),
82 }
83 }
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub struct ConnectorIdentity {
88 pub name: String,
89 pub generation: Uuid,
90}
91
92impl ConnectorIdentity {
93 #[must_use]
94 pub fn new(name: impl Into<String>) -> Self {
95 Self {
96 name: name.into(),
97 generation: Uuid::new_v4(),
98 }
99 }
100}
101
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103#[serde(tag = "type", rename_all = "snake_case")]
104pub enum SourcePosition {
105 Postgres(PostgresPosition),
106 MySql(MySqlPosition),
107 SqlServer(SqlServerPosition),
108 Oracle(OraclePosition),
109 MongoDb(MongoDbPosition),
110 Debezium(DebeziumPosition),
111}
112
113impl SourcePosition {
114 #[must_use]
115 pub fn is_after(&self, other: &Self) -> bool {
116 match (self, other) {
117 (Self::Postgres(left), Self::Postgres(right)) => left.sort_key() > right.sort_key(),
118 (Self::MySql(left), Self::MySql(right)) => left.sort_key() > right.sort_key(),
119 (Self::SqlServer(left), Self::SqlServer(right)) => left.sort_key() > right.sort_key(),
120 (Self::Oracle(left), Self::Oracle(right)) => left.sort_key() > right.sort_key(),
121 (Self::MongoDb(left), Self::MongoDb(right)) => left.sort_key() > right.sort_key(),
122 (Self::Debezium(left), Self::Debezium(right)) => {
123 left.connector == right.connector && left.sort_key() > right.sort_key()
124 }
125 _ => false,
126 }
127 }
128
129 #[must_use]
130 pub fn is_at_or_before(&self, other: &Self) -> bool {
131 self == other || other.is_after(self)
132 }
133}
134
135#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
136pub struct PostgresPosition {
137 pub lsn: u64,
138 pub commit_lsn: Option<u64>,
139 pub transaction_id: Option<u32>,
140 #[serde(default, skip_serializing_if = "Option::is_none")]
141 pub xmin: Option<u32>,
142 pub event_serial: u64,
143 pub snapshot: bool,
144}
145
146impl PostgresPosition {
147 fn sort_key(&self) -> (u64, u8, u64) {
148 (self.lsn, u8::from(!self.snapshot), self.event_serial)
149 }
150}
151
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
153pub struct MySqlPosition {
154 pub binlog_filename: String,
155 pub binlog_position: u64,
156 pub gtid_set: Option<String>,
157 pub server_id: u32,
158 pub event_serial: u64,
159 pub snapshot: bool,
160}
161
162impl MySqlPosition {
163 fn sort_key(&self) -> (&str, u64, u8, u64) {
164 (
165 &self.binlog_filename,
166 self.binlog_position,
167 u8::from(!self.snapshot),
168 self.event_serial,
169 )
170 }
171}
172
173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
174pub struct SqlServerPosition {
175 pub database: String,
176 pub commit_lsn: String,
177 pub change_lsn: String,
178 pub event_serial: u64,
179 pub snapshot: bool,
180}
181
182impl SqlServerPosition {
183 fn sort_key(&self) -> (&str, &str, &str, u8, u64) {
184 (
185 &self.database,
186 &self.commit_lsn,
187 &self.change_lsn,
188 u8::from(!self.snapshot),
189 self.event_serial,
190 )
191 }
192}
193
194#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
195pub struct OraclePosition {
196 pub scn: u64,
197 pub commit_scn: Option<u64>,
198 pub transaction_id: Option<String>,
199 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub rs_id: Option<String>,
201 #[serde(default, skip_serializing_if = "Option::is_none")]
202 pub ssn: Option<u64>,
203 pub event_serial: u64,
204 pub snapshot: bool,
205}
206
207impl OraclePosition {
208 fn sort_key(&self) -> (u64, u8, u64) {
209 (
210 self.commit_scn.unwrap_or(self.scn),
211 u8::from(!self.snapshot),
212 self.event_serial,
213 )
214 }
215}
216
217#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
218pub struct MongoDbPosition {
219 #[serde(default, skip_serializing_if = "Option::is_none")]
220 pub resume_token: Option<String>,
221 #[serde(default, skip_serializing_if = "Option::is_none")]
222 pub cluster_time_seconds: Option<u32>,
223 #[serde(default, skip_serializing_if = "Option::is_none")]
224 pub cluster_time_increment: Option<u32>,
225 pub event_serial: u64,
226 pub snapshot: bool,
227}
228
229impl MongoDbPosition {
230 fn sort_key(&self) -> (u32, u32, u8, u64) {
231 (
232 self.cluster_time_seconds.unwrap_or_default(),
233 self.cluster_time_increment.unwrap_or_default(),
234 u8::from(!self.snapshot),
235 self.event_serial,
236 )
237 }
238}
239
240#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
246pub struct DebeziumPosition {
247 pub connector: String,
248 pub source: BTreeMap<String, serde_json::Value>,
249 pub record_id: String,
250 pub event_serial: u64,
251 pub snapshot: bool,
252}
253
254impl DebeziumPosition {
255 fn sort_key(&self) -> (u8, u64) {
256 (u8::from(!self.snapshot), self.event_serial)
257 }
258}
259
260#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
261#[serde(rename_all = "snake_case")]
262pub enum Operation {
263 Read,
264 Create,
265 Update,
266 Delete,
267 Truncate,
268 Message,
269}
270
271#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
272#[serde(transparent)]
273pub struct EventId(pub String);
274
275impl EventId {
276 #[must_use]
277 pub fn deterministic(
278 connector_name: &str,
279 partition: &str,
280 position: &SourcePosition,
281 collection: &str,
282 ordinal: u64,
283 ) -> Self {
284 let mut hasher = Sha256::new();
285 hasher.update(connector_name.as_bytes());
286 hasher.update([0]);
287 hasher.update(partition.as_bytes());
288 hasher.update([0]);
289 hasher.update(serde_json::to_vec(position).expect("position serialization is infallible"));
290 hasher.update([0]);
291 hasher.update(collection.as_bytes());
292 hasher.update(ordinal.to_be_bytes());
293 Self(hex::encode(hasher.finalize()))
294 }
295
296 #[must_use]
297 pub fn derived(&self, discriminator: &str) -> Self {
298 let mut hasher = Sha256::new();
299 hasher.update(self.0.as_bytes());
300 hasher.update([0]);
301 hasher.update(discriminator.as_bytes());
302 Self(hex::encode(hasher.finalize()))
303 }
304}
305
306#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
307pub struct SourceMetadata {
308 pub connector: String,
309 pub connector_name: String,
310 pub database: String,
311 pub schema: Option<String>,
312 pub table: Option<String>,
313 pub snapshot: bool,
314 pub version: String,
315 pub attributes: BTreeMap<String, serde_json::Value>,
316}
317
318impl SourceMetadata {
319 #[must_use]
320 pub fn collection(&self) -> String {
321 match (&self.schema, &self.table) {
322 (Some(schema), Some(table)) => format!("{}.{}.{}", self.database, schema, table),
323 _ => self.database.clone(),
324 }
325 }
326}
327
328#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
329pub struct TransactionMetadata {
330 pub id: String,
331 pub total_order: Option<u64>,
332 pub collection_order: Option<u64>,
333}
334
335#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
336pub struct FieldSchema {
337 pub name: String,
338 pub type_name: String,
339 pub optional: bool,
340 pub primary_key: bool,
341}
342
343#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
344pub struct EventSchema {
345 pub name: String,
346 pub version: u32,
347 pub fields: Vec<FieldSchema>,
348}
349
350#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
351pub struct ChangeEvent {
352 pub id: EventId,
353 pub source: SourceMetadata,
354 pub position: SourcePosition,
355 pub transaction: Option<TransactionMetadata>,
356 pub operation: Operation,
357 pub before: Option<Row>,
358 pub after: Option<Row>,
359 pub schema: EventSchema,
360 pub source_time: Option<DateTime<Utc>>,
361 pub observed_time: DateTime<Utc>,
362}
363
364#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
365#[serde(rename_all = "snake_case")]
366pub enum RecordBoundary {
367 Data,
368 TransactionCommit,
369 SnapshotComplete,
370 Heartbeat,
371}
372
373#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
374pub struct SourceRecord {
375 pub event: Option<ChangeEvent>,
376 pub position: SourcePosition,
377 pub boundary: RecordBoundary,
378 #[serde(default, skip_serializing_if = "Option::is_none")]
379 pub connector_state: Option<ConnectorStateEnvelope>,
380 #[serde(skip)]
381 pub signal_acknowledgements: Vec<crate::SignalAcknowledgement>,
382}
383
384impl SourceRecord {
385 #[must_use]
386 pub fn data(event: ChangeEvent) -> Self {
387 Self {
388 position: event.position.clone(),
389 event: Some(event),
390 boundary: RecordBoundary::Data,
391 connector_state: None,
392 signal_acknowledgements: Vec::new(),
393 }
394 }
395
396 #[must_use]
397 pub fn with_connector_state(mut self, connector_state: ConnectorStateEnvelope) -> Self {
398 self.connector_state = Some(connector_state);
399 self
400 }
401}
402
403#[derive(Debug, Clone)]
404pub struct EncodedEvent {
405 pub id: EventId,
406 pub destination: String,
407 pub key: Option<Bytes>,
408 pub key_schema: Option<WireSchema>,
409 pub payload: Option<Bytes>,
410 pub payload_schema: Option<WireSchema>,
411 pub headers: BTreeMap<String, String>,
412}
413
414#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
415pub enum WireSchemaType {
416 Avro,
417 Json,
418 Protobuf,
419}
420
421#[derive(Debug, Clone, PartialEq, Eq, Hash)]
422pub struct WireSchema {
423 pub subject: String,
424 pub schema_type: WireSchemaType,
425 pub definition: String,
426}
427
428#[derive(Debug, Clone)]
429pub struct DeliveryBatch {
430 pub events: Vec<EncodedEvent>,
431 pub highest_position: SourcePosition,
432}