diff --git a/CHANGELOG.md b/CHANGELOG.md index f698648..1fc422f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,99 @@ All notable changes to dbmazz will be documented here. ## [Unreleased] +## [2.3.0] - 2026-05-04 + +### Added + +- **MySQL source (BETA).** New CDC source connector that streams from MySQL + via binlog (ROW format, GTID-aware), supporting StarRocks, PostgreSQL, and + Snowflake sinks. Concurrent snapshot + CDC via the read-only DBLog + Incremental Snapshot algorithm. Requires `gtid_mode=ON` and + `binlog_format=ROW`. Setup, configuration, and BETA scope documented in + [`docs/mysql-source.md`](docs/mysql-source.md). +- **`source::create_source` factory** mirroring the existing + `connectors::sinks::create_sink` factory. Single dispatch point per + side of the pipeline; the engine now constructs sources via the + factory rather than ad-hoc match arms. + +### Fixed + +- MySQL source now persists `(binlog_file, position, gtid_executed)` as the + checkpoint, restoring restart correctness across binlog rotations and + daemon restarts. Earlier, the persisted "checkpoint" was a hex-encoded + byte offset mislabeled as a GTID and the parsed GTID was discarded. +- MySQL snapshot progress query no longer uses `FILTER (WHERE ...)` + (PostgreSQL-only syntax that MySQL ≤ 8.4 rejects with a parse error). +- MySQL CDC checkpoints are now persisted only at transaction commit + boundaries, never mid-transaction. The previous code persisted positions + per acknowledged record, including the in-flight `gtid_executed` added + on `GtidEvent`; a crash before the matching `XidEvent` advanced the + saved checkpoint past an uncommitted transaction and silently dropped it + on restart. (Debezium-faithful adaptation: the connector emits per-event + but commits the offset only at transaction boundaries.) +- DDL-only transactions (`CREATE TABLE`, `ALTER TABLE`, etc., which + terminate with `QueryEvent("COMMIT")` instead of `XidEvent`) now produce + a `BinlogEvent::Commit` boundary so the pipeline flushes and the + persisted checkpoint advances past the DDL. +- MySQL snapshot `await_drain` no longer deadlocks under concurrent + `try_drain` calls. The previous polling-then-awaiting pattern lost + `Notify::notify_waiters` wake-ups fired between the flag check and the + await; reproduced reliably under load and verified fixed by a + 10 000-iteration race-stress unit test. +- MySQL snapshot chunk LOW/HIGH watermarks are now derived from the binlog + consumer's live GTID set (an `Arc>` shared with the + parser), not from `SELECT @@global.gtid_executed` against the source. + Eliminates the LOW-capture-vs-chunk-registration race that emitted + duplicate snapshot+CDC records for rows mutated during the window. +- MySQL heartbeat events now carry the live `(file, position, + gtid_executed)` triple and trigger snapshot drain checks so idle + databases don't hang the snapshot worker. Heartbeats previously emitted + a placeholder `SourcePosition::GtidSet("0")` that corrupted any + checkpoint persisting a heartbeat. +- MySQL `TableMapEvent` parsing preserves column ordinals when a column + type is unrecognised. Previously `extract_col_types` silently dropped + unknown columns via `filter_map`, shifting subsequent columns one slot + down and binding row values to the wrong column names — a silent + corruption bug for tables using a type mysql_common didn't yet + recognise. Unknown columns now produce a sentinel byte in their + original slot; downstream value decoding emits `Value::Null` for them + and a structured `ERROR` log surfaces the table+ordinal. +- MySQL CDC startup runs a `GTID_SUBSET(persisted, @@global.gtid_executed)` + probe; if the persisted set isn't a subset of the server's executed set + (binlog purge, server failover, or a pre-fix daemon's mid-transaction + checkpoint), the daemon now exits non-zero with operator-actionable + remediation rather than retry-looping forever. +- MySQL `TIMESTAMP` and `TIMESTAMP2` columns are now emitted as ISO-8601 + formatted strings (`"YYYY-MM-DD HH:MM:SS"` UTC) instead of being passed + through as the raw epoch-seconds integer. Previously every row of a + table containing a `TIMESTAMP` column failed the PG sink's MERGE cast + (`(_data->>'created_at')::timestamp with time zone`), silently dropping + the entire batch and preventing any data from reaching the target. + Surfaced by the first MySQL→PG end-to-end run via `ez-cdc verify`. + This is the minimum-viable temporal fidelity for MySQL beta; the + forward-compatible `Value::Timestamp(i64 micros)` with `tz_aware` + semantics is scoped to `mysql-cdc-beta-to-ga`. + - Both wire-protocol shapes are handled: `MysqlValue::Int(epoch)` + (legacy `TIMESTAMP`, code `0x07`) and `MysqlValue::Bytes(epoch_ascii)` + (mysql_common 0.32.4 returns `TIMESTAMP2` (code `0x11`) as ASCII + epoch bytes in binlog mode). Plain `INT/BIGINT` columns remain + untouched — verified by a unit test asserting non-temporal int + columns keep their `Value::Int64` shape. + +### Removed + +- `SourcePosition::is_ahead_of` no longer attempts to order + `SourcePosition::GtidSet` values. GTID sets are partial orders (set + inclusion of UUID:range pairs); the previous lexicographic string + compare was meaningless. Callers needing partial-order semantics MUST + use `crate::source::mysql::gtid::GtidSet::is_superset_of` directly. + +### Security + +- MySQL source TLS certificate verification is now **on by default**. Set + `MYSQL_TLS_SKIP_VERIFY=true` to opt out (unsafe — for dev environments + only). The previous behaviour silently accepted any certificate. + ## [2.2.0] - 2026-04-29 ### Added diff --git a/Cargo.lock b/Cargo.lock index 1993a56..6afddc3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -913,7 +913,7 @@ dependencies = [ [[package]] name = "dbmazz" -version = "2.2.0" +version = "2.3.0" dependencies = [ "anyhow", "arrow", @@ -933,6 +933,7 @@ dependencies = [ "libc", "memchr", "mysql_async", + "mysql_common", "openssl-sys", "parquet", "pem", diff --git a/Cargo.toml b/Cargo.toml index 34f47c2..27834fb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "dbmazz" -version = "2.2.0" +version = "2.3.0" edition = "2021" license = "Elastic-2.0" # Minimum Supported Rust Version. @@ -10,6 +10,8 @@ rust-version = "1.91.1" [features] default = ["sink-starrocks", "sink-postgres", "sink-snowflake"] sink-starrocks = ["dep:curl", "dep:mysql_async", "dep:openssl-sys"] +# --- Optional: MySQL source --- +mysql-source = ["dep:mysql_async", "dep:mysql_common", "mysql_async?/binlog"] sink-postgres = [] sink-snowflake = [ "dep:reqwest", "dep:arrow", "dep:parquet", @@ -70,8 +72,12 @@ aws-sigv4 = { version = "1.2", optional = true } aws-credential-types = { version = "1.2", optional = true } uuid = { version = "1", features = ["v4"], optional = true } +# --- Optional: MySQL source --- +mysql_common = { version = "=0.32.4", features = ["binlog"], optional = true } + [dev-dependencies] serial_test = "3.0" +mysql_async = "0.34" [profile.release] debug = 1 # Line tables only (flamegraphs work, smaller binary) diff --git a/Dockerfile.mysql b/Dockerfile.mysql new file mode 100644 index 0000000..25882f1 --- /dev/null +++ b/Dockerfile.mysql @@ -0,0 +1,58 @@ +# syntax=docker/dockerfile:1.6 +# +# Multi-stage build for dbmazz with mysql-source + sink-postgres features. +# +# This is an ALTERNATE Dockerfile for local dev / CI when you don't want +# to pre-compile the binary. The production release workflow still uses +# the main Dockerfile with pre-compiled musl-static binaries. +# +# Usage: +# docker build -t dbmazz-mysql:dev -f Dockerfile.mysql . +# +# For multi-arch builds (slower — QEMU emulates the Rust compiler): +# docker buildx build --platform linux/amd64,linux/arm64 \ +# -t dbmazz-mysql:dev -f Dockerfile.mysql . +# +# Security: runs as non-root user (uid 65532), HEALTHCHECK configured. +# Binary: dynamically linked against glibc (debian:bookworm-slim). +# DEV NOTE: this differs from the production image (musl-static). +# Always validate against a musl-static build before release. + +FROM rust:bookworm AS builder +WORKDIR /app + +# ---- Layer 0: system dependencies for compilation ---- +# openssl-sys (transitive via mysql_async) needs headers during build. +RUN apt-get update && apt-get install -y libssl-dev && rm -rf /var/lib/apt/lists/* + +# ---- Layer 1: fetch dependencies (cached unless Cargo.toml/lock changes) ---- +COPY Cargo.toml Cargo.lock ./ +RUN mkdir -p src && touch src/lib.rs +# NOTE: cargo fetch does NOT support --features, so we fetch default deps here. +# Optional deps (mysql_async, mysql_common) will auto-fetch during build. +RUN cargo fetch --locked + +# ---- Layer 2: real source + real build ---- +COPY src/ src/ +RUN cargo build --release --features mysql-source,sink-postgres --locked + +# ==================================================================== +# Runtime stage +# ==================================================================== +FROM debian:bookworm-slim + +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates curl libssl3 \ + && rm -rf /var/lib/apt/lists/* \ + && useradd --system --no-create-home --uid 65532 dbmazz + +COPY --from=builder /app/target/release/dbmazz /usr/local/bin/dbmazz + +USER dbmazz + +EXPOSE 50051 + +HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --retries=3 \ + CMD curl -sf http://127.0.0.1:50051/api/v1/health || exit 1 + +ENTRYPOINT ["/usr/local/bin/dbmazz"] diff --git a/README.md b/README.md index 50fd41d..bf8c8cf 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,7 @@ Full Docker reference (env vars, healthcheck, persisting state, build-from-sourc | PostgreSQL 12+ | **PostgreSQL 15+** | ✅ Stable | Binary `COPY` → raw table → `MERGE` normalizer; supports hard delete | | PostgreSQL 12+ | **Snowflake** | ✅ Stable | Parquet → PUT (stage) → `COPY INTO` → background `MERGE`; JWT key-pair auth supported; requires `ALTER TABLE` privilege on target schema | | PostgreSQL 12+ | S3 / Iceberg | 🚧 Roadmap | Tracked in [issues](https://github.com/ez-cdc/dbmazz/issues) | -| MySQL | * | 🚧 Roadmap | The source layer is generic; PostgreSQL is the only implementation today | +| MySQL 5.7+ / 8.0+ | All sinks | 🧪 Beta | Binlog-based with GTID-aware checkpointing. See [`docs/mysql-source.md`](docs/mysql-source.md). | Adding a new sink is intentionally small: implement a 6-method `Sink` trait and CDC + snapshot work automatically. See [`docs/contributing-connectors.md`](docs/contributing-connectors.md). diff --git a/docs/mysql-source.md b/docs/mysql-source.md new file mode 100644 index 0000000..aa2a1b8 --- /dev/null +++ b/docs/mysql-source.md @@ -0,0 +1,117 @@ +# MySQL source (BETA) + +dbmazz can stream changes from MySQL 5.7+ / 8.0+ to any of the supported sinks (StarRocks, PostgreSQL, Snowflake) via the `mysql-source` cargo feature. + +This document covers MySQL-specific setup, configuration, and the BETA scope. For general dbmazz architecture, see [architecture.md](architecture.md). + +## Prerequisites + +The source MySQL server **must** have: + +| Setting | Required value | Why | +|---|---|---| +| `log_bin` | enabled (any non-empty value) | Binary log is the change stream | +| `binlog_format` | `ROW` | Statement / mixed formats don't carry full row state | +| `binlog_row_image` | `FULL` | Needed for `UPDATE` / `DELETE` reconciliation | +| `gtid_mode` | `ON` | Required for the read-only DBLog incremental snapshot | +| `enforce_gtid_consistency` | `ON` | Pairs with `gtid_mode=ON` | +| `server_id` | unique non-zero | Replication client identity | + +Privileges required for the connection user: `REPLICATION SLAVE`, `REPLICATION CLIENT`, plus `CREATE`, `INSERT`, `UPDATE`, `DELETE` on the source database (dbmazz writes its checkpoint and snapshot-state tables there — `dbmazz_checkpoints` and `dbmazz_snapshot_state`). + +## Configuration + +```yaml +sources: + my-mysql: + type: mysql + url: mysql://user:password@host:3306/dbname + tables: + - orders + - order_items + tls_skip_verify: false # default; set true ONLY for dev MySQL without TLS + gtid_enabled: true # default + # server_id: 5500 # optional; dbmazz auto-assigns if omitted +``` + +Environment variables (set on the dbmazz container by `ez-cdc-cli`, or set directly when running dbmazz standalone): + +| Env var | Default | Notes | +|---|---|---| +| `SOURCE_TYPE` | — | Must be `mysql` | +| `SOURCE_URL` | — | `mysql://user:pass@host:port/dbname` | +| `MYSQL_TLS_SKIP_VERIFY` | `false` | Disables TLS verification — dev only | +| `MYSQL_GTID_ENABLED` | `true` | Required for incremental snapshot | +| `MYSQL_SERVER_ID` | random in [5400, 6400) | Set explicitly when running multiple dbmazz instances against one source | + +## Local development + +Spin up a dev MySQL with the right flags in one line: + +```bash +docker run -d --rm --name mysql-source \ + -p 13306:3306 \ + -e MYSQL_ALLOW_EMPTY_PASSWORD=1 \ + -e MYSQL_DATABASE=dbmazz \ + mysql:8.0 \ + --gtid-mode=ON --enforce-gtid-consistency=ON \ + --log-bin=mysql-bin --server-id=1 \ + --binlog-format=ROW --binlog-row-image=FULL +``` + +The default `ghcr.io/ez-cdc/dbmazz:latest` image is built without the `mysql-source` cargo feature. For now, build a local image: + +```bash +docker build -t dbmazz-mysql:dev -f Dockerfile.mysql . +``` + +Then point `ez-cdc verify` at it via `--image dbmazz-mysql:dev`. The release pipeline will eventually publish a `mysql-source`-enabled image; this manual step goes away then. + +## How it works + +dbmazz follows Debezium's MySQL connector design, adapted to dbmazz's single-binary architecture (no Kafka Connect, no signal table): + +- **Binlog streaming** — ROW format, GTID-aware. Checkpoints are persisted as `(binlog_file, position, gtid_executed)` only at transaction commit boundaries; restart resumes from the last committed GTID set. +- **Incremental snapshot** — read-only DBLog (Andreakis & Papapanagiotou 2020), adapted to use the binlog consumer's live GTID set as low/high watermarks instead of a writable signal table. Concurrent CDC + snapshot is supported; per-PK reconciliation drops snapshot rows that lost a race to a concurrent binlog event. +- **Schema introspection** — `information_schema` query at startup; the schema is cached in-memory and used to map binlog row payloads to the engine's generic `CdcRecord` shape. + +## BETA scope + +What works today: + +- Binlog streaming (INSERT / UPDATE / DELETE) for ROW format, GTID mode. +- Incremental snapshot for tables with single-column integer primary keys. +- Concurrent snapshot + CDC reconciliation. +- Crash-recovery startup probe (validates persisted GTID set vs `@@global.gtid_executed`). +- Verified end-to-end against PostgreSQL and StarRocks sinks via `ez-cdc verify` (Tier 1: A1-A4, B1/B1b/B2/B3, CDC, D4, D5, C10, H1). + +What's known to be incomplete (tracked in `openspec/changes/mysql-cdc-beta-to-ga`): + +- **Type fidelity**: `BIGINT UNSIGNED` overflow at the `i64` boundary; `DECIMAL` precision/scale not propagated from `information_schema`; `DATETIME` microseconds discarded; `ENUM`/`SET` semantics; full JSON typed roundtrip. The `C11` (Type roundtrip) verify check is expected to FAIL until this lands — use `ez-cdc verify --skip C11` in CI. +- **Snapshot bootstrap from arbitrary binlog position**: today the daemon resumes from the persisted checkpoint or starts at the binlog tail; no first-run bootstrap that walks backwards. +- **Cursor-based snapshot chunker**: today's chunker is range-based; cursor-based gives more uniform chunk sizes for non-contiguous PK distributions. +- **Non-integer primary keys**: composite, UUID, and string PKs are not yet supported in the snapshot path. + +## Verifying + +The `ez-cdc-cli` test harness has full MySQL support. After bringing up a MySQL container per the recipe above: + +```bash +# Configure dbmazz to point at it +ez-cdc datasource add # interactive wizard, prompts for tls_skip_verify etc. + +# Run the verify suite +ez-cdc verify --image dbmazz-mysql:dev \ + --source my-mysql \ + --sink \ + --skip C11 +``` + +See the `ez-cdc-cli` repository's README for the full verify command surface. + +## Related documents + +- [architecture.md](architecture.md) — how the engine, source, and sink layers fit together. +- [configuration.md](configuration.md) — env vars, pipeline tuning, sink-specific options. +- [contributing-connectors.md](contributing-connectors.md) — adding a new source or sink. +- [CHANGELOG.md](../CHANGELOG.md) — version-by-version notes including the MySQL beta milestone. diff --git a/src/config.rs b/src/config.rs index b7153fd..6ee64a1 100644 --- a/src/config.rs +++ b/src/config.rs @@ -13,14 +13,21 @@ use tracing::info; #[derive(Debug, Clone, PartialEq, Eq)] pub enum SourceType { Postgres, - // Future: Mysql, Oracle, etc. + Mysql, + // Future: Oracle, etc. } impl SourceType { fn from_str(s: &str) -> Result { match s.to_lowercase().as_str() { "postgres" | "postgresql" => Ok(SourceType::Postgres), - other => anyhow::bail!("Unsupported source type: '{}'. Supported: postgres", other), + "mysql" => Ok(SourceType::Mysql), + other => { + anyhow::bail!( + "Unsupported source type: '{}'. Supported: postgres, mysql", + other + ) + } } } } @@ -29,6 +36,7 @@ impl std::fmt::Display for SourceType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { SourceType::Postgres => write!(f, "postgres"), + SourceType::Mysql => write!(f, "mysql"), } } } @@ -40,6 +48,18 @@ pub struct PostgresSourceConfig { pub publication_name: String, } +/// MySQL-specific source configuration +#[derive(Debug, Clone)] +pub struct MysqlSourceConfig { + pub server_id: u32, + pub gtid_enabled: bool, + /// When `true`, the MySQL TLS handshake accepts any server certificate + /// (no chain or hostname validation). Unsafe — for development only, + /// since it disables protection against on-path attackers. Default: `false`. + /// Toggled via `MYSQL_TLS_SKIP_VERIFY=true`. + pub tls_skip_verify: bool, +} + /// Generic source configuration #[derive(Clone)] pub struct SourceConfig { @@ -47,16 +67,26 @@ pub struct SourceConfig { pub url: String, pub tables: Vec, pub postgres: Option, + pub mysql: Option, } impl SourceConfig { /// Returns the PostgreSQL-specific source config. - /// Panics if source_type is not Postgres (currently the only option). + /// Panics if source_type is not Postgres. pub fn postgres(&self) -> &PostgresSourceConfig { self.postgres .as_ref() .expect("PostgresSourceConfig must be set for Postgres source") } + + /// Returns the MySQL-specific source config. + /// Panics if source_type is not Mysql. + #[allow(dead_code)] + pub fn mysql(&self) -> &MysqlSourceConfig { + self.mysql + .as_ref() + .expect("MysqlSourceConfig must be set for Mysql source") + } } impl std::fmt::Debug for SourceConfig { @@ -91,6 +121,7 @@ impl std::fmt::Debug for SourceConfig { .field("url", &redacted_url) .field("tables", &self.tables) .field("postgres", &self.postgres) + .field("mysql", &self.mysql) .finish() } } @@ -232,6 +263,21 @@ fn optional_env(name: &str, default: &str) -> String { env::var(name).unwrap_or_else(|_| default.to_string()) } +/// Parse MYSQL_SERVER_ID env var, defaulting to a pseudo-random value in [5400, 6400). +fn parse_mysql_server_id() -> u32 { + if let Ok(val) = env::var("MYSQL_SERVER_ID") { + if let Ok(id) = val.parse::() { + return id; + } + } + // Pseudo-random default based on sub-second timing + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .subsec_nanos(); + 5400 + (nanos % 1000) +} + // ============================================================================= // Config Implementation // ============================================================================= @@ -256,7 +302,7 @@ impl Config { .filter(|s| !s.is_empty()) .collect(); - // Source-specific config (Postgres) + // Source-specific config let slot_name = optional_env("SOURCE_SLOT_NAME", "dbmazz_slot"); let publication_name = optional_env("SOURCE_PUBLICATION_NAME", "dbmazz_pub"); @@ -265,6 +311,17 @@ impl Config { slot_name: slot_name.clone(), publication_name: publication_name.clone(), }), + SourceType::Mysql => None, + }; + + // MySQL-specific config + let mysql_config = match source_type { + SourceType::Postgres => None, + SourceType::Mysql => Some(MysqlSourceConfig { + server_id: parse_mysql_server_id(), + gtid_enabled: optional_env("MYSQL_GTID_ENABLED", "true") == "true", + tls_skip_verify: optional_env("MYSQL_TLS_SKIP_VERIFY", "false") == "true", + }), }; let source = SourceConfig { @@ -272,6 +329,7 @@ impl Config { url: source_url.clone(), tables: tables.clone(), postgres: postgres_config, + mysql: mysql_config, }; // Sink configuration @@ -381,6 +439,16 @@ impl Config { info!("Source: Postgres"); } } + SourceType::Mysql => { + if let Some(mysql) = &self.source.mysql { + info!( + "Source: MySQL (server_id: {}, gtid_enabled: {})", + mysql.server_id, mysql.gtid_enabled + ); + } else { + info!("Source: MySQL"); + } + } } // Sink info @@ -526,7 +594,8 @@ mod tests { SourceType::from_str("POSTGRES").unwrap(), SourceType::Postgres ); - assert!(SourceType::from_str("mysql").is_err()); + assert!(SourceType::from_str("mysql").is_ok()); + assert_eq!(SourceType::from_str("MYSQL").unwrap(), SourceType::Mysql); } #[test] @@ -661,4 +730,33 @@ mod tests { clear_env_vars(); } + + #[test] + #[serial] + fn test_mysql_config() { + clear_env_vars(); + + env::set_var("SOURCE_URL", "mysql://localhost/testdb"); + env::set_var("SOURCE_TYPE", "mysql"); + env::set_var("MYSQL_SERVER_ID", "6000"); + env::set_var("MYSQL_GTID_ENABLED", "false"); + env::set_var("SINK_URL", "starrocks.local"); + env::set_var("SINK_TYPE", "starrocks"); + env::set_var("SINK_PORT", "9030"); + env::set_var("SINK_DATABASE", "testdb"); + env::set_var("SINK_USER", "admin"); + env::set_var("SINK_PASSWORD", "secret"); + + let config = Config::from_env().unwrap(); + + assert_eq!(config.source.source_type, SourceType::Mysql); + assert_eq!(config.source.url, "mysql://localhost/testdb"); + assert!(config.source.postgres.is_none()); + + let mysql = config.source.mysql(); + assert_eq!(mysql.server_id, 6000); + assert!(!mysql.gtid_enabled); + + clear_env_vars(); + } } diff --git a/src/connectors/sinks/postgres/merge_generator.rs b/src/connectors/sinks/postgres/merge_generator.rs index 62a0ba3..c453af0 100644 --- a/src/connectors/sinks/postgres/merge_generator.rs +++ b/src/connectors/sinks/postgres/merge_generator.rs @@ -8,7 +8,7 @@ //! - Handles INSERT (NOT MATCHED), DELETE (MATCHED), UPDATE (MATCHED) //! - Generates one WHEN MATCHED clause per unique TOAST column combination -use super::types::pg_oid_to_target_type; +use super::types; use crate::core::traits::SourceTableSchema; /// Generate a complete MERGE SQL statement for a batch range. @@ -34,14 +34,18 @@ pub fn generate_merge_range( to_batch_id: i64, ) -> String { let dst_table = format!("\"{}\".\"{}\"", target_schema, source_schema.name); - let dst_qualified = format!("{}.{}", target_schema, source_schema.name); + // _dst_table in raw table is table.qualified_name() from CdcRecord: + // PG: schema="public", name="users" → "public.users" + // MySQL: schema="dbmazz", name="users" → "dbmazz.users" + // Use source_schema.schema to match what's stored in _dst_table. + let dst_qualified = format!("{}.{}", source_schema.schema, source_schema.name); // Build column extraction expressions: (_data->>'col')::type AS "col" let col_extracts: Vec = source_schema .columns .iter() .map(|col| { - let pg_type = pg_oid_to_target_type(col.pg_type_id); + let pg_type = types::column_type(col); format!( "(_data->>'{name}')::{pg_type} AS \"{name}\"", name = col.name @@ -59,7 +63,7 @@ pub fn generate_merge_range( .iter() .find(|c| &c.name == pk) .expect("PK column must exist in schema"); - let pg_type = pg_oid_to_target_type(col.pg_type_id); + let pg_type = types::column_type(col); format!("(_data->>'{pk}')::{pg_type}", pk = pk) }) .collect(); diff --git a/src/connectors/sinks/postgres/normalizer.rs b/src/connectors/sinks/postgres/normalizer.rs index 1dd6075..adf9ba5 100644 --- a/src/connectors/sinks/postgres/normalizer.rs +++ b/src/connectors/sinks/postgres/normalizer.rs @@ -300,6 +300,10 @@ async fn normalize_batch_range( to_batch_id, ); + info!( + "Normalizer: MERGE SQL for table '{}' in range ({}..{}]:\n{}", + dst_table, from_batch_id, to_batch_id, merge_sql + ); merge_statements.push(merge_sql); } diff --git a/src/connectors/sinks/postgres/raw_table.rs b/src/connectors/sinks/postgres/raw_table.rs index 28a5340..60508ce 100644 --- a/src/connectors/sinks/postgres/raw_table.rs +++ b/src/connectors/sinks/postgres/raw_table.rs @@ -15,7 +15,7 @@ use tokio_postgres::Client; use tracing::info; use super::schema_tracking::{self, SchemaState}; -use super::types::pg_oid_to_target_type; +use super::types; use crate::connectors::sinks::schema_evolution::compute_schema_evolution_plan; use crate::core::record::{CdcRecord, ColumnValue, Value}; use crate::core::traits::SourceTableSchema; @@ -62,15 +62,13 @@ pub async fn write_batch_to_raw( // is complete (Risk #6). A COPY failure rolls back the DDL too. for (table, diff) in &pending_diffs { for added in &diff.added { - let pg_type_id = added - .pg_type_id - .expect("PG sink: AddedColumn must carry pg_type_id (PG source contract)"); + let col_type = match added.pg_type_id { + Some(oid) => types::pg_oid_to_target_type(oid), + None => types::mysql_data_type_to_pg(&added.data_type), + }; let sql = format!( r#"ALTER TABLE "{}"."{}" ADD COLUMN IF NOT EXISTS "{}" {}"#, - target_schema, - table.name, - added.name, - pg_oid_to_target_type(pg_type_id) + target_schema, table.name, added.name, col_type ); tx.batch_execute(&sql).await.with_context(|| { format!( diff --git a/src/connectors/sinks/postgres/setup.rs b/src/connectors/sinks/postgres/setup.rs index 05448a5..d970b9b 100644 --- a/src/connectors/sinks/postgres/setup.rs +++ b/src/connectors/sinks/postgres/setup.rs @@ -10,7 +10,7 @@ use tokio_postgres::Client; use tracing::info; use super::schema_tracking; -use super::types::pg_oid_to_target_type; +use super::types; use crate::core::traits::SourceTableSchema; /// Metadata schema name in the target database @@ -177,7 +177,7 @@ async fn create_target_table( let mut col_defs: Vec = Vec::new(); for col in &source.columns { - let pg_type = pg_oid_to_target_type(col.pg_type_id); + let pg_type = types::column_type(col); let nullable = if col.nullable { "" } else { " NOT NULL" }; col_defs.push(format!(" \"{}\" {}{}", col.name, pg_type, nullable)); } diff --git a/src/connectors/sinks/postgres/types.rs b/src/connectors/sinks/postgres/types.rs index 7e092a0..c8356af 100644 --- a/src/connectors/sinks/postgres/types.rs +++ b/src/connectors/sinks/postgres/types.rs @@ -6,6 +6,43 @@ //! Mostly identity mapping since both sides are PostgreSQL. //! Notable exceptions: serial types become plain integers (no sequence in target). +use crate::core::record::DataType; +use crate::core::traits::SourceColumn; + +/// Maps a SourceColumn's type info to the target PostgreSQL DDL type. +/// Uses mysql_data_type_to_pg for MySQL columns (pg_type_id == 0), +/// otherwise uses pg_oid_to_target_type for PG-to-PG identity mapping. +pub fn column_type(col: &SourceColumn) -> &'static str { + if col.pg_type_id == 0 { + mysql_data_type_to_pg(&col.data_type) + } else { + pg_oid_to_target_type(col.pg_type_id) + } +} + +/// Map a MySQL DataType to the target PostgreSQL column type DDL string. +/// Used when the source is MySQL (pg_type_id is always 0). +/// Falls back to "text" for unknown types. +pub fn mysql_data_type_to_pg(dt: &DataType) -> &'static str { + match dt { + DataType::Boolean => "boolean", + DataType::Int16 => "smallint", + DataType::Int32 => "integer", + DataType::Int64 => "bigint", + DataType::Float32 => "real", + DataType::Float64 => "double precision", + DataType::Decimal { .. } => "numeric", + DataType::String | DataType::Text => "text", + DataType::Bytes => "bytea", + DataType::Json | DataType::Jsonb => "jsonb", + DataType::Date => "date", + DataType::Time => "time without time zone", + DataType::Timestamp => "timestamp without time zone", + DataType::TimestampTz => "timestamp with time zone", + DataType::Uuid => "uuid", + } +} + /// Map a PostgreSQL type OID to the target column type DDL string. /// Returns the SQL type name suitable for CREATE TABLE. pub fn pg_oid_to_target_type(pg_type_id: u32) -> &'static str { diff --git a/src/connectors/sinks/snowflake/setup.rs b/src/connectors/sinks/snowflake/setup.rs index 7c81b7a..34e529f 100644 --- a/src/connectors/sinks/snowflake/setup.rs +++ b/src/connectors/sinks/snowflake/setup.rs @@ -150,7 +150,11 @@ async fn create_target_table( // Build column definitions let mut col_defs: Vec = Vec::new(); for col in &source.columns { - let sf_type = type_mapper.pg_type_to_snowflake(col.pg_type_id); + let sf_type = if col.pg_type_id == 0 { + type_mapper.to_snowflake_type(&col.data_type) + } else { + type_mapper.pg_type_to_snowflake(col.pg_type_id).to_string() + }; let nullable = if col.nullable { "" } else { " NOT NULL" }; col_defs.push(format!( " \"{}\" {}{}", diff --git a/src/core/mod.rs b/src/core/mod.rs index a002e28..6f98588 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -5,4 +5,7 @@ pub mod traits; pub use position::SourcePosition; pub use record::{CdcRecord, ColumnValue, DataType, Value}; -pub use traits::{LoadingModel, Sink, SinkCapabilities, SinkMode, SinkResult}; +pub use traits::{ + LoadingModel, ReplicationStream, Sink, SinkCapabilities, SinkMode, SinkResult, Source, + SourceTableSchema, +}; diff --git a/src/core/position.rs b/src/core/position.rs index d2c8b2d..b38ebe8 100644 --- a/src/core/position.rs +++ b/src/core/position.rs @@ -12,6 +12,17 @@ pub enum SourcePosition { Offset(i64), /// Binlog file position (MySQL) FilePosition { file: String, position: u64 }, + /// MySQL native checkpoint: the (binlog_file, position, gtid_executed) triple. + /// + /// All three are emitted on every binlog event. `gtid_executed` is the + /// MySQL `Gtid_set` accumulated up to this event (formatted as + /// `uuid:1-N,uuid:1-M`). Restart prefers `gtid_executed` when non-empty + /// (failover-safe), falling back to `(file, position)` otherwise. + MysqlBinlog { + file: String, + position: u64, + gtid_executed: String, + }, } #[allow(dead_code)] @@ -36,8 +47,22 @@ impl SourcePosition { Self::FilePosition { file, position } } - /// Compares two positions, returns true if this position is ahead of the other - /// Returns None if positions are incomparable (different types) + /// Creates a new MySQL binlog triple position. + pub fn mysql_binlog(file: String, position: u64, gtid_executed: String) -> Self { + Self::MysqlBinlog { + file, + position, + gtid_executed, + } + } + + /// Compares two positions, returns `Some(true)` iff `self` is strictly + /// ahead of `other`. Returns `None` for incomparable pairs. + /// + /// `GtidSet` pairs are intentionally **incomparable** (returns `None`): + /// MySQL GTID sets are partial orders (set inclusion), not totally + /// ordered. Callers needing partial-order semantics MUST use + /// `crate::source::mysql::gtid::GtidSet::is_superset_of` directly. pub fn is_ahead_of(&self, other: &SourcePosition) -> Option { match (self, other) { (SourcePosition::Lsn(a), SourcePosition::Lsn(b)) => Some(a > b), @@ -60,11 +85,30 @@ impl SourcePosition { Some(f1 > f2) } } - (SourcePosition::GtidSet(a), SourcePosition::GtidSet(b)) => { - // GTID comparison is complex, for now just compare strings - // In production, this should use proper GTID set comparison - Some(a > b) + ( + SourcePosition::MysqlBinlog { + file: f1, + position: p1, + .. + }, + SourcePosition::MysqlBinlog { + file: f2, + position: p2, + .. + }, + ) => { + // Compare by (file, position) — gtid_executed is metadata for restart. + // Binlog file names contain sequence numbers (binlog.000001, binlog.000002), + // so lexicographic ordering is correct when files differ. + if f1 == f2 { + Some(p1 > p2) + } else { + Some(f1 > f2) + } } + // GTID sets are partial orders; lexicographic string compare is + // meaningless. Use `GtidSet::is_superset_of` for set inclusion. + (SourcePosition::GtidSet(_), SourcePosition::GtidSet(_)) => None, _ => None, // Incomparable types } } @@ -79,6 +123,17 @@ impl fmt::Display for SourcePosition { SourcePosition::FilePosition { file, position } => { write!(f, "File:{}:Pos:{}", file, position) } + SourcePosition::MysqlBinlog { + file, + position, + gtid_executed, + } => { + if gtid_executed.is_empty() { + write!(f, "MySQL:{}:{}", file, position) + } else { + write!(f, "MySQL:{}:{}:gtid={}", file, position, gtid_executed) + } + } } } } @@ -139,4 +194,78 @@ mod tests { "File:binlog.001:Pos:500" ); } + + #[test] + fn test_mysql_binlog_comparison() { + let pos1 = SourcePosition::mysql_binlog("binlog.000001".to_string(), 100, String::new()); + let pos2 = SourcePosition::mysql_binlog("binlog.000001".to_string(), 200, String::new()); + let pos3 = SourcePosition::mysql_binlog("binlog.000002".to_string(), 50, String::new()); + + assert_eq!(pos2.is_ahead_of(&pos1), Some(true)); + assert_eq!(pos3.is_ahead_of(&pos1), Some(true)); + assert_eq!(pos3.is_ahead_of(&pos2), Some(true)); + assert_eq!(pos1.is_ahead_of(&pos1), Some(false)); + } + + #[test] + fn test_mysql_binlog_comparison_ignores_gtid_field() { + // gtid_executed is metadata, not used for ordering. + let pos1 = SourcePosition::mysql_binlog( + "binlog.000001".to_string(), + 100, + "uuid-a:1-1".to_string(), + ); + let pos2 = SourcePosition::mysql_binlog( + "binlog.000001".to_string(), + 100, + "uuid-a:1-100".to_string(), + ); + // Same (file, position) → not ahead either way regardless of gtid_executed. + assert_eq!(pos1.is_ahead_of(&pos2), Some(false)); + assert_eq!(pos2.is_ahead_of(&pos1), Some(false)); + } + + #[test] + fn test_mysql_binlog_display() { + let with_gtid = SourcePosition::mysql_binlog( + "binlog.000003".to_string(), + 12345, + "1d51b75e-aaaa-bbbb-cccc-1234567890ab:1-42".to_string(), + ); + assert_eq!( + with_gtid.to_string(), + "MySQL:binlog.000003:12345:gtid=1d51b75e-aaaa-bbbb-cccc-1234567890ab:1-42" + ); + + let without_gtid = + SourcePosition::mysql_binlog("binlog.000003".to_string(), 12345, String::new()); + assert_eq!(without_gtid.to_string(), "MySQL:binlog.000003:12345"); + } + + #[test] + fn test_gtid_set_is_ahead_of_returns_none() { + // GTID sets are partial orders; is_ahead_of must return None for any + // pair, including identical sets. Callers must use + // `GtidSet::is_superset_of` for set-inclusion semantics. + let a = SourcePosition::gtid_set("uuid-A:1-100".into()); + let b = SourcePosition::gtid_set("uuid-B:1-100".into()); + let same = SourcePosition::gtid_set("uuid-A:1-100".into()); + + assert_eq!(a.is_ahead_of(&b), None); + assert_eq!(b.is_ahead_of(&a), None); + assert_eq!(a.is_ahead_of(&same), None); + assert_eq!(same.is_ahead_of(&a), None); + } + + #[test] + fn test_mysql_binlog_serde_roundtrip() { + let pos = SourcePosition::mysql_binlog( + "binlog.000007".to_string(), + 999_999, + "1d51b75e-aaaa-bbbb-cccc-1234567890ab:1-100".to_string(), + ); + let json = serde_json::to_string(&pos).unwrap(); + let back: SourcePosition = serde_json::from_str(&json).unwrap(); + assert_eq!(pos, back); + } } diff --git a/src/core/record.rs b/src/core/record.rs index 2db4a8b..38367ed 100644 --- a/src/core/record.rs +++ b/src/core/record.rs @@ -40,6 +40,22 @@ pub enum CdcRecord { }, } +impl CdcRecord { + /// Returns the source position carried by this record, if any. + /// `Begin` has none (it carries only an XID); every other variant does. + pub fn position(&self) -> Option<&SourcePosition> { + match self { + CdcRecord::Insert { position, .. } + | CdcRecord::Update { position, .. } + | CdcRecord::Delete { position, .. } + | CdcRecord::SchemaChange { position, .. } + | CdcRecord::Commit { position, .. } + | CdcRecord::Heartbeat { position } => Some(position), + CdcRecord::Begin { .. } => None, + } + } +} + /// Reference to a database table #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct TableRef { @@ -99,7 +115,7 @@ impl ColumnDef { } /// Generic value type supporting common database types -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum Value { Null, Bool(bool), diff --git a/src/core/traits.rs b/src/core/traits.rs index e0bbf9d..f182d09 100644 --- a/src/core/traits.rs +++ b/src/core/traits.rs @@ -1,3 +1,4 @@ +use crate::config::SourceType; use crate::core::position::SourcePosition; use crate::core::record::{CdcRecord, DataType}; use anyhow::Result; @@ -78,23 +79,55 @@ pub struct SourceColumn { pub pg_type_id: u32, } +/// Generic replication stream — replaces PG-specific CopyBothDuplex +#[async_trait] +#[allow(dead_code)] +pub trait ReplicationStream: Send + Unpin + 'static { + /// Read the next raw event from the replication stream. + /// Returns None on clean end-of-stream. + async fn next_event(&mut self) -> Option>>; + + /// Send a feedback/keepalive message back to the source. + /// Default implementation is a no-op (MySQL doesn't need this). + async fn send_feedback(&mut self, _data: &[u8]) -> Result<()> { + Ok(()) + } +} + #[async_trait] #[allow(dead_code)] pub trait Source: Send + Sync { /// Returns the name of the source implementation fn name(&self) -> &'static str; - /// Validates the source configuration and connection + /// Returns the source type for dispatch + fn source_type(&self) -> SourceType; + + /// Validate prerequisites (connectivity, GTID, binlog format) async fn validate(&self) -> Result<()>; - /// Starts the source and begins processing CDC events - async fn start(&mut self) -> Result<()>; + /// Setup source-side resources (slots for PG, GTID verification for MySQL) + async fn setup(&mut self, tables: &[String]) -> Result<()>; + + /// Start replication stream from given position + async fn start_replication( + &mut self, + position: Option, + ) -> Result>; + + /// Get current replication position for checkpointing + fn checkpoint_position(&self) -> Option; - /// Stops the source gracefully - async fn stop(&mut self) -> Result<()>; + /// Cleanup source-side resources + async fn cleanup(&mut self) -> Result<()>; - /// Returns the current source position for checkpointing - fn current_position(&self) -> Option; + /// Create the appropriate replication loop for this source type. + /// This replaces the need for downcasting. Each implementation + /// creates the loop variant it needs (PgReplicationLoop or MysqlReplicationLoop). + async fn create_loop( + &mut self, + position: Option, + ) -> Result>; } #[async_trait] diff --git a/src/engine/mod.rs b/src/engine/mod.rs index ff04990..37aa9cf 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -1,32 +1,32 @@ // Copyright 2025 // Licensed under the Elastic License v2.0 +pub mod replication; mod setup; pub mod snapshot; use anyhow::Result; -use futures_util::{SinkExt, StreamExt}; use std::sync::Arc; use std::time::Duration; use tokio::sync::mpsc; -use tracing::{debug, error, info, warn}; +use tracing::{error, info}; -use crate::config::Config; +use crate::config::{Config, SourceType}; use crate::connectors::sinks::create_sink; use crate::control::state::SharedState; -use crate::control::{self, CdcConfig, CdcState, Stage}; -use crate::core::SinkMode; +use crate::control::{self, CdcConfig, Stage}; +use crate::core::{SinkMode, Source, SourcePosition}; use crate::pipeline::schema_cache::SchemaCache; use crate::pipeline::{Pipeline, PipelineEvent}; -use crate::replication::{ - handle_keepalive, handle_xlog_data, parse_replication_message, WalMessage, -}; -use crate::source::postgres::{build_standby_status_update, introspect_schemas, PostgresSource}; +use crate::source::postgres::introspect_schemas; use crate::state_store::StateStore; use setup::SetupManager; /// Factory that creates fresh Sink instances (used by snapshot workers). -type SinkFactory = Arc anyhow::Result> + Send + Sync>; +/// +/// `pub` so integration tests can supply a custom factory (e.g., an +/// in-memory test sink) via [`CdcEngine::with_sink_factory`]. +pub type SinkFactory = Arc anyhow::Result> + Send + Sync>; /// Main CDC engine that orchestrates all components pub struct CdcEngine { @@ -35,33 +35,65 @@ pub struct CdcEngine { state_store: StateStore, /// SchemaCache for converting pgoutput CdcMessage → generic CdcRecord. /// Owned by the engine, passed mutably to the WAL handler. + #[allow(dead_code)] schema_cache: SchemaCache, /// Factory for creating sink instances (snapshot workers need their own). sink_factory: SinkFactory, + /// Registry of in-flight MySQL snapshot chunks. Shared with the + /// `MysqlReplicationLoop` so the binlog consumer can record evictions + /// and signal drain. Always present; empty for non-MySQL pipelines. + #[cfg(feature = "mysql-source")] + active_chunks: crate::engine::snapshot::active_chunks::ActiveChunks, + /// Live, shared view of the MySQL CDC consumer's accumulated + /// `gtid_executed`. Single-writer (the replication loop, via + /// `ParserState`); read by snapshot workers when capturing chunk + /// LOW/HIGH watermarks (Debezium read-only DBLog adaptation). + /// Always present; default-constructed (empty) for non-MySQL. + #[cfg(feature = "mysql-source")] + consumer_gtid: std::sync::Arc>, } impl CdcEngine { pub async fn new(config: Config) -> Result { + let sink_config = config.sink.clone(); + let sink_factory: SinkFactory = + Arc::new(move || create_sink(&sink_config, SinkMode::SnapshotWorker)); + Self::with_sink_factory(config, sink_factory).await + } + + /// Construct a CDC engine with a caller-supplied sink factory. Used by + /// integration tests to inject an in-memory or recording sink without + /// going through `create_sink`. Production callers should use [`new`]. + pub async fn with_sink_factory(config: Config, sink_factory: SinkFactory) -> Result { + let (slot_name, tables_for_cdc) = match config.source.source_type { + SourceType::Postgres => ( + config.source.postgres().slot_name.clone(), + config.source.tables.clone(), + ), + SourceType::Mysql => ("mysql_source".to_string(), config.source.tables.clone()), + }; let cdc_config = CdcConfig { flush_size: config.flush_size, flush_interval_ms: config.flush_interval_ms, - tables: config.source.tables.clone(), - slot_name: config.source.postgres().slot_name.clone(), + tables: tables_for_cdc, + slot_name, }; let shared_state = SharedState::new(cdc_config); let state_store = StateStore::new(&config.source.url).await?; - let sink_config = config.sink.clone(); - let sink_factory: SinkFactory = - Arc::new(move || create_sink(&sink_config, SinkMode::SnapshotWorker)); - Ok(Self { config, shared_state, state_store, schema_cache: SchemaCache::new(), sink_factory, + #[cfg(feature = "mysql-source")] + active_chunks: crate::engine::snapshot::active_chunks::ActiveChunks::new(), + #[cfg(feature = "mysql-source")] + consumer_gtid: std::sync::Arc::new(std::sync::RwLock::new( + crate::source::mysql::gtid::GtidSet::default(), + )), }) } @@ -73,7 +105,7 @@ impl CdcEngine { } /// Execute CDC engine - pub async fn run(mut self) -> Result<()> { + pub async fn run(self) -> Result<()> { self.shared_state .set_stage(Stage::Setup, "Initializing") .await; @@ -96,16 +128,47 @@ impl CdcEngine { // Stage: SETUP - Source Connection self.shared_state - .set_stage(Stage::Setup, "Connecting to PostgreSQL") + .set_stage(Stage::Setup, "Connecting to source") .await; - let source = self.init_source().await?; + let mut source = self.init_source().await?; - // Stage: SETUP - Replication Stream + // Stage: SETUP - Source Setup (connections, schema introspection) self.shared_state - .set_stage(Stage::Setup, "Starting replication stream") + .set_stage(Stage::Setup, "Setting up source") .await; - let replication_stream = source.start_replication_from(start_lsn).await?; - tokio::pin!(replication_stream); + source.setup(&self.config.source.tables).await?; + + // Stage: SETUP - Replication Stream start position + // - Postgres: LSN loaded above as `start_lsn`. + // - MySQL: triple (file, position, gtid_executed) loaded from the + // state store. `None` when no checkpoint exists, which + // means the binlog stream starts from the earliest available. + let start_position = match self.config.source.source_type { + SourceType::Postgres => Some(SourcePosition::Lsn(start_lsn)), + #[cfg(feature = "mysql-source")] + SourceType::Mysql => { + let slot = format!("mysql_{}", self.config.source.mysql().server_id); + match self.state_store.load_mysql_checkpoint(&slot).await? { + Some((file, position, gtid_executed)) => { + info!( + "Checkpoint: Resuming MySQL binlog from file={}, pos={}, gtid_executed={}", + file, position, gtid_executed + ); + Some(SourcePosition::MysqlBinlog { + file, + position, + gtid_executed, + }) + } + None => { + info!("Checkpoint: MySQL has no prior checkpoint (starting from earliest binlog)"); + None + } + } + } + #[cfg(not(feature = "mysql-source"))] + SourceType::Mysql => None, + }; // Stage: SETUP - Sink Connection self.shared_state @@ -123,8 +186,25 @@ impl CdcEngine { self.shared_state .set_stage(Stage::Setup, "Setting up sink") .await; - let source_schemas = - introspect_schemas(&self.config.source.url, &self.config.source.tables).await?; + let source_schemas = match self.config.source.source_type { + SourceType::Postgres => { + introspect_schemas(&self.config.source.url, &self.config.source.tables).await? + } + SourceType::Mysql => { + #[cfg(feature = "mysql-source")] + { + crate::source::mysql::schema::introspect_mysql_schemas( + &self.config.source.url, + &self.config.source.tables, + ) + .await? + } + #[cfg(not(feature = "mysql-source"))] + { + anyhow::bail!("MySQL source requires the mysql-source feature") + } + } + }; if let Err(e) = sink.setup(&source_schemas).await { self.halt_on_setup_error(&format!("Sink setup failed: {}", e)) .await; @@ -160,12 +240,51 @@ impl CdcEngine { // The WAL consumer continues running in parallel; deduplication is handled // via should_emit() in wal_handler using the finished_chunks BTreeMap. if self.config.do_snapshot { - self.spawn_snapshot_worker(self.config.initial_snapshot_only); + match self.config.source.source_type { + SourceType::Postgres => { + self.spawn_snapshot_worker(self.config.initial_snapshot_only); + } + SourceType::Mysql => { + #[cfg(feature = "mysql-source")] + self.spawn_mysql_snapshot_worker(self.config.initial_snapshot_only); + #[cfg(not(feature = "mysql-source"))] + tracing::warn!( + "MySQL snapshot requested but mysql-source feature is not enabled" + ); + } + } } - // Execute main loop - self.run_main_loop(replication_stream, tx, feedback_rx) - .await + // Execute main loop via ReplicationLoop trait (source-agnostic) + let ctx = crate::engine::replication::LoopContext { + shared_state: self.shared_state.clone(), + config: Arc::new(self.config.clone()), + state_store: Arc::new(self.state_store.clone()), + pipeline_tx: tx, + feedback_rx, + source_schemas: Arc::from(source_schemas.as_slice()), + sink_factory: self.sink_factory.clone(), + #[cfg(feature = "mysql-source")] + active_chunks: self.active_chunks.clone(), + #[cfg(feature = "mysql-source")] + consumer_gtid: self.consumer_gtid.clone(), + }; + + match self.config.source.source_type { + SourceType::Postgres => { + let loop_impl = source.create_loop(start_position).await?; + loop_impl.run(ctx).await + } + #[cfg(feature = "mysql-source")] + SourceType::Mysql => { + let loop_impl = source.create_loop(start_position).await?; + loop_impl.run(ctx).await + } + #[cfg(not(feature = "mysql-source"))] + SourceType::Mysql => { + anyhow::bail!("MySQL source requires the mysql-source feature") + } + } } async fn halt_on_setup_error(&self, msg: &str) -> ! { @@ -208,28 +327,84 @@ impl CdcEngine { info!("Snapshot worker spawned"); } + /// Spawn a MySQL snapshot worker task. + /// Used when `DO_SNAPSHOT=true` and `SOURCE_TYPE=mysql`. + #[cfg(feature = "mysql-source")] + fn spawn_mysql_snapshot_worker(&self, shutdown_on_complete: bool) { + let snap_config = Arc::new(self.config.clone()); + let snap_state = self.shared_state.clone(); + let snap_sink_factory = Arc::clone(&self.sink_factory); + let snap_active_chunks = self.active_chunks.clone(); + let snap_consumer_gtid = self.consumer_gtid.clone(); + + tokio::spawn(async move { + match snapshot::mysql::run_mysql_snapshot( + snap_config, + snap_state.clone(), + snap_sink_factory, + snap_active_chunks, + snap_consumer_gtid, + ) + .await + { + Ok(()) => { + snap_state.set_snapshot_active(false); + info!("MySQL snapshot completed successfully"); + if shutdown_on_complete { + info!("Initial snapshot only mode: triggering graceful shutdown"); + let _ = snap_state.shutdown_tx.send(true); + } + } + Err(e) => { + snap_state.set_snapshot_active(false); + snap_state.set_snapshot_error(Some(format!("{}", e))).await; + error!("MySQL snapshot worker error: {}", e); + } + } + }); + info!("MySQL snapshot worker spawned"); + } + /// Execute source setup (replication slot, publication). async fn run_setup(&self) -> Result<(), setup::SetupError> { - let setup_manager = SetupManager::new(self.config.clone()); - setup_manager.run().await + match self.config.source.source_type { + SourceType::Postgres => { + let setup_manager = SetupManager::new(self.config.clone()); + setup_manager.run().await + } + SourceType::Mysql => { + Ok(()) // MySQL setup is done in Source::setup() + } + } } /// Load checkpoint from StateStore async fn load_checkpoint(&self) -> Result { - let slot_name = &self.config.source.postgres().slot_name; - let last_lsn = self.state_store.load_checkpoint(slot_name).await?; - let start_lsn = last_lsn.unwrap_or(0); - - if start_lsn > 0 { - info!("Checkpoint: Resuming from LSN 0x{:X}", start_lsn); - } else { - info!("Checkpoint: Starting from beginning (no previous checkpoint)"); - } + match self.config.source.source_type { + SourceType::Postgres => { + let slot_name = &self.config.source.postgres().slot_name; + let last_lsn = self.state_store.load_checkpoint(slot_name).await?; + let start_lsn = last_lsn.unwrap_or(0); + + if start_lsn > 0 { + info!("Checkpoint: Resuming from LSN 0x{:X}", start_lsn); + } else { + info!("Checkpoint: Starting from beginning (no previous checkpoint)"); + } - self.shared_state.update_lsn(start_lsn); - self.shared_state.confirm_lsn(start_lsn); + self.shared_state.update_lsn(start_lsn); + self.shared_state.confirm_lsn(start_lsn); - Ok(start_lsn) + Ok(start_lsn) + } + SourceType::Mysql => { + // MySQL doesn't use the LSN interface — its checkpoint is the + // (binlog_file, position, gtid_executed) triple, loaded separately + // in `run()` via state_store.load_mysql_checkpoint(). This branch + // returns 0 because the LSN slot is unused for MySQL. + Ok(0) + } + } } fn start_control_server(&self) { @@ -250,17 +425,12 @@ impl CdcEngine { }); } - /// Initialize PostgreSQL source - async fn init_source(&self) -> Result { - let pg = self.config.source.postgres(); - let source = PostgresSource::new( - &self.config.source.url, - pg.slot_name.clone(), - pg.publication_name.clone(), - ) - .await?; - - Ok(source) + /// Initialize source via the [`crate::source::create_source`] factory. + /// Thin wrapper kept on `CdcEngine` for ergonomics; the dispatch + /// itself lives in `src/source/mod.rs`, mirroring the + /// `create_sink` factory under `src/connectors/sinks/mod.rs`. + async fn init_source(&self) -> Result> { + crate::source::create_source(&self.config.source).await } /// Initialize pipeline with sink (core::Sink, no adapter) @@ -309,228 +479,11 @@ impl CdcEngine { (tx, feedback_rx) } - - /// Main replication loop - async fn run_main_loop( - &mut self, - mut replication_stream: S, - tx: mpsc::Sender, - mut feedback_rx: mpsc::Receiver, - ) -> Result<()> - where - S: StreamExt> - + SinkExt - + Unpin, - S::Error: std::error::Error + Send + Sync + 'static, - { - let mut shutdown_rx = self.shared_state.shutdown_tx.subscribe(); - // Subscribe to on-demand snapshot trigger - let mut snapshot_trigger_rx = self.shared_state.subscribe_snapshot_trigger(); - let mut iteration = 0u64; - - loop { - iteration = iteration.wrapping_add(1); - - // 1. Check state changes every 256 iterations to reduce overhead - // With ~287 events/s, this checks state ~1x/second instead of 287x/second - if iteration & 0xFF == 0 { - if let Some(flow) = self.check_state_control_sync(&tx) { - match flow { - ControlFlow::Break => break, - ControlFlow::Continue => { - // Sleep when paused - tokio::time::sleep(Duration::from_millis(100)).await; - continue; - } - } - } - } - - // 2. Main select loop - tokio::select! { - // Shutdown signal - _ = shutdown_rx.changed() => { - if *shutdown_rx.borrow() { - info!("Shutdown signal received"); - break; - } - } - - // On-demand snapshot trigger - Ok(()) = snapshot_trigger_rx.changed() => { - if *snapshot_trigger_rx.borrow() && !self.shared_state.is_snapshot_active() { - info!("On-demand snapshot triggered (CDC_RUNNING → SNAPSHOT)"); - // Reset trigger so it doesn't fire again - let _ = self.shared_state.snapshot_trigger.send(false); - self.spawn_snapshot_worker(false); - } - } - - // Replication messages - data_res = replication_stream.next() => { - match data_res { - Some(Ok(mut data)) => { - if let Some(msg) = parse_replication_message(&mut data) { - let _ = self.handle_replication_message( - msg, - &tx, - &mut replication_stream, - ).await?; - } - } - Some(Err(e)) => { - error!("Replication stream error: {}", e); - break; - } - None => { - warn!("Replication stream ended"); - break; - } - } - } - - // Checkpoint feedback - Some(confirmed_lsn) = feedback_rx.recv() => { - self.handle_checkpoint_feedback( - confirmed_lsn, - &mut replication_stream, - ).await?; - } - } - } - - // Cleanup PostgreSQL resources (drop replication slot) - unless skip_slot_cleanup is set - if self.shared_state.should_skip_slot_cleanup() { - info!("[SKIP] Skipping slot cleanup (upgrade/restart mode)"); - } else if let Err(e) = setup::cleanup_postgres_resources( - &self.config.source.url, - &self.config.source.postgres().slot_name, - ) - .await - { - warn!("Cleanup warning: {}", e); - // Non-fatal - continue shutdown - } - - info!("CDC shutdown complete"); - Ok(()) - } - - /// Check CDC state (Pause/Stop/Draining) - Synchronous - fn check_state_control_sync(&self, tx: &mpsc::Sender) -> Option { - let current_state = self.shared_state.state(); - - match current_state { - CdcState::Stopped => { - info!("CDC stopped. Exiting immediately."); - Some(ControlFlow::Break) - } - CdcState::Draining => { - // Check if channel is empty - if tx.capacity() == self.config.flush_size * 2 { - info!("CDC drained. Exiting gracefully."); - self.shared_state.set_state(CdcState::Stopped); - Some(ControlFlow::Break) - } else { - None // Continue draining - } - } - CdcState::Paused => { - // Return signal to sleep - Some(ControlFlow::Continue) - } - CdcState::Running => None, // Normal operation - } - } - - /// Handle replication messages - async fn handle_replication_message( - &mut self, - msg: WalMessage, - tx: &mpsc::Sender, - replication_stream: &mut S, - ) -> Result - where - S: SinkExt + Unpin, - S::Error: std::error::Error + Send + Sync + 'static, - { - match msg { - WalMessage::XLogData { lsn, data } => { - handle_xlog_data( - data, - lsn, - tx, - &self.shared_state, - &mut self.schema_cache, - self.config.flush_size, - ) - .await?; - Ok(lsn) - } - WalMessage::KeepAlive { - lsn, - reply_requested, - } => { - handle_keepalive(lsn, reply_requested, replication_stream).await?; - Ok(lsn) - } - WalMessage::Unknown(tag) => { - warn!("Unknown replication message tag: {}", tag); - Ok(0) - } - } - } - - /// Handle checkpoint confirmation - async fn handle_checkpoint_feedback( - &self, - confirmed_lsn: u64, - replication_stream: &mut S, - ) -> Result<()> - where - S: SinkExt + Unpin, - S::Error: std::error::Error + Send + Sync + 'static, - { - // CRITICAL: We MUST save checkpoint before confirming to PostgreSQL. - // If we confirm to PostgreSQL but fail to save locally, we could: - // 1. PostgreSQL discards WAL (thinking we persisted it) - // 2. On crash, we restart from old checkpoint - // 3. WAL data is gone → permanent data loss - - // 1. Save checkpoint to persistent storage - let slot_name = &self.config.source.postgres().slot_name; - if let Err(e) = self - .state_store - .save_checkpoint(slot_name, confirmed_lsn) - .await - { - error!( - "Failed to save checkpoint at LSN 0x{:X}: {}", - confirmed_lsn, e - ); - error!("NOT confirming to PostgreSQL to prevent data loss"); - // Return error to halt replication loop - return Err(e); - } - - // 2. Update SharedState (after successful persistence) - self.shared_state.confirm_lsn(confirmed_lsn); - - // 3. Confirm to PostgreSQL (only after checkpoint is safely persisted) - let status = build_standby_status_update(confirmed_lsn); - if let Err(e) = replication_stream.send(status).await { - error!("Failed to send status update to PostgreSQL: {}", e); - error!("Checkpoint saved but not confirmed - may cause duplicate events on restart"); - return Err(anyhow::Error::new(e)); - } - - debug!("Checkpoint confirmed: LSN 0x{:X}", confirmed_lsn); - Ok(()) - } } -/// Flow control for the loop -enum ControlFlow { +/// Flow control for replication loops. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ControlFlow { Continue, Break, } diff --git a/src/engine/replication/mod.rs b/src/engine/replication/mod.rs new file mode 100644 index 0000000..9f900ee --- /dev/null +++ b/src/engine/replication/mod.rs @@ -0,0 +1,97 @@ +//! Replication loop abstraction — each source type implements its own event loop. + +pub mod postgres; +use std::sync::Arc; + +use anyhow::Result; +use async_trait::async_trait; +use tokio::sync::mpsc; +use tracing::info; + +use crate::config::Config; +use crate::control::state::{CdcState, SharedState}; +use crate::control::Stage; +use crate::core::traits::SourceTableSchema; +use crate::core::Sink; +use crate::engine::ControlFlow; +use crate::pipeline::PipelineEvent; +use crate::state_store::StateStore; + +#[cfg(feature = "mysql-source")] +mod mysql; +#[cfg(feature = "mysql-source")] +pub use mysql::MysqlReplicationLoop; + +/// Factory that creates fresh Sink instances (used by snapshot workers). +type SinkFactory = Arc anyhow::Result> + Send + Sync>; + +/// Shared context passed to every ReplicationLoop implementation. +pub struct LoopContext { + pub shared_state: Arc, + pub config: Arc, + pub state_store: Arc, + pub pipeline_tx: mpsc::Sender, + pub feedback_rx: mpsc::Receiver, + pub source_schemas: Arc<[SourceTableSchema]>, + pub sink_factory: SinkFactory, + /// MySQL-only: registry of in-flight snapshot chunks for the read-only + /// DBLog reconciliation. The consumer marks evicted PKs and signals + /// chunk drain when its `current_gtid_set` covers the chunk's HIGH + /// watermark. Always present (default-constructed for non-MySQL + /// pipelines, where it stays empty). + #[cfg(feature = "mysql-source")] + pub active_chunks: crate::engine::snapshot::active_chunks::ActiveChunks, + /// MySQL-only: live, shared view of the consumer's accumulated + /// `gtid_executed`. The MySQL replication loop is the single writer + /// (via `ParserState::current_gtid_set`); snapshot workers read it + /// when registering chunks (LOW watermark) and again after the + /// chunk SELECT (HIGH watermark) — replacing per-chunk + /// `SELECT @@global.gtid_executed` queries against the source. + /// Default-constructed for non-MySQL pipelines. + #[cfg(feature = "mysql-source")] + pub consumer_gtid: std::sync::Arc>, +} + +/// Each source type implements its own replication event loop. +/// The engine picks the right implementation at startup. +#[async_trait] +pub trait ReplicationLoop: Send { + async fn run(self: Box, ctx: LoopContext) -> Result<()>; +} + +/// Shared loop utilities (state check, shutdown, snapshot trigger). +pub struct LoopHelper; + +impl LoopHelper { + /// Check CDC state (Pause/Stop/Draining). Returns control flow signal. + pub fn check_state_control( + state: &CdcState, + pipeline_capacity: usize, + flush_size: usize, + ) -> Option { + match state { + CdcState::Stopped => { + info!("CDC stopped. Exiting immediately."); + Some(ControlFlow::Break) + } + CdcState::Draining => { + if pipeline_capacity == flush_size * 2 { + info!("CDC drained. Exiting gracefully."); + Some(ControlFlow::Break) + } else { + None + } + } + CdcState::Paused => Some(ControlFlow::Continue), + CdcState::Running => None, + } + } + + /// Set up the CDC stage in shared state. + pub async fn set_cdc_stage(shared_state: &SharedState) { + shared_state.set_stage(Stage::Cdc, "Replicating").await; + info!("Connected! Streaming CDC events..."); + } +} + +pub use postgres::PgReplicationLoop; diff --git a/src/engine/replication/mysql.rs b/src/engine/replication/mysql.rs new file mode 100644 index 0000000..8b764ca --- /dev/null +++ b/src/engine/replication/mysql.rs @@ -0,0 +1,539 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! MySQL replication loop — reads binlog events and pushes to pipeline. + +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; +use std::time::Duration; + +use anyhow::Result; +use async_trait::async_trait; +use futures_util::StreamExt; +use mysql_common::binlog::events::TableMapEvent; +use tracing::{debug, error, info, warn}; + +use anyhow::Context; +use mysql_async::prelude::Queryable; + +use crate::core::SourcePosition; +use crate::engine::replication::{LoopContext, LoopHelper, ReplicationLoop}; +use crate::engine::snapshot::mysql::build_mysql_opts; +use crate::engine::ControlFlow; +use crate::pipeline::PipelineEvent; +use crate::source::mysql::converter::convert_to_cdc_records; +use crate::source::mysql::gtid::GtidSet; +use crate::source::mysql::parser::{process_typed_event, BinlogEvent, ParserState}; + +/// MySQL replication loop — reads binlog events and pushes to pipeline. +pub struct MysqlReplicationLoop { + binlog_stream: mysql_async::BinlogStream, +} + +impl MysqlReplicationLoop { + /// Create a new MySQL replication loop. + pub fn new(binlog_stream: mysql_async::BinlogStream) -> Self { + Self { binlog_stream } + } + + /// For a CDC record (Insert/Update/Delete), check whether it mutates a + /// row that falls inside any active snapshot chunk's PK range AND + /// whose event GTID lies in the chunk's `(LOW, HIGH]` window. If so, + /// register the eviction — the snapshot worker will drop the + /// corresponding row from the chunk buffer before emitting. + /// + /// No-op for non-mutation records (Begin/Commit/Heartbeat/SchemaChange). + async fn record_chunk_eviction_if_applicable( + active_chunks: &crate::engine::snapshot::active_chunks::ActiveChunks, + record: &crate::core::CdcRecord, + parser_state: &crate::source::mysql::parser::ParserState, + ) { + use crate::core::CdcRecord; + use crate::engine::snapshot::active_chunks::pk_in_range; + + let (table_ref, columns) = match record { + CdcRecord::Insert { table, columns, .. } | CdcRecord::Delete { table, columns, .. } => { + (table, columns) + } + CdcRecord::Update { + table, new_columns, .. + } => (table, new_columns), + _ => return, + }; + let schema = match &table_ref.schema { + Some(s) => s.clone(), + None => return, + }; + let table = table_ref.name.clone(); + + let snapshots = active_chunks.chunks_for_table(&schema, &table).await; + if snapshots.is_empty() { + return; + } + + // Snapshot the parser's current GTID set once for this batch of chunks + // (cheap clone; HashMap of intervals). Avoids holding the read lock + // across the eviction loop and matches the LOW-via-consumer + // discipline the snapshot worker uses on the other side. + let consumer_gtid_now = parser_state + .current_gtid_set + .read() + .expect("MySQL parser GTID set lock poisoned") + .clone(); + + // The "in window" check has two regimes: + // - high_set is None → SELECT still in flight; every event + // since LOW is a candidate (it can't be after HIGH yet). + // - high_set is Some → strict (LOW, HIGH] check. parser_state + // ⊇ LOW means we've passed LOW; not (parser_state ⊇ HIGH) + // means we haven't drained yet. Both must hold for the + // event to be inside the chunk's window. + for snap in &snapshots { + // Find the PK value by column name on this record. If the + // record doesn't carry the PK column (shouldn't happen for + // ROW format with REPLICA IDENTITY FULL but defensive), skip. + let pk_value = match columns.iter().find(|c| c.name == snap.pk_column) { + Some(c) => c.value.clone(), + None => continue, + }; + if !pk_in_range(&pk_value, &snap.pk_range) { + continue; + } + let in_window = match &snap.high_set { + None => consumer_gtid_now.is_superset_of(&snap.low_set), + Some(high) => { + consumer_gtid_now.is_superset_of(&snap.low_set) + && !consumer_gtid_now.is_superset_of(high) + } + }; + if in_window { + active_chunks.record_eviction(snap.id, &pk_value).await; + } + } + } + + /// Validate that the server's `@@global.gtid_executed` is a superset + /// of the persisted `gtid_executed`. Fatal if not — typically caused + /// by a pre-fix daemon that persisted a mid-transaction GTID whose + /// commit never actually landed in the binlog, or by a server + /// failover that lost transactions, or by binlog purge before resume. + async fn validate_persisted_gtid(source_url: &str, persisted: &str) -> Result<()> { + let opts = build_mysql_opts(source_url, false) + .context("MySQL CDC startup probe: failed to build connection opts")?; + let mut conn = mysql_async::Conn::new(opts) + .await + .context("MySQL CDC startup probe: failed to connect for GTID validation")?; + let row: Option<(u8,)> = conn + .exec_first( + "SELECT GTID_SUBSET(?, @@global.gtid_executed)", + (persisted,), + ) + .await + .context("MySQL CDC startup probe: GTID_SUBSET query failed")?; + // Best-effort close; ignore disconnect errors. + let _ = conn.disconnect().await; + let is_subset = row.map(|(b,)| b != 0).unwrap_or(false); + if !is_subset { + error!( + persisted_gtid_executed = persisted, + "MySQL CDC: persisted gtid_executed is not a subset of the server's \ + @@global.gtid_executed. The server is missing GTIDs that we previously \ + acknowledged — typically caused by a binlog purge or a pre-fix daemon \ + that persisted a mid-transaction checkpoint. Fatal: delete the row \ + from dbmazz_checkpoints and re-run with DO_SNAPSHOT=true to reset." + ); + anyhow::bail!( + "MySQL CDC: persisted gtid_executed not a subset of server's gtid_executed; \ + manual reset required (see logs)" + ); + } + Ok(()) + } + + /// Returns `true` if the event targets a tracked table. + /// + /// Unfiltered types (`Begin`, `Commit`, `Heartbeat`, `TableMap`) always pass. + fn is_tracked_table_event(event: &BinlogEvent, tracked: &HashSet<(String, String)>) -> bool { + match event { + BinlogEvent::Insert { + schema_name, + table_name, + .. + } + | BinlogEvent::Update { + schema_name, + table_name, + .. + } + | BinlogEvent::Delete { + schema_name, + table_name, + .. + } => tracked.contains(&(schema_name.clone(), table_name.clone())), + BinlogEvent::Ddl { schema_name, .. } => { + let has_any = tracked.iter().any(|(s, _)| s == schema_name); + if !has_any { + debug!( + "MySQL CDC: skipping DDL for untracked schema '{}'", + schema_name + ); + } + has_any + } + _ => true, + } + } +} + +#[async_trait] +impl ReplicationLoop for MysqlReplicationLoop { + async fn run(self: Box, ctx: LoopContext) -> Result<()> { + let LoopContext { + shared_state, + config, + state_store, + pipeline_tx, + mut feedback_rx, + source_schemas, + sink_factory, + active_chunks, + consumer_gtid, + .. + } = ctx; + + let mut shutdown_rx = shared_state.shutdown_tx.subscribe(); + let mut snapshot_trigger_rx = shared_state.subscribe_snapshot_trigger(); + let mut iteration = 0u64; + + // Table map event cache and column name map from schema introspection + let mut tme_cache: HashMap> = HashMap::new(); + let mut col_names_map: HashMap<(String, String), Vec> = HashMap::new(); + let mut tracked_tables: HashSet<(String, String)> = HashSet::new(); + for s in source_schemas.iter() { + let names: Vec = s.columns.iter().map(|c| c.name.clone()).collect(); + col_names_map.insert((s.schema.clone(), s.name.clone()), names); + tracked_tables.insert((s.schema.clone(), s.name.clone())); + } + info!( + "MySQL CDC: tracking {} table(s): {:?}", + tracked_tables.len(), + tracked_tables + ); + + // Parser state — tracks the binlog file we're currently in and the + // accumulated GTID-executed set. The set seeds from any prior + // checkpoint persisted in StateStore so resumed streams continue + // adding to a real cumulative set, not start from zero. The GTID + // set lives behind `consumer_gtid` so snapshot workers can read + // it for LOW/HIGH watermarks (DBLog read-only mode). + let (initial_file, initial_set): (String, GtidSet) = match state_store + .load_mysql_checkpoint(&format!("mysql_{}", config.source.mysql().server_id)) + .await + { + Ok(Some((file, _pos, gtid_str))) => { + info!( + "MySQL CDC resume: starting from checkpoint file={}, gtid_executed={}", + file, gtid_str + ); + (file, GtidSet::parse(>id_str).unwrap_or_default()) + } + Ok(None) => { + info!("MySQL CDC: no prior checkpoint, tracking from stream start"); + (String::new(), GtidSet::default()) + } + Err(e) => { + warn!( + "MySQL CDC: failed to load checkpoint ({}); tracking from stream start", + e + ); + (String::new(), GtidSet::default()) + } + }; + // Crash-recovery sanity check: if we're resuming from a persisted + // checkpoint, validate that the server still has every GTID we + // think we've seen. A pre-fix daemon could persist a mid- + // transaction `gtid_executed` whose in-flight GTID never actually + // landed in the binlog — on restart MySQL would error with + // "Slave has more GTIDs than the master has" anyway, but we + // surface a clearer fatal message and avoid the silent loop of + // reconnect attempts. `GTID_SUBSET(persisted, executed) = 1` + // means every persisted GTID is on the server; 0 means we're + // ahead of the source and need an operator reset. + let persisted_gtid_executed = initial_set.format(); + if !persisted_gtid_executed.is_empty() { + Self::validate_persisted_gtid(&config.source.url, &persisted_gtid_executed).await?; + } + + // Seed the shared consumer-GTID handle with the persisted set, then + // hand the same Arc to ParserState. From here on, every parser write + // also updates what snapshot workers observe — no separate channel. + *consumer_gtid + .write() + .expect("consumer_gtid lock poisoned at startup") = initial_set; + let mut parser_state = ParserState::with_shared_gtid(initial_file, consumer_gtid.clone()); + + // Synthetic LSN counter — required because the generic pipeline + // feedback channel speaks in `u64`, but MySQL positions are triples. + // Each PipelineEvent gets a monotonically-increasing synthetic LSN, + // and we keep a (synthetic_lsn -> SourcePosition) map so we can + // resolve back to the real triple when the sink confirms. + let mut next_synthetic_lsn: u64 = 1; + let mut pending_positions: BTreeMap = BTreeMap::new(); + // Commit-boundary buffer. Per Debezium's offset commit contract, we + // persist checkpoints ONLY at transaction commit boundaries — never + // mid-transaction. The pipeline acknowledges per-record (synthetic + // LSN granularity), but each `BinlogEvent::Commit` pushes its + // (synthetic_lsn, position) here, and on feedback we look up the + // highest commit-boundary entry ≤ confirmed_lsn and persist that. + // A crash mid-transaction now resumes from the last committed + // boundary rather than past an in-flight GTID. + // + // Cap is FLUSH_SIZE * 4 to bound memory on bursty commit streams; + // overflow triggers a structured WARN and the persisted checkpoint + // stays pinned at the last in-bounds commit (never advances past + // an unbounded transaction). + let mut pending_txn_positions: VecDeque<(u64, SourcePosition)> = VecDeque::new(); + let txn_buffer_cap = config.flush_size.saturating_mul(4).max(64); + let slot_name = format!("mysql_{}", config.source.mysql().server_id); + + let mut binlog_stream = self.binlog_stream; + let tx = pipeline_tx; + + LoopHelper::set_cdc_stage(&shared_state).await; + + loop { + iteration = iteration.wrapping_add(1); + + // Every 256 iterations, check state control (Pause/Stop/Draining) + if iteration & 0xFF == 0 { + let state = shared_state.state(); + if let Some(flow) = + LoopHelper::check_state_control(&state, tx.capacity(), config.flush_size) + { + match flow { + ControlFlow::Break => break, + ControlFlow::Continue => { + tokio::time::sleep(Duration::from_millis(100)).await; + continue; + } + } + } + } + + tokio::select! { + _ = shutdown_rx.changed() => { + if *shutdown_rx.borrow() { + info!("Shutdown signal received"); + break; + } + } + + Ok(()) = snapshot_trigger_rx.changed() => { + if *snapshot_trigger_rx.borrow() && !shared_state.is_snapshot_active() { + info!("On-demand snapshot triggered"); + let _ = shared_state.snapshot_trigger.send(false); + let snap_config = config.clone(); + let snap_state = shared_state.clone(); + let snap_factory = sink_factory.clone(); + let snap_active_chunks = active_chunks.clone(); + let snap_consumer_gtid = consumer_gtid.clone(); + tokio::spawn(async move { + match crate::engine::snapshot::mysql::run_mysql_snapshot( + snap_config, + snap_state.clone(), + snap_factory, + snap_active_chunks, + snap_consumer_gtid, + ) + .await + { + Ok(()) => { + snap_state.set_snapshot_active(false); + info!("MySQL snapshot completed successfully"); + } + Err(e) => { + snap_state.set_snapshot_active(false); + snap_state.set_snapshot_error(Some(format!("{}", e))).await; + error!("MySQL snapshot worker error: {}", e); + } + } + }); + info!("MySQL snapshot worker spawned"); + } + } + + event_res = binlog_stream.next() => { + match event_res { + Some(Ok(event)) => { + let binlog_events = process_typed_event( + &event, + &mut tme_cache, + &col_names_map, + &mut parser_state, + )?; + for event in &binlog_events { + if !Self::is_tracked_table_event(event, &tracked_tables) { + continue; + } + // Note any commit-boundary GTID label so we can + // record this synthetic LSN as a persistable checkpoint + // boundary AFTER the Commit record is sent to the + // pipeline. ROLLBACK boundaries also count as commit + // boundaries for checkpoint purposes — events streamed + // before the ROLLBACK are already in the pipeline (we + // don't have an "un-commit" channel), so the persistence + // layer just advances past the rollback marker. + let commit_boundary_label = + if let BinlogEvent::Commit { gtid, .. } = event { + Some(gtid.clone()) + } else { + None + }; + + let records = convert_to_cdc_records(event)?; + for record in records { + // DBLog reconciliation: if this record mutates a row + // that falls inside an active snapshot chunk's PK + // range AND the event GTID falls in (LOW, HIGH], mark + // the snapshot row as evicted so the worker drops it + // before emitting. + Self::record_chunk_eviction_if_applicable( + &active_chunks, + &record, + &parser_state, + ) + .await; + + let synthetic_lsn = next_synthetic_lsn; + next_synthetic_lsn = next_synthetic_lsn.wrapping_add(1); + let record_position = record.position().cloned(); + if let Some(pos) = record_position.clone() { + pending_positions.insert(synthetic_lsn, pos); + } + + // If this record is the Commit, record its + // synthetic LSN as a commit-boundary entry so + // the feedback handler persists THIS position + // rather than an arbitrary mid-transaction one. + if let (Some(label), Some(pos)) = + (commit_boundary_label.as_ref(), record_position) + { + if matches!( + record, + crate::core::CdcRecord::Commit { .. } + ) { + // Cap-and-drop policy on overflow: keep + // the persisted checkpoint pinned at the + // most recent successfully-buffered + // commit. Better stale than wrong. + if pending_txn_positions.len() >= txn_buffer_cap { + warn!( + txn_buffer_cap, + txn_label = %label, + "MySQL CDC: pending commit-boundary buffer full; \ + persisted checkpoint will not advance until \ + the pipeline catches up. Consider raising FLUSH_SIZE." + ); + } else { + pending_txn_positions + .push_back((synthetic_lsn, pos)); + } + } + } + + let pipeline_event = PipelineEvent { + lsn: synthetic_lsn, + record, + }; + tx.send(pipeline_event).await.map_err(|_| { + anyhow::anyhow!("Pipeline channel closed") + })?; + } + } + // After a batch of events, wake any snapshot worker whose + // chunk window has now been fully covered by this consumer. + // Snapshot the GTID set under a brief read lock so try_drain + // doesn't hold it for the duration of its registry walk. + let consumer_gtid_now = parser_state + .current_gtid_set + .read() + .expect("MySQL parser GTID set lock poisoned") + .clone(); + active_chunks.try_drain(&consumer_gtid_now).await; + } + Some(Err(e)) => { + error!("MySQL binlog stream error: {}", e); + break; + } + None => { + warn!("MySQL binlog stream ended"); + break; + } + } + } + + // MySQL has no client → server position ack (binlogs are time-purged, + // not consumer-purged), but we DO use the pipeline feedback to drive + // the client-side checkpoint that restart correctness depends on. + // + // CRITICAL: only persist positions at transaction commit boundaries. + // The pipeline acknowledges per-record, but persisting a row event's + // mid-transaction position would let `gtid_executed` include an + // in-flight GTID — on crash before the matching XID, MySQL would + // resume past that GTID entirely and we'd lose the entire txn. + // pending_txn_positions is populated only by `BinlogEvent::Commit`. + Some(confirmed_lsn) = feedback_rx.recv() => { + // Find the highest commit-boundary position whose synthetic + // LSN is ≤ confirmed_lsn. Pop earlier commits from the + // VecDeque (they're now superseded). Anything > confirmed_lsn + // stays for a future feedback message. + let mut latest_commit: Option = None; + while let Some((lsn, _)) = pending_txn_positions.front() { + if *lsn > confirmed_lsn { + break; + } + let (_, pos) = pending_txn_positions.pop_front().unwrap(); + latest_commit = Some(pos); + } + + if let Some(SourcePosition::MysqlBinlog { + ref file, + position: pos, + ref gtid_executed, + }) = latest_commit.as_ref() + { + if let Err(e) = state_store + .save_mysql_checkpoint(&slot_name, file, *pos, gtid_executed) + .await + { + warn!("MySQL checkpoint save failed: {}", e); + } else { + debug!( + "MySQL checkpoint saved (commit boundary): file={}, pos={}, \ + gtid_executed={}", + file, pos, gtid_executed + ); + } + } + // Always drop per-event metadata up to confirmed_lsn so + // pending_positions doesn't grow unbounded; this map is + // now informational only (used by the eviction logic to + // resolve a record's position) — it no longer drives + // persistence. + pending_positions = pending_positions.split_off(&(confirmed_lsn + 1)); + } + } + } + + info!("MySQL CDC shutdown complete"); + Ok(()) + } +} + +#[cfg(test)] +mod send_tests { + #[test] + fn assert_binlog_stream_is_send() { + fn assert_send() {} + assert_send::(); + } +} diff --git a/src/engine/replication/postgres.rs b/src/engine/replication/postgres.rs new file mode 100644 index 0000000..c9c8674 --- /dev/null +++ b/src/engine/replication/postgres.rs @@ -0,0 +1,286 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +use std::time::Duration; + +use anyhow::Result; +use async_trait::async_trait; +use bytes::Bytes; +use tokio::sync::mpsc; +use tracing::{debug, error, info, warn}; + +use crate::control::state::{CdcState, SharedState}; +use crate::core::ReplicationStream; +use crate::engine::replication::{LoopContext, LoopHelper, ReplicationLoop}; +use crate::engine::ControlFlow; +use crate::pipeline::schema_cache::SchemaCache; +use crate::pipeline::PipelineEvent; +use crate::replication::{handle_xlog_data, parse_replication_message, WalMessage}; +use crate::source::postgres::build_standby_status_update; +use crate::state_store::StateStore; + +/// PostgreSQL replication loop. +/// +/// Owns the replication stream and schema cache, and runs the main CDC event +/// loop: reading WAL messages from the stream, handling KeepAlive replies, +/// dispatching checkpoint feedback, and coordinating with the pipeline. +pub struct PgReplicationLoop { + /// Raw replication stream (pgoutput protocol over CopyBothDuplex) + pub replication_stream: Box, + /// Schema cache — updated on Relation messages; used by the converter + /// to resolve column names / types when building CdcRecord. + pub schema_cache: SchemaCache, +} + +impl PgReplicationLoop { + pub fn new(stream: Box, schema_cache: SchemaCache) -> Self { + Self { + replication_stream: stream, + schema_cache, + } + } + + /// Process a single WAL message. + /// + /// - `XLogData`: delegate to `handle_xlog_data` for pgoutput parsing → + /// SchemaCache update → CdcRecord conversion → pipeline send. + /// - `KeepAlive`: if reply is requested, send standby status update back. + /// - `Unknown`: log and skip. + async fn handle_replication_message( + &mut self, + msg: WalMessage, + tx: &mpsc::Sender, + shared_state: &SharedState, + flush_size: usize, + ) -> Result { + match msg { + WalMessage::XLogData { lsn, data } => { + handle_xlog_data( + data, + lsn, + tx, + shared_state, + &mut self.schema_cache, + flush_size, + ) + .await?; + Ok(lsn) + } + WalMessage::KeepAlive { + lsn, + reply_requested, + } => { + if reply_requested { + let status = build_standby_status_update(lsn); + self.replication_stream.send_feedback(&status).await?; + } + Ok(lsn) + } + WalMessage::Unknown(tag) => { + warn!("Unknown replication message tag: {}", tag); + Ok(0) + } + } + } + + /// Persist a checkpoint and confirm to PostgreSQL. + /// + /// Order is critical: + /// 1. Save checkpoint to persistent storage FIRST. + /// 2. Update in-memory confirmed LSN. + /// 3. Send standby status update to PostgreSQL LAST. + /// + /// If we confirmed to PG before saving locally and crashed, PG would + /// discard WAL that we haven't persisted — permanent data loss. + async fn handle_checkpoint_feedback( + &mut self, + confirmed_lsn: u64, + state_store: &StateStore, + shared_state: &SharedState, + slot_name: &str, + ) -> Result<()> { + // 1. Save checkpoint to persistent storage + if let Err(e) = state_store.save_checkpoint(slot_name, confirmed_lsn).await { + error!( + "Failed to save checkpoint at LSN 0x{:X}: {}", + confirmed_lsn, e + ); + error!("NOT confirming to PostgreSQL to prevent data loss"); + return Err(e); + } + + // 2. Update SharedState (after successful persistence) + shared_state.confirm_lsn(confirmed_lsn); + + // 3. Confirm to PostgreSQL (only after checkpoint is safely persisted) + let status = build_standby_status_update(confirmed_lsn); + if let Err(e) = self.replication_stream.send_feedback(&status).await { + error!("Failed to send status update to PostgreSQL: {}", e); + error!("Checkpoint saved but not confirmed - may cause duplicate events on restart"); + return Err(e); + } + + debug!("Checkpoint confirmed: LSN 0x{:X}", confirmed_lsn); + Ok(()) + } +} + +#[async_trait] +impl ReplicationLoop for PgReplicationLoop { + /// Run the PostgreSQL CDC event loop. + /// + /// Loop structure (every iteration, with state check every 256 iterations): + /// tokio::select! { + /// shutdown signal → break & cleanup + /// snapshot trigger → spawn snapshot worker + /// WAL event → parse → handle (XLogData / KeepAlive) + /// checkpoint → save + confirm to PG + /// } + async fn run(self: Box, ctx: LoopContext) -> Result<()> { + // async_trait wraps the body in an async move block where `self` is + // an immutable binding. Rebind as mutable so we can call &mut self + // methods (next_event, handle_replication_message, etc.). + let mut this = self; + + let LoopContext { + shared_state, + config, + state_store, + pipeline_tx, + mut feedback_rx, + source_schemas: _, + sink_factory, + // active_chunks is MySQL-only; Postgres ignores it. + .. + } = ctx; + + let mut shutdown_rx = shared_state.shutdown_tx.subscribe(); + let mut snapshot_trigger_rx = shared_state.subscribe_snapshot_trigger(); + let mut iteration = 0u64; + + let slot_name = config.source.postgres().slot_name.clone(); + let flush_size = config.flush_size; + + loop { + iteration = iteration.wrapping_add(1); + + // Periodically check whether the CDC state (Pause / Stop / Drain) + // has changed via the shared state atom. + if iteration & 0xFF == 0 { + let state = shared_state.state(); + let capacity = pipeline_tx.capacity(); + if let Some(flow) = LoopHelper::check_state_control(&state, capacity, flush_size) { + match flow { + ControlFlow::Break => { + if state == CdcState::Draining { + shared_state.set_state(CdcState::Stopped); + } + break; + } + ControlFlow::Continue => { + tokio::time::sleep(Duration::from_millis(100)).await; + continue; + } + } + } + } + + tokio::select! { + biased; + + // ── Shutdown signal ──────────────────────────────────── + _ = shutdown_rx.changed() => { + if *shutdown_rx.borrow() { + info!("Shutdown signal received"); + break; + } + } + + // ── On-demand snapshot trigger ───────────────────────── + Ok(()) = snapshot_trigger_rx.changed() => { + if *snapshot_trigger_rx.borrow() && !shared_state.is_snapshot_active() { + info!("On-demand snapshot triggered (CDC_RUNNING → SNAPSHOT)"); + let _ = shared_state.snapshot_trigger.send(false); + + let snap_config = config.clone(); + let snap_state = shared_state.clone(); + let snap_sink_factory = sink_factory.clone(); + tokio::spawn(async move { + match crate::engine::snapshot::run_snapshot( + snap_config, + snap_state.clone(), + snap_sink_factory, + ) + .await + { + Ok(()) => { + snap_state.set_snapshot_active(false); + info!("Snapshot completed successfully"); + } + Err(e) => { + snap_state.set_snapshot_active(false); + snap_state + .set_snapshot_error(Some(format!("{}", e))) + .await; + error!("Snapshot worker error: {}", e); + } + } + }); + info!("Snapshot worker spawned"); + } + } + + // ── WAL event from the replication stream ────────────── + data_res = this.replication_stream.next_event() => { + match data_res { + Some(Ok(data)) => { + let mut bytes = Bytes::from(data); + if let Some(msg) = parse_replication_message(&mut bytes) { + this.handle_replication_message( + msg, + &pipeline_tx, + &shared_state, + flush_size, + ).await?; + } + } + Some(Err(e)) => { + error!("Replication stream error: {}", e); + break; + } + None => { + warn!("Replication stream ended"); + break; + } + } + } + + // ── Checkpoint feedback from the pipeline ────────────── + Some(confirmed_lsn) = feedback_rx.recv() => { + this.handle_checkpoint_feedback( + confirmed_lsn, + &state_store, + &shared_state, + &slot_name, + ).await?; + } + } + } + + // Cleanup PG replication slot + if shared_state.should_skip_slot_cleanup() { + info!("[SKIP] Skipping slot cleanup (upgrade/restart mode)"); + } else { + crate::engine::setup::cleanup_postgres_resources( + &config.source.url, + &config.source.postgres().slot_name, + ) + .await + .map_err(|e| warn!("Cleanup warning: {}", e)) + .ok(); + } + + info!("CDC shutdown complete"); + Ok(()) + } +} diff --git a/src/engine/snapshot/active_chunks.rs b/src/engine/snapshot/active_chunks.rs new file mode 100644 index 0000000..8b435e3 --- /dev/null +++ b/src/engine/snapshot/active_chunks.rs @@ -0,0 +1,549 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! Active-chunk registry for the read-only DBLog incremental snapshot +//! reconciliation (T4 / B4). +//! +//! While a MySQL snapshot worker reads a PK-bounded chunk, the binlog +//! stream consumer keeps running. Any binlog event that mutates a row in +//! the chunk's PK range and whose GTID falls inside the chunk's window +//! `(LOW, HIGH]` must override the row read by the snapshot — otherwise +//! the snapshot would write stale data to the sink. +//! +//! This module is the synchronisation point between the two: snapshot +//! workers register their chunks here, the consumer marks evictions and +//! signals the worker once its window has closed. +//! +//! The data structure is a small `HashMap` guarded +//! by a single `RwLock`. Active chunk count = number of in-flight +//! snapshot workers (default 1, capped at the configured parallelism), +//! so contention is negligible. Each chunk owns its own `Notify` so the +//! worker only wakes when its specific window has closed. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use tokio::sync::{Notify, RwLock}; + +use crate::core::Value; +use crate::source::mysql::gtid::GtidSet; + +/// Stable identifier for a snapshot chunk during its lifetime in the +/// registry. Generated by `ActiveChunks::register`. +pub type ChunkId = u64; + +/// Hash-friendly representation of a primary-key value. +/// +/// `Value` includes `Float64`, which doesn't implement `Eq`/`Hash`, so we +/// can't keep evicted PKs as `HashSet` directly. The snapshot +/// chunker only chunks on integer / string / uuid PKs in practice, all +/// of which round-trip losslessly through this format. +pub type PkKey = String; + +/// Stable string encoding of a `Value` for use in `HashSet`. +/// Different variants get different prefixes so e.g. `Int64(1)` and +/// `String("1")` never collide. +pub fn pk_key(value: &Value) -> PkKey { + match value { + Value::Int64(i) => format!("i:{}", i), + Value::String(s) => format!("s:{}", s), + Value::Uuid(u) => format!("u:{}", u), + Value::Decimal(d) => format!("d:{}", d), + Value::Bytes(b) => format!("b:{}", hex_encode(b)), + Value::Bool(b) => format!("B:{}", b), + Value::Timestamp(t) => format!("t:{}", t), + // Float / Json / Null / Unchanged are not valid PK types in + // dbmazz's chunker, but we still want a deterministic key so + // a misuse doesn't silently collapse rows together. + other => format!("?:{:?}", other), + } +} + +fn hex_encode(bytes: &[u8]) -> String { + let mut s = String::with_capacity(bytes.len() * 2); + for b in bytes { + s.push_str(&format!("{:02x}", b)); + } + s +} + +/// Mutable per-chunk state shared between snapshot worker and binlog +/// consumer. All fields are mutated through `ActiveChunks` to keep the +/// locking discipline in one place. +#[derive(Debug)] +pub struct ChunkState { + /// Fully-qualified table the chunk belongs to (`schema`, `table`). + pub table: (String, String), + /// Primary key column name (single-column PKs only — matches the + /// rest of the snapshot module's assumptions). + pub pk_column: String, + /// Inclusive PK range `[start, end]` covered by this chunk. + pub pk_range: (Value, Value), + /// `@@global.gtid_executed` captured immediately before the chunk's + /// `SELECT`. The lower bound of the reconciliation window. + pub low_set: GtidSet, + /// `@@global.gtid_executed` captured immediately after the chunk's + /// `SELECT`. `None` while the `SELECT` is still in flight. + pub high_set: Option, + /// PKs whose row in this chunk has been overridden by a later binlog + /// event in the window — the worker must drop these from the buffer + /// before emitting to the sink. + pub evicted_pks: HashSet, + /// Set to `true` once the consumer's running `gtid_executed` is a + /// superset of `high_set`, meaning every event that could possibly + /// have fallen in the window has been seen. + pub drained: bool, + /// Wakes the snapshot worker waiting in `await_drain`. + pub notify: Arc, +} + +/// Process-wide registry of active snapshot chunks. +/// +/// Cheaply cloneable — the inner state is shared via `Arc`. One instance +/// is constructed per `CdcEngine::run` and threaded into every snapshot +/// worker and into the `MysqlReplicationLoop`. +#[derive(Clone, Default, Debug)] +pub struct ActiveChunks { + inner: Arc, +} + +#[derive(Default, Debug)] +struct Inner { + chunks: RwLock>, + next_id: std::sync::atomic::AtomicU64, +} + +/// RAII handle returned by `register`. Callers may either pass it to +/// `deregister` explicitly or rely on it being dropped — both paths +/// remove the chunk from the registry. +#[must_use = "drop or pass to ActiveChunks::deregister to release the chunk"] +pub struct ChunkHandle { + id: ChunkId, + chunks: ActiveChunks, +} + +impl ChunkHandle { + pub fn id(&self) -> ChunkId { + self.id + } +} + +impl Drop for ChunkHandle { + fn drop(&mut self) { + let chunks = self.chunks.clone(); + let id = self.id; + // Spawn a task to release the lock since Drop can't be async. + // Worst case the chunk hangs around a bit longer; correctness is + // not affected because in-flight events for a deregistered table + // simply find no matching chunk. + tokio::spawn(async move { + chunks.deregister(id).await; + }); + } +} + +impl ActiveChunks { + pub fn new() -> Self { + Self::default() + } + + /// Register a chunk and return a handle. The notify field is owned + /// by the chunk and shared with the caller so they can wait on it. + pub async fn register( + &self, + table: (String, String), + pk_column: String, + pk_range: (Value, Value), + low_set: GtidSet, + ) -> (ChunkHandle, Arc) { + let id = self + .inner + .next_id + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let notify = Arc::new(Notify::new()); + let state = ChunkState { + table, + pk_column, + pk_range, + low_set, + high_set: None, + evicted_pks: HashSet::new(), + drained: false, + notify: notify.clone(), + }; + self.inner.chunks.write().await.insert(id, state); + let handle = ChunkHandle { + id, + chunks: self.clone(), + }; + (handle, notify) + } + + /// Set the chunk's `high_set` once the SELECT has finished. After + /// this point, drain detection is meaningful. + pub async fn set_high_watermark(&self, id: ChunkId, high_set: GtidSet) { + if let Some(state) = self.inner.chunks.write().await.get_mut(&id) { + state.high_set = Some(high_set); + } + } + + /// Mark a PK as overridden by a binlog event. Idempotent — repeated + /// calls for the same `(chunk, pk)` are no-ops. + /// + /// The caller is responsible for ensuring the event's GTID falls in + /// the chunk's window; this method just records the eviction. + pub async fn record_eviction(&self, id: ChunkId, pk: &Value) { + if let Some(state) = self.inner.chunks.write().await.get_mut(&id) { + state.evicted_pks.insert(pk_key(pk)); + } + } + + /// Snapshot the current set of evicted PK keys for a chunk. Used by + /// the snapshot worker right before emitting the reconciled buffer. + pub async fn evicted_pks(&self, id: ChunkId) -> HashSet { + self.inner + .chunks + .read() + .await + .get(&id) + .map(|s| s.evicted_pks.clone()) + .unwrap_or_default() + } + + /// Walk every active chunk; for each whose `high_set` has been set + /// and whose window is now covered by `consumer_gtid_set`, mark it + /// drained and notify its waiter. + /// + /// Called by the binlog consumer after each event so workers wake + /// up promptly. Cheap: chunk count is the snapshot parallelism. + pub async fn try_drain(&self, consumer_gtid_set: &GtidSet) { + let mut chunks = self.inner.chunks.write().await; + for state in chunks.values_mut() { + if state.drained { + continue; + } + if let Some(high) = &state.high_set { + if consumer_gtid_set.is_superset_of(high) { + state.drained = true; + state.notify.notify_waiters(); + } + } + } + } + + /// Wait until the chunk is marked drained. + /// + /// Returns immediately if it already is. The caller passes the + /// `Notify` returned by `register`; we re-check the flag after + /// each wake to handle spurious wakeups. + /// + /// The `Notified` future is created BEFORE the flag check so any + /// `notify_waiters()` call fired between the check and the await + /// still wakes us. `notify_waiters` only wakes futures already + /// registered on the queue — a polling-then-awaiting structure + /// loses wake-ups fired in the gap. + pub async fn await_drain(&self, id: ChunkId, notify: Arc) { + loop { + // Pre-register the waiter on the Notify queue. From this point + // on, any notify_waiters() call will wake `waiter`, including + // calls that race with the flag read below. + let waiter = notify.notified(); + tokio::pin!(waiter); + + let already = self + .inner + .chunks + .read() + .await + .get(&id) + .is_some_and(|s| s.drained); + if already { + return; + } + + waiter.await; + } + } + + /// Look up the (chunk_id, pk_column, pk_range, low_set, high_set) + /// for every active chunk belonging to the given `(schema, table)`. + /// Used by the consumer to know which chunks an incoming event might + /// affect, without holding the registry lock for the whole + /// event-processing pass. + pub async fn chunks_for_table(&self, schema: &str, table: &str) -> Vec { + self.inner + .chunks + .read() + .await + .iter() + .filter(|(_, s)| s.table.0 == schema && s.table.1 == table) + .map(|(id, s)| ChunkSnapshot { + id: *id, + pk_column: s.pk_column.clone(), + pk_range: s.pk_range.clone(), + low_set: s.low_set.clone(), + high_set: s.high_set.clone(), + }) + .collect() + } + + /// Internal: drop a chunk from the registry. Called by `ChunkHandle::Drop` + /// or directly by the worker when it finishes processing. + pub async fn deregister(&self, id: ChunkId) { + self.inner.chunks.write().await.remove(&id); + } + + /// Number of currently-registered chunks. Test/diagnostics only. + /// (`is_empty` would also need to acquire the read lock, so it is not + /// provided as a "free" alternative; check `len() == 0` if needed.) + #[allow(clippy::len_without_is_empty)] + pub async fn len(&self) -> usize { + self.inner.chunks.read().await.len() + } +} + +/// Read-only snapshot of a chunk used by the consumer to evaluate event +/// membership without holding the registry write lock. +#[derive(Debug, Clone)] +pub struct ChunkSnapshot { + pub id: ChunkId, + pub pk_column: String, + pub pk_range: (Value, Value), + pub low_set: GtidSet, + pub high_set: Option, +} + +/// Returns true iff `pk` is inside the chunk's inclusive PK range using +/// the same comparison logic the snapshot worker uses to build chunks. +/// Single-column primary keys only. +pub fn pk_in_range(pk: &Value, range: &(Value, Value)) -> bool { + cmp_value(pk, &range.0).is_ge() && cmp_value(pk, &range.1).is_le() +} + +fn cmp_value(a: &Value, b: &Value) -> std::cmp::Ordering { + use std::cmp::Ordering; + match (a, b) { + (Value::Int64(x), Value::Int64(y)) => x.cmp(y), + (Value::String(x), Value::String(y)) => x.cmp(y), + (Value::Uuid(x), Value::Uuid(y)) => x.cmp(y), + (Value::Decimal(x), Value::Decimal(y)) => x.cmp(y), + (Value::Timestamp(x), Value::Timestamp(y)) => x.cmp(y), + // Falling back to equality: types we don't know how to order + // are treated as not-in-range, which is conservative (the chunk + // simply emits the snapshot row; no eviction). The snapshot + // module only chunks on integer / string / uuid PKs today. + _ => Ordering::Equal, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + fn empty_set() -> GtidSet { + GtidSet::parse("").unwrap() + } + + #[tokio::test] + async fn register_and_deregister() { + let registry = ActiveChunks::new(); + assert_eq!(registry.len().await, 0); + + let (handle, _notify) = registry + .register( + ("db".into(), "t".into()), + "id".into(), + (Value::Int64(1), Value::Int64(100)), + empty_set(), + ) + .await; + assert_eq!(registry.len().await, 1); + + let id = handle.id(); + registry.deregister(id).await; + assert_eq!(registry.len().await, 0); + std::mem::forget(handle); // we already deregistered manually + } + + #[tokio::test] + async fn record_eviction_idempotent() { + let registry = ActiveChunks::new(); + let (handle, _notify) = registry + .register( + ("db".into(), "t".into()), + "id".into(), + (Value::Int64(1), Value::Int64(100)), + empty_set(), + ) + .await; + + registry + .record_eviction(handle.id(), &Value::Int64(42)) + .await; + registry + .record_eviction(handle.id(), &Value::Int64(42)) + .await; + let evicted = registry.evicted_pks(handle.id()).await; + assert_eq!(evicted.len(), 1); + assert!(evicted.contains(&pk_key(&Value::Int64(42)))); + std::mem::forget(handle); + } + + #[tokio::test] + async fn await_drain_blocks_until_high_watermark_covered() { + let registry = ActiveChunks::new(); + let low = GtidSet::parse("uuid:1-10").unwrap(); + let (handle, notify) = registry + .register( + ("db".into(), "t".into()), + "id".into(), + (Value::Int64(1), Value::Int64(100)), + low, + ) + .await; + let id = handle.id(); + + // No high_set yet, no drain — await_drain must not return. + let registry_clone = registry.clone(); + let notify_clone = notify.clone(); + let handle_id = id; + let waiter = + tokio::spawn(async move { registry_clone.await_drain(handle_id, notify_clone).await }); + + tokio::time::sleep(Duration::from_millis(20)).await; + assert!(!waiter.is_finished(), "must not return without drain"); + + // Set a high watermark; consumer hasn't drained past it yet. + let high = GtidSet::parse("uuid:1-50").unwrap(); + registry.set_high_watermark(id, high.clone()).await; + + // Consumer drains exactly to the high watermark. + registry.try_drain(&high).await; + + tokio::time::timeout(Duration::from_secs(1), waiter) + .await + .expect("await_drain returned within timeout") + .unwrap(); + std::mem::forget(handle); + } + + #[tokio::test] + async fn try_drain_does_not_signal_with_partial_coverage() { + let registry = ActiveChunks::new(); + let (handle, _notify) = registry + .register( + ("db".into(), "t".into()), + "id".into(), + (Value::Int64(1), Value::Int64(100)), + empty_set(), + ) + .await; + registry + .set_high_watermark(handle.id(), GtidSet::parse("uuid:1-100").unwrap()) + .await; + + // Consumer at 1-50 — not enough. + registry + .try_drain(&GtidSet::parse("uuid:1-50").unwrap()) + .await; + let snap = ®istry.chunks_for_table("db", "t").await; + assert!(!snap.is_empty()); + + // Now drained. + registry + .try_drain(&GtidSet::parse("uuid:1-100").unwrap()) + .await; + // (We don't expose `drained` on the snapshot; the await_drain + // test above covers the wake-up path.) + std::mem::forget(handle); + } + + #[tokio::test] + async fn chunks_for_table_filters() { + let registry = ActiveChunks::new(); + let (h1, _) = registry + .register( + ("db".into(), "t1".into()), + "id".into(), + (Value::Int64(1), Value::Int64(50)), + empty_set(), + ) + .await; + let (h2, _) = registry + .register( + ("db".into(), "t2".into()), + "id".into(), + (Value::Int64(1), Value::Int64(50)), + empty_set(), + ) + .await; + let snap = registry.chunks_for_table("db", "t1").await; + assert_eq!(snap.len(), 1); + assert_eq!(snap[0].id, h1.id()); + std::mem::forget(h1); + std::mem::forget(h2); + } + + /// Stresses the race window between `await_drain`'s flag check and the + /// future poll. The pre-Notify-pin code lost wake-ups when `try_drain` + /// fired between those two operations and would hang forever. With the + /// fix, every iteration must complete within a tight timeout. + /// + /// 1000 iterations is enough to hit the race reliably on the old code + /// (manually verified during fix development); 10_000 is overkill but + /// adds margin and still finishes well under the cargo-test budget. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn await_drain_no_lost_wakeup() { + for iter in 0..10_000_u32 { + let registry = ActiveChunks::new(); + let high = GtidSet::parse("uuid:1-50").unwrap(); + let (handle, notify) = registry + .register( + ("db".into(), "t".into()), + "id".into(), + (Value::Int64(1), Value::Int64(100)), + empty_set(), + ) + .await; + let id = handle.id(); + registry.set_high_watermark(id, high.clone()).await; + + let waiter_registry = registry.clone(); + let waiter_notify = notify.clone(); + let waiter = + tokio::spawn(async move { waiter_registry.await_drain(id, waiter_notify).await }); + + // No yield between spawn and try_drain — maximises the chance + // that try_drain's notify_waiters() fires while await_drain is + // mid-flight (between `let waiter = notify.notified()` and the + // flag check, or between the flag check and the await). + registry.try_drain(&high).await; + + tokio::time::timeout(Duration::from_millis(50), waiter) + .await + .unwrap_or_else(|_| panic!("await_drain hung at iteration {}", iter)) + .unwrap(); + std::mem::forget(handle); + } + } + + #[test] + fn pk_in_range_inclusive() { + let r = (Value::Int64(10), Value::Int64(20)); + assert!(pk_in_range(&Value::Int64(10), &r)); + assert!(pk_in_range(&Value::Int64(15), &r)); + assert!(pk_in_range(&Value::Int64(20), &r)); + assert!(!pk_in_range(&Value::Int64(9), &r)); + assert!(!pk_in_range(&Value::Int64(21), &r)); + } + + #[test] + fn pk_in_range_string() { + let r = (Value::String("a".into()), Value::String("m".into())); + assert!(pk_in_range(&Value::String("a".into()), &r)); + assert!(pk_in_range(&Value::String("g".into()), &r)); + assert!(pk_in_range(&Value::String("m".into()), &r)); + assert!(!pk_in_range(&Value::String("z".into()), &r)); + } +} diff --git a/src/engine/snapshot/mod.rs b/src/engine/snapshot/mod.rs index bb35877..d276d0b 100644 --- a/src/engine/snapshot/mod.rs +++ b/src/engine/snapshot/mod.rs @@ -14,6 +14,11 @@ pub mod state_store; pub mod utils; pub mod worker; +#[cfg(feature = "mysql-source")] +pub mod active_chunks; +#[cfg(feature = "mysql-source")] +pub mod mysql; + pub use worker::run_snapshot; /// Quote a SQL identifier to prevent SQL injection. diff --git a/src/engine/snapshot/mysql.rs b/src/engine/snapshot/mysql.rs new file mode 100644 index 0000000..043122f --- /dev/null +++ b/src/engine/snapshot/mysql.rs @@ -0,0 +1,1398 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! MySQL snapshot using the Flink CDC Offset Signal Algorithm. +//! +//! For each chunk `[start_pk, end_pk)` of a MySQL table: +//! LOW GTID → SELECT → HIGH GTID → emit rows → mark chunk COMPLETE. +//! Full Offset Signal with binlog upsert (steps 4–5 of the algorithm) +//! requires binlog stream integration from T3. +//! +//! All code behind `#[cfg(feature = "mysql-source")]`. + +use std::collections::HashMap; +use std::sync::{Arc, RwLock}; + +use anyhow::{Context, Result}; +use mysql_async::prelude::Queryable; +use tokio::sync::{Mutex, Semaphore}; +use tokio::task::JoinSet; +use tracing::{debug, error, info, warn}; + +use crate::config::Config; +use crate::control::state::{CdcState, SharedState, Stage}; +use crate::core::position::SourcePosition; +use crate::core::record::DataType; +use crate::core::record::{CdcRecord, ColumnValue, TableRef, Value}; +use crate::core::traits::{Sink, SourceTableSchema}; +use crate::source::mysql::gtid::GtidSet; +use crate::source::mysql::schema::introspect_mysql_schemas; + +/// Run the full MySQL snapshot for all configured tables. +/// +/// Spawns parallel workers (controlled by `config.snapshot_parallel_workers`) +/// and streams chunks from the producer to workers via an mpsc channel. +/// +/// `sink_factory` creates a fresh `Sink` instance for each parallel worker. +/// `consumer_gtid` is the live, shared view of the binlog consumer's +/// accumulated GTID set — chunk LOW/HIGH watermarks are read from this +/// handle, not from `SELECT @@global.gtid_executed`. See +/// `mysql-cdc-correctness` spec, "snapshot chunks SHALL be registered +/// before the LOW watermark is captured" requirement. +pub async fn run_mysql_snapshot( + config: Arc, + shared_state: Arc, + sink_factory: Arc Result> + Send + Sync>, + active_chunks: crate::engine::snapshot::active_chunks::ActiveChunks, + consumer_gtid: Arc>, +) -> Result<()> { + info!( + "MySQL snapshot worker starting (chunk_size={}, workers={})", + config.snapshot_chunk_size, config.snapshot_parallel_workers + ); + + shared_state.set_snapshot_active(true); + shared_state + .set_stage(Stage::Snapshot, "Connecting to MySQL") + .await; + let snapshot_start = std::time::Instant::now(); + + // 1. Connect to MySQL + let pool = build_mysql_pool(&config.source.url, config.source.mysql()) + .context("MySQL snapshot: failed to create connection pool")?; + { + let mut conn = pool + .get_conn() + .await + .context("MySQL snapshot: failed to connect to MySQL")?; + let version: Vec<(String,)> = conn + .query("SELECT VERSION()") + .await + .context("MySQL snapshot: failed to query version")?; + let version_str = version.first().map(|r| r.0.as_str()).unwrap_or("unknown"); + info!("MySQL snapshot: connected to MySQL {}", version_str); + } + + // 2. Ensure chunk state table exists + ensure_mysql_state_table(&pool) + .await + .context("MySQL snapshot: failed to create state table")?; + + // 3. Introspect table schemas + let schemas = introspect_mysql_schemas(&config.source.url, &config.source.tables) + .await + .context("MySQL snapshot: failed to introspect schemas")?; + info!("MySQL snapshot: introspected {} table(s)", schemas.len()); + + // 4. Create sink instances for parallel workers + let n_workers = (config.snapshot_parallel_workers as usize).max(1); + let mut sink_pool: Vec> = Vec::with_capacity(n_workers); + for i in 0..n_workers { + let sink = sink_factory() + .with_context(|| format!("MySQL snapshot: failed to create sink instance {}", i))?; + sink_pool.push(sink); + } + let sink_pool = Arc::new(Mutex::new(sink_pool)); + + // 5. Pre-compute table metadata + let database_name = + extract_database_name(&config.source.url).unwrap_or_else(|| "dbmazz".to_string()); + let mut table_meta: HashMap = HashMap::new(); + for schema in &schemas { + let qualified = format!("{}.{}", schema.schema, schema.name); + let pk_col = find_mysql_integer_pk(schema); + let col_names: Vec = schema.columns.iter().map(|c| c.name.clone()).collect(); + let col_types: Vec = schema.columns.iter().map(|c| c.data_type.clone()).collect(); + table_meta.insert( + qualified.clone(), + TableMeta { + pk_col, + col_names, + col_types, + }, + ); + } + let table_meta = Arc::new(table_meta); + + // 6. Clear per-table progress + shared_state.clear_table_progress().await; + + // 7. Chunk all tables and stream to workers + let slot_name = database_name; + let _tables = config.source.tables.clone(); + let chunk_size = config.snapshot_chunk_size; + + let qualified_tables: Vec = schemas + .iter() + .map(|s| format!("{}.{}", s.schema, s.name)) + .collect(); + + let semaphore = Arc::new(Semaphore::new(n_workers)); + let (tx, mut rx) = tokio::sync::mpsc::channel::<(String, MysqlChunk)>(n_workers * 2); + + let producer_slot_name = slot_name.clone(); + let producer_table_meta = Arc::clone(&table_meta); + + let producer_pool = pool.clone(); + let producer_shared = Arc::clone(&shared_state); + let producer_tables = qualified_tables.clone(); + let producer = tokio::spawn(async move { + for qualified in &producer_tables { + let meta = match producer_table_meta.get(qualified) { + Some(m) => m, + None => { + warn!( + "MySQL snapshot: no metadata for table {}, skipping", + qualified + ); + continue; + } + }; + + if meta.pk_col.is_empty() { + warn!( + "MySQL snapshot: table {} has no integer PK, skipping chunking", + qualified + ); + // Still register as having 0 chunks so progress indicates it was visited + producer_shared.set_table_chunks_total(qualified, 0).await; + continue; + } + + let chunks = chunk_mysql_table(&producer_pool, qualified, &meta.pk_col, chunk_size) + .await + .unwrap_or_else(|e| { + warn!("MySQL snapshot: failed to chunk table {}: {}", qualified, e); + vec![] + }); + + // Skip already-complete chunks (resumability) + let complete_ids = + load_complete_chunk_ids(&producer_pool, &producer_slot_name, qualified) + .await + .unwrap_or_default(); + + let total = chunks.len(); + let skipped = complete_ids.len(); + info!( + "MySQL snapshot: table {}: {} chunks ({} pending, {} already done)", + qualified, + total, + total - skipped, + skipped + ); + + producer_shared + .set_table_chunks_total(qualified, total as u64) + .await; + + // Insert new chunks into state table (idempotent) + for chunk in &chunks { + upsert_mysql_chunk(&producer_pool, &producer_slot_name, qualified, chunk) + .await + .unwrap_or_else(|e| warn!("MySQL snapshot: upsert_chunk failed: {}", e)); + } + + // Send pending chunks to workers + for chunk in chunks { + if complete_ids.contains(&chunk.partition_id) { + continue; + } + if tx.send((qualified.clone(), chunk)).await.is_err() { + warn!("MySQL snapshot: chunk channel closed"); + return; + } + } + } + }); + + let mut join_set = JoinSet::new(); + while let Some((qualified, chunk)) = rx.recv().await { + let pool = pool.clone(); + let sink_pool = Arc::clone(&sink_pool); + let semaphore = Arc::clone(&semaphore); + let slot_name = slot_name.clone(); + let shared_state = Arc::clone(&shared_state); + let table_meta = Arc::clone(&table_meta); + let active_chunks = active_chunks.clone(); + let consumer_gtid = consumer_gtid.clone(); + + join_set.spawn(async move { + let _permit = semaphore.acquire().await.unwrap(); + + // Respect pause flag + while shared_state.is_snapshot_paused() { + shared_state + .set_stage(Stage::Snapshot, "Paused (outside execution window)") + .await; + tokio::time::sleep(tokio::time::Duration::from_secs(2)).await; + if shared_state.state() == CdcState::Stopped { + return Ok(()); + } + } + shared_state + .set_stage(Stage::Snapshot, "Running MySQL snapshot") + .await; + + let meta = table_meta.get(&qualified).ok_or_else(|| { + anyhow::anyhow!("MySQL snapshot: no metadata for table {}", qualified) + })?; + + let mut sink = match sink_pool.lock().await.pop() { + Some(s) => s, + None => return Err(anyhow::anyhow!("MySQL snapshot: sink pool exhausted")), + }; + + let mut conn = pool + .get_conn() + .await + .context("MySQL snapshot: failed to get connection for chunk")?; + + let result = process_mysql_chunk( + &mut conn, + &mut *sink, + &slot_name, + &qualified, + &chunk, + &shared_state, + meta, + &active_chunks, + &consumer_gtid, + ) + .await; + + sink_pool.lock().await.push(sink); + result + }); + } + + if let Err(e) = producer.await { + error!("MySQL snapshot: producer task panicked: {}", e); + } + + while let Some(result) = join_set.join_next().await { + match result { + Ok(Ok(())) => {} + Ok(Err(e)) => error!("MySQL snapshot: chunk failed: {:#}", e), + Err(e) => error!("MySQL snapshot: chunk task panicked: {}", e), + } + } + + // Flush and close all sinks + let mut pool_lock = sink_pool.lock().await; + for sink in pool_lock.iter_mut() { + if let Err(e) = sink.close().await { + error!("MySQL snapshot: failed to close sink: {:#}", e); + } + } + drop(pool_lock); + + let elapsed = snapshot_start.elapsed(); + let (final_total, final_done) = mysql_chunk_counts(&pool, &slot_name) + .await + .unwrap_or((0, 0)); + let final_rows = mysql_total_rows_synced(&pool, &slot_name) + .await + .unwrap_or(0); + shared_state.update_snapshot_progress(final_total as u64, final_done as u64, final_rows as u64); + + if mysql_all_chunks_complete(&pool, &slot_name) + .await + .unwrap_or(false) + { + info!( + "MySQL snapshot complete: {} chunks, {} rows synced in {:.1}s ({:.0} rows/sec)", + final_total, + final_rows, + elapsed.as_secs_f64(), + final_rows as f64 / elapsed.as_secs_f64().max(0.001) + ); + shared_state.set_snapshot_active(false); + shared_state.set_stage(Stage::Cdc, "Replicating").await; + Ok(()) + } else { + let done = final_done as u64; + let total = final_total as u64; + warn!( + "MySQL snapshot finished with failed chunks ({}/{} complete) in {:.1}s", + done, + total, + elapsed.as_secs_f64() + ); + shared_state.set_snapshot_active(false); + shared_state + .set_stage(Stage::Cdc, "Replicating (snapshot incomplete)") + .await; + Err(anyhow::anyhow!( + "MySQL snapshot incomplete: {} of {} chunks failed", + total.saturating_sub(done), + total + )) + } +} + +// Data structures + +/// A single PK-range chunk for a MySQL table. +#[derive(Debug, Clone)] +struct MysqlChunk { + partition_id: i32, + start_pk: i64, + end_pk: i64, +} + +/// Pre-computed metadata for a snapshot table. +struct TableMeta { + pk_col: String, + col_names: Vec, + col_types: Vec, +} + +// Chunking + +/// Find the first integer primary key column from a `SourceTableSchema`. +/// +/// Returns the column name if found, or an empty string if no integer PK exists. +fn find_mysql_integer_pk(schema: &SourceTableSchema) -> String { + for pk_name in &schema.primary_keys { + for col in &schema.columns { + if col.name == *pk_name && is_integer_data_type(&col.data_type) { + return pk_name.clone(); + } + } + } + String::new() +} + +/// Returns `true` if the DataType is an integer suitable for PK-range chunking. +fn is_integer_data_type(dt: &DataType) -> bool { + matches!(dt, DataType::Int16 | DataType::Int32 | DataType::Int64) +} + +/// Divide a MySQL table into PK-range chunks using `MIN(pk)` / `MAX(pk)`. +/// +/// Returns an empty vec if the table is empty or the PK range is degenerate. +async fn chunk_mysql_table( + pool: &mysql_async::Pool, + qualified_table: &str, + pk_col: &str, + chunk_size: u64, +) -> Result> { + let (schema, table) = split_mysql_table_name(qualified_table); + let quoted_table = format!( + "`{}`.`{}`", + schema.replace('`', "``"), + table.replace('`', "``") + ); + let quoted_pk = quote_mysql_ident(pk_col); + + let mut conn = pool + .get_conn() + .await + .context("MySQL snapshot: failed to get connection for chunking")?; + + // Query MIN and MAX of the PK column + let query = format!( + "SELECT MIN({pk}), MAX({pk}) FROM {table}", + pk = quoted_pk, + table = quoted_table, + ); + let row: mysql_async::Row = conn + .query_first(query) + .await + .context("MySQL snapshot: failed to query MIN/MAX PK")? + .ok_or_else(|| anyhow::anyhow!("MySQL snapshot: MIN/MAX query returned no rows"))?; + + let min_pk: Option = match row.as_ref(0) { + Some(&mysql_async::Value::Int(i)) => Some(i), + Some(&mysql_async::Value::UInt(u)) => Some(u as i64), + Some(&mysql_async::Value::NULL) | None => None, + _ => None, + }; + let max_pk: Option = match row.as_ref(1) { + Some(&mysql_async::Value::Int(i)) => Some(i), + Some(&mysql_async::Value::UInt(u)) => Some(u as i64), + Some(&mysql_async::Value::NULL) | None => None, + _ => None, + }; + + let (min_val, max_val) = match (min_pk, max_pk) { + (Some(min), Some(max)) => (min, max), + _ => { + info!( + "MySQL snapshot: table {} is empty — no chunks produced", + qualified_table + ); + return Ok(vec![]); + } + }; + + // Single-value range + if min_val == max_val { + return Ok(vec![MysqlChunk { + partition_id: 0, + start_pk: min_val, + end_pk: max_val + 1, + }]); + } + + let range_len = (max_val - min_val) as u64 + 1; + let num_chunks = range_len.div_ceil(chunk_size).max(1) as i32; + + let mut chunks = Vec::with_capacity(num_chunks as usize); + let range_f64 = (max_val - min_val) as f64; + let step_f64 = range_f64 / num_chunks as f64; + + for i in 0..num_chunks { + let start = min_val + (i as f64 * step_f64) as i64; + let end = if i == num_chunks - 1 { + max_val + 1 + } else { + min_val + ((i + 1) as f64 * step_f64) as i64 + }; + // Skip degenerate chunks where start >= end (can happen when num_chunks > range) + if start >= end && i < num_chunks - 1 { + continue; + } + chunks.push(MysqlChunk { + partition_id: i, + start_pk: start, + end_pk: end, + }); + } + + info!( + "MySQL snapshot: table {}: pk_col={}, min={}, max={}, range={}, chunk_size={}, chunks={}", + qualified_table, + pk_col, + min_val, + max_val, + range_len, + chunk_size, + chunks.len() + ); + + Ok(chunks) +} + +/// Split a potentially qualified MySQL table name into (schema, table). +fn split_mysql_table_name(name: &str) -> (String, String) { + if name.contains('.') { + let parts: Vec<&str> = name.splitn(2, '.').collect(); + (parts[0].to_string(), parts[1].to_string()) + } else { + ("public".to_string(), name.to_string()) + } +} + +// --------------------------------------------------------------------------- +// Chunk processing (Offset Signal Algorithm) +// --------------------------------------------------------------------------- + +/// Process a single MySQL snapshot chunk: +/// LOW GTID → register chunk → SELECT → HIGH GTID → set high watermark +/// → await drain → filter evicted PKs → emit → mark complete. +/// +/// The reconciliation step (after `await_drain`) implements the read-only +/// DBLog Incremental Snapshot algorithm: every binlog event whose GTID +/// falls in `(LOW, HIGH]` and whose PK is in this chunk's range has +/// already been emitted by the CDC stream consumer, so we drop the +/// matching snapshot row to avoid emitting stale data on top of the +/// fresher binlog event. +// Eight related parameters are passed in once each from a single call site; +// grouping them into a struct just to satisfy the lint would add boilerplate +// without making the function easier to read. +#[allow(clippy::too_many_arguments)] +async fn process_mysql_chunk( + conn: &mut mysql_async::Conn, + sink: &mut dyn Sink, + slot_name: &str, + qualified_table: &str, + chunk: &MysqlChunk, + shared_state: &Arc, + meta: &TableMeta, + active_chunks: &crate::engine::snapshot::active_chunks::ActiveChunks, + consumer_gtid: &Arc>, +) -> Result<()> { + debug!( + "MySQL snapshot: processing chunk {}/{}: pk=[{}, {})", + qualified_table, chunk.partition_id, chunk.start_pk, chunk.end_pk + ); + + let (schema, table) = split_mysql_table_name(qualified_table); + let quoted_table = format!( + "`{}`.`{}`", + schema.replace('`', "``"), + table.replace('`', "``") + ); + let quoted_pk = quote_mysql_ident(&meta.pk_col); + + // Step 1: capture LOW watermark from the binlog consumer's live GTID + // set, NOT from `SELECT @@global.gtid_executed` against the source. + // Using the consumer's view is the only watermark that exactly + // corresponds to "what the consumer has seen so far"; events the + // server has but the consumer hasn't processed yet legitimately fall + // INSIDE the window and must be evaluated for eviction. Reading the + // server would race with the consumer and let those events leak past + // the LOW boundary unevicted (snapshot row would emit on top of the + // CDC update — duplicate emission for the same PK). + // + // Step 1b (atomic with step 1, behind a single read of the lock): + // register the chunk in the active-chunks registry with the LOW set + // we just observed. From this instant onward, every binlog event + // the consumer processes is evaluated against this chunk; events + // BEFORE this instant are in `low_set` and excluded from the window. + let low_set = consumer_gtid + .read() + .expect("consumer_gtid lock poisoned") + .clone(); + let low_truncated = truncate_gtid(&low_set.format()); + + // Range is [start_pk, end_pk) in the chunker; the registry uses an + // inclusive [start, end] range, so the upper bound is end_pk - 1. + let pk_range = ( + crate::core::Value::Int64(chunk.start_pk), + crate::core::Value::Int64(chunk.end_pk - 1), + ); + let (chunk_handle, drain_notify) = active_chunks + .register( + (schema.clone(), table.clone()), + meta.pk_col.clone(), + pk_range, + low_set, + ) + .await; + let chunk_id = chunk_handle.id(); + + // Step 2: SELECT rows for this chunk + let cols_sql: String = meta + .col_names + .iter() + .map(|c| quote_mysql_ident(c)) + .collect::>() + .join(", "); + + let select_query = format!( + "SELECT {cols} FROM {table} WHERE {pk} >= ? AND {pk} < ?", + cols = cols_sql, + table = quoted_table, + pk = quoted_pk, + ); + + let rows: Vec = conn + .exec(select_query, (chunk.start_pk, chunk.end_pk)) + .await + .with_context(|| { + format!( + "MySQL snapshot: SELECT failed for {} chunk {}", + qualified_table, chunk.partition_id + ) + })?; + + let row_count = rows.len() as i64; + + // Step 3: HIGH watermark — again from the consumer's live GTID set. + // Once SELECT returns, the snapshot is "as of" some point in the + // committed history; the consumer's set tells us exactly which + // committed transactions could possibly have raced our SELECT. The + // window is `(LOW, HIGH]` for eviction reconciliation. + let high_set = consumer_gtid + .read() + .expect("consumer_gtid lock poisoned") + .clone(); + let high_gtid = high_set.format(); + let high_truncated = truncate_gtid(&high_gtid); + active_chunks.set_high_watermark(chunk_id, high_set).await; + + info!( + "MySQL snapshot: chunk {}/{}: {} rows, GTID range: {} → {}", + qualified_table, chunk.partition_id, row_count, low_truncated, high_truncated, + ); + + // Step 4: wait until the binlog consumer has drained past HIGH, then + // collect the evicted PK set. After this point the eviction set is + // final — no more binlog event in the chunk's window can arrive. + active_chunks.await_drain(chunk_id, drain_notify).await; + let evicted_pks = active_chunks.evicted_pks(chunk_id).await; + if !evicted_pks.is_empty() { + info!( + "MySQL snapshot: chunk {}/{}: reconciliation evicted {} row(s) overridden by concurrent CDC", + qualified_table, chunk.partition_id, evicted_pks.len() + ); + } + // The handle drops at end of function and deregisters the chunk — + // explicit deregister here keeps the hot path tidy. + active_chunks.deregister(chunk_id).await; + std::mem::forget(chunk_handle); // we already deregistered manually + + // Step 5: Convert rows to CdcRecord::Insert (filtering out evicted + // PKs) and emit via sink. The `position` carried with each row is a + // MysqlBinlog triple anchored at HIGH so checkpoint loaders see a + // valid resume point even if the daemon dies right after this batch. + let pk_idx = meta + .col_names + .iter() + .position(|c| c == &meta.pk_col) + .ok_or_else(|| { + anyhow::anyhow!( + "MySQL snapshot: pk column {} not found in select projection", + meta.pk_col + ) + })?; + + let kept_rows: Vec<&mysql_async::Row> = rows + .iter() + .filter(|row| { + let pk_dt = meta + .col_types + .get(pk_idx) + .cloned() + .unwrap_or(DataType::Int64); + let pk_value = read_mysql_value(row, pk_idx, &pk_dt); + !evicted_pks.contains(&crate::engine::snapshot::active_chunks::pk_key(&pk_value)) + }) + .collect(); + + let kept_count = kept_rows.len() as i64; + + if !kept_rows.is_empty() { + let table_ref = TableRef::new(Some(schema), table); + let position = SourcePosition::MysqlBinlog { + file: String::new(), + position: 0, + gtid_executed: high_gtid.clone(), + }; + + let records: Vec = kept_rows + .iter() + .map(|row| { + let columns: Vec = meta + .col_names + .iter() + .enumerate() + .map(|(i, name)| { + let dt = meta.col_types.get(i).cloned().unwrap_or(DataType::String); + let value = read_mysql_value(row, i, &dt); + ColumnValue::new(name.clone(), value) + }) + .collect(); + + CdcRecord::Insert { + table: table_ref.clone(), + columns, + position: position.clone(), + } + }) + .collect(); + + sink.write_batch(records).await.with_context(|| { + format!( + "MySQL snapshot: sink write failed for {} chunk {}", + qualified_table, chunk.partition_id + ) + })?; + + debug!( + "MySQL snapshot: wrote chunk {}/{}: {} rows via sink ({} evicted)", + qualified_table, + chunk.partition_id, + kept_count, + row_count - kept_count + ); + } + + // Step 6: Mark chunk COMPLETE in state table + mark_mysql_chunk_complete( + conn, + slot_name, + qualified_table, + chunk.partition_id, + row_count, + &high_gtid, + ) + .await + .context("MySQL snapshot: failed to mark chunk complete")?; + + // Update progress counters + let (total, done) = mysql_chunk_counts_for_table(conn, slot_name, qualified_table) + .await + .unwrap_or((0, 0)); + let rows_synced = mysql_rows_synced_for_table(conn, slot_name, qualified_table) + .await + .unwrap_or(0); + shared_state.update_snapshot_progress(total as u64, done as u64, rows_synced as u64); + shared_state + .update_table_progress(qualified_table, done as u64, rows_synced as u64) + .await; + + info!( + "MySQL snapshot: chunk {}/{} complete: {} rows, high_gtid={}", + qualified_table, chunk.partition_id, row_count, high_truncated, + ); + + Ok(()) +} + +/// Read a column value from a MySQL Row. Uses `as_ref` to safely handle NULLs. +fn read_mysql_value(row: &mysql_async::Row, idx: usize, dt: &DataType) -> Value { + let raw = match row.as_ref(idx) { + Some(val) => val, + None => return Value::Null, + }; + match raw { + mysql_async::Value::NULL => Value::Null, + mysql_async::Value::Int(i) => Value::Int64(*i), + mysql_async::Value::UInt(u) => Value::Int64(*u as i64), + mysql_async::Value::Float(f) => Value::Float64(*f as f64), + mysql_async::Value::Double(d) => Value::Float64(*d), + mysql_async::Value::Bytes(b) => { + match dt { + DataType::Int16 | DataType::Int32 | DataType::Int64 => { + // Try to parse the bytes as integer (for DECIMAL stored as bytes) + let s = String::from_utf8_lossy(b); + s.parse::().map_or(Value::Null, Value::Int64) + } + DataType::Float32 | DataType::Float64 => { + let s = String::from_utf8_lossy(b); + s.parse::().map_or(Value::Null, Value::Float64) + } + _ => { + let s = String::from_utf8_lossy(b).to_string(); + Value::String(s) + } + } + } + mysql_async::Value::Date(y, m, d, hh, mm, ss, _) => Value::String(format!( + "{:04}-{:02}-{:02} {:02}:{:02}:{:02}", + y, m, d, hh, mm, ss + )), + mysql_async::Value::Time(is_neg, days, h, m, s, _) => { + if *is_neg { + Value::String(format!("-{} {:02}:{:02}:{:02}", days, h, m, s)) + } else { + Value::String(format!("{} {:02}:{:02}:{:02}", days, h, m, s)) + } + } + } +} + +/// Truncate a GTID string for logging (show first 30 chars). +fn truncate_gtid(gtid: &str) -> String { + if gtid.len() > 30 { + format!("{}...", >id[..30]) + } else { + gtid.to_string() + } +} + +// State table management + +/// Create the `dbmazz_snapshot_state` table in MySQL if it doesn't exist. +async fn ensure_mysql_state_table(pool: &mysql_async::Pool) -> Result<()> { + let mut conn = pool + .get_conn() + .await + .context("MySQL snapshot: failed to get connection for state table")?; + + conn.query_drop( + "CREATE TABLE IF NOT EXISTS dbmazz_snapshot_state ( + slot_name VARCHAR(255) NOT NULL, + table_name VARCHAR(255) NOT NULL, + partition_id INT NOT NULL, + start_pk BIGINT NOT NULL, + end_pk BIGINT NOT NULL, + rows_synced BIGINT NOT NULL DEFAULT 0, + status VARCHAR(20) NOT NULL DEFAULT 'PENDING', + hw_gtid TEXT, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (slot_name, table_name, partition_id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", + ) + .await + .context("MySQL snapshot: failed to create dbmazz_snapshot_state table")?; + + info!("MySQL snapshot: ensured dbmazz_snapshot_state table"); + Ok(()) +} + +/// Insert a chunk into the state table (idempotent). +async fn upsert_mysql_chunk( + pool: &mysql_async::Pool, + slot_name: &str, + table_name: &str, + chunk: &MysqlChunk, +) -> Result<()> { + let mut conn = pool + .get_conn() + .await + .context("MySQL snapshot: failed to get connection for upsert_chunk")?; + + conn.exec_drop( + "INSERT INTO dbmazz_snapshot_state + (slot_name, table_name, partition_id, start_pk, end_pk, status) + VALUES (?, ?, ?, ?, ?, 'PENDING') + ON DUPLICATE KEY UPDATE status=status", + ( + slot_name, + table_name, + chunk.partition_id, + chunk.start_pk, + chunk.end_pk, + ), + ) + .await + .context("MySQL snapshot: failed to upsert chunk")?; + + Ok(()) +} + +/// Mark a chunk as COMPLETE with row count and high-water GTID. +async fn mark_mysql_chunk_complete( + conn: &mut mysql_async::Conn, + slot_name: &str, + table_name: &str, + partition_id: i32, + rows_synced: i64, + hw_gtid: &str, +) -> Result<()> { + conn.exec_drop( + "UPDATE dbmazz_snapshot_state + SET status = 'COMPLETE', rows_synced = ?, hw_gtid = ?, updated_at = NOW() + WHERE slot_name = ? AND table_name = ? AND partition_id = ?", + (rows_synced, hw_gtid, slot_name, table_name, partition_id), + ) + .await + .context("MySQL snapshot: failed to mark chunk complete")?; + + debug!( + "MySQL snapshot: chunk {}.{}/{} complete: {} rows, hw_gtid truncated={}", + slot_name, + table_name, + partition_id, + rows_synced, + truncate_gtid(hw_gtid), + ); + Ok(()) +} + +/// Load partition IDs of COMPLETE chunks for a specific table (resumability). +async fn load_complete_chunk_ids( + pool: &mysql_async::Pool, + slot_name: &str, + table_name: &str, +) -> Result> { + let mut conn = pool + .get_conn() + .await + .context("MySQL snapshot: failed to get connection for load_complete")?; + + let rows: Vec<(i32,)> = conn + .exec( + "SELECT partition_id FROM dbmazz_snapshot_state + WHERE slot_name = ? AND table_name = ? AND status = 'COMPLETE'", + (slot_name, table_name), + ) + .await + .context("MySQL snapshot: failed to load complete chunk IDs")?; + + Ok(rows.into_iter().map(|r| r.0).collect()) +} + +/// Check whether all chunks for a slot are COMPLETE. +async fn mysql_all_chunks_complete(pool: &mysql_async::Pool, slot_name: &str) -> Result { + let mut conn = pool + .get_conn() + .await + .context("MySQL snapshot: failed to get connection for all_complete")?; + + let row: Option<(i64,)> = conn + .exec_first( + "SELECT COUNT(*) FROM dbmazz_snapshot_state + WHERE slot_name = ? AND status != 'COMPLETE'", + (slot_name,), + ) + .await?; + let pending: i64 = row.map(|r| r.0).unwrap_or(0); + Ok(pending == 0) +} + +/// Count total and COMPLETE chunks for a slot. +async fn mysql_chunk_counts(pool: &mysql_async::Pool, slot_name: &str) -> Result<(i64, i64)> { + let mut conn = pool.get_conn().await?; + + let row: Option<(i64, i64)> = conn + .exec_first( + "SELECT COUNT(*), + COALESCE(SUM(CASE WHEN status = 'COMPLETE' THEN 1 ELSE 0 END), 0) + FROM dbmazz_snapshot_state + WHERE slot_name = ?", + (slot_name,), + ) + .await?; + + Ok(row.unwrap_or((0, 0))) +} + +/// Count total and COMPLETE chunks for a specific table. +async fn mysql_chunk_counts_for_table( + conn: &mut mysql_async::Conn, + slot_name: &str, + table_name: &str, +) -> Result<(i64, i64)> { + // MySQL ≤ 8.4 does not support `FILTER (WHERE ...)` (introduced in + // 9.7 innovation, no LTS yet). Use the universal CASE WHEN form. + let row: Option<(i64, i64)> = conn + .exec_first( + "SELECT COALESCE(SUM(CASE WHEN status = 'COMPLETE' THEN 1 ELSE 0 END), 0), + COALESCE(SUM(CASE WHEN status = 'COMPLETE' THEN rows_synced ELSE 0 END), 0) + FROM dbmazz_snapshot_state + WHERE slot_name = ? AND table_name = ?", + (slot_name, table_name), + ) + .await?; + + Ok(row.unwrap_or((0, 0))) +} + +/// Total rows synced across all COMPLETE chunks for a slot. +async fn mysql_total_rows_synced(pool: &mysql_async::Pool, slot_name: &str) -> Result { + let mut conn = pool.get_conn().await?; + + let row: Option<(i64,)> = conn + .exec_first( + "SELECT COALESCE(SUM(rows_synced), 0) + FROM dbmazz_snapshot_state + WHERE slot_name = ? AND status = 'COMPLETE'", + (slot_name,), + ) + .await?; + + Ok(row.map(|r| r.0).unwrap_or(0)) +} + +/// Total rows synced for a specific table. +async fn mysql_rows_synced_for_table( + conn: &mut mysql_async::Conn, + slot_name: &str, + table_name: &str, +) -> Result { + let row: Option<(i64,)> = conn + .exec_first( + "SELECT COALESCE(SUM(rows_synced), 0) + FROM dbmazz_snapshot_state + WHERE slot_name = ? AND table_name = ? AND status = 'COMPLETE'", + (slot_name, table_name), + ) + .await?; + + Ok(row.map(|r| r.0).unwrap_or(0)) +} + +// Connection helpers + +/// Build a `mysql_async::Pool` from the source URL. +fn build_mysql_pool( + url: &str, + mysql_cfg: &crate::config::MysqlSourceConfig, +) -> Result { + let opts = build_mysql_opts(url, mysql_cfg.tls_skip_verify)?; + Ok(mysql_async::Pool::new(opts)) +} + +/// Build `mysql_async::Opts` from a `mysql://` URL. Visible to other +/// MySQL-feature modules (e.g., the replication loop's startup probe). +pub(crate) fn build_mysql_opts(url: &str, tls_skip_verify: bool) -> Result { + let parsed = url::Url::parse(url).context("MySQL snapshot: failed to parse MySQL URL")?; + + anyhow::ensure!( + parsed.scheme() == "mysql", + "MySQL snapshot: unsupported scheme '{}' — expected 'mysql://'", + parsed.scheme() + ); + + let host = parsed.host_str().unwrap_or("localhost"); + let port = parsed.port().unwrap_or(3306); + let user = if !parsed.username().is_empty() { + parsed.username() + } else { + "root" + }; + let password = parsed.password().unwrap_or(""); + let database = parsed.path().trim_start_matches('/'); + + let builder = mysql_async::OptsBuilder::default() + .ip_or_hostname(host) + .tcp_port(port) + .db_name(Some(database)) + .user(Some(user)) + .pass(Some(password)) + .ssl_opts(crate::source::mysql::mysql_ssl_opts(tls_skip_verify)); + + Ok(mysql_async::Opts::from(builder)) +} + +/// Extract the database name from a MySQL URL. +fn extract_database_name(url: &str) -> Option { + let parsed = url::Url::parse(url).ok()?; + let db = parsed.path().trim_start_matches('/'); + if db.is_empty() { + None + } else { + Some(db.to_string()) + } +} + +/// Quote a MySQL identifier by wrapping in backticks. +/// Handles dotted names like `mydb.orders` → `mydb`.`orders`. +fn quote_mysql_ident(name: &str) -> String { + if name.contains('.') { + name.split('.') + .map(|part| format!("`{}`", part.replace('`', "``"))) + .collect::>() + .join(".") + } else { + format!("`{}`", name.replace('`', "``")) + } +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::core::traits::SourceColumn; + + /// Guards against re-introducing the Postgres-only filtered-aggregate + /// clause in SQL that targets MySQL. MySQL ≤ 8.4 rejects that syntax. + /// The pattern is built from runtime concatenation so this test's body + /// does not itself contain the literal it forbids. + #[test] + fn no_postgres_filtered_aggregate_in_mysql_snapshot_sql() { + let src = include_str!("mysql.rs"); + let forbidden = format!("{}{}{}", "FILTER", " (", "WHERE"); + // Skip lines that intentionally describe the pattern (this test's + // own assert text and the comment in mysql_chunk_counts_for_table). + let offending: Vec = src + .lines() + .enumerate() + .filter(|(_, line)| line.contains(&forbidden)) + .filter(|(_, line)| { + !line.contains("MySQL ≤ 8.4") + && !line.contains("does not support") + && !line.trim_start().starts_with("//") + }) + .map(|(i, _)| i + 1) + .collect(); + assert!( + offending.is_empty(), + "MySQL snapshot SQL must not use the Postgres-only filtered \ + aggregate clause; offending lines: {:?}", + offending + ); + } + + fn make_test_schema(name: &str, pk_name: &str, pk_type: DataType) -> SourceTableSchema { + SourceTableSchema { + schema: "testdb".to_string(), + name: name.to_string(), + columns: vec![ + SourceColumn { + name: pk_name.to_string(), + data_type: pk_type, + nullable: false, + pg_type_id: 0, + }, + SourceColumn { + name: "name".to_string(), + data_type: DataType::String, + nullable: true, + pg_type_id: 0, + }, + SourceColumn { + name: "amount".to_string(), + data_type: DataType::Float64, + nullable: true, + pg_type_id: 0, + }, + ], + primary_keys: vec![pk_name.to_string()], + } + } + + // is_integer_data_type tests + + #[test] + fn test_is_integer_data_type_returns_true_for_integers() { + assert!(is_integer_data_type(&DataType::Int16)); + assert!(is_integer_data_type(&DataType::Int32)); + assert!(is_integer_data_type(&DataType::Int64)); + } + + #[test] + fn test_is_integer_data_type_returns_false_for_non_integers() { + assert!(!is_integer_data_type(&DataType::Float64)); + assert!(!is_integer_data_type(&DataType::String)); + assert!(!is_integer_data_type(&DataType::Boolean)); + assert!(!is_integer_data_type(&DataType::Decimal { + precision: 10, + scale: 2 + })); + assert!(!is_integer_data_type(&DataType::Date)); + assert!(!is_integer_data_type(&DataType::Json)); + } + + // find_mysql_integer_pk tests + + #[test] + fn test_find_mysql_integer_pk_bigint() { + let schema = make_test_schema("users", "id", DataType::Int64); + let pk = find_mysql_integer_pk(&schema); + assert_eq!(pk, "id"); + } + + #[test] + fn test_find_mysql_integer_pk_int32() { + let schema = make_test_schema("orders", "order_id", DataType::Int32); + let pk = find_mysql_integer_pk(&schema); + assert_eq!(pk, "order_id"); + } + + #[test] + fn test_find_mysql_integer_pk_prefers_integer_over_float() { + // PK is "id" which is Int64 — should find it + let schema = make_test_schema("products", "id", DataType::Int64); + let pk = find_mysql_integer_pk(&schema); + assert_eq!(pk, "id"); + } + + #[test] + fn test_find_mysql_integer_pk_returns_empty_for_non_integer() { + let schema = SourceTableSchema { + schema: "testdb".to_string(), + name: "events".to_string(), + columns: vec![SourceColumn { + name: "uuid".to_string(), + data_type: DataType::String, + nullable: false, + pg_type_id: 0, + }], + primary_keys: vec!["uuid".to_string()], + }; + let pk = find_mysql_integer_pk(&schema); + assert_eq!(pk, ""); + } + + #[test] + fn test_find_mysql_integer_pk_returns_empty_for_no_pk() { + let schema = SourceTableSchema { + schema: "testdb".to_string(), + name: "nopk".to_string(), + columns: vec![SourceColumn { + name: "id".to_string(), + data_type: DataType::Int64, + nullable: false, + pg_type_id: 0, + }], + primary_keys: vec![], + }; + let pk = find_mysql_integer_pk(&schema); + assert_eq!(pk, ""); + } + + // split_mysql_table_name tests + + #[test] + fn test_split_mysql_table_name_qualified() { + let (schema, table) = split_mysql_table_name("mydb.orders"); + assert_eq!(schema, "mydb"); + assert_eq!(table, "orders"); + } + + #[test] + fn test_split_mysql_table_name_unqualified() { + let (schema, table) = split_mysql_table_name("orders"); + assert_eq!(schema, "public"); + assert_eq!(table, "orders"); + } + + #[test] + fn test_split_mysql_table_name_multi_part() { + let (schema, table) = split_mysql_table_name("a.b.c"); + assert_eq!(schema, "a"); + assert_eq!(table, "b.c"); // splitn(2, '.') delimited + } + + // quote_mysql_ident tests + + #[test] + fn test_quote_mysql_ident_simple() { + assert_eq!(quote_mysql_ident("id"), "`id`"); + assert_eq!(quote_mysql_ident("order_id"), "`order_id`"); + } + + #[test] + fn test_quote_mysql_ident_qualified() { + assert_eq!(quote_mysql_ident("mydb.orders"), "`mydb`.`orders`"); + } + + #[test] + fn test_quote_mysql_ident_escapes_backtick() { + assert_eq!(quote_mysql_ident("table`name"), "`table``name`"); + } + + // build_mysql_opts tests + + #[test] + fn test_build_mysql_opts_full_url() { + let opts = build_mysql_opts("mysql://user:pass@host:3307/mydb", false).unwrap(); + let _ = opts; + } + + #[test] + fn test_build_mysql_opts_defaults() { + let opts = build_mysql_opts("mysql://root@localhost/test", false).unwrap(); + let _ = opts; + } + + #[test] + fn test_build_mysql_opts_invalid_scheme() { + let result = build_mysql_opts("postgres://localhost/db", false); + assert!(result.is_err()); + assert!(result + .unwrap_err() + .to_string() + .contains("unsupported scheme")); + } + + #[test] + fn test_build_mysql_opts_bad_url() { + let result = build_mysql_opts("not-a-url", false); + assert!(result.is_err()); + } + + #[test] + fn test_build_mysql_opts_tls_skip_verify_toggle() { + // Both modes parse successfully — runtime SslOpts are opaque, so + // we only smoke-test the surface here. Behaviour is covered by + // integration tests that exercise the actual TLS handshake. + let _ = build_mysql_opts("mysql://root@localhost/test", true).unwrap(); + let _ = build_mysql_opts("mysql://root@localhost/test", false).unwrap(); + } + + // extract_database_name tests + + #[test] + fn test_extract_database_name_normal() { + assert_eq!( + extract_database_name("mysql://user:pass@host/mydb").as_deref(), + Some("mydb") + ); + } + + #[test] + fn test_extract_database_name_with_port() { + assert_eq!( + extract_database_name("mysql://user:pass@host:3306/mydb").as_deref(), + Some("mydb") + ); + } + + #[test] + fn test_extract_database_name_no_path() { + assert_eq!(extract_database_name("mysql://host"), None); + } + + #[test] + fn test_extract_database_name_bad_url() { + assert_eq!(extract_database_name(""), None); + } + + // truncate_gtid tests + + #[test] + fn test_truncate_gtid_short() { + assert_eq!(truncate_gtid("abc-123"), "abc-123"); + } + + #[test] + fn test_truncate_gtid_long() { + let long = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:1-100"; + let truncated = truncate_gtid(long); + assert!(truncated.len() <= 33); + assert!(truncated.ends_with("...")); + } + + // Chunk logic tests + + #[test] + fn test_extract_column_names() { + let schema = make_test_schema("t", "id", DataType::Int64); + let names: Vec = schema.columns.iter().map(|c| c.name.clone()).collect(); + assert_eq!(names, vec!["id", "name", "amount"]); + } + + #[test] + fn test_chunk_mysql_table_edge_cases() { + // We can't test chunk_mysql_table without a live MySQL connection, + // but we test that the basic arithmetic works via the helper type. + let chunk = MysqlChunk { + partition_id: 0, + start_pk: 0, + end_pk: 100, + }; + assert_eq!(chunk.start_pk, 0); + assert_eq!(chunk.end_pk, 100); + assert_eq!(chunk.partition_id, 0); + } + + // MysqlChunk construction tests + + #[test] + fn test_mysql_chunk_construction() { + let c1 = MysqlChunk { + partition_id: 0, + start_pk: 0, + end_pk: 50000, + }; + assert_eq!(c1.partition_id, 0); + assert!(c1.start_pk < c1.end_pk); + + let c2 = MysqlChunk { + partition_id: 1, + start_pk: 50000, + end_pk: i64::MAX, + }; + assert_eq!(c2.partition_id, 1); + assert!(c2.start_pk < c2.end_pk); + } + + // is_integer_data_type exhaustive tests + + #[test] + fn test_is_integer_data_type_all_variants() { + assert!(is_integer_data_type(&DataType::Int16)); + assert!(is_integer_data_type(&DataType::Int32)); + assert!(is_integer_data_type(&DataType::Int64)); + + assert!(!is_integer_data_type(&DataType::Boolean)); + assert!(!is_integer_data_type(&DataType::Float32)); + assert!(!is_integer_data_type(&DataType::Float64)); + assert!(!is_integer_data_type(&DataType::Decimal { + precision: 10, + scale: 2 + })); + assert!(!is_integer_data_type(&DataType::String)); + assert!(!is_integer_data_type(&DataType::Text)); + assert!(!is_integer_data_type(&DataType::Bytes)); + assert!(!is_integer_data_type(&DataType::Json)); + assert!(!is_integer_data_type(&DataType::Jsonb)); + assert!(!is_integer_data_type(&DataType::Uuid)); + assert!(!is_integer_data_type(&DataType::Date)); + assert!(!is_integer_data_type(&DataType::Time)); + assert!(!is_integer_data_type(&DataType::Timestamp)); + assert!(!is_integer_data_type(&DataType::TimestampTz)); + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..6744c39 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,38 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! dbmazz — Change Data Capture daemon. +//! +//! Reads database write-ahead logs (WAL) and streams changes to supported +//! sinks (StarRocks, PostgreSQL, Snowflake). +//! +//! This library crate is the core of dbmazz. The binary entrypoint +//! in `main.rs` parses configuration and starts the engine. +//! +//! # Organization +//! +//! | Module | Role | +//! |--------|------| +//! | [`config`] | Environment-based configuration | +//! | [`connectors`] | Sink implementations (StarRocks, PG, Snowflake) | +//! | [`control`] | HTTP control plane for worker-agent management | +//! | [`core`] | Generic abstractions (CdcRecord, DataType, Source, Sink) | +//! | [`engine`] | CDC orchestration (setup, run, snapshot) | +//! | [`pipeline`] | Batching + dispatch to sink | +//! | [`replication`] | WAL handling (pgoutput parsing, LSN tracking) | +//! | [`source`] | Source connectors (PostgreSQL, MySQL) | +//! | [`state_store`] | LSN checkpoint persistence | +//! | [`utils`] | Shared utilities | + +#![warn(clippy::all)] + +pub mod config; +pub mod connectors; +pub mod control; +pub mod core; +pub mod engine; +pub mod pipeline; +pub mod replication; +pub mod source; +pub mod state_store; +pub mod utils; diff --git a/src/main.rs b/src/main.rs index 2353448..be5fab6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,22 +3,11 @@ #![warn(clippy::all)] -mod config; -mod connectors; -mod control; -mod core; -mod engine; -mod pipeline; -mod replication; -mod source; -mod state_store; -mod utils; - use anyhow::Result; use dotenvy::dotenv; -use crate::config::Config; -use crate::engine::CdcEngine; +use dbmazz::config::Config; +use dbmazz::engine::CdcEngine; #[tokio::main] async fn main() -> Result<()> { diff --git a/src/pipeline/schema_cache.rs b/src/pipeline/schema_cache.rs index 3718881..4371564 100644 --- a/src/pipeline/schema_cache.rs +++ b/src/pipeline/schema_cache.rs @@ -98,3 +98,9 @@ impl SchemaCache { self.cache.get(&id).map(|s| s.name.clone()) } } + +impl Default for SchemaCache { + fn default() -> Self { + Self::new() + } +} diff --git a/src/replication/mod.rs b/src/replication/mod.rs index a8a313c..da1553d 100644 --- a/src/replication/mod.rs +++ b/src/replication/mod.rs @@ -1,6 +1,7 @@ // Copyright 2025 // Licensed under the Elastic License v2.0 +pub mod pg_stream; mod wal_handler; -pub use wal_handler::{handle_keepalive, handle_xlog_data, parse_replication_message, WalMessage}; +pub use wal_handler::{handle_xlog_data, parse_replication_message, WalMessage}; diff --git a/src/replication/pg_stream.rs b/src/replication/pg_stream.rs new file mode 100644 index 0000000..1d45222 --- /dev/null +++ b/src/replication/pg_stream.rs @@ -0,0 +1,49 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +use anyhow::Result; +use async_trait::async_trait; +use bytes::Bytes; +use futures_util::{SinkExt, StreamExt}; +use std::pin::Pin; +use tokio_postgres::CopyBothDuplex; + +use crate::core::ReplicationStream; + +/// Wraps a PostgreSQL `CopyBothDuplex` stream as a generic `ReplicationStream`. +/// +/// This is the bridge between the tokio-postgres replication protocol and the +/// source-agnostic `ReplicationStream` trait used by the engine. +/// +/// `CopyBothDuplex` uses `pin_project!` internally and is `!Unpin`, so we store +/// it in a `Pin>` to satisfy the `Unpin` requirement of `ReplicationStream`. +pub struct PgReplicationStream { + inner: Pin>>, +} + +impl PgReplicationStream { + pub fn new(inner: CopyBothDuplex) -> Self { + Self { + inner: Box::pin(inner), + } + } +} + +#[async_trait] +impl ReplicationStream for PgReplicationStream { + async fn next_event(&mut self) -> Option>> { + match self.inner.as_mut().next().await { + Some(Ok(bytes)) => Some(Ok(bytes.to_vec())), + Some(Err(e)) => Some(Err(e.into())), + None => None, + } + } + + async fn send_feedback(&mut self, data: &[u8]) -> Result<()> { + self.inner + .as_mut() + .send(Bytes::copy_from_slice(data)) + .await?; + Ok(()) + } +} diff --git a/src/replication/wal_handler.rs b/src/replication/wal_handler.rs index fe5f82f..1fae8ca 100644 --- a/src/replication/wal_handler.rs +++ b/src/replication/wal_handler.rs @@ -187,6 +187,7 @@ async fn extract_int_pk( } /// Handle KeepAlive message +#[allow(dead_code)] pub async fn handle_keepalive( lsn: u64, reply_requested: bool, diff --git a/src/source/mod.rs b/src/source/mod.rs index 12f1ebc..7a34fc6 100644 --- a/src/source/mod.rs +++ b/src/source/mod.rs @@ -1,3 +1,158 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! # Source Connectors +//! +//! Source connector implementations that read change events from upstream +//! databases. Each source implements the `Source` trait from +//! [`crate::core::traits`]. +//! +//! ## Available Sources +//! +//! - **PostgreSQL**: Logical replication via the `pgoutput` plugin +//! (replication slot + publication). +//! - **MySQL** (BETA, behind the `mysql-source` cargo feature): Binlog +//! streaming with GTID-aware checkpoints + the read-only DBLog +//! incremental snapshot algorithm. See `docs/mysql-source.md` for +//! prerequisites, configuration, and the BETA scope. +//! +//! ## Usage +//! +//! ```rust,ignore +//! use crate::source::create_source; +//! +//! let mut source = create_source(&config.source).await?; +//! source.setup(&tables).await?; +//! ``` +//! +//! Mirrors the [`crate::connectors::sinks::create_sink`] factory shape so +//! the engine constructs sources via a single dispatch point regardless +//! of the configured `SourceType`. + pub mod converter; pub mod parser; pub mod postgres; + +#[cfg(feature = "mysql-source")] +pub mod mysql; + +use anyhow::Result; + +use crate::config::{SourceConfig, SourceType}; +use crate::core::Source; + +#[cfg(feature = "mysql-source")] +use self::mysql::MysqlSource; +use self::postgres::PostgresSource; + +/// Creates a source connector based on the provided configuration. +/// +/// Factory function that instantiates the appropriate `Source` +/// implementation based on the `source_type` field. Mirrors the +/// `create_sink` factory in `src/connectors/sinks/mod.rs` so the engine +/// has a single dispatch point per side of the pipeline. +/// +/// # Arguments +/// +/// * `config` — the source configuration (URL, tables, source-type- +/// specific block such as `PostgresSourceConfig` or +/// `MysqlSourceConfig`). +/// +/// # Errors +/// +/// - Returns an error if the configured `SourceType` is not enabled in +/// this build (e.g., `Mysql` without the `mysql-source` cargo feature). +/// - Propagates any connection or validation error from the underlying +/// source constructor. +pub async fn create_source(config: &SourceConfig) -> Result> { + match config.source_type { + SourceType::Postgres => { + let pg = config.postgres(); + let source = PostgresSource::new( + &config.url, + pg.slot_name.clone(), + pg.publication_name.clone(), + ) + .await?; + Ok(Box::new(source)) + } + #[cfg(feature = "mysql-source")] + SourceType::Mysql => { + let mysql_cfg = config.mysql(); + let source = MysqlSource::new(&config.url, mysql_cfg).await?; + Ok(Box::new(source)) + } + #[cfg(not(feature = "mysql-source"))] + SourceType::Mysql => { + anyhow::bail!( + "MySQL source support is not enabled in this build. \ + Rebuild with --features mysql-source." + ) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::{PostgresSourceConfig, SourceConfig}; + + /// Verifies the factory dispatches to the Postgres branch and surfaces + /// connection errors (we don't have a live PG in unit tests, so the + /// constructor will fail on connect — what matters is the dispatch + /// reaches the Postgres branch, not that it succeeds end-to-end). + #[tokio::test] + async fn create_source_dispatches_postgres() { + let config = SourceConfig { + source_type: SourceType::Postgres, + url: "postgres://invalid-host-for-unit-test:5432/none".to_string(), + tables: vec!["t".to_string()], + postgres: Some(PostgresSourceConfig { + slot_name: "test_slot".to_string(), + publication_name: "test_pub".to_string(), + }), + mysql: None, + }; + let result = create_source(&config).await; + // Dispatch reached Postgres; the underlying connect fails (no + // server), which is what we want: the error proves we hit the + // PG branch and didn't, e.g., panic on a missing PG config. + let err = match result { + Err(e) => e.to_string().to_lowercase(), + Ok(_) => panic!("expected create_source to fail without a real PG server"), + }; + assert!( + err.contains("connect") + || err.contains("resolve") + || err.contains("dns") + || err.contains("no such") + || err.contains("address"), + "expected a connection-shaped error, got: {err}" + ); + } + + #[cfg(feature = "mysql-source")] + #[tokio::test] + async fn create_source_dispatches_mysql() { + use crate::config::MysqlSourceConfig; + let config = SourceConfig { + source_type: SourceType::Mysql, + url: "mysql://invalid-host-for-unit-test:3306/none".to_string(), + tables: vec!["t".to_string()], + postgres: None, + mysql: Some(MysqlSourceConfig { + server_id: 5400, + gtid_enabled: true, + tls_skip_verify: false, + }), + }; + // MysqlSource::new doesn't open a connection at construction + // time — it only parses the URL and stashes config. So this + // call should SUCCEED (the connection is opened on `setup()`). + // The assertion verifies we hit the MySQL branch (returns Ok). + let result = create_source(&config).await; + if let Err(e) = result { + panic!("expected MySQL branch to construct without connecting; got: {e}"); + } + } +} diff --git a/src/source/mysql/binlog_stream.rs b/src/source/mysql/binlog_stream.rs new file mode 100644 index 0000000..7394236 --- /dev/null +++ b/src/source/mysql/binlog_stream.rs @@ -0,0 +1,125 @@ +use std::str::FromStr; + +use anyhow::{Context, Result}; +use async_trait::async_trait; +use futures_util::StreamExt; +use mysql_common::packets::Sid; +use mysql_common::proto::MySerialize; +use tracing::{info, warn}; + +use crate::core::ReplicationStream; + +pub struct MysqlBinlogStream { + inner: mysql_async::BinlogStream, +} + +impl MysqlBinlogStream { + /// Open a binlog stream against `conn` using `server_id`. + /// + /// `initial_gtid_set`, when `Some` and non-empty, requests the server + /// to start streaming at the position immediately after the supplied + /// `Gtid_set` — restoring restart correctness from the checkpoint. + /// When `None` or empty, the stream starts from the earliest available + /// binlog (the original behaviour). + pub async fn new( + conn: mysql_async::Conn, + server_id: u32, + initial_gtid_set: Option<&str>, + ) -> Result { + let mut request = mysql_async::BinlogStreamRequest::new(server_id).with_gtid(); + + let owned_sids: Vec> = match initial_gtid_set { + Some(set) if !set.trim().is_empty() => { + let mut parsed = Vec::new(); + for part in set.split(',') { + let part = part.trim(); + if part.is_empty() { + continue; + } + match Sid::from_str(part) { + Ok(sid) => parsed.push(sid), + Err(e) => { + warn!( + "Failed to parse Gtid_set fragment '{}': {} — \ + ignoring this fragment for resume", + part, e + ); + } + } + } + parsed + } + _ => Vec::new(), + }; + if !owned_sids.is_empty() { + request = request.with_gtid_set(owned_sids.clone()); + info!( + "MySQL binlog stream resuming with {} GTID source(s)", + owned_sids.len() + ); + } + + let stream: mysql_async::BinlogStream = conn + .get_binlog_stream(request) + .await + .context("Failed to start MySQL binlog stream")?; + info!("MySQL binlog stream started (server_id: {})", server_id); + Ok(Self { inner: stream }) + } + + /// Returns the next typed binlog event as parsed by mysql_async's EventStreamReader. + pub async fn next_event_typed( + &mut self, + ) -> Option> { + let result = self.inner.next().await?; + Some(match result { + Ok(event) => Ok(event), + Err(e) => Err(anyhow::anyhow!("Binlog stream error: {}", e)), + }) + } + + /// Resolve schema + table name for a table_id from the internal TME cache. + pub fn get_table_name(&self, table_id: u64) -> Option<(String, String)> { + self.inner.get_tme(table_id).map(|tme| { + let schema = tme.database_name().to_string(); + let table = tme.table_name().to_string(); + (schema, table) + }) + } + + /// Consume self and return the inner BinlogStream (for direct typed access). + pub fn into_inner(self) -> mysql_async::BinlogStream { + self.inner + } + + /// Get raw column type codes for a table_id from the internal TME cache. + pub fn get_column_types(&self, table_id: u64) -> Option> { + self.inner.get_tme(table_id).map(|tme| { + (0..tme.columns_count() as usize) + .filter_map(|i| tme.get_raw_column_type(i).ok().flatten()) + .map(|ct| ct as u8) + .collect() + }) + } +} + +#[async_trait] +impl ReplicationStream for MysqlBinlogStream { + async fn next_event(&mut self) -> Option>> { + let result = self.inner.next().await?; + Some(match result { + Ok(event) => { + let header = event.header(); + let mut buf = Vec::new(); + header.serialize(&mut buf); + buf.extend_from_slice(event.data()); + Ok(buf) + } + Err(e) => Err(anyhow::anyhow!("Binlog stream error: {}", e)), + }) + } + + async fn send_feedback(&mut self, _data: &[u8]) -> Result<()> { + Ok(()) + } +} diff --git a/src/source/mysql/converter.rs b/src/source/mysql/converter.rs new file mode 100644 index 0000000..5b53fd1 --- /dev/null +++ b/src/source/mysql/converter.rs @@ -0,0 +1,461 @@ +use mysql_common::binlog::value::BinlogValue; +use mysql_common::value::Value as MysqlValue; + +use crate::core::record::{CdcRecord, ColumnValue, TableRef, Value}; +use anyhow::Result; + +use super::parser::BinlogEvent; + +/// Convert a parsed BinlogEvent (with typed BinlogValue rows) to CdcRecords. +pub fn convert_to_cdc_records(event: &BinlogEvent) -> Result> { + Ok(match event { + BinlogEvent::Insert { + schema_name, + table_name, + rows, + col_names, + col_types, + position, + .. + } => { + if rows.is_empty() { + vec![CdcRecord::Insert { + table: TableRef::new(Some(schema_name.clone()), table_name.clone()), + columns: vec![], + position: position.clone(), + }] + } else { + let mut records = Vec::with_capacity(rows.len()); + for row_values in rows { + let cols = decode_row_values(row_values, col_names, col_types); + records.push(CdcRecord::Insert { + table: TableRef::new(Some(schema_name.clone()), table_name.clone()), + columns: cols, + position: position.clone(), + }); + } + records + } + } + BinlogEvent::Update { + schema_name, + table_name, + before_rows, + after_rows, + col_names, + col_types, + position, + .. + } => { + if before_rows.is_empty() && after_rows.is_empty() { + vec![CdcRecord::Update { + table: TableRef::new(Some(schema_name.clone()), table_name.clone()), + old_columns: None, + new_columns: vec![], + position: position.clone(), + }] + } else { + let mut records = Vec::with_capacity(before_rows.len().max(after_rows.len())); + let pairs = before_rows.iter().zip(after_rows.iter()); + for (before, after) in pairs { + let old_cols = decode_row_values(before, col_names, col_types); + let new_cols = decode_row_values(after, col_names, col_types); + records.push(CdcRecord::Update { + table: TableRef::new(Some(schema_name.clone()), table_name.clone()), + old_columns: Some(old_cols), + new_columns: new_cols, + position: position.clone(), + }); + } + records + } + } + BinlogEvent::Delete { + schema_name, + table_name, + rows, + col_names, + col_types, + position, + .. + } => { + if rows.is_empty() { + vec![CdcRecord::Delete { + table: TableRef::new(Some(schema_name.clone()), table_name.clone()), + columns: vec![], + position: position.clone(), + }] + } else { + let mut records = Vec::with_capacity(rows.len()); + for row_values in rows { + let cols = decode_row_values(row_values, col_names, col_types); + records.push(CdcRecord::Delete { + table: TableRef::new(Some(schema_name.clone()), table_name.clone()), + columns: cols, + position: position.clone(), + }); + } + records + } + } + BinlogEvent::Begin { .. } => vec![CdcRecord::Begin { xid: 0 }], + BinlogEvent::Commit { position, .. } => vec![CdcRecord::Commit { + xid: 0, + position: position.clone(), + commit_timestamp_us: 0, + }], + BinlogEvent::Heartbeat { position } => vec![CdcRecord::Heartbeat { + position: position.clone(), + }], + BinlogEvent::TableMap { .. } => vec![], + BinlogEvent::Ddl { .. } => vec![], + }) +} + +/// Relevant MySQL column type codes used to dispatch value formatting +/// for types where the wire representation alone is ambiguous (e.g. +/// `TIMESTAMP` arrives as an `Int(epoch_seconds)` indistinguishable +/// from a plain `INT` column unless we consult the column type code +/// from the preceding TableMapEvent). +/// +/// Source: `mysql_common::binlog::consts::ColumnType`. Replicated as +/// `u8` constants here so we don't drag the enum through the value- +/// mapping hot path. +const MYSQL_TYPE_TIMESTAMP: u8 = 0x07; +const MYSQL_TYPE_TIMESTAMP2: u8 = 0x11; + +/// Map a typed BinlogValue to our generic Value, dispatching on the +/// MySQL column type code where the wire representation is ambiguous. +/// +/// `col_type` comes from the preceding TableMapEvent (parser.rs +/// extract_col_types). For columns we couldn't resolve a type for +/// (UNKNOWN_COLUMN_TYPE sentinel), the dispatch falls through to the +/// default arms. +fn map_binlog_value(bv: &BinlogValue<'static>, col_type: u8) -> Value { + match bv { + BinlogValue::Value(val) => map_mysql_value(val, col_type), + BinlogValue::Jsonb(val) => match serde_json::Value::try_from(val.clone()) { + Ok(json) => Value::Json(json.to_string()), + Err(_) => Value::Json("{}".to_string()), + }, + BinlogValue::JsonDiff(_) => Value::Json("{}".to_string()), + } +} + +/// Map `mysql_common::Value` to our generic `Value`, dispatching on the +/// MySQL column type code for ambiguous wire representations. +/// +/// **TIMESTAMP / TIMESTAMP2** arrive as `MysqlValue::Int(epoch_seconds)` +/// — indistinguishable from a plain `INT` column at the wire level. We +/// consult `col_type` to format them as ISO-8601 strings the downstream +/// PG sink can cast to `TIMESTAMP WITH TIME ZONE`. Without this, every +/// row containing a TIMESTAMP column fails the sink's MERGE cast and +/// nothing lands in the target. +/// +/// **DATETIME** already arrives as a structured `MysqlValue::Date` and +/// is formatted independently of `col_type`. +/// +/// This is the minimum-viable temporal fidelity for MySQL beta. The +/// proper fix (`Value::Timestamp(i64 micros)` with `tz_aware`) is +/// scoped to `mysql-cdc-beta-to-ga`. Today's String-encoded ISO is +/// forward-compatible: the upcoming sink-side typed binding will +/// recognise both shapes during the transition. +fn map_mysql_value(val: &MysqlValue, col_type: u8) -> Value { + match val { + MysqlValue::NULL => Value::Null, + MysqlValue::Int(i) => match col_type { + MYSQL_TYPE_TIMESTAMP | MYSQL_TYPE_TIMESTAMP2 => format_epoch_as_iso(*i), + _ => Value::Int64(*i), + }, + MysqlValue::UInt(u) => match col_type { + MYSQL_TYPE_TIMESTAMP | MYSQL_TYPE_TIMESTAMP2 => format_epoch_as_iso(*u as i64), + _ => Value::Int64(*u as i64), + }, + MysqlValue::Float(f) => Value::Float64(*f as f64), + MysqlValue::Double(d) => Value::Float64(*d), + MysqlValue::Bytes(b) => { + // Empirical observation: mysql_common 0.32.4 in binlog mode + // returns TIMESTAMP/TIMESTAMP2 columns as `MysqlValue::Bytes` + // containing the ASCII epoch (e.g. b"1778368097"), not as + // `MysqlValue::Int`. Catch that path so the downstream sink + // sees an ISO timestamp string instead of the raw epoch. + if matches!(col_type, MYSQL_TYPE_TIMESTAMP | MYSQL_TYPE_TIMESTAMP2) { + if let Ok(s) = std::str::from_utf8(b) { + if let Ok(epoch) = s.parse::() { + return format_epoch_as_iso(epoch); + } + } + } + match String::from_utf8(b.clone()) { + Ok(s) => Value::String(s), + Err(_) => Value::Bytes(b.clone()), + } + } + MysqlValue::Date(y, m, d, hh, mm, ss, _us) => Value::String(format!( + "{:04}-{:02}-{:02} {:02}:{:02}:{:02}", + y, m, d, hh, mm, ss + )), + MysqlValue::Time(is_neg, days, h, m, s, _us) => { + if *is_neg { + Value::String(format!("-{} {}:{:02}:{:02}", days, h, m, s)) + } else { + Value::String(format!("{} {}:{:02}:{:02}", days, h, m, s)) + } + } + } +} + +/// Format a unix epoch (seconds) as an ISO-8601 UTC timestamp string the +/// PG / Snowflake / StarRocks sinks can cast to a timestamp column. +/// +/// MySQL TIMESTAMP is always stored UTC internally regardless of the +/// session timezone, so `from_timestamp` with UTC is the correct mapping. +fn format_epoch_as_iso(epoch_seconds: i64) -> Value { + use chrono::DateTime; + match DateTime::from_timestamp(epoch_seconds, 0) { + Some(dt) => Value::String(dt.format("%Y-%m-%d %H:%M:%S").to_string()), + // chrono only fails for values outside MIN..=MAX (~262k years + // before/after epoch). Surface as Null with a structured log + // rather than panic; the row still flows. + None => { + tracing::warn!( + epoch_seconds, + "MySQL TIMESTAMP value outside chrono representable range; emitting NULL" + ); + Value::Null + } + } +} + +/// Decode a Vec into Vec using column names +/// and the MySQL column type codes from the TableMapEvent. +/// +/// `col_types` MUST be the same length as `col_names` (both come from +/// schema introspection / TableMapEvent in lockstep). When a row has +/// fewer values than expected (binlog protocol oddity), the loop +/// truncates to the shortest of the three slices. +fn decode_row_values( + row_values: &[BinlogValue<'static>], + col_names: &[String], + col_types: &[u8], +) -> Vec { + let num = row_values.len().min(col_names.len()).min(col_types.len()); + let mut columns = Vec::with_capacity(num); + for i in 0..num { + let value = map_binlog_value(&row_values[i], col_types[i]); + columns.push(ColumnValue::new(col_names[i].clone(), value)); + } + columns +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::core::SourcePosition; + + fn v_int(i: i64) -> BinlogValue<'static> { + BinlogValue::Value(MysqlValue::Int(i)) + } + + fn v_str(s: &str) -> BinlogValue<'static> { + BinlogValue::Value(MysqlValue::Bytes(s.as_bytes().to_vec())) + } + + fn v_float(f: f32) -> BinlogValue<'static> { + BinlogValue::Value(MysqlValue::Float(f)) + } + + fn v_double(d: f64) -> BinlogValue<'static> { + BinlogValue::Value(MysqlValue::Double(d)) + } + + /// MySQL type code constants for tests (mirror the private consts). + const MYSQL_TYPE_LONG: u8 = 0x03; // INT + const MYSQL_TYPE_VARCHAR: u8 = 0x0f; // VARCHAR + const MYSQL_TYPE_TIMESTAMP_T: u8 = 0x07; + const MYSQL_TYPE_TIMESTAMP2_T: u8 = 0x11; + const MYSQL_TYPE_FLOAT: u8 = 0x04; + const MYSQL_TYPE_DOUBLE: u8 = 0x05; + + #[test] + fn test_decode_row_values_simple() { + let col_names = vec!["id".to_string(), "name".to_string()]; + let col_types = vec![MYSQL_TYPE_LONG, MYSQL_TYPE_VARCHAR]; + let row = vec![v_int(42), v_str("hi")]; + let cols = decode_row_values(&row, &col_names, &col_types); + assert_eq!(cols.len(), 2); + assert_eq!(cols[0].name, "id"); + assert_eq!(cols[0].value, Value::Int64(42)); + assert_eq!(cols[1].name, "name"); + assert_eq!(cols[1].value, Value::String("hi".to_string())); + } + + #[test] + fn test_decode_row_values_empty() { + let cols = decode_row_values(&[], &[], &[]); + assert!(cols.is_empty()); + } + + #[test] + fn test_bytes_for_timestamp_column_emits_iso() { + // mysql_common 0.32.4 in binlog mode returns TIMESTAMP as + // ASCII-epoch bytes, not as Int. Catch that path too. + let col_names = vec!["created_at".to_string()]; + let col_types = vec![MYSQL_TYPE_TIMESTAMP_T]; + let row = vec![BinlogValue::Value(MysqlValue::Bytes( + b"1778368097".to_vec(), + ))]; + let cols = decode_row_values(&row, &col_names, &col_types); + assert_eq!( + cols[0].value, + Value::String("2026-05-09 23:08:17".to_string()) + ); + } + + #[test] + fn test_int_for_timestamp_column_emits_iso() { + // 1778368097 = 2026-05-09 23:08:17 UTC + let col_names = vec!["created_at".to_string()]; + let col_types = vec![MYSQL_TYPE_TIMESTAMP_T]; + let row = vec![v_int(1778368097)]; + let cols = decode_row_values(&row, &col_names, &col_types); + assert_eq!(cols.len(), 1); + assert_eq!( + cols[0].value, + Value::String("2026-05-09 23:08:17".to_string()) + ); + } + + #[test] + fn test_int_for_timestamp2_column_emits_iso() { + let col_names = vec!["updated_at".to_string()]; + let col_types = vec![MYSQL_TYPE_TIMESTAMP2_T]; + let row = vec![v_int(0)]; // 1970-01-01 00:00:00 UTC + let cols = decode_row_values(&row, &col_names, &col_types); + assert_eq!( + cols[0].value, + Value::String("1970-01-01 00:00:00".to_string()) + ); + } + + #[test] + fn test_int_for_plain_int_column_stays_int() { + // Same Int(value) payload, but col_type is INT — must NOT + // be reinterpreted as a timestamp. + let col_names = vec!["count".to_string()]; + let col_types = vec![MYSQL_TYPE_LONG]; + let row = vec![v_int(1778368097)]; + let cols = decode_row_values(&row, &col_names, &col_types); + assert_eq!(cols[0].value, Value::Int64(1778368097)); + } + + #[test] + #[allow(clippy::approx_constant)] // arbitrary test values, not π/e + fn test_decode_row_values_float_double() { + let col_names = vec!["f".to_string(), "d".to_string()]; + let col_types = vec![MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE]; + let row = vec![v_float(3.14), v_double(2.71828)]; + let cols = decode_row_values(&row, &col_names, &col_types); + assert_eq!(cols.len(), 2); + assert_eq!(cols[0].name, "f"); + assert!( + (match &cols[0].value { + Value::Float64(v) => *v, + _ => 0.0, + } - 3.14) + .abs() + < 0.001 + ); + assert_eq!(cols[1].name, "d"); + assert!( + (match &cols[1].value { + Value::Float64(v) => *v, + _ => 0.0, + } - 2.71828) + .abs() + < 0.001 + ); + } + + #[test] + fn test_convert_insert_event() { + let event = BinlogEvent::Insert { + table_id: 1, + schema_name: "test".to_string(), + table_name: "users".to_string(), + rows: vec![vec![v_int(42), v_str("hi")]], + col_names: vec!["id".to_string(), "name".to_string()], + col_types: vec![3, 15], + position: SourcePosition::GtidSet("1".to_string()), + }; + + let records = convert_to_cdc_records(&event).unwrap(); + assert_eq!(records.len(), 1); + match &records[0] { + CdcRecord::Insert { table, columns, .. } => { + assert_eq!(table.qualified_name(), "test.users"); + assert_eq!(columns.len(), 2); + assert_eq!(columns[0].name, "id"); + assert_eq!(columns[0].value, Value::Int64(42)); + assert_eq!(columns[1].name, "name"); + assert_eq!(columns[1].value, Value::String("hi".to_string())); + } + _ => panic!("Expected Insert"), + } + } + + #[test] + fn test_convert_update_event() { + let event = BinlogEvent::Update { + table_id: 1, + schema_name: "test".to_string(), + table_name: "t".to_string(), + before_rows: vec![vec![v_int(10)]], + after_rows: vec![vec![v_int(20)]], + col_names: vec!["id".to_string()], + col_types: vec![3], + position: SourcePosition::GtidSet("1".to_string()), + }; + + let records = convert_to_cdc_records(&event).unwrap(); + assert_eq!(records.len(), 1); + match &records[0] { + CdcRecord::Update { + old_columns, + new_columns, + .. + } => { + let old = old_columns.as_ref().unwrap(); + let new = new_columns; + assert_eq!(old.len(), 1); + assert_eq!(old[0].value, Value::Int64(10)); + assert_eq!(new.len(), 1); + assert_eq!(new[0].value, Value::Int64(20)); + } + _ => panic!("Expected Update"), + } + } + + #[test] + fn test_convert_delete_event() { + let event = BinlogEvent::Delete { + table_id: 1, + schema_name: "test".to_string(), + table_name: "t".to_string(), + rows: vec![vec![v_int(99)]], + col_names: vec!["id".to_string()], + col_types: vec![3], + position: SourcePosition::GtidSet("1".to_string()), + }; + + let records = convert_to_cdc_records(&event).unwrap(); + assert_eq!(records.len(), 1); + match &records[0] { + CdcRecord::Delete { columns, .. } => { + assert_eq!(columns.len(), 1); + assert_eq!(columns[0].value, Value::Int64(99)); + } + _ => panic!("Expected Delete"), + } + } +} diff --git a/src/source/mysql/gtid.rs b/src/source/mysql/gtid.rs new file mode 100644 index 0000000..1113694 --- /dev/null +++ b/src/source/mysql/gtid.rs @@ -0,0 +1,523 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! MySQL GTID set parsing and comparison. +//! +//! Provides [`GtidSet`] for parsing GTID set strings +//! (`UUID1:N1[-M1],UUID2:N2[-M2]`) and set membership checks +//! used by the Offset Signal Algorithm (T6). + +use std::collections::HashMap; + +use anyhow::{Context, Result}; + +/// A single GTID with a source UUID and transaction number. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Gtid { + pub uuid: String, + pub transaction_id: u64, +} + +/// A contiguous range of GTIDs for the same source UUID, inclusive on both ends. +#[derive(Debug, Clone)] +pub struct GtidInterval { + pub uuid: String, + pub start: u64, + pub end: u64, +} + +/// A parsed MySQL GTID set — map from UUID to inclusive `(start, end)` intervals. +/// +/// Parsed order is preserved; intervals may overlap. +/// An empty or whitespace-only string parses to an empty set. +#[derive(Debug, Clone, Default)] +pub struct GtidSet { + pub intervals: HashMap>, +} + +impl GtidSet { + /// Parse a GTID set string (`UUID1:N1[-M1],UUID2:N2[-M2]`). + /// + /// # Errors + /// + /// Returns an error if the format is invalid or transaction IDs are not valid [`u64`] values. + pub fn parse(s: &str) -> Result { + let mut intervals: HashMap> = HashMap::new(); + + let s = s.trim(); + if s.is_empty() { + return Ok(Self { intervals }); + } + + for part in s.split(',') { + let part = part.trim(); + if part.is_empty() { + continue; + } + + // Split by ':' to get UUID and interval(s) + let colon_pos = part + .find(':') + .context("Invalid GTID format: missing colon")?; + let uuid = part[..colon_pos].to_string(); + let range_str = &part[colon_pos + 1..]; + + let entry = intervals.entry(uuid).or_default(); + + for range_part in range_str.split(':') { + let range_part = range_part.trim(); + if range_part.is_empty() { + continue; + } + + if let Some(dash_pos) = range_part.find('-') { + let start: u64 = range_part[..dash_pos] + .parse() + .context("Invalid GTID interval start")?; + let end: u64 = range_part[dash_pos + 1..] + .parse() + .context("Invalid GTID interval end")?; + entry.push((start, end)); + } else { + let single: u64 = range_part + .parse() + .context("Invalid GTID transaction number")?; + entry.push((single, single)); + } + } + } + + Ok(Self { intervals }) + } + + /// Check if a single GTID (`UUID:N`) is in this set. + pub fn contains(&self, uuid: &str, transaction_id: u64) -> bool { + if let Some(ranges) = self.intervals.get(uuid) { + for &(start, end) in ranges { + if transaction_id >= start && transaction_id <= end { + return true; + } + } + } + false + } + + /// Convenience wrapper around [`contains`](Self::contains) that parses a `UUID:N` string. + /// + /// # Errors + /// + /// Returns an error if the GTID string is malformed. + pub fn contains_gtid_str(&self, gtid_str: &str) -> Result { + let colon_pos = gtid_str + .find(':') + .context("Invalid GTID format: missing colon")?; + let uuid = >id_str[..colon_pos]; + let txn: u64 = gtid_str[colon_pos + 1..] + .parse() + .context("Invalid GTID transaction number")?; + Ok(self.contains(uuid, txn)) + } + + /// Returns `true` if the GTID is in `(low_set, high_set]` — not in `low_set` but in `high_set`. + /// + /// Core predicate of the Offset Signal Algorithm (T6) for determining + /// whether a transaction falls within a delta window between two GTID sets. + /// + /// # Errors + /// + /// Returns an error if any input strings are malformed. + pub fn gtid_in_range(gtid_str: &str, low_set: &str, high_set: &str) -> Result { + let colon_pos = gtid_str.find(':').context("Invalid GTID format")?; + let uuid = >id_str[..colon_pos]; + let txn: u64 = gtid_str[colon_pos + 1..] + .parse() + .context("Invalid GTID transaction number")?; + + let low = GtidSet::parse(low_set)?; + let high = GtidSet::parse(high_set)?; + + Ok(!low.contains(uuid, txn) && high.contains(uuid, txn)) + } + + /// Append a single GTID `(uuid, transaction_id)` to this set. + /// + /// If the new transaction is contiguous with the last interval for that + /// UUID (i.e. `last.end + 1 == transaction_id`), the interval is extended + /// in place. Otherwise a new singleton interval is added. This keeps the + /// serialized form compact for the common case of monotonic GTID + /// streaming from a single source. + pub fn add_gtid(&mut self, uuid: String, transaction_id: u64) { + let entry = self.intervals.entry(uuid).or_default(); + if let Some(last) = entry.last_mut() { + if last.1 + 1 == transaction_id { + last.1 = transaction_id; + return; + } + if transaction_id >= last.0 && transaction_id <= last.1 { + // Already covered; idempotent on duplicate event delivery. + return; + } + } + entry.push((transaction_id, transaction_id)); + } + + /// Returns `true` if the set has no entries. + pub fn is_empty(&self) -> bool { + self.intervals.values().all(|v| v.is_empty()) + } + + /// Returns `true` iff every `(uuid, txn)` covered by `other` is also + /// covered by `self`. Used by the DBLog incremental snapshot + /// reconciliation (T4) to detect when the binlog stream consumer has + /// drained past a chunk's HIGH watermark. + /// + /// Complexity: O(I·log I) per UUID where I is the interval count for + /// that UUID, independent of the transaction-id ranges. We never + /// iterate individual GTID numbers — that would blow up for sources + /// that have executed millions of transactions. + pub fn is_superset_of(&self, other: &GtidSet) -> bool { + for (uuid, other_ranges) in &other.intervals { + let self_ranges = match self.intervals.get(uuid) { + Some(r) if !r.is_empty() => r, + _ => return false, + }; + + // Sort and coalesce self's intervals for this UUID once. + let mut sorted = self_ranges.clone(); + sorted.sort_by_key(|&(s, _)| s); + let mut merged: Vec<(u64, u64)> = Vec::with_capacity(sorted.len()); + for r in sorted { + if let Some(last) = merged.last_mut() { + if r.0 <= last.1.saturating_add(1) { + last.1 = last.1.max(r.1); + continue; + } + } + merged.push(r); + } + + for &(o_start, o_end) in other_ranges { + let covered = merged.iter().any(|&(s, e)| s <= o_start && o_end <= e); + if !covered { + return false; + } + } + } + true + } + + /// Format the GTID set into its canonical string representation (UUIDs are sorted lexicographically). + pub fn format(&self) -> String { + let mut parts = Vec::new(); + let mut uuids: Vec<&String> = self.intervals.keys().collect(); + uuids.sort(); + for uuid in uuids { + if let Some(ranges) = self.intervals.get(uuid.as_str()) { + let range_strs: Vec = ranges + .iter() + .map(|&(start, end)| { + if start == end { + format!("{}", start) + } else { + format!("{}-{}", start, end) + } + }) + .collect(); + parts.push(format!("{}:{}", uuid, range_strs.join(":"))); + } + } + parts.join(",") + } +} + +impl std::fmt::Display for GtidSet { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.format()) + } +} + +impl std::str::FromStr for GtidSet { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + GtidSet::parse(s) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_parse_single_gtid() { + let set = GtidSet::parse("3E11FA47-71CA-11E7-81E2-2115B5C6C7F5:1").unwrap(); + assert!(set.contains("3E11FA47-71CA-11E7-81E2-2115B5C6C7F5", 1)); + assert!(!set.contains("3E11FA47-71CA-11E7-81E2-2115B5C6C7F5", 2)); + } + + #[test] + fn test_parse_interval() { + let set = GtidSet::parse("3E11FA47-71CA-11E7-81E2-2115B5C6C7F5:1-100").unwrap(); + assert!(set.contains("3E11FA47-71CA-11E7-81E2-2115B5C6C7F5", 1)); + assert!(set.contains("3E11FA47-71CA-11E7-81E2-2115B5C6C7F5", 50)); + assert!(set.contains("3E11FA47-71CA-11E7-81E2-2115B5C6C7F5", 100)); + assert!(!set.contains("3E11FA47-71CA-11E7-81E2-2115B5C6C7F5", 101)); + } + + #[test] + fn test_parse_multiple_uuids() { + let set = GtidSet::parse("uuid1:1-10,uuid2:20-30").unwrap(); + assert!(set.contains("uuid1", 5)); + assert!(!set.contains("uuid1", 15)); + assert!(set.contains("uuid2", 25)); + assert!(!set.contains("uuid2", 35)); + } + + #[test] + fn test_multiple_intervals_same_uuid() { + let set = GtidSet::parse("uuid:1-10:20-30").unwrap(); + assert!(set.contains("uuid", 5)); + assert!(!set.contains("uuid", 15)); + assert!(set.contains("uuid", 25)); + assert!(!set.contains("uuid", 35)); + } + + #[test] + fn test_gtid_in_range() { + // 127 is in (1-100, 1-153] — NOT in low_set, IS in high_set + let result = GtidSet::gtid_in_range("uuid:127", "uuid:1-100", "uuid:1-153").unwrap(); + assert!(result); + + // 50 IS in low_set, so NOT in (low_set, high_set] + let result2 = GtidSet::gtid_in_range("uuid:50", "uuid:1-100", "uuid:1-153").unwrap(); + assert!(!result2); + + // 200 is NOT in high_set, so NOT in (low_set, high_set] + let result3 = GtidSet::gtid_in_range("uuid:200", "uuid:1-100", "uuid:1-153").unwrap(); + assert!(!result3); + } + + #[test] + fn test_gtid_in_range_different_uuids() { + // Different UUID in low vs high — GTID only in high_set + let result = GtidSet::gtid_in_range("uuid2:50", "uuid1:1-100", "uuid2:1-100").unwrap(); + assert!(result); + + // GTID in both low and high (different UUIDs) + let result2 = GtidSet::gtid_in_range("uuid1:50", "uuid1:1-100", "uuid2:1-100").unwrap(); + assert!(!result2); + } + + #[test] + fn test_empty_set() { + let set = GtidSet::parse("").unwrap(); + assert!(!set.contains("any", 1)); + + let set = GtidSet::parse(" ").unwrap(); + assert!(!set.contains("any", 1)); + } + + #[test] + fn test_roundtrip() { + let input = + "3E11FA47-71CA-11E7-81E2-2115B5C6C7F5:1-49,5A11FB48-82DB-23F8-92F3-3226C6D7D8G6:50-100"; + let set = GtidSet::parse(input).unwrap(); + let output = set.to_string(); + assert!(output.contains("3E11FA47-71CA-11E7-81E2-2115B5C6C7F5")); + assert!(output.contains("5A11FB48-82DB-23F8-92F3-3226C6D7D8G6")); + assert!(output.contains("1-49")); + assert!(output.contains("50-100")); + } + + #[test] + fn test_roundtrip_single_transactions() { + let input = "uuid:1:5:10"; + let set = GtidSet::parse(input).unwrap(); + let output = set.to_string(); + assert!(output.contains("1")); + assert!(output.contains("5")); + assert!(output.contains("10")); + } + + #[test] + fn test_contains_gtid_str() { + let set = GtidSet::parse("uuid:1-100").unwrap(); + assert!(set.contains_gtid_str("uuid:50").unwrap()); + assert!(!set.contains_gtid_str("uuid:101").unwrap()); + } + + #[test] + fn test_contains_gtid_str_invalid() { + let set = GtidSet::parse("uuid:1-100").unwrap(); + assert!(set.contains_gtid_str("uuid:invalid").is_err()); + assert!(set.contains_gtid_str("no-colon").is_err()); + } + + #[test] + fn test_parse_error_missing_colon() { + let result = GtidSet::parse("no-colon-here"); + assert!(result.is_err()); + } + + #[test] + fn test_parse_error_invalid_number() { + let result = GtidSet::parse("uuid:abc"); + assert!(result.is_err()); + } + + #[test] + fn test_parse_error_invalid_interval() { + let result = GtidSet::parse("uuid:1-abc"); + assert!(result.is_err()); + + let result = GtidSet::parse("uuid:abc-10"); + assert!(result.is_err()); + } + + #[test] + fn test_display_trait() { + let set = GtidSet::parse("uuid:1-100").unwrap(); + let display_str = format!("{}", set); + assert_eq!(display_str, "uuid:1-100"); + } + + #[test] + fn test_from_str_trait() { + let set: GtidSet = "uuid:1-100".parse().unwrap(); + assert!(set.contains("uuid", 50)); + } + + #[test] + fn test_contains_after_multiple_uuids() { + let set = GtidSet::parse("uuid1:1-10,uuid2:20-30:40-50,uuid3:60").unwrap(); + assert!(set.contains("uuid2", 25)); + assert!(set.contains("uuid2", 45)); + assert!(set.contains("uuid3", 60)); + assert!(!set.contains("uuid2", 35)); + assert!(!set.contains("uuid3", 61)); + } + + #[test] + fn test_whitespace_handling() { + let set = GtidSet::parse(" uuid1:1-10 , uuid2:20-30 ").unwrap(); + assert!(set.contains("uuid1", 5)); + assert!(set.contains("uuid2", 25)); + } + + #[test] + fn test_add_gtid_extends_contiguous() { + let mut set = GtidSet::parse("uuid:1-5").unwrap(); + set.add_gtid("uuid".to_string(), 6); + assert_eq!(set.format(), "uuid:1-6"); + set.add_gtid("uuid".to_string(), 7); + assert_eq!(set.format(), "uuid:1-7"); + } + + #[test] + fn test_add_gtid_new_singleton_when_gap() { + let mut set = GtidSet::parse("uuid:1-5").unwrap(); + set.add_gtid("uuid".to_string(), 10); + // Gap: keeps as separate interval. Format keeps insertion order per uuid. + assert!(set.contains("uuid", 5)); + assert!(set.contains("uuid", 10)); + assert!(!set.contains("uuid", 6)); + } + + #[test] + fn test_add_gtid_idempotent_on_duplicate() { + let mut set = GtidSet::parse("uuid:1-5").unwrap(); + set.add_gtid("uuid".to_string(), 3); + assert_eq!(set.format(), "uuid:1-5"); + } + + #[test] + fn test_add_gtid_new_uuid() { + let mut set = GtidSet::parse("uuid-a:1-5").unwrap(); + set.add_gtid("uuid-b".to_string(), 1); + assert!(set.contains("uuid-a", 3)); + assert!(set.contains("uuid-b", 1)); + } + + #[test] + fn test_superset_empty_empty() { + let a = GtidSet::parse("").unwrap(); + let b = GtidSet::parse("").unwrap(); + assert!(a.is_superset_of(&b)); + } + + #[test] + fn test_superset_self() { + let a = GtidSet::parse("uuid-a:1-100,uuid-b:1-50").unwrap(); + assert!(a.is_superset_of(&a.clone())); + } + + #[test] + fn test_superset_proper() { + let big = GtidSet::parse("uuid-a:1-100").unwrap(); + let small = GtidSet::parse("uuid-a:50-90").unwrap(); + assert!(big.is_superset_of(&small)); + assert!(!small.is_superset_of(&big)); + } + + #[test] + fn test_superset_different_uuids() { + let a = GtidSet::parse("uuid-a:1-100").unwrap(); + let b = GtidSet::parse("uuid-b:1-100").unwrap(); + assert!(!a.is_superset_of(&b)); + assert!(!b.is_superset_of(&a)); + } + + #[test] + fn test_superset_overlapping_but_not_superset() { + // a covers 1-50, b covers 25-100 — neither is superset of the other. + let a = GtidSet::parse("uuid:1-50").unwrap(); + let b = GtidSet::parse("uuid:25-100").unwrap(); + assert!(!a.is_superset_of(&b)); + assert!(!b.is_superset_of(&a)); + } + + #[test] + fn test_superset_split_intervals_get_coalesced() { + // self has [1-50, 51-100] (split intervals, contiguous); + // is_superset_of must coalesce them and recognise [1-100] coverage. + let self_set = GtidSet::parse("uuid:1-50:51-100").unwrap(); + let other = GtidSet::parse("uuid:1-100").unwrap(); + assert!(self_set.is_superset_of(&other)); + } + + #[test] + fn test_superset_huge_range_does_not_iterate_txns() { + // If is_superset_of iterated each txn, this would take seconds. + // The interval-aware impl is constant-time in this metric. + let big = GtidSet::parse("uuid:1-100000000").unwrap(); + let small = GtidSet::parse("uuid:50000000-60000000").unwrap(); + assert!(big.is_superset_of(&small)); + } + + #[test] + fn test_add_gtid_to_empty() { + let mut set = GtidSet::parse("").unwrap(); + assert!(set.is_empty()); + set.add_gtid("uuid".to_string(), 1); + assert_eq!(set.format(), "uuid:1"); + assert!(!set.is_empty()); + } + + #[test] + fn test_gtid_struct_equality() { + let g1 = Gtid { + uuid: "uuid1".to_string(), + transaction_id: 42, + }; + let g2 = Gtid { + uuid: "uuid1".to_string(), + transaction_id: 42, + }; + let g3 = Gtid { + uuid: "uuid1".to_string(), + transaction_id: 43, + }; + assert_eq!(g1, g2); + assert_ne!(g1, g3); + } +} diff --git a/src/source/mysql/mod.rs b/src/source/mysql/mod.rs new file mode 100644 index 0000000..3d0fbdb --- /dev/null +++ b/src/source/mysql/mod.rs @@ -0,0 +1,609 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +#![allow(dead_code)] + +//! MySQL change data capture source. +//! +//! Provides the `MysqlSource` struct implementing the `Source` trait for MySQL. +//! Reads the MySQL binary log (binlog) using GTID-based replication. +//! +//! All code in this module is behind `#[cfg(feature = "mysql-source")]`. + +use std::collections::HashMap; +use std::sync::Arc; + +use anyhow::{Context, Result}; +use async_trait::async_trait; +use mysql_async::prelude::Queryable; +use tokio::sync::Mutex; +use tracing::{info, warn}; + +use crate::config::{MysqlSourceConfig, SourceType}; +use crate::core::traits::SourceTableSchema; +use crate::core::{ReplicationStream, Source, SourcePosition}; + +pub mod binlog_stream; +pub mod converter; +pub mod gtid; +pub mod parser; +pub mod schema; +pub mod setup; + +/// Parsed MySQL connection details derived from a URL. +/// +/// Created from a `mysql://user:password@host:port/db` URL. +/// This struct is private to the mysql source module. +/// +/// Note: manual Debug impl redacts the password to prevent credential leaks. +#[derive(Clone)] +struct MysqlConnectionConfig { + host: String, + port: u16, + database: String, + user: String, + password: String, + server_id: u32, + tls_skip_verify: bool, +} + +impl std::fmt::Debug for MysqlConnectionConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("MysqlConnectionConfig") + .field("host", &self.host) + .field("port", &self.port) + .field("database", &self.database) + .field("user", &self.user) + .field("password", &"[REDACTED]") + .field("server_id", &self.server_id) + .field("tls_skip_verify", &self.tls_skip_verify) + .finish() + } +} + +impl MysqlConnectionConfig { + /// Parse a MySQL URL into connection configuration. + /// + /// # Format + /// `mysql://user:password@host:port/database` + /// + /// # Errors + /// Returns an error if the URL cannot be parsed or is missing required fields. + fn from_url(url: &str, server_id: u32, tls_skip_verify: bool) -> Result { + let parsed = url::Url::parse(url) + .context("Failed to parse MySQL URL. Expected: mysql://user:pass@host:port/db")?; + + let scheme = parsed.scheme(); + anyhow::ensure!( + scheme == "mysql", + "Unsupported URL scheme '{}' for MySQL source. Expected 'mysql://'", + scheme + ); + + let host = parsed + .host_str() + .context("Missing host in MySQL URL")? + .to_string(); + let port = parsed.port().unwrap_or(3306); + let database = parsed.path().trim_start_matches('/').to_string(); + + // url crate percent-decodes the username automatically + let user = if !parsed.username().is_empty() { + parsed.username().to_string() + } else { + "root".to_string() + }; + + // Password must be extracted raw (url crate already percent-decodes) + let password = parsed.password().unwrap_or("").to_string(); + + anyhow::ensure!( + !database.is_empty(), + "Missing database name in MySQL URL. Expected: mysql://user:pass@host:port/db" + ); + + Ok(Self { + host, + port, + database, + user, + password, + server_id, + tls_skip_verify, + }) + } + + /// Build `mysql_async::Opts` for creating connections. + /// + /// TLS is enabled with full verification by default. When the connection + /// config has `tls_skip_verify = true`, certificate validation is + /// disabled (development only). + fn to_opts(&self) -> mysql_async::Opts { + let builder = mysql_async::OptsBuilder::default() + .ip_or_hostname(self.host.clone()) + .tcp_port(self.port) + .db_name(Some(self.database.clone())) + .user(Some(self.user.clone())) + .pass(Some(self.password.clone())) + .ssl_opts(mysql_ssl_opts(self.tls_skip_verify)); + mysql_async::Opts::from(builder) + } +} + +/// Build `SslOpts` for MySQL connections. +/// +/// Default: rely on the system trust store. When `skip_verify` is true, +/// the danger flag is set — emit a `warn!` once at startup so the unsafe +/// posture is visible in logs. +pub(crate) fn mysql_ssl_opts(skip_verify: bool) -> mysql_async::SslOpts { + let opts = mysql_async::SslOpts::default(); + if skip_verify { + opts.with_danger_accept_invalid_certs(true) + } else { + opts + } +} + +/// MySQL source for Change Data Capture. +/// +/// Manages two MySQL connections: `query_conn` for metadata queries and +/// `binlog_conn` for binary log reading. The live `(file, position, +/// gtid_executed)` checkpoint is owned by the replication loop and +/// persisted to `StateStore`; this struct holds no in-memory checkpoint. +pub struct MysqlSource { + config: MysqlConnectionConfig, + server_id: u32, + use_gtid: bool, + /// Connection for metadata queries, wrapped in `Mutex` because `mysql_async::Conn` is not `Sync`. + query_conn: Option>, + /// Dedicated connection for binlog streaming. + binlog_conn: Option>, + /// Cached table schemas keyed by fully-qualified table name (`db.table`). + schema_cache: Arc>>, +} + +impl MysqlSource { + /// Creates a new `MysqlSource` struct without connecting. + /// + /// Connections are opened lazily in [`Source::setup()`]. + pub async fn new(url: &str, config: &MysqlSourceConfig) -> Result { + let conn_config = + MysqlConnectionConfig::from_url(url, config.server_id, config.tls_skip_verify)?; + info!( + "MySQL source configured (server_id: {}, gtid: {})", + config.server_id, config.gtid_enabled + ); + if config.tls_skip_verify { + warn!( + "MySQL TLS certificate verification disabled \ + (MYSQL_TLS_SKIP_VERIFY=true). This is unsafe in production." + ); + } + Ok(Self { + config: conn_config, + server_id: config.server_id, + use_gtid: config.gtid_enabled, + query_conn: None, + binlog_conn: None, + schema_cache: Arc::new(Mutex::new(HashMap::new())), + }) + } + + /// Helper: open a connection using the stored config. + async fn open_connection(&self) -> Result { + let pool = mysql_async::Pool::new(self.config.to_opts()); + pool.get_conn() + .await + .context("Failed to connect to MySQL server") + } +} + +#[async_trait] +impl Source for MysqlSource { + fn name(&self) -> &'static str { + "mysql" + } + + fn source_type(&self) -> SourceType { + SourceType::Mysql + } + + /// Validate MySQL source prerequisites. + /// + /// Validation requires a live connection, so actual checks are deferred + /// to [`setup()`](Source::setup). This returns `Ok(())` unconditionally. + async fn validate(&self) -> Result<()> { + // Validation happens in setup() since we need a connection. + Ok(()) + } + + /// Setup: connect to MySQL, verify prerequisites, and introspect schemas. + /// + /// Checks: server version >= 5.7, GTID mode, binlog_format=ROW, + /// binlog_row_image=FULL, REPLICATION SLAVE privilege, and detects Aurora. + /// Opens two connections: one for queries and one for binlog streaming. + async fn setup(&mut self, tables: &[String]) -> Result<()> { + // 1. Open query connection + let mut conn = self.open_connection().await?; + + // 2. Verify server version >= 5.7 + let version_row: Vec<(String,)> = conn + .query("SELECT VERSION()") + .await + .context("Failed to get MySQL version")?; + let version_str = version_row + .first() + .map(|r| r.0.as_str()) + .unwrap_or("unknown"); + info!("MySQL server version: {}", version_str); + + let major_ok: bool = version_str + .split('.') + .next() + .and_then(|s: &str| s.parse::().ok()) + .map(|major: u32| major >= 5) + .unwrap_or(false); + anyhow::ensure!( + major_ok, + "MySQL server version must be >= 5.7 for CDC. Got: {}", + version_str + ); + info!(" Server version check passed ✓"); + + // 3. Verify GTID mode (if enabled) + if self.use_gtid { + let gtid_row: Vec<(String,)> = conn + .query("SELECT @@global.gtid_mode") + .await + .context("Failed to check GTID mode")?; + let gtid_mode = gtid_row.first().map(|r| r.0.as_str()).unwrap_or("OFF"); + anyhow::ensure!( + gtid_mode.eq_ignore_ascii_case("ON"), + "GTID mode must be ON for MySQL CDC. Current: {}. \ + Set gtid_mode=ON and enforce_gtid_consistency=ON", + gtid_mode + ); + info!(" GTID mode: ON ✓"); + } else { + info!(" GTID mode: not checked (disabled)"); + } + + // 4. Verify binlog_format = ROW + let format_row: Vec<(String,)> = conn + .query("SELECT @@global.binlog_format") + .await + .context("Failed to check binlog_format")?; + let binlog_format = format_row + .first() + .map(|r| r.0.as_str()) + .unwrap_or("unknown"); + anyhow::ensure!( + binlog_format.eq_ignore_ascii_case("ROW"), + "binlog_format must be ROW for MySQL CDC. Current: {}", + binlog_format + ); + info!(" binlog_format: ROW ✓"); + + // 5. Verify binlog_row_image = FULL + let image_row: Vec<(String,)> = conn + .query("SELECT @@global.binlog_row_image") + .await + .context("Failed to check binlog_row_image")?; + let row_image = image_row.first().map(|r| r.0.as_str()).unwrap_or("unknown"); + anyhow::ensure!( + row_image.eq_ignore_ascii_case("FULL"), + "binlog_row_image must be FULL for MySQL CDC. Current: {}", + row_image + ); + info!(" binlog_row_image: FULL ✓"); + + // 6. Check REPLICATION SLAVE privilege + // Try mysql.user first; fall back to SHOW GRANTS for RDS/Aurora/Cloud SQL + let has_replication = match conn + .exec_first::<(String,), _, _>( + "SELECT Repl_slave_priv FROM mysql.user WHERE User = ?", + (self.config.user.as_str(),), + ) + .await + { + Ok(Some(row)) => row.0.to_uppercase() == "Y", + _ => { + let grant_rows: Vec<(String,)> = conn + .query("SHOW GRANTS") + .await + .context("Failed to check MySQL privileges")?; + grant_rows.iter().any(|row| { + let upper = row.0.to_uppercase(); + upper.contains("REPLICATION SLAVE") || upper.contains("ALL PRIVILEGES") + }) + } + }; + anyhow::ensure!( + has_replication, + "MySQL user missing REPLICATION SLAVE privilege. \ + Required for binlog reading. \ + Run: GRANT REPLICATION SLAVE ON *.* TO ''@'';" + ); + info!(" REPLICATION SLAVE privilege: ✓"); + + // 7. Detect Amazon Aurora (best-effort) + let is_aurora: bool = conn + .query_first::<(String,), &str>("SELECT @@aurora_version") + .await + .ok() + .flatten() + .is_some(); + if is_aurora { + info!(" Detected Amazon Aurora MySQL"); + } + + // 8. Open a separate binlog connection + let binlog_conn = self.open_connection().await?; + + // 9. Introspect table schemas + if !tables.is_empty() { + let schemas = + schema::introspect_mysql_schemas_inner(&mut conn, tables, &self.config.database) + .await + .context("Failed to introspect MySQL table schemas")?; + + let mut cache = self.schema_cache.lock().await; + for s in schemas { + let key = format!("{}.{}", s.schema, s.name); + cache.insert(key, s); + } + info!(" Cached schemas for {} table(s)", tables.len()); + } + + self.query_conn = Some(Mutex::new(conn)); + self.binlog_conn = Some(Mutex::new(binlog_conn)); + + info!("MySQL setup complete ✓"); + Ok(()) + } + + /// Start MySQL binlog replication. Consumes the binlog connection and returns a MysqlBinlogStream. + async fn start_replication( + &mut self, + position: Option, + ) -> Result> { + use crate::source::mysql::binlog_stream::MysqlBinlogStream; + + let binlog_conn: mysql_async::Conn = self + .binlog_conn + .take() + .ok_or_else(|| anyhow::anyhow!("binlog connection not available"))? + .into_inner(); + + let server_id = self.config.server_id; + let resume_gtid = extract_resume_gtid_set(&position); + match resume_gtid.as_deref() { + Some(gtid) if !gtid.is_empty() => { + info!("Resuming MySQL binlog from Gtid_set: {}", gtid) + } + _ => info!("Starting MySQL binlog from earliest available position"), + } + let stream = MysqlBinlogStream::new(binlog_conn, server_id, resume_gtid.as_deref()).await?; + + Ok(Box::new(stream)) + } + + /// MySQL has no in-source checkpoint state — the live triple + /// `(file, position, gtid_executed)` is owned by the replication loop + /// and persisted to `StateStore::save_mysql_checkpoint`. + fn checkpoint_position(&self) -> Option { + None + } + + /// Cleanup: drop connections and release resources. + async fn cleanup(&mut self) -> Result<()> { + self.query_conn = None; + self.binlog_conn = None; + self.schema_cache.lock().await.clear(); + info!("MySQL cleanup complete"); + Ok(()) + } + + async fn create_loop( + &mut self, + position: Option, + ) -> Result> { + let resume_gtid = extract_resume_gtid_set(&position); + let typed_stream = self.start_replication_typed(resume_gtid.as_deref()).await?; + Ok(Box::new( + crate::engine::replication::MysqlReplicationLoop::new(typed_stream), + )) + } +} + +/// Pick the GTID-set string the binlog stream should resume from. +/// Only `MysqlBinlog { gtid_executed }` carries a meaningful resume value; +/// every other variant means "no checkpoint, start from the earliest +/// available binlog". +fn extract_resume_gtid_set(position: &Option) -> Option { + match position { + Some(SourcePosition::MysqlBinlog { gtid_executed, .. }) if !gtid_executed.is_empty() => { + Some(gtid_executed.clone()) + } + _ => None, + } +} + +impl MysqlSource { + /// Start a typed binlog stream (used by `create_loop`). + pub async fn start_replication_typed( + &mut self, + initial_gtid_set: Option<&str>, + ) -> Result { + use crate::source::mysql::binlog_stream::MysqlBinlogStream; + let conn: mysql_async::Conn = self + .binlog_conn + .take() + .ok_or_else(|| anyhow::anyhow!("binlog connection not available"))? + .into_inner(); + let stream = MysqlBinlogStream::new(conn, self.config.server_id, initial_gtid_set).await?; + Ok(stream.into_inner()) + } +} + +// Manual Debug impl to avoid leaking credentials +impl std::fmt::Debug for MysqlSource { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("MysqlSource") + .field("host", &self.config.host) + .field("port", &self.config.port) + .field("database", &self.config.database) + .field("user", &self.config.user) + .field("server_id", &self.server_id) + .field("use_gtid", &self.use_gtid) + .field("has_query_conn", &self.query_conn.is_some()) + .field("has_binlog_conn", &self.binlog_conn.is_some()) + .finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_mysql_connection_config_parsing() { + let cfg = + MysqlConnectionConfig::from_url("mysql://user:pass@localhost:3306/mydb", 5400, false) + .unwrap(); + assert_eq!(cfg.host, "localhost"); + assert_eq!(cfg.port, 3306); + assert_eq!(cfg.database, "mydb"); + assert_eq!(cfg.user, "user"); + assert_eq!(cfg.password, "pass"); + assert!(!cfg.tls_skip_verify); + + let cfg = MysqlConnectionConfig::from_url("mysql://host.com/db", 5401, true).unwrap(); + assert_eq!(cfg.host, "host.com"); + assert_eq!(cfg.port, 3306); + assert_eq!(cfg.database, "db"); + assert_eq!(cfg.user, "root"); + assert_eq!(cfg.password, ""); + assert!(cfg.tls_skip_verify); + + let result = MysqlConnectionConfig::from_url("mysql://user:pass@localhost", 5402, false); + assert!(result.is_err()); // no database path + + let result = MysqlConnectionConfig::from_url("postgres://localhost/db", 5403, false); + assert!(result.is_err()); // wrong scheme + + let cfg = MysqlConnectionConfig::from_url( + "mysql://user%40host:p%40ss@localhost/mydb", + 5404, + false, + ) + .unwrap(); + assert_eq!(cfg.host, "localhost"); + assert_eq!(cfg.user, "user%40host"); + assert_eq!(cfg.password, "p%40ss"); + } + + #[tokio::test] + async fn test_mysql_source_new() { + let mysql_config = MysqlSourceConfig { + server_id: 6000, + gtid_enabled: true, + tls_skip_verify: false, + }; + let source = MysqlSource::new("mysql://root@localhost/testdb", &mysql_config).await; + assert!(source.is_ok()); + let source = source.unwrap(); + assert_eq!(source.server_id, 6000); + assert!(source.use_gtid); + assert!(source.query_conn.is_none()); + assert!(source.binlog_conn.is_none()); + } + + #[test] + fn test_source_trait_methods() { + let mysql_config = MysqlSourceConfig { + server_id: 6000, + gtid_enabled: true, + tls_skip_verify: false, + }; + let rt = tokio::runtime::Runtime::new().unwrap(); + let source = rt + .block_on(MysqlSource::new( + "mysql://root@localhost/testdb", + &mysql_config, + )) + .unwrap(); + + assert_eq!(source.name(), "mysql"); + assert_eq!(source.source_type(), SourceType::Mysql); + assert!(source.checkpoint_position().is_none()); + } + + #[test] + fn test_debug_no_credentials() { + let mysql_config = MysqlSourceConfig { + server_id: 6000, + gtid_enabled: true, + tls_skip_verify: false, + }; + let rt = tokio::runtime::Runtime::new().unwrap(); + let source = rt + .block_on(MysqlSource::new( + "mysql://user:secret@host:3306/db", + &mysql_config, + )) + .unwrap(); + + let debug_str = format!("{:?}", source); + // Password should never appear in debug output + assert!(!debug_str.contains("secret")); + // Sanity checks + assert!(debug_str.contains("host")); + assert!(debug_str.contains("user")); + assert!(debug_str.contains("database")); + assert!(debug_str.contains("server_id")); + } + + #[test] + fn test_mysql_source_type_display() { + assert_eq!(SourceType::Mysql.to_string(), "mysql"); + } + + #[test] + fn test_typo_mapping_exhaustive() { + // Verify all expected MySQL type names map without panic + let cases = [ + ("tinyint", "Int16"), + ("smallint", "Int16"), + ("mediumint", "Int32"), + ("int", "Int32"), + ("bigint", "Int64"), + ("float", "Float32"), + ("double", "Float64"), + ("decimal", "Decimal"), + ("date", "Date"), + ("time", "Time"), + ("datetime", "Timestamp"), + ("timestamp", "Timestamp"), + ("char", "String"), + ("varchar", "String"), + ("text", "Text"), + ("blob", "Bytes"), + ("json", "Json"), + ("bool", "Boolean"), + ("boolean", "Boolean"), + ("unknown_type", "String"), + ]; + for (mysql_type, expected_variant) in &cases { + let dt = crate::source::mysql::schema::mysql_type_to_data_type(mysql_type); + let actual = format!("{:?}", dt); + assert!( + actual.starts_with(expected_variant), + "mysql_type={} -> {:?} (expected starts with {})", + mysql_type, + dt, + expected_variant + ); + } + } +} diff --git a/src/source/mysql/parser.rs b/src/source/mysql/parser.rs new file mode 100644 index 0000000..5217d38 --- /dev/null +++ b/src/source/mysql/parser.rs @@ -0,0 +1,578 @@ +use std::collections::HashMap; +use std::sync::{Arc, RwLock}; + +use anyhow::{Context, Result}; +use mysql_common::binlog::events::{ + DeleteRowsEvent, DeleteRowsEventV1, EventData, GtidEvent, PartialUpdateRowsEvent, + RowsEventData, RowsEventRows, TableMapEvent, UpdateRowsEvent, UpdateRowsEventV1, + WriteRowsEvent, WriteRowsEventV1, +}; +use mysql_common::binlog::value::BinlogValue; + +use crate::core::SourcePosition; +use crate::source::mysql::gtid::GtidSet; + +/// MySQL binlog event types relevant for CDC processing. +/// Populated from mysql_async's typed events — no raw byte parsing. +/// +/// `Commit` carries a GTID label whose prefix indicates the commit kind: +/// * regular GTID string (`UUID:N`) — InnoDB transaction terminated by +/// XidEvent or InnoDB DDL terminated by QueryEvent("COMMIT") +/// * `ROLLBACK:` — `QueryEvent("ROLLBACK")`. The replication +/// loop drops in-flight buffered events for this transaction before +/// the Commit propagates to the pipeline. +/// * `XID:` — fallback for non-GTID setups +#[derive(Debug, Clone)] +pub enum BinlogEvent { + Begin { + gtid: String, + timestamp: u32, + }, + Commit { + gtid: String, + timestamp: u32, + position: SourcePosition, + }, + Insert { + table_id: u64, + schema_name: String, + table_name: String, + rows: Vec>>, + col_names: Vec, + col_types: Vec, + position: SourcePosition, + }, + Update { + table_id: u64, + schema_name: String, + table_name: String, + before_rows: Vec>>, + after_rows: Vec>>, + col_names: Vec, + col_types: Vec, + position: SourcePosition, + }, + Delete { + table_id: u64, + schema_name: String, + table_name: String, + rows: Vec>>, + col_names: Vec, + col_types: Vec, + position: SourcePosition, + }, + TableMap { + table_id: u64, + col_types: Vec, + }, + /// Server-emitted binary log heartbeat. Carries the live position so + /// the pipeline can advance its checkpoint and snapshot drain checks + /// fire even on idle databases. + Heartbeat { + position: SourcePosition, + }, + Ddl { + schema_name: String, + query: String, + }, +} + +/// Mutable parser state carried across binlog events on the same stream. +/// +/// `current_file` advances on real `RotateEvent`s. `current_gtid_set` +/// accumulates every `GtidEvent` in transaction order. `current_txn_gtid` +/// holds the GTID of the in-flight transaction (used to label `Commit`). +/// +/// All three fields are part of the on-the-wire `MysqlBinlog` checkpoint +/// emitted with each event; restart correctness depends on them being +/// kept up to date. +/// +/// `current_gtid_set` is wrapped in `Arc>` so the snapshot +/// worker can read the consumer's live GTID set when registering chunks +/// (DBLog read-only LOW/HIGH watermarks). The replication loop is the +/// single writer; the lock is `std::sync::RwLock` because +/// `process_typed_event` is synchronous and held for negligibly short +/// windows (one `format()` or one `add_gtid()` per event). +#[derive(Debug, Default, Clone)] +pub struct ParserState { + pub current_file: String, + pub current_gtid_set: Arc>, + pub current_txn_gtid: Option, +} + +impl ParserState { + /// Construct a fresh parser state, wrapping the initial GTID set in a new + /// `Arc>`. Use [`with_shared_gtid`] when the loop wants to + /// share the same Arc with snapshot workers. + pub fn new(initial_file: String, initial_gtid_set: GtidSet) -> Self { + Self::with_shared_gtid(initial_file, Arc::new(RwLock::new(initial_gtid_set))) + } + + /// Construct a parser state that shares an externally-owned GTID set + /// (typically from `LoopContext::consumer_gtid`). The replication loop + /// uses this so the snapshot worker can observe the live GTID set + /// without going through the loop itself. + pub fn with_shared_gtid(initial_file: String, current_gtid_set: Arc>) -> Self { + Self { + current_file: initial_file, + current_gtid_set, + current_txn_gtid: None, + } + } + + /// Cheap clone of the shared GTID set Arc — for plumbing into + /// `LoopContext::consumer_gtid` and snapshot workers. + pub fn shared_gtid(&self) -> Arc> { + self.current_gtid_set.clone() + } +} + +/// Process a typed binlog event from mysql_async into our BinlogEvent enum. +/// +/// Required: +/// - `tme_cache`: persistent cache mapping table_id → TableMapEvent (populated by TABLE_MAP_EVENT) +/// - `col_names_map`: (schema, table) → Vec from schema introspection +/// - `state`: mutable parser state (current binlog file, accumulated GTID set, +/// in-flight transaction GTID). Must outlive a single event so GTIDs and +/// file rotations are tracked across calls. +pub fn process_typed_event( + event: &mysql_common::binlog::events::Event, + tme_cache: &mut HashMap>, + col_names_map: &HashMap<(String, String), Vec>, + state: &mut ParserState, +) -> Result> { + let data = event + .read_data() + .context("Failed to read binlog event data")? + .context("Unknown binlog event type")?; + + let header = event.header(); + let timestamp = header.timestamp(); + let log_pos = header.log_pos(); + + // Helper: build the canonical MySQL checkpoint position for an event in + // this stream. The triple (file, position, gtid_executed) is what restart + // logic in MysqlSource::start_replication consumes. Holds a brief read + // lock on the shared GTID set; snapshot workers reading concurrently + // see the same `gtid_executed` snapshot the position carries. + let make_position = |state: &ParserState| SourcePosition::MysqlBinlog { + file: state.current_file.clone(), + position: log_pos as u64, + gtid_executed: state + .current_gtid_set + .read() + .expect("MySQL parser GTID set lock poisoned") + .format(), + }; + + match data { + EventData::TableMapEvent(tme) => { + tme_cache.insert(tme.table_id(), tme.clone().into_owned()); + Ok(vec![BinlogEvent::TableMap { + table_id: tme.table_id(), + col_types: extract_col_types(&tme), + }]) + } + + EventData::RowsEvent(rows_data) => { + let table_id = rows_data.table_id(); + let tme = tme_cache.get(&table_id).ok_or_else(|| { + anyhow::anyhow!( + "MySQL binlog protocol violation: RowsEvent for table_id {} \ + arrived without a preceding TableMapEvent in this session. \ + Aborting CDC to avoid emitting events with incorrect schema metadata.", + table_id + ) + })?; + + let schema = tme.database_name().to_string(); + let table = tme.table_name().to_string(); + + let col_types = extract_col_types(tme); + let col_names = col_names_map + .get(&(schema.clone(), table.clone())) + .cloned() + .unwrap_or_else(|| (0..col_types.len()).map(|i| format!("@{}", i)).collect()); + + /// Helper: extract rows from any rows event that has `rows()`. + fn collect_after( + re: &R, + tme: &TableMapEvent, + ) -> Result>>> + where + R: RowsEventLike, + { + let mut rows = Vec::new(); + for row_result in re.rows(tme) { + let (_before, after) = row_result?; + if let Some(row) = after { + rows.push(row.unwrap()); + } + } + Ok(rows) + } + + // Update events return (before_rows, after_rows). Local helper — + // not worth a top-level type alias just to satisfy clippy. + #[allow(clippy::type_complexity)] + fn collect_before_after( + re: &R, + tme: &TableMapEvent, + ) -> Result<( + Vec>>, + Vec>>, + )> + where + R: RowsEventLike, + { + let mut before = Vec::new(); + let mut after = Vec::new(); + for row_result in re.rows(tme) { + let (b, a) = row_result?; + if let Some(row) = b { + before.push(row.unwrap()); + } + if let Some(row) = a { + after.push(row.unwrap()); + } + } + Ok((before, after)) + } + + fn collect_before( + re: &R, + tme: &TableMapEvent, + ) -> Result>>> + where + R: RowsEventLike, + { + let mut rows = Vec::new(); + for row_result in re.rows(tme) { + let (before, _after) = row_result?; + if let Some(row) = before { + rows.push(row.unwrap()); + } + } + Ok(rows) + } + + match rows_data { + RowsEventData::WriteRowsEvent(ref re) => { + let rows = collect_after(re, tme)?; + Ok(vec![BinlogEvent::Insert { + table_id, + schema_name: schema, + table_name: table, + rows, + col_names, + col_types, + position: make_position(state), + }]) + } + RowsEventData::WriteRowsEventV1(ref re) => { + let rows = collect_after(re, tme)?; + Ok(vec![BinlogEvent::Insert { + table_id, + schema_name: schema, + table_name: table, + rows, + col_names, + col_types, + position: make_position(state), + }]) + } + RowsEventData::UpdateRowsEvent(ref re) => { + let (before_rows, after_rows) = collect_before_after(re, tme)?; + Ok(vec![BinlogEvent::Update { + table_id, + schema_name: schema, + table_name: table, + before_rows, + after_rows, + col_names, + col_types, + position: make_position(state), + }]) + } + RowsEventData::UpdateRowsEventV1(ref re) => { + let (before_rows, after_rows) = collect_before_after(re, tme)?; + Ok(vec![BinlogEvent::Update { + table_id, + schema_name: schema, + table_name: table, + before_rows, + after_rows, + col_names, + col_types, + position: make_position(state), + }]) + } + RowsEventData::DeleteRowsEvent(ref re) => { + let rows = collect_before(re, tme)?; + Ok(vec![BinlogEvent::Delete { + table_id, + schema_name: schema, + table_name: table, + rows, + col_names, + col_types, + position: make_position(state), + }]) + } + RowsEventData::DeleteRowsEventV1(ref re) => { + let rows = collect_before(re, tme)?; + Ok(vec![BinlogEvent::Delete { + table_id, + schema_name: schema, + table_name: table, + rows, + col_names, + col_types, + position: make_position(state), + }]) + } + _ => Ok(vec![]), + } + } + + EventData::GtidEvent(gtid_event) => { + // Track the in-flight transaction GTID and merge it into the + // executed-set running tally. Both are used for the next emitted + // events' SourcePosition and for the Commit label. Brief write + // lock — `add_gtid` is O(1) amortised when transactions arrive + // monotonically (Debezium's standard streaming case). + let gtid = format_gtid(>id_event); + if let Some((uuid, txn_str)) = gtid.split_once(':') { + if let Ok(txn) = txn_str.parse::() { + state + .current_gtid_set + .write() + .expect("MySQL parser GTID set lock poisoned") + .add_gtid(uuid.to_string(), txn); + } + } + state.current_txn_gtid = Some(gtid.clone()); + Ok(vec![BinlogEvent::Begin { gtid, timestamp }]) + } + + EventData::XidEvent(_xid) => { + // The Commit event labels the transaction that just finished. + // Use the GTID parsed from the preceding GtidEvent if present. + // Falling back to an XID-derived label is only for non-GTID setups + // where MySQL never emits a GtidEvent — but in that mode restart + // is already (file, position)-only. + let gtid = state + .current_txn_gtid + .take() + .unwrap_or_else(|| format!("XID:{}", timestamp)); + Ok(vec![BinlogEvent::Commit { + gtid, + timestamp, + position: make_position(state), + }]) + } + + EventData::QueryEvent(qe) => { + // mysql_common surfaces BEGIN, COMMIT, and ROLLBACK as plain + // QueryEvents — there are no dedicated variants. Dispatching on + // the leading keyword is exactly what Debezium's binlog reader + // does (mysql-binlog-connector-java + DdlParser) and is needed + // so DDL-only transactions (which don't emit XidEvent) still + // produce a `Commit` boundary the replication loop can use to + // advance its persisted checkpoint. + let q = qe.query(); + let head = q + .split_whitespace() + .next() + .unwrap_or("") + .to_ascii_uppercase(); + + match head.as_str() { + "BEGIN" => { + // GtidEvent (in GTID mode) emits Begin with the real + // GTID right before this BEGIN QueryEvent. To avoid + // double Begin emission we only emit here when no + // GTID label is in flight (non-GTID setups, MyISAM, + // mixed-engine transactions). The synthetic file-based + // label keeps restart-from-(file,position) coherent. + if state.current_txn_gtid.is_some() { + return Ok(vec![]); + } + let gtid = format!("FILE:{}", state.current_file); + state.current_txn_gtid = Some(gtid.clone()); + Ok(vec![BinlogEvent::Begin { gtid, timestamp }]) + } + "COMMIT" => { + // Symmetric to BEGIN: most InnoDB transactions terminate + // with XidEvent which already produces a Commit. We only + // emit here for transactions that DON'T finish with XID + // (DDL transactions, MyISAM). Detect by whether the prior + // event was already an XID-induced Commit (current_txn_gtid + // taken to None) — in that case do nothing. + let Some(gtid) = state.current_txn_gtid.take() else { + return Ok(vec![]); + }; + Ok(vec![BinlogEvent::Commit { + gtid, + timestamp, + position: make_position(state), + }]) + } + "ROLLBACK" => { + // The label is consumed by the replication loop to + // recognise this as a rollback boundary; the in-flight + // per-event buffer is discarded BEFORE the Commit + // propagates to the pipeline. The Commit itself still + // flows so the persisted checkpoint can advance past + // the rollback (otherwise we'd re-replay the doomed + // transaction every restart). + state.current_txn_gtid.take(); + Ok(vec![BinlogEvent::Commit { + gtid: format!("ROLLBACK:{}", timestamp), + timestamp, + position: make_position(state), + }]) + } + _ => Ok(vec![BinlogEvent::Ddl { + schema_name: qe.schema().to_string(), + query: qe.query().to_string(), + }]), + } + } + + EventData::HeartbeatEvent => { + // Server-emitted binary log heartbeats carry the current binlog + // (file, position). Forwarding them into ParserState makes the + // consumer's GTID/file state advance during low-traffic windows + // — without this, snapshot workers waiting in await_drain hang + // until a real write happens. Debezium relies on the same + // mechanism for read-only incremental snapshots in idle + // databases. + // + // mysql_common's HeartbeatLogEvent doesn't surface log_filename + // through a stable accessor in 0.32.x, so we rely on the + // RotateEvent path to update current_file. The heartbeat + // position itself is built from log_pos (which the header + // gives us) and the live GTID set, which is enough to drive + // pipeline progress and try_drain. + Ok(vec![BinlogEvent::Heartbeat { + position: make_position(state), + }]) + } + + EventData::RotateEvent(rotate) => { + // RotateEvent advances current_file. The TableMap cache is left + // intact: real rotations re-emit TableMaps for active tables, and + // mysql_async/MariaDB occasionally emit "fake" RotateEvents on + // reconnect (see Debezium PR #4959, MariaDB KB on fake rotate). + // Invalidating the cache here breaks those streams. + state.current_file = rotate.name().to_string(); + Ok(vec![]) + } + + EventData::FormatDescriptionEvent(_) | EventData::StopEvent => Ok(vec![]), + + _ => Ok(vec![]), + } +} + +/// Sentinel byte for column slots whose MySQL type code couldn't be +/// resolved via `TableMapEvent::get_raw_column_type`. Mapped at the +/// converter layer to `Value::Null` so column ordinals are preserved +/// end-to-end. The byte 0xFE is reserved by mysql_common for invalid +/// column types (`MYSQL_TYPE_INVALID`-adjacent), so it cannot collide +/// with a real type code. +pub(crate) const UNKNOWN_COLUMN_TYPE: u8 = 0xFE; + +/// Extract raw column type codes from a TableMapEvent. +/// +/// MUST preserve column ordinals: a column whose type code can't be +/// resolved becomes `UNKNOWN_COLUMN_TYPE` in its original slot, NOT +/// dropped. The previous `filter_map` shifted later columns one slot +/// down whenever an unknown type appeared, binding row values to the +/// wrong column names downstream — a silent corruption bug for tables +/// that use a type mysql_common doesn't recognise yet. +fn extract_col_types(tme: &TableMapEvent<'_>) -> Vec { + (0..tme.columns_count() as usize) + .map(|i| match tme.get_raw_column_type(i) { + Ok(Some(ct)) => ct as u8, + Ok(None) | Err(_) => { + tracing::error!( + table_id = tme.table_id(), + column_ordinal = i, + "MySQL TableMapEvent has an unrecognised column type; \ + column will be emitted as NULL until schema introspection refreshes" + ); + UNKNOWN_COLUMN_TYPE + } + }) + .collect() +} + +/// Abstraction over rows events that can produce `RowsEventRows`. +trait RowsEventLike { + fn rows<'a>(&'a self, table_map_event: &'a TableMapEvent<'a>) -> RowsEventRows<'a>; +} + +impl RowsEventLike for WriteRowsEvent<'_> { + fn rows<'a>(&'a self, table_map_event: &'a TableMapEvent<'a>) -> RowsEventRows<'a> { + self.rows(table_map_event) + } +} +impl RowsEventLike for WriteRowsEventV1<'_> { + fn rows<'a>(&'a self, table_map_event: &'a TableMapEvent<'a>) -> RowsEventRows<'a> { + self.rows(table_map_event) + } +} +impl RowsEventLike for UpdateRowsEvent<'_> { + fn rows<'a>(&'a self, table_map_event: &'a TableMapEvent<'a>) -> RowsEventRows<'a> { + self.rows(table_map_event) + } +} +impl RowsEventLike for UpdateRowsEventV1<'_> { + fn rows<'a>(&'a self, table_map_event: &'a TableMapEvent<'a>) -> RowsEventRows<'a> { + self.rows(table_map_event) + } +} +impl RowsEventLike for DeleteRowsEvent<'_> { + fn rows<'a>(&'a self, table_map_event: &'a TableMapEvent<'a>) -> RowsEventRows<'a> { + self.rows(table_map_event) + } +} +impl RowsEventLike for DeleteRowsEventV1<'_> { + fn rows<'a>(&'a self, table_map_event: &'a TableMapEvent<'a>) -> RowsEventRows<'a> { + self.rows(table_map_event) + } +} +impl RowsEventLike for PartialUpdateRowsEvent<'_> { + fn rows<'a>(&'a self, table_map_event: &'a TableMapEvent<'a>) -> RowsEventRows<'a> { + self.rows(table_map_event) + } +} + +/// Format a GTID from a GtidEvent. +fn format_gtid(event: &GtidEvent) -> String { + let sid = event.sid(); + let gno = event.gno(); + format!( + "{:02X}{:02X}{:02X}{:02X}-{:02X}{:02X}-{:02X}{:02X}-\ + {:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}:{}", + sid[0], + sid[1], + sid[2], + sid[3], + sid[4], + sid[5], + sid[6], + sid[7], + sid[8], + sid[9], + sid[10], + sid[11], + sid[12], + sid[13], + sid[14], + sid[15], + gno + ) +} diff --git a/src/source/mysql/schema.rs b/src/source/mysql/schema.rs new file mode 100644 index 0000000..f20eaf3 --- /dev/null +++ b/src/source/mysql/schema.rs @@ -0,0 +1,220 @@ +use anyhow::{Context, Result}; +use mysql_async::prelude::Queryable; +use tracing::info; + +use crate::core::traits::{SourceColumn, SourceTableSchema}; +use crate::core::DataType; + +/// Escape a MySQL identifier by wrapping it in backticks. +fn quote_identifier(s: &str) -> String { + format!("`{}`", s.replace('`', "``")) +} + +/// Escape a string literal for safe MySQL interpolation. +fn quote_string(s: &str) -> String { + let escaped = s.replace('\\', "\\\\").replace('\'', "\\'"); + format!("'{}'", escaped) +} + +/// Build mysql_async::Opts from a parsed URL. +#[allow(dead_code)] +fn build_opts_from_url(parsed: url::Url) -> Result { + let host = parsed.host_str().unwrap_or("localhost"); + let port = parsed.port().unwrap_or(3306); + let user = if !parsed.username().is_empty() { + parsed.username() + } else { + "root" + }; + let password = parsed.password().unwrap_or(""); + let database = parsed.path().trim_start_matches('/'); + + let builder = mysql_async::OptsBuilder::default() + .ip_or_hostname(host) + .tcp_port(port) + .db_name(Some(database)) + .user(Some(user)) + .pass(Some(password)); + Ok(mysql_async::Opts::from(builder)) +} + +/// Introspects MySQL tables to get their schemas (columns, types, PKs). +pub async fn introspect_mysql_schemas( + url: &str, + tables: &[String], +) -> Result> { + let parsed = url::Url::parse(url).context("Failed to parse MySQL URL")?; + let database = parsed.path().trim_start_matches('/').to_string(); + let opts = build_opts_from_url(parsed)?; + let pool = mysql_async::Pool::new(opts); + let mut conn = pool + .get_conn() + .await + .context("Failed to connect to MySQL for schema introspection")?; + let schemas = introspect_mysql_schemas_inner(&mut conn, tables, &database).await?; + info!( + " Introspected {} MySQL source table schema(s)", + schemas.len() + ); + Ok(schemas) +} + +pub(crate) async fn introspect_mysql_schemas_inner( + conn: &mut mysql_async::Conn, + tables: &[String], + default_database: &str, +) -> Result> { + let mut schemas = Vec::with_capacity(tables.len()); + for table in tables { + let (schema_name, table_name) = if table.contains('.') { + let parts: Vec<&str> = table.splitn(2, '.').collect(); + (parts[0].to_string(), parts[1].to_string()) + } else { + (default_database.to_string(), table.to_string()) + }; + let columns = introspect_columns(conn, &schema_name, &table_name) + .await + .with_context(|| format!("Failed to introspect columns for {}", table))?; + let primary_keys = introspect_primary_keys(conn, &schema_name, &table_name) + .await + .with_context(|| format!("Failed to introspect PKs for {}", table))?; + schemas.push(SourceTableSchema { + schema: schema_name, + name: table_name, + columns, + primary_keys, + }); + } + Ok(schemas) +} + +async fn introspect_columns( + conn: &mut mysql_async::Conn, + schema: &str, + table: &str, +) -> Result> { + let col_query = format!( + "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE \ + FROM information_schema.columns \ + WHERE TABLE_SCHEMA = {} AND TABLE_NAME = {} \ + ORDER BY ORDINAL_POSITION", + quote_string(schema), + quote_string(table), + ); + let col_rows: Vec<(String, String, String)> = conn + .query(col_query) + .await + .context("Failed to query information_schema.columns")?; + let columns: Vec = col_rows + .into_iter() + .map(|(name, data_type, nullable)| SourceColumn { + name, + data_type: mysql_type_to_data_type(&data_type), + nullable: nullable.to_uppercase() == "YES", + pg_type_id: 0, + }) + .collect(); + Ok(columns) +} + +async fn introspect_primary_keys( + conn: &mut mysql_async::Conn, + schema: &str, + table: &str, +) -> Result> { + let pk_query = format!( + "SELECT COLUMN_NAME \ + FROM information_schema.key_column_usage \ + WHERE TABLE_SCHEMA = {} AND TABLE_NAME = {} AND CONSTRAINT_NAME = 'PRIMARY' \ + ORDER BY ORDINAL_POSITION", + quote_string(schema), + quote_string(table), + ); + let pk_rows: Vec<(String,)> = conn + .query(pk_query) + .await + .context("Failed to query primary keys")?; + Ok(pk_rows.into_iter().map(|r| r.0).collect()) +} + +/// Maps MySQL type name strings to generic DataType. +pub fn mysql_type_to_data_type(mysql_type: &str) -> DataType { + match mysql_type.to_uppercase().as_str() { + "TINYINT" => DataType::Int16, + "BOOL" | "BOOLEAN" => DataType::Boolean, + "SMALLINT" | "YEAR" => DataType::Int16, + "MEDIUMINT" | "INT" | "INTEGER" => DataType::Int32, + "BIGINT" => DataType::Int64, + "FLOAT" => DataType::Float32, + "DOUBLE" | "REAL" => DataType::Float64, + "DECIMAL" | "NUMERIC" => DataType::Decimal { + precision: 38, + scale: 9, + }, + "DATE" => DataType::Date, + "TIME" => DataType::Time, + "TIMESTAMP" => DataType::TimestampTz, + "DATETIME" => DataType::Timestamp, + "CHAR" | "VARCHAR" | "ENUM" | "SET" => DataType::String, + "TEXT" | "MEDIUMTEXT" | "LONGTEXT" => DataType::Text, + "BINARY" | "VARBINARY" | "BLOB" | "MEDIUMBLOB" | "LONGBLOB" | "TINYBLOB" | "GEOMETRY" + | "POINT" | "LINESTRING" | "POLYGON" => DataType::Bytes, + "JSON" => DataType::Json, + _ => { + tracing::warn!("Unknown MySQL type: {}, treating as String", mysql_type); + DataType::String + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_quote_string() { + assert_eq!(quote_string("normal"), "'normal'"); + assert_eq!(quote_string("it's"), "'it\\'s'"); + assert_eq!(quote_string(""), "''"); + } + + #[test] + fn test_quote_identifier() { + assert_eq!(quote_identifier("normal"), "`normal`"); + assert_eq!(quote_identifier("it`self"), "`it``self`"); + } + + #[test] + fn test_mysql_type_to_data_type() { + assert_eq!(mysql_type_to_data_type("TINYINT"), DataType::Int16); + assert_eq!(mysql_type_to_data_type("BOOL"), DataType::Boolean); + assert_eq!(mysql_type_to_data_type("INT"), DataType::Int32); + assert_eq!(mysql_type_to_data_type("BIGINT"), DataType::Int64); + assert_eq!(mysql_type_to_data_type("FLOAT"), DataType::Float32); + assert_eq!(mysql_type_to_data_type("DOUBLE"), DataType::Float64); + assert_eq!( + mysql_type_to_data_type("DECIMAL"), + DataType::Decimal { + precision: 38, + scale: 9 + } + ); + assert_eq!(mysql_type_to_data_type("DATE"), DataType::Date); + assert_eq!(mysql_type_to_data_type("TIME"), DataType::Time); + assert_eq!(mysql_type_to_data_type("DATETIME"), DataType::Timestamp); + assert_eq!(mysql_type_to_data_type("TIMESTAMP"), DataType::TimestampTz); + assert_eq!(mysql_type_to_data_type("VARCHAR"), DataType::String); + assert_eq!(mysql_type_to_data_type("TEXT"), DataType::Text); + assert_eq!(mysql_type_to_data_type("BLOB"), DataType::Bytes); + assert_eq!(mysql_type_to_data_type("JSON"), DataType::Json); + assert_eq!(mysql_type_to_data_type("GEOMETRY"), DataType::Bytes); + assert_eq!(mysql_type_to_data_type("UNKNOWN"), DataType::String); + } + + #[test] + fn test_build_opts_from_url() { + let parsed = url::Url::parse("mysql://user:pass@host:3307/dbname").unwrap(); + let opts = build_opts_from_url(parsed).unwrap(); + let _ = opts; + } +} diff --git a/src/source/mysql/setup.rs b/src/source/mysql/setup.rs new file mode 100644 index 0000000..bf832f5 --- /dev/null +++ b/src/source/mysql/setup.rs @@ -0,0 +1,10 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! MySQL setup utilities. +//! +//! Currently, GTID/binlog validation is inlined in [`MysqlSource::setup()`](super::MysqlSource). +//! As the MySQL CDC implementation grows, setup-related checks (privilege validation, +//! Aurora detection, connection parameter tuning) should be extracted into this module. + +// Future: extract setup checks here when they grow beyond the inline implementation. diff --git a/src/source/postgres.rs b/src/source/postgres.rs index 131b838..e676c1a 100644 --- a/src/source/postgres.rs +++ b/src/source/postgres.rs @@ -1,10 +1,14 @@ use anyhow::{Context, Result}; +use async_trait::async_trait; use bytes::{BufMut, Bytes, BytesMut}; use std::time::{SystemTime, UNIX_EPOCH}; use tokio_postgres::{Client, Config, CopyBothDuplex, NoTls}; use tracing::{error, info, warn}; +use crate::config::SourceType; use crate::core::traits::{SourceColumn, SourceTableSchema}; +use crate::core::{ReplicationStream, Source, SourcePosition}; +use crate::replication::pg_stream::PgReplicationStream; use crate::source::converter::pg_type_to_data_type; use crate::utils::validate_sql_identifier; @@ -341,3 +345,59 @@ impl PostgresSource { .replace("replication=database&", "") } } + +#[async_trait] +impl Source for PostgresSource { + fn name(&self) -> &'static str { + "postgres" + } + + fn source_type(&self) -> SourceType { + SourceType::Postgres + } + + async fn validate(&self) -> Result<()> { + // Validation is handled in PostgresSource::new() + Ok(()) + } + + async fn setup(&mut self, _tables: &[String]) -> Result<()> { + // No special setup needed for PG (already done in new()) + Ok(()) + } + + async fn start_replication( + &mut self, + position: Option, + ) -> Result> { + let start_lsn = match position { + Some(SourcePosition::Lsn(lsn)) => lsn, + _ => 0, + }; + let stream = self.start_replication_from(start_lsn).await?; + Ok(Box::new(PgReplicationStream::new(stream))) + } + + fn checkpoint_position(&self) -> Option { + // PG tracks this via the feedback loop + None + } + + async fn cleanup(&mut self) -> Result<()> { + // Cleanup is done in engine's run_main_loop + Ok(()) + } + + async fn create_loop( + &mut self, + position: Option, + ) -> Result> { + let stream = self.start_replication(position).await?; + Ok(Box::new( + crate::engine::replication::PgReplicationLoop::new( + stream, + crate::pipeline::schema_cache::SchemaCache::new(), + ), + )) + } +} diff --git a/src/state_store.rs b/src/state_store.rs index def1226..5946636 100644 --- a/src/state_store.rs +++ b/src/state_store.rs @@ -7,14 +7,63 @@ use tokio::sync::Mutex; use tokio_postgres::{Client, NoTls}; use tracing::error; +#[cfg(feature = "mysql-source")] +use anyhow::Context; +#[cfg(feature = "mysql-source")] +use mysql_async::prelude::Queryable; +#[cfg(feature = "mysql-source")] +use tracing::info; + +/// Backend for checkpoint persistence. +/// +/// Detects the database scheme from the URL: +/// - `postgres://` → PostgreSQL with `lsn BIGINT` +/// - `mysql://` → MySQL with `(mysql_binlog_file, mysql_gtid_set)` +#[derive(Clone)] +enum StoreBackend { + Postgres { + client: Arc>, + }, + #[cfg(feature = "mysql-source")] + Mysql { + conn: Arc>, + }, +} + #[derive(Clone)] pub struct StateStore { - client: Arc>, + backend: StoreBackend, } impl StateStore { + /// Create a new state store. URL scheme selects the backend (`postgres://` or `mysql://`). pub async fn new(database_url: &str) -> Result { - // Create regular connection (non-replication) for checkpoints + if database_url.starts_with("postgres://") || database_url.starts_with("postgresql://") { + Self::new_postgres(database_url).await + } else if database_url.starts_with("mysql://") { + #[cfg(feature = "mysql-source")] + { + Self::new_mysql(database_url).await + } + #[cfg(not(feature = "mysql-source"))] + { + anyhow::bail!( + "MySQL checkpoint store requires the 'mysql-source' feature. \ + Build with --features mysql-source" + ) + } + } else { + anyhow::bail!( + "Unsupported state store URL scheme. \ + Expected 'postgres://', 'postgresql://', or 'mysql://', got: '{}'", + database_url.split("://").next().unwrap_or(database_url) + ) + } + } + + /// PostgreSQL backend (original implementation, unchanged behavior). + async fn new_postgres(database_url: &str) -> Result { + // Remove replication query param so we connect as a regular client let clean_url = database_url .replace("?replication=database", "") .replace("&replication=database", "") @@ -24,7 +73,7 @@ impl StateStore { tokio::spawn(async move { if let Err(e) = connection.await { - error!("StateStore connection error: {}", e); + error!("StateStore (PostgreSQL) connection error: {}", e); } }); @@ -41,31 +90,195 @@ impl StateStore { .await?; Ok(Self { - client: Arc::new(Mutex::new(client)), + backend: StoreBackend::Postgres { + client: Arc::new(Mutex::new(client)), + }, + }) + } + + /// MySQL backend — creates `dbmazz_checkpoints` with the + /// `(mysql_binlog_file, mysql_gtid_set)` triple used by MySQL CDC + /// restart. + #[cfg(feature = "mysql-source")] + async fn new_mysql(database_url: &str) -> Result { + let opts = build_mysql_opts(database_url) + .context("StateStore (MySQL): failed to parse MySQL URL")?; + + let mut conn = mysql_async::Conn::new(opts) + .await + .context("StateStore (MySQL): failed to connect")?; + info!("StateStore (MySQL): connected"); + + conn.query_drop( + "CREATE TABLE IF NOT EXISTS dbmazz_checkpoints ( + slot_name VARCHAR(255) PRIMARY KEY, + mysql_binlog_file VARCHAR(512) NOT NULL, + mysql_binlog_position BIGINT UNSIGNED NOT NULL, + mysql_gtid_set TEXT NOT NULL, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ON UPDATE CURRENT_TIMESTAMP + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", + ) + .await + .context("StateStore (MySQL): failed to create dbmazz_checkpoints table")?; + info!("StateStore (MySQL): ensured dbmazz_checkpoints table"); + + Ok(Self { + backend: StoreBackend::Mysql { + conn: Arc::new(Mutex::new(conn)), + }, }) } + /// Persist a Postgres LSN checkpoint for the given slot. + /// + /// MySQL uses `save_mysql_checkpoint` instead — this method is + /// Postgres-only and rejects calls against the MySQL backend. pub async fn save_checkpoint(&self, slot: &str, lsn: u64) -> Result<()> { - let client = self.client.lock().await; - client - .execute( - "INSERT INTO dbmazz_checkpoints (slot_name, lsn) VALUES ($1, $2) - ON CONFLICT (slot_name) DO UPDATE SET lsn = $2, updated_at = NOW()", - &[&slot, &(lsn as i64)], - ) - .await?; - Ok(()) + match &self.backend { + StoreBackend::Postgres { client } => { + let client = client.lock().await; + client + .execute( + "INSERT INTO dbmazz_checkpoints (slot_name, lsn) + VALUES ($1, $2) + ON CONFLICT (slot_name) + DO UPDATE SET lsn = $2, updated_at = NOW()", + &[&slot, &(lsn as i64)], + ) + .await?; + Ok(()) + } + #[cfg(feature = "mysql-source")] + StoreBackend::Mysql { .. } => { + anyhow::bail!( + "save_checkpoint(slot, lsn) is Postgres-only; \ + use save_mysql_checkpoint(slot, file, position, gtid_set) for MySQL." + ) + } + } } - pub async fn load_checkpoint(&self, slot: &str) -> Result> { - let client = self.client.lock().await; - let row = client - .query_opt( - "SELECT lsn FROM dbmazz_checkpoints WHERE slot_name = $1", - &[&slot], - ) - .await?; + /// Persist the MySQL binlog checkpoint triple `(file, position, gtid_set)`. + /// Rejected by the Postgres backend — Postgres uses `save_checkpoint`. + #[cfg(feature = "mysql-source")] + pub async fn save_mysql_checkpoint( + &self, + slot: &str, + binlog_file: &str, + position: u64, + gtid_set: &str, + ) -> Result<()> { + match &self.backend { + StoreBackend::Postgres { .. } => anyhow::bail!( + "save_mysql_checkpoint called on a Postgres state store; \ + use save_checkpoint(slot, lsn) for Postgres." + ), + StoreBackend::Mysql { conn } => { + let mut conn = conn.lock().await; + conn.exec_drop( + "INSERT INTO dbmazz_checkpoints \ + (slot_name, mysql_binlog_file, mysql_binlog_position, mysql_gtid_set) \ + VALUES (?, ?, ?, ?) \ + ON DUPLICATE KEY UPDATE \ + mysql_binlog_file = VALUES(mysql_binlog_file), \ + mysql_binlog_position = VALUES(mysql_binlog_position), \ + mysql_gtid_set = VALUES(mysql_gtid_set), \ + updated_at = CURRENT_TIMESTAMP", + (slot, binlog_file, position, gtid_set), + ) + .await + .context("StateStore (MySQL): failed to save mysql checkpoint")?; + Ok(()) + } + } + } - Ok(row.map(|r| r.get::<_, i64>(0) as u64)) + /// Load the MySQL binlog checkpoint triple, or `None` if not persisted. + /// Rejected by the Postgres backend. + #[cfg(feature = "mysql-source")] + pub async fn load_mysql_checkpoint(&self, slot: &str) -> Result> { + match &self.backend { + StoreBackend::Postgres { .. } => anyhow::bail!( + "load_mysql_checkpoint called on a Postgres state store; \ + use load_checkpoint(slot) for Postgres." + ), + StoreBackend::Mysql { conn } => { + let mut conn = conn.lock().await; + let row: Option<(String, u64, String)> = conn + .exec_first( + "SELECT mysql_binlog_file, mysql_binlog_position, mysql_gtid_set \ + FROM dbmazz_checkpoints \ + WHERE slot_name = ?", + (slot,), + ) + .await + .context("StateStore (MySQL): failed to load mysql checkpoint")?; + Ok(row) + } + } } + + /// Load the last Postgres LSN checkpoint for the given slot. + /// Postgres-only — MySQL uses `load_mysql_checkpoint`. + pub async fn load_checkpoint(&self, slot: &str) -> Result> { + match &self.backend { + StoreBackend::Postgres { client } => { + let client = client.lock().await; + let row = client + .query_opt( + "SELECT lsn FROM dbmazz_checkpoints WHERE slot_name = $1", + &[&slot], + ) + .await?; + Ok(row.map(|r| r.get::<_, i64>(0) as u64)) + } + #[cfg(feature = "mysql-source")] + StoreBackend::Mysql { .. } => anyhow::bail!( + "load_checkpoint(slot) is Postgres-only; \ + use load_mysql_checkpoint(slot) for MySQL." + ), + } + } +} + +/// Build `mysql_async::Opts` from a `mysql://` URL. +/// +/// Reads `MYSQL_TLS_SKIP_VERIFY` to honour the same opt-out the source +/// connections use. The state store usually runs against the same MySQL +/// instance as the source, so a single env var controls both. +#[cfg(feature = "mysql-source")] +fn build_mysql_opts(url: &str) -> Result { + let parsed = url::Url::parse(url).context("StateStore (MySQL): failed to parse URL")?; + + anyhow::ensure!( + parsed.scheme() == "mysql", + "StateStore (MySQL): unsupported scheme '{}'", + parsed.scheme() + ); + + let host = parsed.host_str().unwrap_or("localhost"); + let port = parsed.port().unwrap_or(3306); + let user = if !parsed.username().is_empty() { + parsed.username() + } else { + "root" + }; + let password = parsed.password().unwrap_or(""); + let database = parsed.path().trim_start_matches('/'); + + let tls_skip_verify = std::env::var("MYSQL_TLS_SKIP_VERIFY") + .map(|v| v == "true") + .unwrap_or(false); + let ssl_opts = crate::source::mysql::mysql_ssl_opts(tls_skip_verify); + + let builder = mysql_async::OptsBuilder::default() + .ip_or_hostname(host) + .tcp_port(port) + .db_name(Some(database)) + .user(Some(user)) + .pass(Some(password)) + .ssl_opts(ssl_opts); + + Ok(mysql_async::Opts::from(builder)) } diff --git a/tests/common/mod.rs b/tests/common/mod.rs new file mode 100644 index 0000000..a79a9fa --- /dev/null +++ b/tests/common/mod.rs @@ -0,0 +1,198 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! Shared helpers for the MySQL integration tests. +//! +//! Tests are gated behind `TEST_MYSQL_URL`. To run them locally: +//! +//! ```sh +//! docker run -d --rm --name dbmazz-test-mysql \ +//! -p 13306:3306 \ +//! -e MYSQL_ALLOW_EMPTY_PASSWORD=1 \ +//! -e MYSQL_DATABASE=dbmazz_test \ +//! mysql:8.0 \ +//! --gtid-mode=ON --enforce-gtid-consistency=ON \ +//! --log-bin=mysql-bin --server-id=1 \ +//! --binlog-format=ROW --binlog-row-image=FULL +//! +//! # wait ~10s for MySQL to come up +//! TEST_MYSQL_URL=mysql://root@127.0.0.1:13306/dbmazz_test \ +//! cargo test --features mysql-source -- --ignored +//! ``` +//! +//! Each test creates a unique database under the configured server so +//! parallel tests don't collide; the database is dropped on teardown. + +#![allow(dead_code)] // helpers are unused in some test files + +use std::sync::{Arc, Mutex}; + +use anyhow::{Context, Result}; +use async_trait::async_trait; +use mysql_async::prelude::Queryable; + +use dbmazz::core::traits::{LoadingModel, Sink, SinkCapabilities, SinkResult, SourceTableSchema}; +use dbmazz::core::CdcRecord; + +/// Returns the MySQL URL for tests, or `None` if the env var is unset +/// (tests skip with a helpful message in that case). +pub fn test_mysql_url() -> Option { + std::env::var("TEST_MYSQL_URL").ok() +} + +/// Skip-or-panic helper: returns the URL if set, otherwise prints a +/// recipe and exits the test successfully (so CI doesn't fail when +/// the env var is unset). +pub fn require_mysql_url() -> String { + match test_mysql_url() { + Some(u) => u, + None => { + eprintln!( + "TEST_MYSQL_URL not set; skipping integration test. \ + See tests/common/mod.rs for setup instructions." + ); + // The `#[ignore]` attribute already keeps these out of CI; + // this `panic!` only fires when someone runs `--ignored` + // without TEST_MYSQL_URL set, in which case skipping + // silently would be misleading. + panic!("TEST_MYSQL_URL must be set to run this integration test"); + } + } +} + +/// Build a randomized database name so parallel tests don't collide +/// (and a leftover db from a prior crashed run doesn't poison state). +pub fn unique_db_name(prefix: &str) -> String { + use std::time::{SystemTime, UNIX_EPOCH}; + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + format!("{}_{}", prefix, nanos) +} + +/// Open a non-replication connection to the MySQL server (root URL). +/// Used by tests for setup/teardown SQL. +pub async fn connect_admin(url: &str) -> Result { + let opts = mysql_async::Opts::from_url(url).context("parse mysql url")?; + let conn = mysql_async::Conn::new(opts) + .await + .context("connect to mysql")?; + Ok(conn) +} + +/// Drop the test database. Best-effort; logs but doesn't fail. +pub async fn drop_database(admin_url: &str, db: &str) { + if let Ok(mut conn) = connect_admin(admin_url).await { + let _ = conn + .query_drop(format!("DROP DATABASE IF EXISTS `{}`", db)) + .await; + let _ = conn.disconnect().await; + } +} + +/// In-memory sink that records every `write_batch` call. Cheaply +/// cloneable — the captured records live behind an `Arc>` so +/// the test can inspect them after the engine completes. +#[derive(Clone, Default)] +pub struct RecordingSink { + pub records: Arc>>, + pub setup_calls: Arc>, + pub close_calls: Arc>, +} + +impl RecordingSink { + pub fn new() -> Self { + Self::default() + } + + /// Snapshot of all records emitted so far. Cloned so the caller can + /// hold it without keeping the lock. + pub fn captured(&self) -> Vec { + self.records.lock().unwrap().clone() + } + + /// Count of records of a specific shape, by table name. Useful for + /// assertions like "exactly N inserts for users table". + pub fn count_inserts_for(&self, schema: &str, table: &str) -> usize { + self.records + .lock() + .unwrap() + .iter() + .filter(|r| match r { + CdcRecord::Insert { table: t, .. } => { + t.schema.as_deref() == Some(schema) && t.name == table + } + _ => false, + }) + .count() + } + + pub fn count_updates_for(&self, schema: &str, table: &str) -> usize { + self.records + .lock() + .unwrap() + .iter() + .filter(|r| match r { + CdcRecord::Update { table: t, .. } => { + t.schema.as_deref() == Some(schema) && t.name == table + } + _ => false, + }) + .count() + } + + /// Build a sink_factory function that constructs an Arc-cloned + /// view of this RecordingSink for each call (snapshot workers + /// request a fresh sink via the factory). + pub fn factory(&self) -> dbmazz::engine::SinkFactory { + let recorder = self.clone(); + Arc::new(move || -> anyhow::Result> { Ok(Box::new(recorder.clone())) }) + } +} + +#[async_trait] +impl Sink for RecordingSink { + fn name(&self) -> &'static str { + "recording" + } + + fn capabilities(&self) -> SinkCapabilities { + SinkCapabilities { + supports_upsert: true, + supports_delete: true, + supports_schema_evolution: false, + supports_transactions: false, + loading_model: LoadingModel::Streaming, + min_batch_size: None, + max_batch_size: Some(10_000), + optimal_flush_interval_ms: 500, + } + } + + async fn validate_connection(&self) -> Result<()> { + Ok(()) + } + + async fn setup(&mut self, _source_schemas: &[SourceTableSchema]) -> Result<()> { + *self.setup_calls.lock().unwrap() += 1; + Ok(()) + } + + async fn write_batch(&mut self, batch: Vec) -> Result { + let count = batch.len(); + let mut records = self.records.lock().unwrap(); + records.extend(batch); + Ok(SinkResult { + records_written: count, + bytes_written: 0, + last_position: None, + schema_evolution_skipped: 0, + }) + } + + async fn close(&mut self) -> Result<()> { + *self.close_calls.lock().unwrap() += 1; + Ok(()) + } +} diff --git a/tests/mysql_cdc_concurrent_snapshot.rs b/tests/mysql_cdc_concurrent_snapshot.rs new file mode 100644 index 0000000..2b667f7 --- /dev/null +++ b/tests/mysql_cdc_concurrent_snapshot.rs @@ -0,0 +1,320 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! End-to-end integration test: concurrent snapshot + CDC against a real +//! MySQL instance, with a recording sink. +//! +//! Exercises the full DBLog read-only reconciliation path: +//! * snapshot reads chunks bounded by `[start_pk, end_pk)`, +//! * binlog consumer concurrently processes random UPDATEs, +//! * eviction is recorded for PKs that fall in active chunks' windows, +//! * snapshot worker drains drained chunks and emits non-evicted rows, +//! * `try_drain` fires on every event including heartbeats so quiet +//! intervals don't stall the snapshot worker. +//! +//! Final assertion: every PK observed by the source ends up in the +//! recorder's captured records exactly the right number of times — no +//! PK is missing, no PK has a "stale snapshot Insert" emitted on top +//! of a CDC Update for the same PK with a more recent value. +//! +//! Gated behind TEST_MYSQL_URL — see tests/common/mod.rs. + +#![cfg(feature = "mysql-source")] + +mod common; + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::Result; +use mysql_async::prelude::Queryable; + +use common::{connect_admin, drop_database, require_mysql_url, unique_db_name, RecordingSink}; + +const SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(180); +const ROW_COUNT: i32 = 5_000; +const UPDATE_COUNT: usize = 500; +const CHUNK_SIZE: u64 = 500; + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires TEST_MYSQL_URL — see tests/common/mod.rs"] +async fn concurrent_snapshot_and_cdc_no_data_loss_or_duplicates() -> Result<()> { + let admin_url = require_mysql_url(); + let db = unique_db_name("dbmazz_cs"); + + // ------------------------------------------------------------------- + // Setup: create database + populate. + // ------------------------------------------------------------------- + let mut admin = connect_admin(&admin_url).await?; + admin + .query_drop(format!("CREATE DATABASE `{}`", db)) + .await?; + admin + .query_drop(format!( + "CREATE TABLE `{}`.`accounts` (\ + id INT PRIMARY KEY, \ + balance INT NOT NULL\ + ) ENGINE=InnoDB", + db + )) + .await?; + let inserts: String = (1..=ROW_COUNT) + .map(|i| format!("({}, {})", i, i * 10)) + .collect::>() + .join(","); + admin + .query_drop(format!( + "INSERT INTO `{}`.`accounts` (id, balance) VALUES {}", + db, inserts + )) + .await?; + admin.disconnect().await?; + + let test_url = url_with_database(&admin_url, &db); + + // ------------------------------------------------------------------- + // Spawn dbmazz with a recording sink and DO_SNAPSHOT=true so the + // snapshot starts as soon as the daemon comes up. CDC is running + // concurrently from the moment the binlog stream opens. + // ------------------------------------------------------------------- + let recorder = RecordingSink::new(); + let config = make_config(&test_url, /*do_snapshot=*/ true); + let engine = dbmazz::engine::CdcEngine::with_sink_factory(config, recorder.factory()).await?; + let shared_state = engine.shared_state(); + let shared_for_main = Arc::clone(&shared_state); + + let engine_handle = tokio::spawn(async move { engine.run().await }); + + // Wait for the engine to enter Cdc stage (binlog stream open). + wait_for_cdc(&shared_for_main, Duration::from_secs(20)).await?; + + // ------------------------------------------------------------------- + // Drive concurrent UPDATEs. Random PKs in [1, ROW_COUNT]. + // ------------------------------------------------------------------- + let mut update_handles = Vec::new(); + // Deterministic stride pick — UPDATE_COUNT distinct PKs spread over + // [1, ROW_COUNT]. Avoids pulling rand into dev-deps and keeps the + // test reproducible across runs. + let stride = (ROW_COUNT as usize / UPDATE_COUNT).max(1); + let targets: Vec = (1..=ROW_COUNT).step_by(stride).take(UPDATE_COUNT).collect(); + let expected_post_update_balance: HashMap = targets + .iter() + .map(|&pk| (pk, pk * 10 + 1)) // increment by 1 — distinct from pre-snapshot value + .collect(); + + for &pk in &targets { + let url = test_url.clone(); + let db_name = db.clone(); + let new_balance = pk * 10 + 1; + update_handles.push(tokio::spawn(async move { + // Spread UPDATEs across the snapshot window. + tokio::time::sleep(Duration::from_millis((pk as u64 % 1000).saturating_add(10))).await; + let mut conn = connect_admin(&url).await?; + conn.exec_drop( + format!( + "UPDATE `{}`.`accounts` SET balance = ? WHERE id = ?", + db_name + ), + (new_balance, pk), + ) + .await?; + conn.disconnect().await?; + Ok::<_, anyhow::Error>(()) + })); + } + + // Wait for snapshot completion or timeout. + let snap_done = tokio::time::timeout(SNAPSHOT_TIMEOUT, async { + loop { + if !shared_state.is_snapshot_active() { + break; + } + tokio::time::sleep(Duration::from_millis(200)).await; + } + }) + .await; + assert!( + snap_done.is_ok(), + "snapshot did not complete within {:?}", + SNAPSHOT_TIMEOUT + ); + + // Ensure all UPDATEs have actually committed; flush via sleep so + // the binlog consumer has a chance to forward them. + for h in update_handles { + h.await??; + } + tokio::time::sleep(Duration::from_secs(2)).await; + + // Tear down. + let _ = shared_state.shutdown_tx.send(true); + let _ = tokio::time::timeout(Duration::from_secs(15), engine_handle).await; + + // ------------------------------------------------------------------- + // Assertions. + // ------------------------------------------------------------------- + let captured = recorder.captured(); + + // 1. Every PK 1..=ROW_COUNT appears at least once in the captured + // records (either as snapshot Insert or — for late-bootstrap — + // no record, but our test bootstraps before the binlog stream + // rotates, so all rows must be observed). + let mut seen_pks: std::collections::HashSet = std::collections::HashSet::new(); + let mut latest_balance: HashMap = HashMap::new(); + let mut snapshot_inserts_per_pk: HashMap = HashMap::new(); + + for r in &captured { + match r { + dbmazz::core::CdcRecord::Insert { table, columns, .. } if table.name == "accounts" => { + if let (Some(pk), Some(balance)) = + (extract_int(columns, "id"), extract_int(columns, "balance")) + { + seen_pks.insert(pk as i32); + latest_balance.insert(pk as i32, balance as i32); + *snapshot_inserts_per_pk.entry(pk as i32).or_default() += 1; + } + } + dbmazz::core::CdcRecord::Update { + table, new_columns, .. + } if table.name == "accounts" => { + if let (Some(pk), Some(balance)) = ( + extract_int(new_columns, "id"), + extract_int(new_columns, "balance"), + ) { + seen_pks.insert(pk as i32); + latest_balance.insert(pk as i32, balance as i32); + } + } + _ => {} + } + } + + let missing: Vec = (1..=ROW_COUNT) + .filter(|pk| !seen_pks.contains(pk)) + .collect(); + assert!( + missing.is_empty(), + "{} PKs missing from sink output (first 20: {:?})", + missing.len(), + missing.iter().take(20).collect::>() + ); + + // 2. For every PK that received a concurrent UPDATE, the latest + // balance observed at the sink matches the post-update value + // (`pk*10 + 1`), not the pre-update value (`pk*10`). This is + // the C3 fix: even if the snapshot SELECT raced the UPDATE, + // the eviction (or order-of-arrival) must surface the latest + // value as the last write to the sink. + let mut wrong: Vec<(i32, i32, i32)> = Vec::new(); + for (pk, &expected) in &expected_post_update_balance { + match latest_balance.get(pk) { + Some(&actual) if actual == expected => {} // correct + Some(&actual) => wrong.push((*pk, expected, actual)), + None => wrong.push((*pk, expected, -1)), + } + } + assert!( + wrong.is_empty(), + "{} PKs have wrong final balance at sink (sample: {:?})", + wrong.len(), + wrong.iter().take(5).collect::>() + ); + + // 3. Snapshot Inserts per PK should be ≤ 1. More than one means a + // chunk overlap — would indicate a regression in chunker logic. + let multi_insert: Vec<(i32, u32)> = snapshot_inserts_per_pk + .iter() + .filter(|(_, &n)| n > 1) + .map(|(pk, n)| (*pk, *n)) + .collect(); + assert!( + multi_insert.is_empty(), + "PKs received >1 snapshot Insert: {:?}", + multi_insert.iter().take(5).collect::>() + ); + + drop_database(&admin_url, &db).await; + Ok(()) +} + +async fn wait_for_cdc(state: &dbmazz::control::SharedState, timeout: Duration) -> Result<()> { + let res = tokio::time::timeout(timeout, async { + loop { + let (stage, _detail) = state.stage().await; + if matches!(stage, dbmazz::control::Stage::Cdc) { + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + }) + .await; + res.map_err(|_| anyhow::anyhow!("dbmazz did not reach CDC stage within {:?}", timeout))?; + Ok(()) +} + +fn extract_int(columns: &[dbmazz::core::ColumnValue], name: &str) -> Option { + columns.iter().find(|c| c.name == name).and_then(|c| { + if let dbmazz::core::Value::Int64(i) = &c.value { + Some(*i) + } else { + None + } + }) +} + +fn make_config(source_url: &str, do_snapshot: bool) -> dbmazz::config::Config { + use dbmazz::config::{ + Config, MysqlSourceConfig, PostgresSinkConfig, SinkConfig, SinkSpecificConfig, SinkType, + SourceConfig, SourceType, + }; + + let mysql_source = MysqlSourceConfig { + server_id: 5401, + gtid_enabled: true, + tls_skip_verify: false, + }; + + let source = SourceConfig { + source_type: SourceType::Mysql, + url: source_url.to_string(), + tables: vec!["accounts".to_string()], + postgres: None, + mysql: Some(mysql_source), + }; + + let sink = SinkConfig { + sink_type: SinkType::Postgres, + url: "127.0.0.1".to_string(), + port: 5432, + database: "irrelevant".to_string(), + user: "irrelevant".to_string(), + password: "irrelevant".to_string(), + specific: SinkSpecificConfig::Postgres(PostgresSinkConfig { + schema: "public".to_string(), + job_name: "test".to_string(), + }), + }; + + Config { + source, + sink, + flush_size: 200, + flush_interval_ms: 200, + do_snapshot, + initial_snapshot_only: false, + control_port: 0, + snapshot_chunk_size: CHUNK_SIZE, + snapshot_parallel_workers: 1, + } +} + +fn url_with_database(base_url: &str, db: &str) -> String { + match url::Url::parse(base_url) { + Ok(mut u) => { + u.set_path(&format!("/{}", db)); + u.to_string() + } + Err(_) => format!("{}/{}", base_url.trim_end_matches('/'), db), + } +} diff --git a/tests/mysql_snapshot_low_watermark.rs b/tests/mysql_snapshot_low_watermark.rs new file mode 100644 index 0000000..a370f80 --- /dev/null +++ b/tests/mysql_snapshot_low_watermark.rs @@ -0,0 +1,313 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! Integration test for the snapshot LOW-watermark race fix (C3). +//! +//! Pre-fix, the snapshot worker captured `LOW = SELECT @@global.gtid_executed` +//! BEFORE registering the chunk in the active-chunks registry. Any binlog +//! event with `gtid > LOW` that mutated a row in the chunk's PK range and +//! arrived between the capture and the registration was processed by the +//! consumer with no chunk present — no eviction recorded — and the +//! subsequent SELECT then read the post-mutation value. The snapshot would +//! emit an Insert for the row at the same time the CDC consumer emitted +//! an Update, producing duplicate emission for one PK. +//! +//! Post-fix, the chunk is registered using the binlog consumer's live GTID +//! set as LOW (atomically with the registry insert), so any event the +//! consumer hasn't seen yet is in the chunk's window and gets evicted. +//! +//! This test: +//! 1. populates `users` with 1000 rows +//! 2. spawns dbmazz with a recording sink +//! 3. triggers a single snapshot chunk +//! 4. concurrently issues an UPDATE for PK 500 +//! 5. waits for snapshot completion +//! 6. asserts: PK 500 appears AT MOST once in snapshot Inserts AND +//! the post-update value is observable in the captured records. +//! +//! Gated behind TEST_MYSQL_URL — see tests/common/mod.rs for the docker +//! recipe and run instructions. + +#![cfg(feature = "mysql-source")] + +mod common; + +use std::sync::Arc; +use std::time::Duration; + +use anyhow::Result; +use mysql_async::prelude::Queryable; + +use common::{connect_admin, drop_database, require_mysql_url, unique_db_name, RecordingSink}; + +const SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(60); +const ROW_COUNT: i32 = 1000; +const TARGET_PK: i32 = 500; + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires TEST_MYSQL_URL — see tests/common/mod.rs"] +async fn snapshot_low_watermark_no_duplicate_emission() -> Result<()> { + let admin_url = require_mysql_url(); + let db = unique_db_name("dbmazz_lw"); + + // ------------------------------------------------------------------- + // Setup: create database, populate test table. + // ------------------------------------------------------------------- + let mut admin = connect_admin(&admin_url).await?; + admin + .query_drop(format!("CREATE DATABASE `{}`", db)) + .await?; + + // Build a URL that targets the new database for dbmazz config. + let test_url = url_with_database(&admin_url, &db); + + admin + .query_drop(format!( + "CREATE TABLE `{}`.`users` (\ + id INT PRIMARY KEY, \ + name VARCHAR(64) NOT NULL\ + ) ENGINE=InnoDB", + db + )) + .await?; + + // Insert ROW_COUNT rows. + let inserts: String = (1..=ROW_COUNT) + .map(|i| format!("({}, 'snap-{}')", i, i)) + .collect::>() + .join(","); + admin + .query_drop(format!( + "INSERT INTO `{}`.`users` (id, name) VALUES {}", + db, inserts + )) + .await?; + admin.disconnect().await?; + + // ------------------------------------------------------------------- + // Drive dbmazz programmatically. We want full control over snapshot + // trigger timing, so we DO NOT pass DO_SNAPSHOT=true; we call + // `shared_state.snapshot_trigger.send(true)` after a brief delay, + // and concurrently issue the racing UPDATE. + // ------------------------------------------------------------------- + let recorder = RecordingSink::new(); + let config = make_config(&test_url, &db, /*do_snapshot=*/ false); + let engine = dbmazz::engine::CdcEngine::with_sink_factory(config, recorder.factory()).await?; + + let shared_state = engine.shared_state(); + let recorder_for_update = recorder.clone(); + let url_for_update = test_url.clone(); + let db_for_update = db.clone(); + let shared_for_trigger = Arc::clone(&shared_state); + + let engine_handle = tokio::spawn(async move { engine.run().await }); + + // Wait briefly for the binlog consumer to be running and tracking. + // 1 second is generous on a local docker instance. + tokio::time::sleep(Duration::from_secs(1)).await; + + // Trigger snapshot. + let _ = shared_for_trigger.snapshot_trigger.send(true); + + // Concurrent UPDATE. Run in a separate task; small jitter so the + // race window is exercised across runs. + let update_handle = tokio::spawn(async move { + // Tiny jitter to interleave with snapshot SELECT timing. + tokio::time::sleep(Duration::from_millis(50)).await; + let mut conn = connect_admin(&url_for_update).await?; + conn.exec_drop( + format!( + "UPDATE `{}`.`users` SET name = ? WHERE id = ?", + db_for_update + ), + ("cdc-updated-500", TARGET_PK), + ) + .await?; + conn.disconnect().await?; + let _ = recorder_for_update; // keep recorder alive across awaits + Ok::<_, anyhow::Error>(()) + }); + + // Wait for snapshot to complete or timeout. Snapshot completion is + // signalled by `is_snapshot_active() == false` AFTER the trigger + // landed (so we wait for it to flip true → false rather than + // spuriously matching the initial false). + let snap_completed = tokio::time::timeout(SNAPSHOT_TIMEOUT, async { + loop { + if shared_state.is_snapshot_active() { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + loop { + if !shared_state.is_snapshot_active() { + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + }) + .await; + assert!( + snap_completed.is_ok(), + "snapshot did not complete within {:?}", + SNAPSHOT_TIMEOUT + ); + update_handle.await??; + + // Give the CDC consumer a moment to flush the post-update row event + // through the pipeline / sink. + tokio::time::sleep(Duration::from_millis(500)).await; + + // ------------------------------------------------------------------- + // Tear down the engine. + // ------------------------------------------------------------------- + let _ = shared_state.shutdown_tx.send(true); + let _ = tokio::time::timeout(Duration::from_secs(10), engine_handle).await; + + // ------------------------------------------------------------------- + // Assertions. + // ------------------------------------------------------------------- + let captured = recorder.captured(); + let inserts_for_target: Vec<_> = captured + .iter() + .filter(|r| matches!(r, + dbmazz::core::CdcRecord::Insert { table, columns, .. } + if table.name == "users" + && columns.iter().any(|c| c.name == "id" + && matches!(&c.value, dbmazz::core::Value::Int64(i) if *i == TARGET_PK as i64)) + )) + .collect(); + let updates_for_target: Vec<_> = captured + .iter() + .filter(|r| matches!(r, + dbmazz::core::CdcRecord::Update { table, new_columns, .. } + if table.name == "users" + && new_columns.iter().any(|c| c.name == "id" + && matches!(&c.value, dbmazz::core::Value::Int64(i) if *i == TARGET_PK as i64)) + )) + .collect(); + + // Pre-fix: 1 Insert (snap-500) + 1 Update (cdc-updated-500) = 2 events. + // Post-fix correct: either + // (a) 0 Insert + 1 Update (eviction worked, only CDC saw the row), OR + // (b) 1 Insert (cdc-updated-500) + 1 Update (cdc-updated-500), where + // the snapshot SELECT already saw the new value because the + // UPDATE landed before SELECT. + // What MUST NOT happen: 1 Insert (snap-500, the stale value) + 1 Update + // — that means we emitted the snapshot row on top of a CDC update. + + let stale_insert = inserts_for_target.iter().any(|r| match r { + dbmazz::core::CdcRecord::Insert { columns, .. } => columns + .iter() + .any(|c| c.name == "name" + && matches!(&c.value, dbmazz::core::Value::String(s) if s == &format!("snap-{}", TARGET_PK))), + _ => false, + }); + assert!( + !stale_insert, + "PK {} was emitted as snapshot Insert with the pre-update value 'snap-{}'; \ + eviction failed (LOW-watermark race regression). \ + Inserts: {}, Updates: {}", + TARGET_PK, + TARGET_PK, + inserts_for_target.len(), + updates_for_target.len() + ); + + // We should still see the post-update value reach the sink (via either + // path). + let saw_post_update = captured.iter().any(|r| { + let cols_check = |columns: &[dbmazz::core::ColumnValue]| { + let id_match = columns.iter().any(|c| { + c.name == "id" + && matches!(&c.value, dbmazz::core::Value::Int64(i) if *i == TARGET_PK as i64) + }); + let name_match = columns.iter().any(|c| { + c.name == "name" + && matches!(&c.value, dbmazz::core::Value::String(s) if s == "cdc-updated-500") + }); + id_match && name_match + }; + match r { + dbmazz::core::CdcRecord::Insert { table, columns, .. } if table.name == "users" => { + cols_check(columns) + } + dbmazz::core::CdcRecord::Update { + table, new_columns, .. + } if table.name == "users" => cols_check(new_columns), + _ => false, + } + }); + assert!( + saw_post_update, + "the post-update value 'cdc-updated-500' for PK {} never reached the sink", + TARGET_PK + ); + + // Cleanup. + drop_database(&admin_url, &db).await; + Ok(()) +} + +/// Build a dbmazz Config pointed at the test MySQL with a recording sink +/// stand-in (sink_type=postgres but the factory is overridden by +/// `with_sink_factory`, so the SINK_URL is never dialed). +fn make_config(source_url: &str, _db: &str, do_snapshot: bool) -> dbmazz::config::Config { + use dbmazz::config::{Config, MysqlSourceConfig, SinkConfig, SourceConfig, SourceType}; + + let mysql_source = MysqlSourceConfig { + server_id: 5400, + gtid_enabled: true, + tls_skip_verify: false, + }; + + let source = SourceConfig { + source_type: SourceType::Mysql, + url: source_url.to_string(), + tables: vec!["users".to_string()], + postgres: None, + mysql: Some(mysql_source), + }; + + // Sink config is required by `Config` but the factory we pass to + // `with_sink_factory` is what actually creates the sink — these + // values are never dialled in this test. + let sink = SinkConfig { + sink_type: dbmazz::config::SinkType::Postgres, + url: "127.0.0.1".to_string(), + port: 5432, + database: "irrelevant".to_string(), + user: "irrelevant".to_string(), + password: "irrelevant".to_string(), + specific: dbmazz::config::SinkSpecificConfig::Postgres( + dbmazz::config::PostgresSinkConfig { + schema: "public".to_string(), + job_name: "test".to_string(), + }, + ), + }; + + Config { + source, + sink, + flush_size: 100, + flush_interval_ms: 200, + do_snapshot, + initial_snapshot_only: false, + control_port: 0, // disabled — control server bound to "0" is dev-only + snapshot_chunk_size: ROW_COUNT as u64, // single chunk + snapshot_parallel_workers: 1, + } +} + +/// Replace the path component of a `mysql://...` URL with `/` so +/// connections target the test database. +fn url_with_database(base_url: &str, db: &str) -> String { + match url::Url::parse(base_url) { + Ok(mut u) => { + u.set_path(&format!("/{}", db)); + u.to_string() + } + Err(_) => format!("{}/{}", base_url.trim_end_matches('/'), db), + } +}