rustcdc 0.6.7

Embeddable Rust CDC library focused on correctness-first capture primitives
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
use super::*;

impl CdcRuntime {
    /// Start the runtime and initialize source handles.
    pub async fn start(&mut self) -> Result<()> {
        match self.state {
            RuntimeState::Idle | RuntimeState::Stopped => {}
            RuntimeState::Running => {
                let error = Error::StateError("runtime already started".into());
                self.record_runtime_error("runtime.start.state", &error);
                return Err(error);
            }
            RuntimeState::Stopping => {
                let error = Error::StateError("runtime is currently stopping".into());
                self.record_runtime_error("runtime.start.state", &error);
                return Err(error);
            }
        }

        if self.config.options.schema_history_retention.is_none() {
            return Err(Error::ConfigError(
                "no schema_history_retention policy configured; schema history will grow \
                 unboundedly. Configure RuntimeOptions::with_schema_history_retention() to \
                 avoid resource exhaustion in DDL-heavy deployments."
                    .into(),
            ));
        }

        let committed_event_count = self
            .config
            .checkpoint
            .get_committed_count()
            .await
            .inspect_err(|error| {
                self.record_runtime_error("runtime.start.committed_count", error)
            })?;
        self.commit_barrier
            .hydrate_committed_event_count(committed_event_count)
            .inspect_err(|error| {
                self.record_runtime_error("runtime.start.barrier_hydrate", error)
            })?;

        if matches!(self.source, RuntimeSource::Disabled) {
            self.state = RuntimeState::Running;
            self.observability().tracer.trace_checkpoint_barrier("open");
            return Ok(());
        }

        if self.config.incremental_snapshot.is_some() && !self.config.snapshot_tables.is_empty() {
            return Err(Error::ConfigError(
                "cannot configure both snapshot_tables and incremental_snapshot; choose one startup mode"
                    .into(),
            ));
        }

        let mut checkpoint_offset = self.config.checkpoint.load().await?;
        if let Some(offset) = checkpoint_offset.as_ref() {
            if self.is_snapshot_checkpoint(offset.as_ref()) {
                if self.config.incremental_snapshot.is_some() {
                    return Err(Error::ConfigError(
                        "cannot resume incremental snapshot startup from a snapshot checkpoint"
                            .into(),
                    ));
                }
                if !self.source_capabilities().snapshot_checkpoint_resume {
                    tracing::warn!(
                        target: "rustcdc::runtime",
                        source = self.config.source.source_type().unwrap_or("unknown"),
                        "snapshot checkpoint resume is unsupported by connector; restarting snapshot from scratch"
                    );
                    checkpoint_offset = None;
                }

                if checkpoint_offset.is_some() && self.config.snapshot_tables.is_empty() {
                    return Err(Error::ConfigError(
                        "snapshot_tables must not be empty when resuming from a snapshot checkpoint"
                            .into(),
                    ));
                }
            }
        }

        self.source
            .connect()
            .await
            .inspect_err(|error| self.record_runtime_error("runtime.start.connect", error))?;

        if let Some(incremental) = self.config.incremental_snapshot.clone() {
            self.snapshot = None;
            self.stream = Some(
                self.source
                    .start_incremental_snapshot(incremental, checkpoint_offset.as_deref())
                    .await?,
            );
            self.handoff_complete = true;

            self.state = RuntimeState::Running;
            self.observability().tracer.trace_checkpoint_barrier("open");
            self.started_at_ms = Some(now_millis());
            self.last_poll_at_ms = None;
            self.last_source_event_ts_ms = None;
            self.last_commit_at_ms = None;
            self.total_events_polled = 0;
            self.total_events_committed = 0;
            self.total_events_deduplicated = 0;
            return Ok(());
        }

        if let Some(offset) = checkpoint_offset.as_ref() {
            if self.is_snapshot_checkpoint(offset.as_ref()) {
                self.snapshot = Some(
                    self.source
                        .start_snapshot_from_checkpoint(
                            &self.config.snapshot_tables,
                            offset.as_ref(),
                        )
                        .await?,
                );
                let stream_resume_from = self
                    .stream_resume_offset_for_snapshot_checkpoint(offset.as_ref())?
                    .ok_or_else(|| {
                        Error::StateError(
                            "cannot resume streaming after snapshot checkpoint: no \
                             'snapshot_watermark' LSN was found in the checkpoint payload. \
                             Streaming without a known start position risks a data-loss window. \
                             Re-run the snapshot from scratch to obtain a fresh watermark."
                                .into(),
                        )
                    })?;
                self.stream = Some(
                    self.source
                        .start_stream(Some(stream_resume_from.as_ref()))
                        .await?,
                );
                self.handoff_complete = false;
            } else {
                self.stream = Some(self.source.start_stream(Some(offset.as_ref())).await?);
                self.snapshot = None;
                self.handoff_complete = true;
            }
        } else if self.config.snapshot_tables.is_empty() {
            self.snapshot = None;
            self.stream = Some(self.source.start_stream(None).await?);
            self.handoff_complete = true;
        } else {
            self.snapshot = Some(
                self.source
                    .start_snapshot(&self.config.snapshot_tables)
                    .await?,
            );
            self.stream = Some(self.source.start_stream(None).await?);
            self.handoff_complete = false;
        }

        self.state = RuntimeState::Running;
        self.observability().tracer.trace_checkpoint_barrier("open");
        self.started_at_ms = Some(now_millis());
        self.last_poll_at_ms = None;
        self.last_source_event_ts_ms = None;
        self.last_commit_at_ms = None;
        self.total_events_polled = 0;
        self.total_events_committed = 0;
        self.total_events_deduplicated = 0;
        Ok(())
    }

