Skip to main content

rustium_core/
event.rs

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}
109
110impl SourcePosition {
111    #[must_use]
112    pub fn is_after(&self, other: &Self) -> bool {
113        match (self, other) {
114            (Self::Postgres(left), Self::Postgres(right)) => left.sort_key() > right.sort_key(),
115            (Self::MySql(left), Self::MySql(right)) => left.sort_key() > right.sort_key(),
116            (Self::SqlServer(left), Self::SqlServer(right)) => left.sort_key() > right.sort_key(),
117            _ => false,
118        }
119    }
120
121    #[must_use]
122    pub fn is_at_or_before(&self, other: &Self) -> bool {
123        self == other || other.is_after(self)
124    }
125}
126
127#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128pub struct PostgresPosition {
129    pub lsn: u64,
130    pub commit_lsn: Option<u64>,
131    pub transaction_id: Option<u32>,
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub xmin: Option<u32>,
134    pub event_serial: u64,
135    pub snapshot: bool,
136}
137
138impl PostgresPosition {
139    fn sort_key(&self) -> (u64, u8, u64) {
140        (self.lsn, u8::from(!self.snapshot), self.event_serial)
141    }
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
145pub struct MySqlPosition {
146    pub binlog_filename: String,
147    pub binlog_position: u64,
148    pub gtid_set: Option<String>,
149    pub server_id: u32,
150    pub event_serial: u64,
151    pub snapshot: bool,
152}
153
154impl MySqlPosition {
155    fn sort_key(&self) -> (&str, u64, u8, u64) {
156        (
157            &self.binlog_filename,
158            self.binlog_position,
159            u8::from(!self.snapshot),
160            self.event_serial,
161        )
162    }
163}
164
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166pub struct SqlServerPosition {
167    pub database: String,
168    pub commit_lsn: String,
169    pub change_lsn: String,
170    pub event_serial: u64,
171    pub snapshot: bool,
172}
173
174impl SqlServerPosition {
175    fn sort_key(&self) -> (&str, &str, &str, u8, u64) {
176        (
177            &self.database,
178            &self.commit_lsn,
179            &self.change_lsn,
180            u8::from(!self.snapshot),
181            self.event_serial,
182        )
183    }
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
187#[serde(rename_all = "snake_case")]
188pub enum Operation {
189    Read,
190    Create,
191    Update,
192    Delete,
193    Truncate,
194    Message,
195}
196
197#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
198#[serde(transparent)]
199pub struct EventId(pub String);
200
201impl EventId {
202    #[must_use]
203    pub fn deterministic(
204        connector_name: &str,
205        partition: &str,
206        position: &SourcePosition,
207        collection: &str,
208        ordinal: u64,
209    ) -> Self {
210        let mut hasher = Sha256::new();
211        hasher.update(connector_name.as_bytes());
212        hasher.update([0]);
213        hasher.update(partition.as_bytes());
214        hasher.update([0]);
215        hasher.update(serde_json::to_vec(position).expect("position serialization is infallible"));
216        hasher.update([0]);
217        hasher.update(collection.as_bytes());
218        hasher.update(ordinal.to_be_bytes());
219        Self(hex::encode(hasher.finalize()))
220    }
221
222    #[must_use]
223    pub fn derived(&self, discriminator: &str) -> Self {
224        let mut hasher = Sha256::new();
225        hasher.update(self.0.as_bytes());
226        hasher.update([0]);
227        hasher.update(discriminator.as_bytes());
228        Self(hex::encode(hasher.finalize()))
229    }
230}
231
232#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
233pub struct SourceMetadata {
234    pub connector: String,
235    pub connector_name: String,
236    pub database: String,
237    pub schema: Option<String>,
238    pub table: Option<String>,
239    pub snapshot: bool,
240    pub version: String,
241    pub attributes: BTreeMap<String, serde_json::Value>,
242}
243
244impl SourceMetadata {
245    #[must_use]
246    pub fn collection(&self) -> String {
247        match (&self.schema, &self.table) {
248            (Some(schema), Some(table)) => format!("{}.{}.{}", self.database, schema, table),
249            _ => self.database.clone(),
250        }
251    }
252}
253
254#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
255pub struct TransactionMetadata {
256    pub id: String,
257    pub total_order: Option<u64>,
258    pub collection_order: Option<u64>,
259}
260
261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
262pub struct FieldSchema {
263    pub name: String,
264    pub type_name: String,
265    pub optional: bool,
266    pub primary_key: bool,
267}
268
269#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
270pub struct EventSchema {
271    pub name: String,
272    pub version: u32,
273    pub fields: Vec<FieldSchema>,
274}
275
276#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
277pub struct ChangeEvent {
278    pub id: EventId,
279    pub source: SourceMetadata,
280    pub position: SourcePosition,
281    pub transaction: Option<TransactionMetadata>,
282    pub operation: Operation,
283    pub before: Option<Row>,
284    pub after: Option<Row>,
285    pub schema: EventSchema,
286    pub source_time: Option<DateTime<Utc>>,
287    pub observed_time: DateTime<Utc>,
288}
289
290#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
291#[serde(rename_all = "snake_case")]
292pub enum RecordBoundary {
293    Data,
294    TransactionCommit,
295    SnapshotComplete,
296    Heartbeat,
297}
298
299#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
300pub struct SourceRecord {
301    pub event: Option<ChangeEvent>,
302    pub position: SourcePosition,
303    pub boundary: RecordBoundary,
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub connector_state: Option<ConnectorStateEnvelope>,
306    #[serde(skip)]
307    pub signal_acknowledgements: Vec<crate::SignalAcknowledgement>,
308}
309
310impl SourceRecord {
311    #[must_use]
312    pub fn data(event: ChangeEvent) -> Self {
313        Self {
314            position: event.position.clone(),
315            event: Some(event),
316            boundary: RecordBoundary::Data,
317            connector_state: None,
318            signal_acknowledgements: Vec::new(),
319        }
320    }
321
322    #[must_use]
323    pub fn with_connector_state(mut self, connector_state: ConnectorStateEnvelope) -> Self {
324        self.connector_state = Some(connector_state);
325        self
326    }
327}
328
329#[derive(Debug, Clone)]
330pub struct EncodedEvent {
331    pub id: EventId,
332    pub destination: String,
333    pub key: Option<Bytes>,
334    pub key_schema: Option<WireSchema>,
335    pub payload: Option<Bytes>,
336    pub payload_schema: Option<WireSchema>,
337    pub headers: BTreeMap<String, String>,
338}
339
340#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
341pub enum WireSchemaType {
342    Avro,
343    Json,
344    Protobuf,
345}
346
347#[derive(Debug, Clone, PartialEq, Eq, Hash)]
348pub struct WireSchema {
349    pub subject: String,
350    pub schema_type: WireSchemaType,
351    pub definition: String,
352}
353
354#[derive(Debug, Clone)]
355pub struct DeliveryBatch {
356    pub events: Vec<EncodedEvent>,
357    pub highest_position: SourcePosition,
358}