rustium-core 0.1.0-alpha.2

Core event model and runtime for Rustium
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use std::collections::BTreeMap;

use bytes::Bytes;
use chrono::{DateTime, Utc};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use uuid::Uuid;

pub type Row = IndexMap<String, DataValue>;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConnectorStateEnvelope {
    pub format: String,
    pub version: u32,
    pub payload: serde_json::Value,
}

impl ConnectorStateEnvelope {
    #[must_use]
    pub fn new(format: impl Into<String>, version: u32, payload: serde_json::Value) -> Self {
        Self {
            format: format.into(),
            version,
            payload,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum DataValue {
    Null,
    Boolean(bool),
    Int32(i32),
    Int64(i64),
    UInt64(u64),
    Float64(f64),
    Decimal(String),
    String(String),
    Bytes(Vec<u8>),
    Date(String),
    Time(String),
    Timestamp(String),
    Uuid(Uuid),
    Json(serde_json::Value),
    Array(Vec<DataValue>),
    Map(BTreeMap<String, DataValue>),
    Unavailable,
}

impl DataValue {
    #[must_use]
    pub fn to_json(&self, unavailable_value: &str) -> serde_json::Value {
        match self {
            Self::Null => serde_json::Value::Null,
            Self::Boolean(value) => (*value).into(),
            Self::Int32(value) => (*value).into(),
            Self::Int64(value) => (*value).into(),
            Self::UInt64(value) => (*value).into(),
            Self::Float64(value) => serde_json::Number::from_f64(*value)
                .map_or(serde_json::Value::Null, serde_json::Value::Number),
            Self::Decimal(value)
            | Self::String(value)
            | Self::Date(value)
            | Self::Time(value)
            | Self::Timestamp(value) => value.clone().into(),
            Self::Bytes(value) => hex::encode(value).into(),
            Self::Uuid(value) => value.to_string().into(),
            Self::Json(value) => value.clone(),
            Self::Array(values) => values
                .iter()
                .map(|value| value.to_json(unavailable_value))
                .collect::<Vec<_>>()
                .into(),
            Self::Map(values) => values
                .iter()
                .map(|(key, value)| (key.clone(), value.to_json(unavailable_value)))
                .collect::<serde_json::Map<_, _>>()
                .into(),
            Self::Unavailable => unavailable_value.into(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConnectorIdentity {
    pub name: String,
    pub generation: Uuid,
}

impl ConnectorIdentity {
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            generation: Uuid::new_v4(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum SourcePosition {
    Postgres(PostgresPosition),
    MySql(MySqlPosition),
    SqlServer(SqlServerPosition),
    Oracle(OraclePosition),
    MongoDb(MongoDbPosition),
    Debezium(DebeziumPosition),
}

impl SourcePosition {
    #[must_use]
    pub fn is_after(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Postgres(left), Self::Postgres(right)) => left.sort_key() > right.sort_key(),
            (Self::MySql(left), Self::MySql(right)) => left.sort_key() > right.sort_key(),
            (Self::SqlServer(left), Self::SqlServer(right)) => left.sort_key() > right.sort_key(),
            (Self::Oracle(left), Self::Oracle(right)) => left.sort_key() > right.sort_key(),
            (Self::MongoDb(left), Self::MongoDb(right)) => left.sort_key() > right.sort_key(),
            (Self::Debezium(left), Self::Debezium(right)) => {
                left.connector == right.connector && left.sort_key() > right.sort_key()
            }
            _ => false,
        }
    }

    #[must_use]
    pub fn is_at_or_before(&self, other: &Self) -> bool {
        self == other || other.is_after(self)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PostgresPosition {
    pub lsn: u64,
    pub commit_lsn: Option<u64>,
    pub transaction_id: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub xmin: Option<u32>,
    pub event_serial: u64,
    pub snapshot: bool,
}

impl PostgresPosition {
    fn sort_key(&self) -> (u64, u8, u64) {
        (self.lsn, u8::from(!self.snapshot), self.event_serial)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MySqlPosition {
    pub binlog_filename: String,
    pub binlog_position: u64,
    pub gtid_set: Option<String>,
    pub server_id: u32,
    pub event_serial: u64,
    pub snapshot: bool,
}

impl MySqlPosition {
    fn sort_key(&self) -> (&str, u64, u8, u64) {
        (
            &self.binlog_filename,
            self.binlog_position,
            u8::from(!self.snapshot),
            self.event_serial,
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SqlServerPosition {
    pub database: String,
    pub commit_lsn: String,
    pub change_lsn: String,
    pub event_serial: u64,
    pub snapshot: bool,
}

impl SqlServerPosition {
    fn sort_key(&self) -> (&str, &str, &str, u8, u64) {
        (
            &self.database,
            &self.commit_lsn,
            &self.change_lsn,
            u8::from(!self.snapshot),
            self.event_serial,
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OraclePosition {
    pub scn: u64,
    pub commit_scn: Option<u64>,
    pub transaction_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rs_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ssn: Option<u64>,
    pub event_serial: u64,
    pub snapshot: bool,
}

impl OraclePosition {
    fn sort_key(&self) -> (u64, u8, u64) {
        (
            self.commit_scn.unwrap_or(self.scn),
            u8::from(!self.snapshot),
            self.event_serial,
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MongoDbPosition {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resume_token: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cluster_time_seconds: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cluster_time_increment: Option<u32>,
    pub event_serial: u64,
    pub snapshot: bool,
}

impl MongoDbPosition {
    fn sort_key(&self) -> (u32, u32, u8, u64) {
        (
            self.cluster_time_seconds.unwrap_or_default(),
            self.cluster_time_increment.unwrap_or_default(),
            u8::from(!self.snapshot),
            self.event_serial,
        )
    }
}

/// Durable position for connectors executed by an upstream Debezium engine.
///
/// `source` preserves the connector-specific source metadata without forcing
/// proprietary offsets such as VGTID or Spanner partition tokens into a
/// lossy common scalar.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DebeziumPosition {
    pub connector: String,
    pub source: BTreeMap<String, serde_json::Value>,
    pub record_id: String,
    pub event_serial: u64,
    pub snapshot: bool,
}

impl DebeziumPosition {
    fn sort_key(&self) -> (u8, u64) {
        (u8::from(!self.snapshot), self.event_serial)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Operation {
    Read,
    Create,
    Update,
    Delete,
    Truncate,
    Message,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct EventId(pub String);

impl EventId {
    #[must_use]
    pub fn deterministic(
        connector_name: &str,
        partition: &str,
        position: &SourcePosition,
        collection: &str,
        ordinal: u64,
    ) -> Self {
        let mut hasher = Sha256::new();
        hasher.update(connector_name.as_bytes());
        hasher.update([0]);
        hasher.update(partition.as_bytes());
        hasher.update([0]);
        hasher.update(serde_json::to_vec(position).expect("position serialization is infallible"));
        hasher.update([0]);
        hasher.update(collection.as_bytes());
        hasher.update(ordinal.to_be_bytes());
        Self(hex::encode(hasher.finalize()))
    }

    #[must_use]
    pub fn derived(&self, discriminator: &str) -> Self {
        let mut hasher = Sha256::new();
        hasher.update(self.0.as_bytes());
        hasher.update([0]);
        hasher.update(discriminator.as_bytes());
        Self(hex::encode(hasher.finalize()))
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SourceMetadata {
    pub connector: String,
    pub connector_name: String,
    pub database: String,
    pub schema: Option<String>,
    pub table: Option<String>,
    pub snapshot: bool,
    pub version: String,
    pub attributes: BTreeMap<String, serde_json::Value>,
}

impl SourceMetadata {
    #[must_use]
    pub fn collection(&self) -> String {
        match (&self.schema, &self.table) {
            (Some(schema), Some(table)) => format!("{}.{}.{}", self.database, schema, table),
            _ => self.database.clone(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransactionMetadata {
    pub id: String,
    pub total_order: Option<u64>,
    pub collection_order: Option<u64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FieldSchema {
    pub name: String,
    pub type_name: String,
    pub optional: bool,
    pub primary_key: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EventSchema {
    pub name: String,
    pub version: u32,
    pub fields: Vec<FieldSchema>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ChangeEvent {
    pub id: EventId,
    pub source: SourceMetadata,
    pub position: SourcePosition,
    pub transaction: Option<TransactionMetadata>,
    pub operation: Operation,
    pub before: Option<Row>,
    pub after: Option<Row>,
    pub schema: EventSchema,
    pub source_time: Option<DateTime<Utc>>,
    pub observed_time: DateTime<Utc>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RecordBoundary {
    Data,
    TransactionCommit,
    SnapshotComplete,
    Heartbeat,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SourceRecord {
    pub event: Option<ChangeEvent>,
    pub position: SourcePosition,
    pub boundary: RecordBoundary,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub connector_state: Option<ConnectorStateEnvelope>,
    #[serde(skip)]
    pub signal_acknowledgements: Vec<crate::SignalAcknowledgement>,
}

impl SourceRecord {
    #[must_use]
    pub fn data(event: ChangeEvent) -> Self {
        Self {
            position: event.position.clone(),
            event: Some(event),
            boundary: RecordBoundary::Data,
            connector_state: None,
            signal_acknowledgements: Vec::new(),
        }
    }

    #[must_use]
    pub fn with_connector_state(mut self, connector_state: ConnectorStateEnvelope) -> Self {
        self.connector_state = Some(connector_state);
        self
    }
}

#[derive(Debug, Clone)]
pub struct EncodedEvent {
    pub id: EventId,
    pub destination: String,
    pub key: Option<Bytes>,
    pub key_schema: Option<WireSchema>,
    pub payload: Option<Bytes>,
    pub payload_schema: Option<WireSchema>,
    pub headers: BTreeMap<String, String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WireSchemaType {
    Avro,
    Json,
    Protobuf,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct WireSchema {
    pub subject: String,
    pub schema_type: WireSchemaType,
    pub definition: String,
}

#[derive(Debug, Clone)]
pub struct DeliveryBatch {
    pub events: Vec<EncodedEvent>,
    pub highest_position: SourcePosition,
}