    fn is_snapshot_checkpoint(&self, offset: &dyn Offset) -> bool {
        let Some(source_type) = self.config.source.source_type() else {
            return false;
        };
        let expected_snapshot_source = format!("{source_type}_snapshot");
        offset.source_type() == expected_snapshot_source
    }

    #[allow(unused_variables)]
    fn stream_resume_offset_for_snapshot_checkpoint(
        &self,
        snapshot_checkpoint: &dyn Offset,
    ) -> Result<Option<Box<dyn Offset>>> {
        #[cfg(feature = "postgres")]
        if matches!(&self.config.source, RuntimeSourceConfig::Postgres(_)) {
            return Ok(Some(Box::new(
                self.postgres_stream_offset_from_snapshot_checkpoint(snapshot_checkpoint)?,
            )));
        }

        #[cfg(feature = "mysql")]
        let mysql_family = {
            let mysql_family = matches!(&self.config.source, RuntimeSourceConfig::Mysql(_));
            #[cfg(feature = "mariadb")]
            let mysql_family =
                mysql_family || matches!(&self.config.source, RuntimeSourceConfig::MariaDb(_));
            mysql_family
        };

        #[cfg(feature = "mysql")]
        if mysql_family {
            let offset = Self::mysql_stream_offset_from_snapshot_checkpoint(snapshot_checkpoint)?;
            #[cfg(feature = "mariadb")]
            if matches!(&self.config.source, RuntimeSourceConfig::MariaDb(_)) {
                return Ok(Some(Box::new(GenericOffset::new(
                    "mariadb",
                    offset.encode()?,
                ))));
            }
            return Ok(Some(Box::new(offset)));
        }

        #[cfg(feature = "sqlserver")]
        if matches!(&self.config.source, RuntimeSourceConfig::SqlServer(_)) {
            return Ok(Some(Box::new(
                Self::sqlserver_stream_offset_from_snapshot_checkpoint(snapshot_checkpoint)?,
            )));
        }

        Ok(None)
    }

    #[cfg(feature = "postgres")]
    fn postgres_stream_offset_from_snapshot_checkpoint(
        &self,
        snapshot_checkpoint: &dyn Offset,
    ) -> Result<PostgresOffset> {
        let payload = snapshot_checkpoint.encode()?;
        let value: serde_json::Value = serde_json::from_slice(&payload)
            .map_err(|error| Error::CheckpointError(error.to_string()))?;

        let lsn = value
            .get("snapshot_watermark")
            .and_then(|entry| entry.as_u64())
            .ok_or_else(|| {
                Error::CheckpointError(
                    "postgres snapshot checkpoint is missing 'snapshot_watermark'".into(),
                )
            })?;

        let slot_name = match &self.config.source {
            RuntimeSourceConfig::Postgres(cfg) => cfg.replication_slot_name.clone(),
            _ => {
                return Err(Error::StateError(
                    "postgres stream resume conversion called for non-postgres runtime source"
                        .into(),
                ));
            }
        };

        Ok(PostgresOffset { lsn, slot_name })
    }

