Skip to main content

risingwave_connector/source/cdc/
split.rs

1// Copyright 2022 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::marker::PhantomData;
16
17use anyhow::Context;
18use risingwave_common::types::JsonbVal;
19use serde::{Deserialize, Serialize};
20
21use crate::error::ConnectorResult;
22use crate::source::cdc::external::DebeziumOffset;
23use crate::source::cdc::external::postgres::PostgresOffset;
24use crate::source::cdc::{CdcSourceType, CdcSourceTypeTrait, Mariadb, Mysql, Postgres, SqlServer};
25use crate::source::{SplitId, SplitMetaData};
26
27/// The base states of a CDC split, which will be persisted to checkpoint.
28/// CDC source only has single split, so we use the `source_id` to identify the split.
29#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Hash)]
30pub struct CdcSplitBase {
31    pub split_id: u32,
32    pub start_offset: Option<String>,
33    pub snapshot_done: bool,
34}
35
36impl CdcSplitBase {
37    pub fn new(split_id: u32, start_offset: Option<String>) -> Self {
38        Self {
39            split_id,
40            start_offset,
41            snapshot_done: false,
42        }
43    }
44}
45
46trait CdcSplitTrait: Send + Sync {
47    fn split_id(&self) -> u32;
48    fn start_offset(&self) -> &Option<String>;
49    fn is_snapshot_done(&self) -> bool;
50    fn update_offset(&mut self, last_seen_offset: String) -> ConnectorResult<()>;
51
52    // MySQL and MongoDB shares the same logic to extract the snapshot flag
53    fn extract_snapshot_flag(&self, start_offset: &str) -> ConnectorResult<bool> {
54        // if snapshot_done is already true, it won't be changed
55        let mut snapshot_done = self.is_snapshot_done();
56        if snapshot_done {
57            return Ok(snapshot_done);
58        }
59
60        let dbz_offset: DebeziumOffset = serde_json::from_str(start_offset).with_context(|| {
61            format!(
62                "invalid cdc offset: {}, split: {}",
63                start_offset,
64                self.split_id()
65            )
66        })?;
67
68        // heartbeat event should not update the `snapshot_done` flag
69        if !dbz_offset.is_heartbeat {
70            snapshot_done = match dbz_offset.source_offset.snapshot {
71                Some(val) => !val,
72                None => true,
73            };
74        }
75        Ok(snapshot_done)
76    }
77}
78
79#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Hash)]
80pub struct MysqlCdcSplit {
81    pub inner: CdcSplitBase,
82}
83
84#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Hash)]
85pub struct MariadbCdcSplit {
86    pub inner: CdcSplitBase,
87}
88
89#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Hash)]
90pub struct PostgresCdcSplit {
91    pub inner: CdcSplitBase,
92}
93
94#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Hash)]
95pub struct MongodbCdcSplit {
96    pub inner: CdcSplitBase,
97}
98
99#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Hash)]
100pub struct SqlServerCdcSplit {
101    pub inner: CdcSplitBase,
102}
103
104#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Hash)]
105pub struct OracleCdcSplit {
106    pub inner: CdcSplitBase,
107}
108
109impl MysqlCdcSplit {
110    pub fn new(split_id: u32, start_offset: Option<String>) -> Self {
111        let split = CdcSplitBase {
112            split_id,
113            start_offset,
114            snapshot_done: false,
115        };
116        Self { inner: split }
117    }
118
119    /// Extract MySQL CDC binlog offset (file sequence and position) from the offset JSON string.
120    ///
121    /// MySQL binlog offset format:
122    /// ```json
123    /// {
124    ///   "sourcePartition": { "server": "..." },
125    ///   "sourceOffset": {
126    ///     "file": "binlog.000123",
127    ///     "pos": 456789,
128    ///     ...
129    ///   }
130    /// }
131    /// ```
132    ///
133    /// Returns `Some((file_seq, position))` where:
134    /// - `file_seq`: the numeric part of binlog filename (e.g., 123 from "binlog.000123")
135    /// - `position`: the byte offset within the binlog file
136    pub fn mysql_binlog_offset(&self) -> Option<(u64, u64)> {
137        let offset_str = self.inner.start_offset.as_ref()?;
138        let offset = serde_json::from_str::<serde_json::Value>(offset_str).ok()?;
139        let source_offset = offset.get("sourceOffset")?;
140
141        let file = source_offset.get("file")?.as_str()?;
142        let pos = source_offset.get("pos")?.as_u64()?;
143
144        let file_seq = extract_binlog_file_seq(file)?;
145
146        Some((file_seq, pos))
147    }
148}
149
150impl MariadbCdcSplit {
151    pub fn new(split_id: u32, start_offset: Option<String>) -> Self {
152        Self {
153            inner: CdcSplitBase::new(split_id, start_offset),
154        }
155    }
156
157    pub fn mariadb_binlog_offset(&self) -> Option<(u64, u64)> {
158        binlog_offset(&self.inner)
159    }
160}
161
162impl CdcSplitTrait for MariadbCdcSplit {
163    fn split_id(&self) -> u32 {
164        self.inner.split_id
165    }
166
167    fn start_offset(&self) -> &Option<String> {
168        &self.inner.start_offset
169    }
170
171    fn is_snapshot_done(&self) -> bool {
172        self.inner.snapshot_done
173    }
174
175    fn update_offset(&mut self, last_seen_offset: String) -> ConnectorResult<()> {
176        self.inner.snapshot_done = self.extract_snapshot_flag(last_seen_offset.as_str())?;
177        self.inner.start_offset = Some(last_seen_offset);
178        Ok(())
179    }
180}
181
182impl CdcSplitTrait for MysqlCdcSplit {
183    fn split_id(&self) -> u32 {
184        self.inner.split_id
185    }
186
187    fn start_offset(&self) -> &Option<String> {
188        &self.inner.start_offset
189    }
190
191    fn is_snapshot_done(&self) -> bool {
192        self.inner.snapshot_done
193    }
194
195    fn update_offset(&mut self, last_seen_offset: String) -> ConnectorResult<()> {
196        // if snapshot_done is already true, it won't be updated
197        self.inner.snapshot_done = self.extract_snapshot_flag(last_seen_offset.as_str())?;
198        self.inner.start_offset = Some(last_seen_offset);
199        Ok(())
200    }
201}
202
203impl PostgresCdcSplit {
204    pub fn new(split_id: u32, start_offset: Option<String>) -> Self {
205        let split = CdcSplitBase {
206            split_id,
207            start_offset,
208            snapshot_done: false,
209        };
210        Self { inner: split }
211    }
212
213    /// Extract PostgreSQL LSN value from the offset JSON string.
214    ///
215    /// This function parses the offset JSON and extracts the LSN value from the sourceOffset.lsn field.
216    /// Returns Some(lsn) if the LSN is found and can be parsed as u64, None otherwise.
217    pub fn pg_lsn(&self) -> Option<u64> {
218        let offset_str = self.inner.start_offset.as_ref()?;
219        let offset = serde_json::from_str::<serde_json::Value>(offset_str).ok()?;
220        let source_offset = offset.get("sourceOffset")?;
221        let lsn = source_offset.get("lsn")?;
222        lsn.as_u64()
223    }
224
225    /// Extract PostgreSQL `lsn_commit` from the current offset (last commit position).
226    pub fn pg_lsn_commit(&self) -> Option<u64> {
227        let offset_str = self.inner.start_offset.as_ref()?;
228        extract_postgres_lsn_commit_from_offset_str(offset_str)
229    }
230
231    /// Extract PostgreSQL `lsn_proc` from the current offset (last completely processed position).
232    pub fn pg_lsn_proc(&self) -> Option<u64> {
233        let offset_str = self.inner.start_offset.as_ref()?;
234        extract_postgres_lsn_proc_from_offset_str(offset_str)
235    }
236}
237
238impl CdcSplitTrait for PostgresCdcSplit {
239    fn split_id(&self) -> u32 {
240        self.inner.split_id
241    }
242
243    fn start_offset(&self) -> &Option<String> {
244        &self.inner.start_offset
245    }
246
247    fn is_snapshot_done(&self) -> bool {
248        self.inner.snapshot_done
249    }
250
251    fn update_offset(&mut self, last_seen_offset: String) -> ConnectorResult<()> {
252        let new_snapshot_done = self.extract_snapshot_flag(last_seen_offset.as_str())?;
253
254        // Monotonicity guard for streaming-phase Postgres CDC offsets.
255        //
256        // Debezium's task-level auto-restart (BaseSourceTask) reloads
257        // effectiveOffset from ConfigurableOffsetBackingStore, which lags
258        // dbz's in-memory position by one barrier + async commit cycle.
259        // After a broken pipe, dbz re-emits older WAL events whose LSNs
260        // are smaller than the freshest entry we already persisted.
261        // Without this guard those stale LSNs would overwrite the split
262        // state, the store would then be pushed backwards via the next
263        // barrier, and a subsequent restart would load the stale value.
264        //
265        // We guard both `lsn_commit` and `lsn_proc` because dbz consumes
266        // them for two different things on resume:
267        //   - `lsn_commit` is what `validateLogPosition` checks against
268        //     PG slot.restart_lsn; regression here causes a fatal
269        //     `DebeziumException` ("change stream ... no longer available").
270        //   - `lsn_proc` is the start position for `startStreaming` and
271        //     the key `WalPositionLocator` uses to deduplicate replayed
272        //     events on restart; regression here can lead to silent
273        //     data loss / a hung resume if PG has already advanced past
274        //     the rewound value.
275        //
276        // The per-message `lsn` field is intentionally NOT used as a
277        // monotonicity key: under concurrent overlapping transactions
278        // PG streams events in commit order, so the per-event physical
279        // lsn can legitimately move backwards when a long-running
280        // earlier transaction commits later than a shorter newer one.
281        // Only `lsn_commit` and `lsn_proc` are monotonic under correct
282        // dbz behavior.
283        //
284        // If both offsets are parseable as streaming Postgres offsets, use
285        // the same `(lsn_commit, lsn_proc)` ordering as snapshot backfill
286        // deduplication. Snapshot / heartbeat / incomplete offsets are not
287        // comparable and pass through.
288        if let (Some(old_offset), Some(new_offset)) = (
289            self.inner
290                .start_offset
291                .as_deref()
292                .and_then(parse_postgres_offset_from_offset_str),
293            parse_postgres_offset_from_offset_str(&last_seen_offset),
294        ) && new_offset < old_offset
295        {
296            tracing::warn!(
297                split_id = self.inner.split_id,
298                ?old_offset,
299                ?new_offset,
300                "Rejecting backward Postgres CDC offset update; \
301                 keeping current state to prevent state-table regression."
302            );
303            return Ok(());
304        }
305
306        self.inner.snapshot_done = new_snapshot_done;
307        self.inner.start_offset = Some(last_seen_offset);
308        Ok(())
309    }
310
311    fn extract_snapshot_flag(&self, start_offset: &str) -> ConnectorResult<bool> {
312        // if snapshot_done is already true, it won't be changed
313        let mut snapshot_done = self.is_snapshot_done();
314        if snapshot_done {
315            return Ok(snapshot_done);
316        }
317
318        let dbz_offset: DebeziumOffset = serde_json::from_str(start_offset).with_context(|| {
319            format!(
320                "invalid postgres offset: {}, split: {}",
321                start_offset, self.inner.split_id
322            )
323        })?;
324
325        // heartbeat event should not update the `snapshot_done` flag
326        if !dbz_offset.is_heartbeat {
327            snapshot_done = dbz_offset
328                .source_offset
329                .last_snapshot_record
330                .unwrap_or(false);
331        }
332        Ok(snapshot_done)
333    }
334}
335
336impl MongodbCdcSplit {
337    pub fn new(split_id: u32, start_offset: Option<String>) -> Self {
338        let split = CdcSplitBase {
339            split_id,
340            start_offset,
341            snapshot_done: false,
342        };
343        Self { inner: split }
344    }
345}
346
347impl CdcSplitTrait for MongodbCdcSplit {
348    fn split_id(&self) -> u32 {
349        self.inner.split_id
350    }
351
352    fn start_offset(&self) -> &Option<String> {
353        &self.inner.start_offset
354    }
355
356    fn is_snapshot_done(&self) -> bool {
357        self.inner.snapshot_done
358    }
359
360    fn update_offset(&mut self, last_seen_offset: String) -> ConnectorResult<()> {
361        // if snapshot_done is already true, it will remain true
362        self.inner.snapshot_done = self.extract_snapshot_flag(last_seen_offset.as_str())?;
363        self.inner.start_offset = Some(last_seen_offset);
364        Ok(())
365    }
366}
367
368impl SqlServerCdcSplit {
369    pub fn new(split_id: u32, start_offset: Option<String>) -> Self {
370        let split = CdcSplitBase {
371            split_id,
372            start_offset,
373            snapshot_done: false,
374        };
375        Self { inner: split }
376    }
377
378    /// Extract SQL Server `change_lsn` value from the offset JSON string.
379    pub fn sql_server_change_lsn(&self) -> Option<u128> {
380        let offset_str = self.inner.start_offset.as_ref()?;
381        extract_sql_server_change_lsn_from_offset_str(offset_str)
382    }
383
384    /// Extract SQL Server `commit_lsn` value from the offset JSON string.
385    pub fn sql_server_commit_lsn(&self) -> Option<u128> {
386        let offset_str = self.inner.start_offset.as_ref()?;
387        extract_sql_server_commit_lsn_from_offset_str(offset_str)
388    }
389}
390
391impl CdcSplitTrait for SqlServerCdcSplit {
392    fn split_id(&self) -> u32 {
393        self.inner.split_id
394    }
395
396    fn start_offset(&self) -> &Option<String> {
397        &self.inner.start_offset
398    }
399
400    fn is_snapshot_done(&self) -> bool {
401        self.inner.snapshot_done
402    }
403
404    fn update_offset(&mut self, last_seen_offset: String) -> ConnectorResult<()> {
405        // if snapshot_done is already true, it will remain true
406        self.inner.snapshot_done = self.extract_snapshot_flag(last_seen_offset.as_str())?;
407        self.inner.start_offset = Some(last_seen_offset);
408        Ok(())
409    }
410}
411
412impl OracleCdcSplit {
413    pub fn new(split_id: u32, start_offset: Option<String>) -> Self {
414        Self {
415            inner: CdcSplitBase::new(split_id, start_offset),
416        }
417    }
418}
419
420impl CdcSplitTrait for OracleCdcSplit {
421    fn split_id(&self) -> u32 {
422        self.inner.split_id
423    }
424
425    fn start_offset(&self) -> &Option<String> {
426        &self.inner.start_offset
427    }
428
429    fn is_snapshot_done(&self) -> bool {
430        self.inner.snapshot_done
431    }
432
433    fn update_offset(&mut self, last_seen_offset: String) -> ConnectorResult<()> {
434        self.inner.start_offset = Some(last_seen_offset);
435        Ok(())
436    }
437}
438
439/// We use this struct to wrap the specific split, which act as an interface to other modules
440#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Hash)]
441pub struct DebeziumCdcSplit<T: CdcSourceTypeTrait> {
442    pub mysql_split: Option<MysqlCdcSplit>,
443    pub mariadb_split: Option<MariadbCdcSplit>,
444
445    #[serde(rename = "pg_split")] // backward compatibility
446    pub postgres_split: Option<PostgresCdcSplit>,
447    pub mongodb_split: Option<MongodbCdcSplit>,
448    pub sql_server_split: Option<SqlServerCdcSplit>,
449    pub oracle_split: Option<OracleCdcSplit>,
450
451    #[serde(skip)]
452    pub _phantom: PhantomData<T>,
453}
454
455macro_rules! dispatch_cdc_split_inner {
456    ($dbz_split:expr, $as_type:tt, {$({$cdc_source_type:tt, $cdc_source_split:tt}),*}, $body:expr) => {
457        match T::source_type() {
458            $(
459                CdcSourceType::$cdc_source_type => {
460                    $crate::paste! {
461                        $dbz_split.[<$cdc_source_split>]
462                            .[<as_ $as_type>]()
463                            .expect(concat!(stringify!([<$cdc_source_type:lower>]), " split must exist"))
464                            .$body
465                    }
466                }
467            )*
468            CdcSourceType::Unspecified => {
469                unreachable!("invalid debezium split");
470            }
471        }
472    }
473}
474
475// call corresponding split method of the specific cdc source type
476macro_rules! dispatch_cdc_split {
477    ($dbz_split:expr, $as_type:tt, $body:expr) => {
478        dispatch_cdc_split_inner!($dbz_split, $as_type, {
479            {Mysql, mysql_split},
480            {Mariadb, mariadb_split},
481            {Postgres, postgres_split},
482            {Mongodb, mongodb_split},
483            {SqlServer, sql_server_split},
484            {Oracle, oracle_split}
485        }, $body)
486    }
487}
488
489impl<T: CdcSourceTypeTrait> SplitMetaData for DebeziumCdcSplit<T> {
490    fn id(&self) -> SplitId {
491        format!("{}", self.split_id()).into()
492    }
493
494    fn encode_to_json(&self) -> JsonbVal {
495        serde_json::to_value(self.clone()).unwrap().into()
496    }
497
498    fn restore_from_json(value: JsonbVal) -> ConnectorResult<Self> {
499        serde_json::from_value(value.take()).map_err(Into::into)
500    }
501
502    fn update_offset(&mut self, last_seen_offset: String) -> ConnectorResult<()> {
503        self.update_offset_inner(last_seen_offset)
504    }
505}
506
507impl<T: CdcSourceTypeTrait> DebeziumCdcSplit<T> {
508    pub fn new(split_id: u32, start_offset: Option<String>) -> Self {
509        let mut ret = Self {
510            mysql_split: None,
511            mariadb_split: None,
512            postgres_split: None,
513            mongodb_split: None,
514            sql_server_split: None,
515            oracle_split: None,
516            _phantom: PhantomData,
517        };
518        match T::source_type() {
519            CdcSourceType::Mysql => {
520                let split = MysqlCdcSplit::new(split_id, start_offset);
521                ret.mysql_split = Some(split);
522            }
523            CdcSourceType::Mariadb => {
524                let split = MariadbCdcSplit::new(split_id, start_offset);
525                ret.mariadb_split = Some(split);
526            }
527            CdcSourceType::Postgres => {
528                let split = PostgresCdcSplit::new(split_id, start_offset);
529                ret.postgres_split = Some(split);
530            }
531            CdcSourceType::Mongodb => {
532                let split = MongodbCdcSplit::new(split_id, start_offset);
533                ret.mongodb_split = Some(split);
534            }
535            CdcSourceType::SqlServer => {
536                let split = SqlServerCdcSplit::new(split_id, start_offset);
537                ret.sql_server_split = Some(split);
538            }
539            CdcSourceType::Oracle => {
540                let split = OracleCdcSplit::new(split_id, start_offset);
541                ret.oracle_split = Some(split);
542            }
543            CdcSourceType::Unspecified => {
544                unreachable!("invalid debezium split")
545            }
546        }
547        ret
548    }
549
550    pub fn split_id(&self) -> u32 {
551        dispatch_cdc_split!(self, ref, split_id())
552    }
553
554    pub fn start_offset(&self) -> &Option<String> {
555        dispatch_cdc_split!(self, ref, start_offset())
556    }
557
558    pub fn snapshot_done(&self) -> bool {
559        dispatch_cdc_split!(self, ref, is_snapshot_done())
560    }
561
562    pub fn update_offset_inner(&mut self, last_seen_offset: String) -> ConnectorResult<()> {
563        dispatch_cdc_split!(self, mut, update_offset(last_seen_offset)?);
564        Ok(())
565    }
566}
567
568impl DebeziumCdcSplit<Postgres> {
569    /// Extract PostgreSQL LSN value from the current split offset.
570    ///
571    /// Returns Some(lsn) if the LSN is found and can be parsed as u64, None otherwise.
572    pub fn pg_lsn(&self) -> Option<u64> {
573        self.postgres_split.as_ref()?.pg_lsn()
574    }
575}
576
577impl DebeziumCdcSplit<Mysql> {
578    /// Extract MySQL CDC binlog offset (file sequence and position) from the current split offset.
579    ///
580    /// Returns `Some((file_seq, position))` where:
581    /// - `file_seq`: the numeric part of binlog filename (e.g., 123 from "binlog.000123")
582    /// - `position`: the byte offset within the binlog file
583    pub fn mysql_binlog_offset(&self) -> Option<(u64, u64)> {
584        self.mysql_split.as_ref()?.mysql_binlog_offset()
585    }
586}
587
588impl DebeziumCdcSplit<Mariadb> {
589    pub fn mariadb_binlog_offset(&self) -> Option<(u64, u64)> {
590        self.mariadb_split.as_ref()?.mariadb_binlog_offset()
591    }
592}
593
594fn binlog_offset(split: &CdcSplitBase) -> Option<(u64, u64)> {
595    let offset_str = split.start_offset.as_ref()?;
596    let offset = serde_json::from_str::<serde_json::Value>(offset_str).ok()?;
597    let source_offset = offset.get("sourceOffset")?;
598    let file = source_offset.get("file")?.as_str()?;
599    let pos = source_offset.get("pos")?.as_u64()?;
600    Some((extract_binlog_file_seq(file)?, pos))
601}
602
603impl DebeziumCdcSplit<SqlServer> {
604    /// Extract SQL Server CDC `change_lsn` from the current split offset.
605    pub fn sql_server_change_lsn(&self) -> Option<u128> {
606        self.sql_server_split.as_ref()?.sql_server_change_lsn()
607    }
608
609    /// Extract SQL Server CDC `commit_lsn` from the current split offset.
610    pub fn sql_server_commit_lsn(&self) -> Option<u128> {
611        self.sql_server_split.as_ref()?.sql_server_commit_lsn()
612    }
613}
614
615/// Extract the numeric sequence from a MySQL binlog file name `<basename>.<sequence>`.
616///
617/// The basename is configurable (`binlog`, `mysql-bin`, `mysql-bin-changelog` on RDS/Aurora, ...),
618/// so we take the number after the last `.` rather than assuming a fixed prefix.
619pub fn extract_binlog_file_seq(file_name: &str) -> Option<u64> {
620    file_name.rsplit('.').next()?.parse::<u64>().ok()
621}
622
623/// Extract PostgreSQL LSN value from a CDC offset JSON string.
624///
625/// This is a standalone helper function that can be used when you only have the offset string
626/// (e.g., in callbacks) and don't have access to the Split object.
627///
628/// Returns Some(lsn) if the LSN is found and can be parsed as u64, None otherwise.
629pub fn extract_postgres_lsn_from_offset_str(offset_str: &str) -> Option<u64> {
630    let offset = serde_json::from_str::<serde_json::Value>(offset_str).ok()?;
631    let source_offset = offset.get("sourceOffset")?;
632    let lsn = source_offset.get("lsn")?;
633    lsn.as_u64()
634}
635
636fn parse_postgres_offset_from_offset_str(offset_str: &str) -> Option<PostgresOffset> {
637    PostgresOffset::parse_debezium_offset(offset_str).ok()
638}
639
640/// Extract PostgreSQL `lsn_commit` from a CDC offset JSON string.
641///
642/// `lsn_commit` is the WAL position of the last COMMIT message dbz has
643/// processed. It is the value dbz flushes to PG (`flushLsn`) to advance
644/// `confirmed_flush_lsn`, and the value `validateLogPosition` compares
645/// against `slot.restart_lsn` on restart. Must be monotonic across
646/// restarts -- a regression here can cause a fatal `DebeziumException`
647/// ("change stream ... no longer available").
648pub fn extract_postgres_lsn_commit_from_offset_str(offset_str: &str) -> Option<u64> {
649    let offset = serde_json::from_str::<serde_json::Value>(offset_str).ok()?;
650    let source_offset = offset.get("sourceOffset")?;
651    let lsn = source_offset.get("lsn_commit")?;
652    lsn.as_u64()
653}
654
655/// Extract PostgreSQL `lsn_proc` from a CDC offset JSON string.
656///
657/// `lsn_proc` is the WAL position of the last message dbz has fully
658/// processed. On restart dbz uses it as the start position passed to
659/// `startStreaming`, and as the dedup key for `WalPositionLocator` to
660/// filter replayed events. A regression can cause silent data loss or
661/// a hung resume if PG has already advanced past the rewound value.
662pub fn extract_postgres_lsn_proc_from_offset_str(offset_str: &str) -> Option<u64> {
663    let offset = serde_json::from_str::<serde_json::Value>(offset_str).ok()?;
664    let source_offset = offset.get("sourceOffset")?;
665    let lsn = source_offset.get("lsn_proc")?;
666    lsn.as_u64()
667}
668
669/// Parse SQL Server LSN string (`XXXXXXXX:XXXXXXXX:XXXX`) into a comparable integer.
670pub fn parse_sql_server_lsn_str(lsn: &str) -> Option<u128> {
671    let mut parts = lsn.split(':');
672    let part0 = u32::from_str_radix(parts.next()?, 16).ok()? as u128;
673    let part1 = u32::from_str_radix(parts.next()?, 16).ok()? as u128;
674    let part2 = u16::from_str_radix(parts.next()?, 16).ok()? as u128;
675    if parts.next().is_some() {
676        return None;
677    }
678
679    Some((part0 << 48) | (part1 << 16) | part2)
680}
681
682/// Extract SQL Server `change_lsn` from a CDC offset JSON string.
683pub fn extract_sql_server_change_lsn_from_offset_str(offset_str: &str) -> Option<u128> {
684    let offset = serde_json::from_str::<serde_json::Value>(offset_str).ok()?;
685    let source_offset = offset.get("sourceOffset")?;
686    let lsn = source_offset.get("change_lsn")?.as_str()?;
687    parse_sql_server_lsn_str(lsn)
688}
689
690/// Extract SQL Server `commit_lsn` from a CDC offset JSON string.
691pub fn extract_sql_server_commit_lsn_from_offset_str(offset_str: &str) -> Option<u128> {
692    let offset = serde_json::from_str::<serde_json::Value>(offset_str).ok()?;
693    let source_offset = offset.get("sourceOffset")?;
694    let lsn = source_offset.get("commit_lsn")?.as_str()?;
695    parse_sql_server_lsn_str(lsn)
696}
697
698#[cfg(test)]
699mod tests {
700    use super::*;
701
702    #[test]
703    fn mariadb_split_round_trip_and_binlog_offset() {
704        let offset = r#"{"sourcePartition":{"server":"RW_CDC_1"},"sourceOffset":{"file":"mariadb-bin.000123","pos":456},"isHeartbeat":false}"#;
705        let split = DebeziumCdcSplit::<Mariadb>::new(1, Some(offset.to_owned()));
706        assert_eq!(split.mariadb_binlog_offset(), Some((123, 456)));
707
708        let json = split.encode_to_json();
709        let restored = DebeziumCdcSplit::<Mariadb>::restore_from_json(json).unwrap();
710        assert_eq!(restored, split);
711    }
712
713    #[test]
714    fn test_parse_sql_server_lsn_str() {
715        let lsn = "00000027:00000ac0:0002";
716        let parsed = parse_sql_server_lsn_str(lsn).unwrap();
717        let expected = ((0x00000027_u128) << 48) | ((0x00000ac0_u128) << 16) | (0x0002_u128);
718        assert_eq!(parsed, expected);
719    }
720
721    /// Build a streaming-phase PG offset JSON. Sets `lsn`, `lsn_proc`,
722    /// and `lsn_commit` all to the same value -- this is the common
723    /// shape for the guard's basic monotonic tests.
724    fn pg_streaming_offset_json(lsn: u64) -> String {
725        pg_streaming_offset_json_full(lsn, lsn, lsn)
726    }
727
728    /// Build a streaming-phase PG offset JSON with independent control
729    /// over `lsn`, `lsn_proc`, and `lsn_commit`. Used to exercise
730    /// transaction-interleave and asymmetric-regression scenarios.
731    fn pg_streaming_offset_json_full(lsn: u64, lsn_proc: u64, lsn_commit: u64) -> String {
732        format!(
733            r#"{{
734                "sourcePartition": {{"server": "RW_CDC_1001"}},
735                "sourceOffset": {{
736                    "last_snapshot_record": false,
737                    "lsn": {lsn},
738                    "lsn_proc": {lsn_proc},
739                    "lsn_commit": {lsn_commit},
740                    "txId": 12345,
741                    "ts_usec": 1700000000000000
742                }},
743                "isHeartbeat": false
744            }}"#
745        )
746    }
747
748    #[test]
749    fn test_postgres_offset_monotonic_guard_rejects_backward_lsn() {
750        let mut split = PostgresCdcSplit::new(1, Some(pg_streaming_offset_json(200)));
751
752        // Push a backward LSN -- must be rejected, current offset kept.
753        split
754            .update_offset(pg_streaming_offset_json(150))
755            .expect("update_offset must not error on rejection");
756        assert_eq!(split.pg_lsn(), Some(200));
757    }
758
759    #[test]
760    fn test_postgres_offset_monotonic_guard_allows_forward_lsn() {
761        let mut split = PostgresCdcSplit::new(1, Some(pg_streaming_offset_json(200)));
762
763        split.update_offset(pg_streaming_offset_json(250)).unwrap();
764        assert_eq!(split.pg_lsn(), Some(250));
765    }
766
767    #[test]
768    fn test_postgres_offset_monotonic_guard_allows_equal_lsn() {
769        let mut split = PostgresCdcSplit::new(1, Some(pg_streaming_offset_json(200)));
770
771        // Equal is allowed (no regression).
772        split.update_offset(pg_streaming_offset_json(200)).unwrap();
773        assert_eq!(split.pg_lsn(), Some(200));
774    }
775
776    #[test]
777    fn test_postgres_offset_snapshot_phase_bypasses_guard() {
778        let snapshot_offset = r#"{
779            "sourcePartition": {"server": "RW_CDC_1001"},
780            "sourceOffset": {
781                "last_snapshot_record": false,
782                "lsn": 150,
783                "txId": 12345,
784                "ts_usec": 1700000000000000
785            },
786            "isHeartbeat": false
787        }"#;
788        let mut split = PostgresCdcSplit::new(1, Some(pg_streaming_offset_json(200)));
789
790        // Snapshot / incomplete offsets do not have a comparable streaming
791        // `lsn_proc`, so they pass through even when the plain `lsn` is lower.
792        split.update_offset(snapshot_offset.to_owned()).unwrap();
793        assert_eq!(split.pg_lsn(), Some(150));
794    }
795
796    #[test]
797    fn test_postgres_offset_lsn_commit_regression_rejected() {
798        // `lsn_commit` regressing alone must trigger reject -- this is
799        // the field validateLogPosition checks, regression here is the
800        // catastrophic case.
801        let initial = pg_streaming_offset_json_full(200, 200, 200);
802        let mut split = PostgresCdcSplit::new(1, Some(initial));
803
804        // lsn_commit 200 -> 150, but lsn / lsn_proc stay at 200.
805        let new = pg_streaming_offset_json_full(200, 200, 150);
806        split.update_offset(new).unwrap();
807
808        assert_eq!(
809            split.pg_lsn_commit(),
810            Some(200),
811            "lsn_commit must not regress"
812        );
813    }
814
815    #[test]
816    fn test_postgres_offset_lsn_proc_regression_rejected() {
817        // `lsn_proc` regressing alone must trigger reject -- this is the
818        // field dbz uses as the startStreaming resume position, and
819        // WalPositionLocator's dedup key on restart.
820        let initial = pg_streaming_offset_json_full(200, 200, 200);
821        let mut split = PostgresCdcSplit::new(1, Some(initial));
822
823        // lsn_proc 200 -> 150, but lsn / lsn_commit stay at 200.
824        let new = pg_streaming_offset_json_full(200, 150, 200);
825        split.update_offset(new).unwrap();
826
827        assert_eq!(split.pg_lsn_proc(), Some(200), "lsn_proc must not regress");
828    }
829
830    #[test]
831    fn test_postgres_offset_interleaved_tx_lsn_proc_drop_allowed_by_commit_lsn() {
832        // Concurrent overlapping transactions under PG logical
833        // replication produce a state-table chunk where the per-event
834        // `lsn` and `lsn_proc` move backwards while `lsn_commit`
835        // strictly advances (because PG streams events in commit
836        // order, and the earlier-begin transaction's INSERT has a
837        // smaller physical LSN even though it commits later).
838        //
839        // Use the same Postgres offset ordering as #22503: compare
840        // `lsn_commit` first, then `lsn_proc`. Since the commit LSN
841        // advances, this update is not a regression.
842        let initial = pg_streaming_offset_json_full(33_967_592, 33_967_592, 33_893_392);
843        let mut split = PostgresCdcSplit::new(1, Some(initial));
844
845        let new = pg_streaming_offset_json_full(33_918_336, 33_918_336, 33_969_832);
846        split.update_offset(new).unwrap();
847
848        assert_eq!(split.pg_lsn_commit(), Some(33_969_832));
849        assert_eq!(split.pg_lsn_proc(), Some(33_918_336));
850    }
851
852    #[test]
853    fn test_extract_binlog_file_seq() {
854        // default MySQL 8.0 basename
855        assert_eq!(extract_binlog_file_seq("binlog.000123"), Some(123));
856        // `--log-bin=mysql-bin`
857        assert_eq!(extract_binlog_file_seq("mysql-bin.000123"), Some(123));
858        // `<hostname>-bin` on older versions
859        assert_eq!(extract_binlog_file_seq("my-host-bin.000001"), Some(1));
860        // RDS / Aurora MySQL
861        assert_eq!(
862            extract_binlog_file_seq("mysql-bin-changelog.037568"),
863            Some(37568)
864        );
865        // invalid suffix
866        assert_eq!(extract_binlog_file_seq("binlog.index"), None);
867        assert_eq!(extract_binlog_file_seq("no-extension"), None);
868    }
869
870    #[test]
871    fn test_mysql_binlog_offset() {
872        let offset = r#"{
873            "sourcePartition": {"server": "test"},
874            "sourceOffset": {
875                "file": "mysql-bin-changelog.037568",
876                "pos": 12345
877            },
878            "isHeartbeat": false
879        }"#;
880        let split = MysqlCdcSplit::new(1, Some(offset.to_owned()));
881        assert_eq!(split.mysql_binlog_offset(), Some((37568, 12345)));
882    }
883
884    #[test]
885    fn test_extract_sql_server_lsn_from_offset_str() {
886        let offset = r#"{
887            "sourcePartition": {"server":"RW_CDC_1001"},
888            "sourceOffset": {
889                "change_lsn":"00000027:00000ac0:0001",
890                "commit_lsn":"00000027:00000ac0:0002"
891            },
892            "isHeartbeat": false
893        }"#;
894
895        let change_lsn = extract_sql_server_change_lsn_from_offset_str(offset).unwrap();
896        let commit_lsn = extract_sql_server_commit_lsn_from_offset_str(offset).unwrap();
897        assert!(change_lsn < commit_lsn);
898    }
899}