    #[cfg(feature = "mysql")]
    fn mysql_stream_offset_from_snapshot_checkpoint(
        snapshot_checkpoint: &dyn Offset,
    ) -> Result<MysqlOffset> {
        let payload = snapshot_checkpoint.encode()?;
        let value: serde_json::Value = serde_json::from_slice(&payload)
            .map_err(|error| Error::CheckpointError(error.to_string()))?;

        let binlog_file = value
            .get("binlog_file")
            .and_then(|entry| entry.as_str())
            .ok_or_else(|| {
                Error::CheckpointError("mysql snapshot checkpoint is missing 'binlog_file'".into())
            })?
            .to_string();
        let binlog_pos = value
            .get("binlog_pos")
            .and_then(|entry| entry.as_u64())
            .ok_or_else(|| {
                Error::CheckpointError("mysql snapshot checkpoint is missing 'binlog_pos'".into())
            })?;
        let binlog_pos = u32::try_from(binlog_pos).map_err(|_| {
            Error::CheckpointError("mysql snapshot checkpoint binlog_pos exceeds u32".into())
        })?;
        let gtid = value
            .get("gtid")
            .and_then(|entry| entry.as_str())
            .unwrap_or_default()
            .to_string();

        Ok(MysqlOffset {
            gtid,
            binlog_file,
            binlog_pos,
        })
    }

    #[cfg(feature = "sqlserver")]
    fn sqlserver_stream_offset_from_snapshot_checkpoint(
        snapshot_checkpoint: &dyn Offset,
    ) -> Result<GenericOffset> {
        let payload = snapshot_checkpoint.encode()?;
        let value: serde_json::Value = serde_json::from_slice(&payload)
            .map_err(|error| Error::CheckpointError(error.to_string()))?;

        let lsn_start = value
            .get("lsn_start")
            .and_then(|entry| entry.as_array())
            .ok_or_else(|| {
                Error::CheckpointError(
                    "sqlserver snapshot checkpoint is missing 'lsn_start'".into(),
                )
            })?;

        if lsn_start.len() != 10 {
            return Err(Error::CheckpointError(
                "sqlserver snapshot checkpoint lsn_start must contain exactly 10 bytes".into(),
            ));
        }

        let mut bytes = Vec::with_capacity(10);
        for value in lsn_start {
            let byte = value.as_u64().ok_or_else(|| {
                Error::CheckpointError(
                    "sqlserver snapshot checkpoint lsn_start contains non-byte value".into(),
                )
            })?;
            let byte = u8::try_from(byte).map_err(|_| {
                Error::CheckpointError(
                    "sqlserver snapshot checkpoint lsn_start contains out-of-range byte".into(),
                )
            })?;
            bytes.push(byte);
        }

        Ok(GenericOffset::new(
            "sqlserver",
            serde_json::to_vec(&format!(
                "0x{}",
                bytes
                    .iter()
                    .map(|byte| format!("{byte:02X}"))
                    .collect::<String>()
            ))
            .map_err(|error| Error::SerializationError(error.to_string()))?,
        ))
    }

    /// Stop the runtime.
    ///
    /// This is safe-by-default and will fail if there are uncommitted in-memory
    /// events. Callers must acknowledge deliveries first, or use `force_stop()`
    /// to explicitly drain pending events.
    pub async fn stop(&mut self) -> Result<Vec<Event>> {
        match self.state {
            RuntimeState::Idle | RuntimeState::Stopped => {
                self.state = RuntimeState::Stopped;
                return Ok(Vec::new());
            }
            RuntimeState::Stopping => {
                let error = Error::StateError("runtime already stopping".into());
                self.record_runtime_error("runtime.stop.state", &error);
                return Err(error);
            }
            RuntimeState::Running => {}
        }

        let pending_events = self
            .commit_barrier
            .pending_count()
            .saturating_add(self.injected_events.len())
            .saturating_add(self.pending_source_events.len());
        if pending_events > 0 {
            let error = Error::StateError(format!(
                "runtime has {pending_events} uncommitted events; commit acknowledgements before stop or call force_stop()"
            ));
            self.record_runtime_error("runtime.stop.uncommitted", &error);
            return Err(error);
        }

        self.state = RuntimeState::Stopping;
        self.delivered_not_committed = 0;
        self.pending_delivery = None;
        self.source.close().await;

        self.snapshot = None;
        self.stream = None;
        self.started_at_ms = None;
        self.last_source_event_ts_ms = None;
        self.observability()
            .tracer
            .trace_checkpoint_barrier("stopped");
        self.state = RuntimeState::Stopped;

        if let Some(mutex) = self.registered_sink.take() {
            let mut sink = mutex
                .into_inner()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let result = if let Some(timeout_ms) = self.config.options.sink_close_timeout_ms {
                sink.close_with_timeout(timeout_ms).await
            } else {
                sink.close().await
            };
            if let Err(ref e) = result {
                self.observability()
                    .metrics
                    .record_error(e, "runtime.stop.sink_close");
            }
            result?;
        }

        Ok(Vec::new())
    }

    /// Force stop the runtime and drain all pending in-memory events.
    ///
    /// This is intended for emergency shutdown paths where replay/duplication
    /// handling is delegated to the embedder.
    pub async fn force_stop(&mut self) -> Result<Vec<Event>> {
        match self.state {
            RuntimeState::Idle | RuntimeState::Stopped => {
                self.state = RuntimeState::Stopped;
                return Ok(Vec::new());
            }
            RuntimeState::Stopping => {
                let error = Error::StateError("runtime already stopping".into());
                self.record_runtime_error("runtime.force_stop.state", &error);
                return Err(error);
            }
            RuntimeState::Running => {}
        }

        self.state = RuntimeState::Stopping;
        let mut drained = std::mem::take(&mut self.injected_events)
            .into_iter()
            .collect::<Vec<_>>();
        if let Some(pending) = self.pending_delivery.take() {
            // Only re-drain events that were not yet committed.
            drained.extend(pending.events[pending.committed_prefix..].iter().cloned());
        }
        drained.extend(self.buffered_events.drain(..));
        drained.extend(self.pending_source_events.drain(..));
        self.commit_barrier.clear_pending();
        let drained_event_count = drained.len();
        for event in &drained {
            self.observability()
                .tracer
                .trace_event_end(&Self::event_trace_id(event), "force_stopped");
        }
        tracing::warn!(
            target: "rustcdc::core::runtime",
            shutdown_mode = "forced",
            drained_events = drained_event_count,
            "force_stop called; uncommitted events discarded — embedder must handle replay/deduplication"
        );
        self.delivered_not_committed = 0;
        self.source.close().await;

        self.snapshot = None;
        self.stream = None;
        self.started_at_ms = None;
        self.last_source_event_ts_ms = None;
        self.observability()
            .tracer
            .trace_checkpoint_barrier("stopped");
        self.state = RuntimeState::Stopped;

        if let Some(mutex) = self.registered_sink.take() {
            let mut sink = mutex
                .into_inner()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let result = if let Some(timeout_ms) = self.config.options.sink_close_timeout_ms {
                sink.close_with_timeout(timeout_ms).await
            } else {
                sink.close().await
            };
            if let Err(ref e) = result {
                self.observability()
                    .metrics
                    .record_error(e, "runtime.force_stop.sink_close");
            }
            result?;
        }

        Ok(drained)
    }

    /// Drain buffered in-flight events, acknowledge them, then stop the runtime cleanly.
    ///
    /// This is a convenience shortcut for the common shutdown pattern:
    ///
    /// ```ignore
    /// while let Ok(batch) = runtime.poll_event_batch().await {
    ///     if batch.is_empty() { break; }
    ///     runtime.commit_ack(batch.ack_mode()).await?;
    /// }
    /// runtime.stop().await?;
    /// ```
    ///
    /// # Termination semantics
    ///
    /// `drain_and_stop` terminates on the **first empty batch** returned by
    /// `poll_event_batch()`. For a finite source (e.g. a snapshot or a mock),
    /// this drains all buffered events. For a **continuous live-replication
    /// stream**, the source will appear empty as soon as the internal buffer
    /// drains — which may happen quickly even while the upstream database is
    /// still producing writes. In that case `drain_and_stop` stops after the
    /// current buffer is consumed, not after the stream is logically
    /// exhausted.
    ///
    /// For continuous streams, prefer calling [`CdcRuntime::stop()`] after your consumer
    /// loop signals shutdown, or use [`CdcRuntime::force_stop()`] if you need an
    /// unconditional immediate halt.
    ///
    /// Returns the total number of events that were drained and committed.
    pub async fn drain_and_stop(&mut self) -> Result<usize> {
        let mut total = 0usize;
        loop {
            let batch = self.poll_event_batch().await?;
            if batch.is_empty() {
                break;
            }
            total = total.saturating_add(batch.len());
            self.commit_ack(batch.ack_mode()).await?;
        }
        self.stop().await?;
        Ok(total)
    }
}