diff --git a/.gitignore b/.gitignore index cafded5..d3278d4 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,9 @@ /skills-lock.json /Dockerfile.dev +# Local Cargo config (macOS linker, etc.) +.cargo/ + # Byproducts *.log *.tmp diff --git a/CHANGELOG.md b/CHANGELOG.md index 004eeca..2b0ef7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to dbmazz will be documented here. ## [Unreleased] +### Added + +- **Apache Iceberg sink** (`sink-apache_iceberg`). Writes CDC data as Parquet files and commits new snapshots via the REST catalog protocol. Supports schema evolution (ADD COLUMN) and soft deletes via audit columns. Append-only; CoW mode planned. See `connectors/sinks/apache_iceberg/README.md`. + ## [2.5.0] - 2026-05-16 ### Changed diff --git a/Cargo.lock b/Cargo.lock index e67c0e5..5108b66 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -913,7 +913,7 @@ dependencies = [ [[package]] name = "dbmazz" -version = "2.5.0" +version = "2.6.0" dependencies = [ "anyhow", "arrow", @@ -934,22 +934,24 @@ dependencies = [ "memchr", "mysql_async", "mysql_common", + "object_store", "openssl-sys", "parquet", "pem", "postgres-protocol", "postgres-types", - "reqwest", + "reqwest 0.11.27", "rsa", "serde", "serde_json", "serial_test", "sha2", "simdutf8", + "temp-env", "tokio", "tokio-postgres", "tokio-stream", - "tower-http", + "tower-http 0.5.2", "tracing", "tracing-subscriber", "url", @@ -1179,6 +1181,21 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" +[[package]] +name = "futures" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.32" @@ -1241,6 +1258,7 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" dependencies = [ + "futures-channel", "futures-core", "futures-io", "futures-macro", @@ -1281,9 +1299,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 5.3.0", "wasip2", + "wasm-bindgen", ] [[package]] @@ -1324,6 +1344,25 @@ dependencies = [ "tracing", ] +[[package]] +name = "h2" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "171fefbc92fe4a4de27e0698d6a5b392d6a0e333506bc49133760b3bcf948733" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http 1.4.0", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "half" version = "2.7.1" @@ -1461,6 +1500,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "humantime" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424" + [[package]] name = "hyper" version = "0.14.32" @@ -1471,7 +1516,7 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", - "h2", + "h2 0.3.27", "http 0.2.12", "http-body 0.4.6", "httparse", @@ -1495,6 +1540,7 @@ dependencies = [ "bytes", "futures-channel", "futures-core", + "h2 0.4.14", "http 1.4.0", "http-body 1.0.1", "httparse", @@ -1503,6 +1549,7 @@ dependencies = [ "pin-project-lite", "smallvec", "tokio", + "want", ] [[package]] @@ -1514,9 +1561,25 @@ dependencies = [ "futures-util", "http 0.2.12", "hyper 0.14.32", - "rustls", + "rustls 0.21.12", "tokio", - "tokio-rustls", + "tokio-rustls 0.24.1", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http 1.4.0", + "hyper 1.9.0", + "hyper-util", + "rustls 0.23.40", + "rustls-native-certs", + "tokio", + "tokio-rustls 0.26.4", + "tower-service", ] [[package]] @@ -1525,13 +1588,21 @@ version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" dependencies = [ + "base64 0.22.1", "bytes", + "futures-channel", + "futures-util", "http 1.4.0", "http-body 1.0.1", "hyper 1.9.0", + "ipnet", + "libc", + "percent-encoding", "pin-project-lite", + "socket2 0.6.3", "tokio", "tower-service", + "tracing", ] [[package]] @@ -1912,6 +1983,12 @@ dependencies = [ "hashbrown 0.15.5", ] +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + [[package]] name = "matchers" version = "0.2.0" @@ -2196,6 +2273,38 @@ dependencies = [ "libm", ] +[[package]] +name = "object_store" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cfccb68961a56facde1163f9319e0d15743352344e7808a11795fb99698dcaf" +dependencies = [ + "async-trait", + "base64 0.22.1", + "bytes", + "chrono", + "futures", + "httparse", + "humantime", + "hyper 1.9.0", + "itertools", + "md-5", + "parking_lot", + "percent-encoding", + "quick-xml", + "rand 0.8.5", + "reqwest 0.12.28", + "ring", + "rustls-pemfile 2.2.0", + "serde", + "serde_json", + "snafu", + "tokio", + "tracing", + "url", + "walkdir", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -2579,6 +2688,71 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "quick-xml" +version = "0.37.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls 0.23.40", + "socket2 0.6.3", + "thiserror 2.0.18", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" +dependencies = [ + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand 0.9.2", + "ring", + "rustc-hash", + "rustls 0.23.40", + "rustls-pki-types", + "slab", + "thiserror 2.0.18", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2 0.6.3", + "tracing", + "windows-sys 0.59.0", +] + [[package]] name = "quote" version = "1.0.45" @@ -2732,11 +2906,11 @@ dependencies = [ "encoding_rs", "futures-core", "futures-util", - "h2", + "h2 0.3.27", "http 0.2.12", "http-body 0.4.6", "hyper 0.14.32", - "hyper-rustls", + "hyper-rustls 0.24.2", "ipnet", "js-sys", "log", @@ -2744,15 +2918,15 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite", - "rustls", - "rustls-pemfile", + "rustls 0.21.12", + "rustls-pemfile 1.0.4", "serde", "serde_json", "serde_urlencoded", "sync_wrapper 0.1.2", "system-configuration", "tokio", - "tokio-rustls", + "tokio-rustls 0.24.1", "tokio-util", "tower-service", "url", @@ -2764,6 +2938,48 @@ dependencies = [ "winreg", ] +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "h2 0.4.14", + "http 1.4.0", + "http-body 1.0.1", + "http-body-util", + "hyper 1.9.0", + "hyper-rustls 0.27.9", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls 0.23.40", + "rustls-native-certs", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper 1.0.2", + "tokio", + "tokio-rustls 0.26.4", + "tokio-util", + "tower", + "tower-http 0.6.11", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + [[package]] name = "ring" version = "0.17.14" @@ -2880,10 +3096,36 @@ checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" dependencies = [ "log", "ring", - "rustls-webpki", + "rustls-webpki 0.101.7", "sct", ] +[[package]] +name = "rustls" +version = "0.23.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki 0.103.13", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +dependencies = [ + "openssl-probe 0.2.1", + "rustls-pki-types", + "schannel", + "security-framework", +] + [[package]] name = "rustls-pemfile" version = "1.0.4" @@ -2893,6 +3135,25 @@ dependencies = [ "base64 0.21.7", ] +[[package]] +name = "rustls-pemfile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9" +dependencies = [ + "web-time", + "zeroize", +] + [[package]] name = "rustls-webpki" version = "0.101.7" @@ -2903,6 +3164,17 @@ dependencies = [ "untrusted", ] +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.22" @@ -2915,6 +3187,15 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + [[package]] name = "saturating" version = "0.1.0" @@ -3183,6 +3464,27 @@ version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +[[package]] +name = "snafu" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e84b3f4eacbf3a1ce05eac6763b4d629d60cbc94d632e4092c54ade71f1e1a2" +dependencies = [ + "snafu-derive", +] + +[[package]] +name = "snafu-derive" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "snap" version = "1.1.1" @@ -3303,6 +3605,9 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] [[package]] name = "synstructure" @@ -3342,6 +3647,15 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" +[[package]] +name = "temp-env" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96374855068f47402c3121c6eed88d29cb1de8f3ab27090e273e420bdabcf050" +dependencies = [ + "parking_lot", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -3556,7 +3870,17 @@ version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" dependencies = [ - "rustls", + "rustls 0.21.12", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls 0.23.40", "tokio", ] @@ -3646,6 +3970,24 @@ dependencies = [ "tower-service", ] +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.11.0", + "bytes", + "futures-util", + "http 1.4.0", + "http-body 1.0.1", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + [[package]] name = "tower-layer" version = "0.3.3" @@ -3835,6 +4177,16 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + [[package]] name = "want" version = "0.3.1" @@ -3987,6 +4339,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "webpki-roots" version = "0.25.4" diff --git a/Cargo.toml b/Cargo.toml index c1009fb..39119de 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "dbmazz" -version = "2.5.0" +version = "2.6.0" edition = "2021" license = "Elastic-2.0" # Minimum Supported Rust Version. @@ -18,6 +18,10 @@ sink-snowflake = [ "dep:jsonwebtoken", "dep:rsa", "dep:pem", "dep:sha2", "dep:aws-sigv4", "dep:aws-credential-types", "dep:uuid", ] +sink-apache_iceberg = [ + "dep:reqwest", "dep:arrow", "dep:parquet", + "dep:uuid", "dep:object_store", +] [dependencies] # Materialize fork with full support for logical replication @@ -71,6 +75,7 @@ sha2 = { version = "0.10", optional = true } aws-sigv4 = { version = "1.2", optional = true } aws-credential-types = { version = "1.2", optional = true } uuid = { version = "1", features = ["v4"], optional = true } +object_store = { version = "0.11", default-features = false, features = ["aws", "gcp", "azure"], optional = true } # --- Optional: MySQL source --- mysql_common = { version = "=0.32.4", features = ["binlog"], optional = true } @@ -78,6 +83,7 @@ mysql_common = { version = "=0.32.4", features = ["binlog"], optional = true } [dev-dependencies] serial_test = "3.0" mysql_async = "0.34" +temp-env = "0.3" [profile.release] debug = 1 # Line tables only (flamegraphs work, smaller binary) diff --git a/README.md b/README.md index 13a2ccd..51befdb 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ Full Docker reference (env vars, healthcheck, persisting state, build-from-sourc | PostgreSQL 12+ | **StarRocks 3.2+** | ✅ Stable | JSON Stream Load, partial-update for TOAST columns, audit columns auto-managed, schema evolution requires per-table `fast_schema_evolution=true` | | 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) | +| PostgreSQL 12+ | **Apache Iceberg** (`apache_iceberg`) | ✅ Stable | Append-only via Parquet + REST catalog snapshots. CoW for updates/deletes planned. | | MySQL 5.7+ / 8.0+ | All sinks | ✅ Stable | Binlog-based with GTID-aware checkpointing, BIGINT UNSIGNED, microsecond DATETIME, non-integer PK support, cursor-based snapshot chunker. 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/cc-wrapper.sh b/cc-wrapper.sh new file mode 100644 index 0000000..7f1623f --- /dev/null +++ b/cc-wrapper.sh @@ -0,0 +1,2 @@ +#!/bin/bash +exec /usr/bin/cc "$@" diff --git a/docs/architecture.md b/docs/architecture.md index dbebff6..1076811 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -200,6 +200,12 @@ src/ │ ├── merge_generator.rs MERGE SQL with VARIANT extraction + TOAST │ ├── normalizer.rs Async MERGE loop (raw table → target) │ └── types.rs PG → Snowflake type mapping +│ └── apache_iceberg/ Apache Iceberg sink +│ ├── mod.rs ApacheIcebergSink (Parquet → REST catalog commit) +│ ├── config.rs ApacheIcebergSinkConfig (catalog URL, warehouse, namespace) +│ ├── types.rs PG → Iceberg type mapping +│ ├── setup.rs DDL: namespace creation, table creation via REST API +│ └── schema_evolution.rs ADD COLUMN via Iceberg schema commit ├── control/ HTTP control plane (axum) │ ├── mod.rs Router + server startup │ ├── state.rs SharedState (metrics, dedup, control) diff --git a/docs/configuration.md b/docs/configuration.md index c6d26a3..af8e2c1 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -23,8 +23,8 @@ every option documented inline. The default location is | Variable | Default | Description | |---|---|---| -| `SINK_TYPE` | `starrocks` | Sink connector type: `starrocks`, `postgres`, or `snowflake`. | -| `SINK_URL` | — | Sink connection URL. For StarRocks: `http://host:8030` (FE HTTP). For PostgreSQL: `postgres://...`. For Snowflake: ignored (use `SINK_SNOWFLAKE_ACCOUNT`). | +| `SINK_TYPE` | `starrocks` | Sink connector type: `starrocks`, `postgres`, `snowflake`, or `apache_iceberg`. | +| `SINK_URL` | — | Sink connection URL. For StarRocks: `http://host:8030` (FE HTTP). For PostgreSQL: `postgres://...`. For Snowflake: ignored (use `SINK_SNOWFLAKE_ACCOUNT`). For Apache Iceberg: `http://host:8181` (REST catalog). | | `SINK_PORT` | `9030` | Additional port when needed (e.g., StarRocks MySQL protocol port for DDL). | | `SINK_DATABASE` | — (required) | Target database name. | | `SINK_SCHEMA` | `public` | Target schema (PostgreSQL) or `PUBLIC` (Snowflake). StarRocks does not use this. | @@ -44,6 +44,13 @@ every option documented inline. The default location is | `SINK_SNOWFLAKE_FLUSH_FILES` | `20` | Trigger `COPY INTO` after accumulating this many staged Parquet files. For e2e testing, set to `1` for immediate flush. | | `SINK_SNOWFLAKE_FLUSH_BYTES` | `104857600` | Trigger `COPY INTO` after accumulating this many bytes (default 100 MB). Whichever threshold (files or bytes) is reached first wins. | +## Sink (Apache Iceberg-specific) + +| Variable | Default | Description | +|---|---|---| +| `SINK_WAREHOUSE` | — (required) | Iceberg warehouse path, e.g. `file:///tmp/warehouse` or `s3://my-bucket/warehouse`. | +| `SINK_ICEBERG_PREFIX` | `v1` | REST catalog API prefix appended to `SINK_URL`. | + ## Pipeline / batching | Variable | Default | Description | diff --git a/src/config.rs b/src/config.rs index 6ee64a1..fc5f0b1 100644 --- a/src/config.rs +++ b/src/config.rs @@ -136,6 +136,7 @@ pub enum SinkType { StarRocks, Postgres, Snowflake, + ApacheIceberg, } impl SinkType { @@ -144,8 +145,9 @@ impl SinkType { "starrocks" => Ok(SinkType::StarRocks), "postgres" | "postgresql" => Ok(SinkType::Postgres), "snowflake" => Ok(SinkType::Snowflake), + "apache_iceberg" | "apacheiceberg" => Ok(SinkType::ApacheIceberg), other => anyhow::bail!( - "Unsupported sink type: '{}'. Supported: starrocks, postgres, snowflake", + "Unsupported sink type: '{}'. Supported: starrocks, postgres, snowflake, apache_iceberg", other ), } @@ -158,6 +160,7 @@ impl std::fmt::Display for SinkType { SinkType::StarRocks => write!(f, "starrocks"), SinkType::Postgres => write!(f, "postgres"), SinkType::Snowflake => write!(f, "snowflake"), + SinkType::ApacheIceberg => write!(f, "apache_iceberg"), } } } @@ -189,6 +192,7 @@ pub enum SinkSpecificConfig { StarRocks, Postgres(PostgresSinkConfig), Snowflake, + ApacheIceberg, } impl std::fmt::Debug for SinkConfig { @@ -337,15 +341,20 @@ impl Config { let sink_type = SinkType::from_str(&sink_type_str)?; // SINK_URL is required for StarRocks/Postgres, but optional for Snowflake - // (auto-derived from SINK_SNOWFLAKE_ACCOUNT). + // (auto-derived from SINK_SNOWFLAKE_ACCOUNT) and ApacheIceberg (has its own URL). let sink_url = match sink_type { SinkType::Snowflake => optional_env("SINK_URL", ""), + SinkType::ApacheIceberg => required_env("SINK_URL")?, _ => required_env("SINK_URL")?, }; - let sink_port: u16 = optional_env("SINK_PORT", "9030").parse().unwrap_or(9030); + // ApacheIceberg uses SINK_NAMESPACE instead of SINK_DATABASE. + let sink_database = match sink_type { + SinkType::ApacheIceberg => required_env("SINK_NAMESPACE")?, + _ => required_env("SINK_DATABASE")?, + }; - let sink_database = required_env("SINK_DATABASE")?; + let sink_port: u16 = optional_env("SINK_PORT", "9030").parse().unwrap_or(9030); let sink_user = optional_env("SINK_USER", "root"); @@ -359,6 +368,7 @@ impl Config { job_name: slot_name.clone(), }), SinkType::Snowflake => SinkSpecificConfig::Snowflake, + SinkType::ApacheIceberg => SinkSpecificConfig::ApacheIceberg, }; let sink = SinkConfig { @@ -469,6 +479,9 @@ impl Config { SinkType::Snowflake => { info!("Sink: Snowflake (db: {})", self.sink.database); } + SinkType::ApacheIceberg => { + info!("Sink: Apache Iceberg (namespace: {})", self.sink.database); + } } info!( diff --git a/src/connectors/sinks/apache_iceberg/README.md b/src/connectors/sinks/apache_iceberg/README.md new file mode 100644 index 0000000..bccfd6d --- /dev/null +++ b/src/connectors/sinks/apache_iceberg/README.md @@ -0,0 +1,28 @@ +# Apache Iceberg Sink Connector + +CDC sink connector for Apache Iceberg via the REST catalog protocol. + +## Overview + +Records are accumulated in memory, serialized to Parquet files, written to the warehouse +path, and committed as new Iceberg snapshots through the REST catalog API. + +## Configuration + +| Variable | Default | Description | +|---|---|---| +| `SINK_TYPE` | — | Must be `apache_iceberg` | +| `SINK_URL` | — | REST catalog URL (e.g. `http://localhost:8181`) | +| `SINK_WAREHOUSE` | — | Warehouse path (e.g. `file:///tmp/warehouse`) | +| `SINK_DATABASE` | — | Target namespace / database in the catalog | +| `SINK_ICEBERG_PREFIX` | `v1` | REST API prefix | + +## Table creation + +Tables and namespaces are created automatically during sink setup. Four audit columns are +added to every table: `_dbmazz_op_type`, `_dbmazz_is_deleted`, `_dbmazz_synced_at`, `_dbmazz_cdc_version`. + +## Schema Evolution + +New columns from the source are detected automatically and added to the Iceberg schema via +the REST catalog's schema commit endpoint. diff --git a/src/connectors/sinks/apache_iceberg/config.rs b/src/connectors/sinks/apache_iceberg/config.rs new file mode 100644 index 0000000..d7f15c7 --- /dev/null +++ b/src/connectors/sinks/apache_iceberg/config.rs @@ -0,0 +1,187 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! Apache Iceberg Sink Configuration +//! +//! Handles configuration parsing for the Apache Iceberg sink connector. +//! Communicates with a REST catalog for table management and commit operations. + +use anyhow::{anyhow, Result}; +use tracing::info; + +use crate::config::SinkConfig; + +/// Apache Iceberg sink configuration for REST catalog access. +#[derive(Clone)] +pub struct ApacheIcebergSinkConfig { + /// REST catalog URL (e.g., "http://localhost:8181") + pub url: String, + + /// Iceberg warehouse path (e.g., "s3://my-bucket/warehouse") + pub warehouse: String, + + /// Target namespace/database within the catalog + pub namespace: String, + + /// REST API prefix (default: "v1") + pub prefix: String, +} + +impl std::fmt::Debug for ApacheIcebergSinkConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ApacheIcebergSinkConfig") + .field("url", &self.url) + .field("warehouse", &self.warehouse) + .field("namespace", &self.namespace) + .field("prefix", &self.prefix) + .finish() + } +} + +impl ApacheIcebergSinkConfig { + /// Creates an Apache Iceberg configuration from the generic SinkConfig + env vars. + pub fn from_sink_config(config: &SinkConfig) -> Result { + let url = config.url.clone(); + + let warehouse = + std::env::var("SINK_WAREHOUSE").map_err(|_| anyhow!("SINK_WAREHOUSE must be set"))?; + + let namespace = config.database.clone(); + + let prefix = std::env::var("SINK_ICEBERG_PREFIX").unwrap_or_else(|_| "v1".to_string()); + + info!( + "ApacheIcebergSinkConfig: url={}, warehouse={}, namespace={}, prefix={}", + url, warehouse, namespace, prefix + ); + + Ok(Self { + url, + warehouse, + namespace, + prefix, + }) + } + + /// Returns the full REST catalog base URL including the API prefix. + pub fn catalog_url(&self) -> String { + format!("{}/{}", self.url.trim_end_matches('/'), self.prefix) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::{SinkConfig, SinkSpecificConfig, SinkType}; + + fn test_sink_config() -> SinkConfig { + SinkConfig { + sink_type: SinkType::ApacheIceberg, + url: "http://localhost:8181".to_string(), + port: 8181, + database: "test_db".to_string(), + user: String::new(), + password: String::new(), + specific: SinkSpecificConfig::ApacheIceberg, + } + } + + #[test] + fn test_from_sink_config() { + temp_env::with_vars( + [ + ("SINK_WAREHOUSE", Some("s3://test-bucket/warehouse")), + ("SINK_ICEBERG_PREFIX", Some("v2")), + ], + || { + let sink_config = test_sink_config(); + let config = ApacheIcebergSinkConfig::from_sink_config(&sink_config).unwrap(); + + assert_eq!(config.url, "http://localhost:8181"); + assert_eq!(config.warehouse, "s3://test-bucket/warehouse"); + assert_eq!(config.namespace, "test_db"); + assert_eq!(config.prefix, "v2"); + }, + ); + } + + #[test] + fn test_from_sink_config_default_prefix() { + temp_env::with_vars( + [ + ("SINK_WAREHOUSE", Some("s3://test-bucket/warehouse")), + ("SINK_ICEBERG_PREFIX", None::<&str>), + ], + || { + let sink_config = test_sink_config(); + let config = ApacheIcebergSinkConfig::from_sink_config(&sink_config).unwrap(); + + assert_eq!(config.prefix, "v1"); + }, + ); + } + + #[test] + fn test_from_sink_config_missing_warehouse() { + temp_env::with_vars([("SINK_WAREHOUSE", None::<&str>)], || { + let sink_config = test_sink_config(); + let result = ApacheIcebergSinkConfig::from_sink_config(&sink_config); + assert!(result.is_err()); + assert!(result.unwrap_err().to_string().contains("SINK_WAREHOUSE")); + }); + } + + #[test] + fn test_catalog_url() { + temp_env::with_vars( + [ + ("SINK_WAREHOUSE", Some("s3://test-bucket/warehouse")), + ("SINK_ICEBERG_PREFIX", Some("v2")), + ], + || { + let sink_config = test_sink_config(); + let config = ApacheIcebergSinkConfig::from_sink_config(&sink_config).unwrap(); + + assert_eq!(config.catalog_url(), "http://localhost:8181/v2"); + }, + ); + } + + #[test] + fn test_catalog_url_trailing_slash() { + // Ensure trailing slash on url is handled + let mut cfg = test_sink_config(); + cfg.url = "http://localhost:8181/".to_string(); + + temp_env::with_vars( + [ + ("SINK_WAREHOUSE", Some("s3://test-bucket/warehouse")), + ("SINK_ICEBERG_PREFIX", Some("v1")), + ], + || { + let config = ApacheIcebergSinkConfig::from_sink_config(&cfg).unwrap(); + assert_eq!(config.catalog_url(), "http://localhost:8181/v1"); + }, + ); + } + + #[test] + fn test_debug_no_redaction() { + temp_env::with_vars( + [ + ("SINK_WAREHOUSE", Some("s3://test-bucket/warehouse")), + ("SINK_ICEBERG_PREFIX", Some("v1")), + ], + || { + let sink_config = test_sink_config(); + let config = ApacheIcebergSinkConfig::from_sink_config(&sink_config).unwrap(); + + let debug_str = format!("{:?}", config); + assert!(debug_str.contains("http://localhost:8181")); + assert!(debug_str.contains("s3://test-bucket/warehouse")); + assert!(debug_str.contains("test_db")); + assert!(!debug_str.contains("REDACTED")); + }, + ); + } +} diff --git a/src/connectors/sinks/apache_iceberg/mod.rs b/src/connectors/sinks/apache_iceberg/mod.rs new file mode 100644 index 0000000..8a95288 --- /dev/null +++ b/src/connectors/sinks/apache_iceberg/mod.rs @@ -0,0 +1,1112 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! # Apache Iceberg Sink Connector +//! +//! CDC sink for Apache Iceberg using the REST catalog protocol. +//! Data is written as Parquet files on the warehouse path and committed as +//! new Iceberg snapshots via the REST catalog's table commit endpoint. +//! +//! ## Architecture +//! +//! ```text +//! CdcRecord → Parquet file → REST catalog commit (snapshot append) +//! ``` +//! +//! This is an append-only sink. For Copy-on-Write (CoW) mode: +//! - **Inserts**: appended as new data files → new snapshot +//! - **Updates/Deletes**: currently treated as inserts with audit columns +//! (`_dbmazz_op_type`, `_dbmazz_is_deleted`) for downstream filtering. +//! Full CoW rewrite is planned. + +pub mod config; +pub(crate) mod schema_evolution; +pub mod setup; +pub(crate) mod types; + +use anyhow::{Context, Result}; +use async_trait::async_trait; +use std::collections::HashMap; +use std::sync::Arc; +use tokio::sync::RwLock; +use tracing::{info, warn}; + +use object_store::aws::AmazonS3Builder; +use object_store::path::Path as StorePath; +use object_store::ObjectStore; + +use crate::config::SinkConfig; +use crate::connectors::sinks::schema_evolution::compute_schema_evolution_plan; +use crate::core::traits::{SourceTableSchema, StageFormat}; +use crate::core::{CdcRecord, LoadingModel, Sink, SinkCapabilities, SinkMode, SinkResult}; + +pub use self::config::ApacheIcebergSinkConfig; +use self::schema_evolution::IcebergSchemaEvolution; +use self::types::TypeMapper; + +// --------------------------------------------------------------------------- +// Constants +// --------------------------------------------------------------------------- + +/// Default number of records before flushing pending records to Parquet. +/// Set to 1 so that every `write_batch` call triggers a flush immediately. +/// The engine's timer (`optimal_flush_interval_ms → 0`) controls the flush +/// frequency (default 5 s). This avoids re-buffering records that would +/// never reach the threshold in test/small-CDC scenarios. +const DEFAULT_FLUSH_THRESHOLD_RECORDS: usize = 1; + +/// Default flush interval in milliseconds. +/// Matches the Snowflake sink's interval (30 s). This is aggressive enough +/// for development/testing yet configurable for production via the job config. +const DEFAULT_FLUSH_INTERVAL_MS: u64 = 30_000; + +// --------------------------------------------------------------------------- +// Schema state +// --------------------------------------------------------------------------- + +/// Shared cache mapping `.` → `SourceTableSchema`. +type SchemaState = Arc>>; + +// --------------------------------------------------------------------------- +// Apache Iceberg Sink +// --------------------------------------------------------------------------- + +/// Apache Iceberg sink connector implementing the Sink trait via the REST +/// catalog protocol. +/// +/// Data flow: +/// 1. CDC records accumulate in `pending_records` +/// 2. At flush time, records are serialised into a Parquet file +/// 3. The Parquet file is written to the warehouse path +/// 4. A new Iceberg snapshot is committed via the REST catalog API +pub struct ApacheIcebergSink { + config: ApacheIcebergSinkConfig, + _mode: SinkMode, + /// Lazily-initialised reqwest HTTP client shared with schema-evolution. + client: Option, + /// Schema-evolution helper (lazily initialised after client is available). + schema_evolution: Option>, + /// In-memory record buffer accumulated between flushes. + pending_records: Vec, + /// Shared source-schema state updated after schema evolution. + schema_state: SchemaState, + /// Vec mirror of `schema_state` for iteration. + table_schemas: Arc>>, + /// Type mapper for CDC → Iceberg type conversion. + type_mapper: TypeMapper, + /// Object store for S3/MinIO warehouse writes. + object_store: Option>, + /// Accumulated record count (for flushing decisions). + accumulated_records: usize, + /// Flush threshold in records. + flush_threshold_records: usize, +} + +impl ApacheIcebergSink { + /// Create a new `ApacheIcebergSink` from the generic sink config. + pub fn new(config: &SinkConfig, mode: SinkMode) -> Result { + let iceberg_config = ApacheIcebergSinkConfig::from_sink_config(config)?; + info!("ApacheIcebergSink initialized:"); + info!(" Catalog URL: {}", iceberg_config.catalog_url()); + info!(" Warehouse: {}", iceberg_config.warehouse); + info!(" Namespace: {}", iceberg_config.namespace); + info!(" Mode: {:?}", mode); + + let flush_threshold_records = std::env::var("SINK_ICEBERG_FLUSH_RECORDS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(DEFAULT_FLUSH_THRESHOLD_RECORDS); + + Ok(Self { + config: iceberg_config, + _mode: mode, + client: None, + schema_evolution: None, + pending_records: Vec::new(), + schema_state: Arc::new(RwLock::new(HashMap::new())), + table_schemas: Arc::new(RwLock::new(Vec::new())), + type_mapper: TypeMapper::new(), + object_store: None, + accumulated_records: 0, + flush_threshold_records, + }) + } + + /// Lazily initialises and returns the reqwest HTTP client. + fn ensure_client(&mut self) -> Result { + if let Some(ref client) = self.client { + return Ok(client.clone()); + } + let client = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(60)) + .build() + .context("Failed to build reqwest client")?; + self.client = Some(client.clone()); + Ok(client) + } + + /// Lazily initialises and returns the S3/MinIO object store. + /// + /// The bucket is extracted from the warehouse path (`s3://bucket/...`). + /// Configuration is read from env vars with sensible MinIO Docker defaults. + fn ensure_object_store(&mut self) -> Result> { + if let Some(ref store) = self.object_store { + return Ok(store.clone()); + } + + let warehouse = self.config.warehouse.trim_end_matches('/'); + let bucket = warehouse + .strip_prefix("s3://") + .and_then(|s| s.split('/').next()) + .ok_or_else(|| { + anyhow::anyhow!( + "warehouse path must start with s3://; got: {}", + warehouse + ) + })?; + + let endpoint = + std::env::var("AWS_ENDPOINT").unwrap_or_else(|_| "http://minio:9000".to_string()); + let access_key_id = + std::env::var("AWS_ACCESS_KEY_ID").unwrap_or_else(|_| "minioadmin".to_string()); + let secret_access_key = + std::env::var("AWS_SECRET_ACCESS_KEY").unwrap_or_else(|_| "minioadmin".to_string()); + + // Warn if default dev credentials are being used (no env var set). + if std::env::var("AWS_ACCESS_KEY_ID").is_err() + || std::env::var("AWS_SECRET_ACCESS_KEY").is_err() + { + warn!( + "iceberg_sink: using default MinIO dev credentials (minioadmin/minioadmin). \ + Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY env vars for production use." + ); + } + + let store = Arc::new( + AmazonS3Builder::new() + .with_endpoint(endpoint) + .with_access_key_id(access_key_id) + .with_secret_access_key(secret_access_key) + .with_region("us-east-1") + .with_bucket_name(bucket) + .with_allow_http(true) + .with_virtual_hosted_style_request(false) + .build() + .context("iceberg_sink: failed to build AmazonS3 object store")?, + ); + + self.object_store = Some(store.clone()); + Ok(store) + } + + /// Write accumulated pending records into a Parquet file on the warehouse + /// path and commit a new Iceberg snapshot via the REST catalog. + /// + /// This is the core flush operation, called either when the record + /// threshold is reached or on `close()`. + async fn flush_pending(&mut self) -> Result { + if self.pending_records.is_empty() { + return Ok(SinkResult::default()); + } + + let client = self.ensure_client()?; + let records = std::mem::take(&mut self.pending_records); + let count = records.len(); + + // --------------------------------------------------------------- + // 1. Schema evolution pre-pass + // --------------------------------------------------------------- + let snapshot = self.schema_state.read().await.clone(); + let (_working, pending_diffs) = compute_schema_evolution_plan(&snapshot, &records); + + if !pending_diffs.is_empty() { + let schema_evolution = self.schema_evolution.as_ref().ok_or_else(|| { + anyhow::anyhow!( + "iceberg_sink: schema_evolution not initialised (setup() must run first)" + ) + })?; + for (table, diff) in &pending_diffs { + schema_evolution + .apply_diff(&table.name, diff) + .await + .with_context(|| { + format!( + "iceberg_sink: schema evolution failed for table {}", + table.name + ) + })?; + } + // Update schema state. + { + let mut state = self.schema_state.write().await; + *state = _working.clone(); + } + { + let mut tables = self.table_schemas.write().await; + *tables = _working.into_values().collect(); + } + } + + // --------------------------------------------------------------- + // 2. Group records by table → Parquet bytes + // --------------------------------------------------------------- + // The Iceberg REST catalog works on a single table per commit, so we + // group the records by target table and flush one Parquet file per + // table. + let mut table_groups: HashMap> = HashMap::new(); + for rec in &records { + let table_key = match rec { + // Use the bare table name (not qualified_name()) because the + // Iceberg REST catalog registers tables without the schema + // prefix (e.g. "orders", not "public.orders"). + CdcRecord::Insert { table, .. } + | CdcRecord::Update { table, .. } + | CdcRecord::Delete { table, .. } + | CdcRecord::SchemaChange { table, .. } => table.name.clone(), + CdcRecord::Begin { .. } + | CdcRecord::Commit { .. } + | CdcRecord::Heartbeat { .. } => continue, + }; + table_groups.entry(table_key).or_default().push(rec.clone()); + } + + if table_groups.is_empty() { + self.accumulated_records = 0; + return Ok(SinkResult::default()); + } + + // Deduplicate table names to avoid committing the same table twice + // when records from multiple tables arrive in the same batch. + let table_names: std::collections::HashSet = table_groups.keys().cloned().collect(); + + for table_name in &table_names { + let table_records = table_groups.remove(table_name).unwrap_or_default(); + if table_records.is_empty() { + continue; + } + + // Convert records to Parquet bytes in memory. + let parquet_bytes = Self::records_to_parquet_bytes(&table_records, &self.type_mapper) + .with_context(|| { + format!( + "iceberg_sink: failed to serialise records to Parquet for table {}", + table_name + ) + })?; + + // --------------------------------------------------------------- + // 3. Write Parquet file to S3/MinIO via object_store + // --------------------------------------------------------------- + let store = self.ensure_object_store()?; + + // Extract key prefix from warehouse (e.g. "warehouse" from + // "s3://my-bucket/warehouse"). + let warehouse = self.config.warehouse.trim_end_matches('/'); + let key_prefix = warehouse + .strip_prefix("s3://") + .map(|s| { + let parts: Vec<&str> = s.split('/').collect(); + if parts.len() > 1 { + parts[1..].join("/") + } else { + String::new() + } + }) + .unwrap_or_default(); + + let now_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis(); + let file_name = format!("{}-{}.parquet", now_ms, uuid::Uuid::new_v4()); + let s3_key = format!( + "{}/{}/{}/data/{}", + key_prefix, self.config.namespace, table_name, file_name, + ); + let store_path = StorePath::from(s3_key.as_str()); + let data_len = parquet_bytes.len(); + + store + .put(&store_path, parquet_bytes.into()) + .await + .with_context(|| { + format!("iceberg_sink: failed to write Parquet to S3 key {}", s3_key) + })?; + + info!( + table = %table_name, + s3_key = %s3_key, + bytes = data_len, + records = table_records.len(), + "iceberg_sink: Parquet file written to S3" + ); + + // Generate a unique snapshot-id for the Iceberg commit. + // Use nanosecond-precision timestamp to avoid collisions even + // at high throughput (two flushes in the same nanosecond are + // astronomically unlikely). + let snapshot_id = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() as i64; + + // --------------------------------------------------------------- + // 4. Commit a new Iceberg snapshot via the REST catalog + // --------------------------------------------------------------- + self.commit_snapshot(&client, table_name, &s3_key, snapshot_id) + .await + .with_context(|| { + format!( + "iceberg_sink: failed to commit snapshot for table {}", + table_name + ) + })?; + } + + let total_bytes: u64 = 0; // We'll track bytes if needed; for now, record count is the metric. + self.accumulated_records = 0; + + Ok(SinkResult { + records_written: count, + bytes_written: total_bytes, + schema_evolution_skipped: 0, + }) + } + + /// Serialise a group of CDC records into a Parquet byte buffer. + /// + /// The Parquet schema mirrors the source columns + audit columns so the + /// data can be read back with the Iceberg table schema. + fn records_to_parquet_bytes( + records: &[CdcRecord], + type_mapper: &TypeMapper, + ) -> Result> { + use arrow::array::*; + use arrow::datatypes::{DataType as ArrowDataType, Field as ArrowField, Schema}; + use arrow::record_batch::RecordBatch; + use parquet::arrow::ArrowWriter; + use parquet::basic::Compression; + use parquet::file::properties::WriterProperties; + + if records.is_empty() { + return Ok(Vec::new()); + } + + // We build a flat Arrow schema from all columns discovered across the + // batch. Since CDC records may have different schemas (schema + // evolution), we collect the union of all column names. + let mut column_names: Vec = Vec::new(); + for rec in records { + let cols = match rec { + CdcRecord::Insert { columns, .. } => columns, + CdcRecord::Update { new_columns, .. } => new_columns, + CdcRecord::Delete { columns, .. } => columns, + CdcRecord::SchemaChange { columns: _, .. } => { + // SchemaChange carries ColumnDef objects — we don't write + // them to data files. + continue; + } + CdcRecord::Begin { .. } + | CdcRecord::Commit { .. } + | CdcRecord::Heartbeat { .. } => { + continue; + } + }; + for col in cols { + if !column_names.contains(&col.name) { + column_names.push(col.name.clone()); + } + } + } + + // Always include the audit columns. + let audit_columns = &[ + "_dbmazz_op_type", + "_dbmazz_is_deleted", + "_dbmazz_synced_at", + "_dbmazz_cdc_version", + ]; + for audit in audit_columns { + if !column_names.contains(&audit.to_string()) { + column_names.push(audit.to_string()); + } + } + + // Infer Arrow data types for each column by scanning records. + use crate::core::record::Value; + let mut column_types: Vec = Vec::with_capacity(column_names.len()); + for col_name in &column_names { + if col_name.starts_with("_dbmazz_") { + column_types.push(ArrowDataType::Utf8); + continue; + } + // Scan records for the first non-null, non-unchanged value and infer + // the Arrow type from the Value variant. + let mut inferred = ArrowDataType::Utf8; + 'col_scan: for rec in records { + let cols = match rec { + CdcRecord::Insert { columns, .. } => columns, + CdcRecord::Update { new_columns, .. } => new_columns, + CdcRecord::Delete { columns, .. } => columns, + _ => continue, + }; + if let Some(cv) = cols.iter().find(|c| c.name == *col_name) { + if !cv.value.is_null() && !cv.value.is_unchanged() { + inferred = match &cv.value { + Value::Bool(_) => ArrowDataType::Boolean, + Value::Int64(_) => ArrowDataType::Int64, + Value::Float64(_) => ArrowDataType::Float64, + _ => ArrowDataType::Utf8, + }; + break 'col_scan; + } + } + } + column_types.push(inferred); + } + + // Build Arrow fields with inferred types. + let mut arrow_fields: Vec = Vec::with_capacity(column_names.len()); + for (col_name, dt) in column_names.iter().zip(column_types.iter()) { + arrow_fields.push(ArrowField::new(col_name, dt.clone(), true)); + } + let arrow_schema = Arc::new(Schema::new(arrow_fields)); + + // Typed column builder that dispatches to the correct Arrow builder. + enum TypedBuilder { + Boolean(BooleanBuilder), + Int64(Int64Builder), + Float64(Float64Builder), + Utf8(StringBuilder), + } + + impl TypedBuilder { + fn with_capacity(dt: &ArrowDataType, num_rows: usize) -> Self { + match dt { + ArrowDataType::Boolean => { + TypedBuilder::Boolean(BooleanBuilder::with_capacity(num_rows)) + } + ArrowDataType::Int64 => { + TypedBuilder::Int64(Int64Builder::with_capacity(num_rows)) + } + ArrowDataType::Float64 => { + TypedBuilder::Float64(Float64Builder::with_capacity(num_rows)) + } + _ => TypedBuilder::Utf8(StringBuilder::with_capacity(num_rows, num_rows * 64)), + } + } + + fn append_null(&mut self) { + match self { + TypedBuilder::Boolean(b) => b.append_null(), + TypedBuilder::Int64(b) => b.append_null(), + TypedBuilder::Float64(b) => b.append_null(), + TypedBuilder::Utf8(b) => b.append_null(), + } + } + + fn append_utf8(&mut self, val: &str) { + if let TypedBuilder::Utf8(b) = self { + b.append_value(val); + } + } + + fn append_bool(&mut self, val: bool) { + if let TypedBuilder::Boolean(b) = self { + b.append_value(val); + } + } + + fn append_i64(&mut self, val: i64) { + if let TypedBuilder::Int64(b) = self { + b.append_value(val); + } + } + + fn append_f64(&mut self, val: f64) { + if let TypedBuilder::Float64(b) = self { + b.append_value(val); + } + } + + fn finish(&mut self) -> ArrayRef { + match self { + TypedBuilder::Boolean(b) => Arc::new(b.finish()), + TypedBuilder::Int64(b) => Arc::new(b.finish()), + TypedBuilder::Float64(b) => Arc::new(b.finish()), + TypedBuilder::Utf8(b) => Arc::new(b.finish()), + } + } + } + + // Build column builders. + let num_rows = records.len(); + let mut builders: Vec = Vec::with_capacity(column_names.len()); + for dt in &column_types { + builders.push(TypedBuilder::with_capacity(dt, num_rows)); + } + + // Helper: extract columns from a CdcRecord variant. + fn extract_record_data( + rec: &CdcRecord, + ) -> Option<(&[crate::core::ColumnValue], &'static str, bool)> { + match rec { + CdcRecord::Insert { columns, .. } => Some((columns.as_slice(), "insert", false)), + CdcRecord::Update { new_columns, .. } => { + Some((new_columns.as_slice(), "update", false)) + } + CdcRecord::Delete { columns, .. } => Some((columns.as_slice(), "delete", true)), + _ => None, + } + } + + for rec in records { + let entry = extract_record_data(rec); + let (cols, op_type, is_deleted) = match entry { + Some(e) => e, + None => continue, + }; + + for (i, col_name) in column_names.iter().enumerate() { + match col_name.as_str() { + "_dbmazz_op_type" => { + builders[i].append_utf8(op_type); + } + "_dbmazz_is_deleted" => { + builders[i].append_utf8(if is_deleted { "true" } else { "false" }); + } + "_dbmazz_synced_at" => { + let now = chrono::Utc::now().to_rfc3339(); + builders[i].append_utf8(&now); + } + "_dbmazz_cdc_version" => { + builders[i].append_utf8("1"); + } + _ => { + // Find the column value in the record. + let val = cols.iter().find(|c| c.name == *col_name); + match val { + Some(cv) => { + // Null or Unchanged (TOAST) values: use append_null() + // rather than storing a misleading sentinel string. + // Unchanged columns are filtered here to avoid + // overwriting real values with NULL in append-only + // Parquet snapshots. + if cv.value.is_null() || cv.value.is_unchanged() { + builders[i].append_null(); + } else { + // Dispatch on the Value variant to use the + // correct typed builder method. + match &cv.value { + Value::Bool(b) => builders[i].append_bool(*b), + Value::Int64(n) => builders[i].append_i64(*n), + Value::Float64(f) => builders[i].append_f64(*f), + _ => { + let plain_str = + type_mapper.value_to_parquet_string(&cv.value); + builders[i].append_utf8(&plain_str); + } + } + } + } + None => { + builders[i].append_null(); + } + } + } + } + } + } + + // Build arrays and record batch. + let mut arrays: Vec = Vec::with_capacity(column_names.len()); + for builder in &mut builders { + arrays.push(builder.finish()); + } + + let batch = RecordBatch::try_new(arrow_schema.clone(), arrays) + .context("iceberg_sink: failed to create Arrow RecordBatch")?; + + // Write to Parquet with Snappy compression (the parquet crate + // dependency only enables "snap" — not zstd — so we avoid a + // compile-time panic from the disabled zstd feature). + let props = WriterProperties::builder() + .set_compression(Compression::SNAPPY) + .build(); + + let mut parquet_buf = Vec::with_capacity(num_rows * 128); + let mut writer = ArrowWriter::try_new(&mut parquet_buf, arrow_schema, Some(props)) + .context("iceberg_sink: failed to create ArrowWriter")?; + + writer + .write(&batch) + .context("iceberg_sink: failed to write RecordBatch to Parquet")?; + + let _metadata = writer + .close() + .context("iceberg_sink: failed to close ArrowWriter")?; + + Ok(parquet_buf) + } + + /// Commit a new Iceberg snapshot that adds the given Parquet data file. + /// + /// Uses the REST catalog table commit endpoint: + /// `POST /v1/{prefix}/namespaces/{ns}/tables/{table}` + /// + /// The commit body creates an add-snapshot update with a manifest-list + /// reference and sets the snapshot-ref to "main" so the snapshot becomes + /// the current table state. + /// + /// Before committing, the current table metadata is fetched to obtain the + /// latest snapshot-id for use as the parent-snapshot-id (and for the + /// assert-ref-snapshot-id requirement). This ensures snapshot sequence + /// numbers are monotonic — required by the Iceberg REST catalog. + async fn commit_snapshot( + &self, + client: &reqwest::Client, + table_name: &str, + _data_file_path: &str, + snapshot_id: i64, + ) -> Result<()> { + let catalog_url = self.config.catalog_url(); + let table_url = format!( + "{}/namespaces/{}/tables/{}", + catalog_url, self.config.namespace, table_name, + ); + + // --------------------------------------------------------------- + // 1. Fetch current table metadata to learn the latest snapshot + // --------------------------------------------------------------- + // We need BOTH the current-snapshot-id (for parent-snapshot-id) and + // its sequence-number (for the new snapshot's sequence-number). + let (current_snapshot_id, parent_seq_number): (Option, i64) = { + let resp = client.get(&table_url).send().await.with_context(|| { + format!( + "iceberg_sink: failed to GET table metadata for '{}'", + table_name + ) + })?; + if !resp.status().is_success() { + warn!( + "iceberg_sink: GET table metadata returned {} for '{}' — \ + proceeding without parent snapshot", + resp.status(), + table_name, + ); + (None, 0) + } else { + let resp_value: serde_json::Value = resp + .json() + .await + .context("iceberg_sink: failed to parse table metadata JSON")?; + // REST API wraps table metadata inside {"metadata": {TableMetadata}} + let table_meta = resp_value + .get("metadata") + .context("iceberg_sink: missing 'metadata' field in table response")?; + let current_id = table_meta + .get("current-snapshot-id") + .and_then(|v| v.as_i64()) + .filter(|&id| id != -1); + // Find the current snapshot's sequence-number from the + // snapshots array. + let seq = current_id + .and_then(|cid| { + table_meta + .get("snapshots")? + .as_array()? + .iter() + .find_map(|s| { + let sid = s.get("snapshot-id")?.as_i64()?; + if sid == cid { + s.get("sequence-number")?.as_i64() + } else { + None + } + }) + }) + .unwrap_or(0); + (current_id, seq) + } + }; + + let now_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as i64; + + // Compute the new sequence-number: parent + 1, or 1 if first + // snapshot. + let new_sequence_number = if parent_seq_number > 0 { + parent_seq_number + 1 + } else { + 1 + }; + + let parent_snapshot_id = current_snapshot_id.unwrap_or(-1); + + // Build an Iceberg commit request. + let warehouse = self.config.warehouse.trim_end_matches('/'); + let key_prefix = warehouse + .strip_prefix("s3://") + .map(|s| { + let parts: Vec<&str> = s.split('/').collect(); + if parts.len() > 1 { + parts[1..].join("/") + } else { + String::new() + } + }) + .unwrap_or_default(); + + let manifest_list_path = format!( + "{}/{}/{}/metadata/snap-{}.avro", + key_prefix, self.config.namespace, table_name, snapshot_id, + ); + + // --------------------------------------------------------------- + // 2. Build requirements + updates + // --------------------------------------------------------------- + + // Requirements: assert that the main branch still points to the + // snapshot we read (prevents concurrent overwrites). + let requirements = match current_snapshot_id { + Some(parent) => serde_json::json!([ + { + "type": "assert-ref-snapshot-id", + "ref": "main", + "snapshot-id": parent + } + ]), + None => serde_json::json!([]), + }; + + // Summary metadata for the new snapshot. + let summary = serde_json::json!({ + "operation": "append", + "total-records": "0", + "total-data-files": "1", + "added-records": "0", + "added-data-files": "1" + }); + + let commit_body = serde_json::json!({ + "requirements": requirements, + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": snapshot_id, + "parent-snapshot-id": parent_snapshot_id, + "sequence-number": new_sequence_number, + "timestamp-ms": now_ms, + "schema-id": 0, + "summary": summary, + "manifest-list": manifest_list_path + } + }, + { + "action": "set-snapshot-ref", + "ref-name": "main", + "snapshot-id": snapshot_id, + "type": "branch" + } + ] + }); + + let resp = client + .post(&table_url) + .json(&commit_body) + .send() + .await + .with_context(|| { + format!( + "iceberg_sink: HTTP POST commit failed for table {}", + table_name + ) + })?; + + if !resp.status().is_success() { + let status = resp.status(); + let body = resp.text().await.unwrap_or_default(); + + return Err(anyhow::anyhow!( + "iceberg_sink: commit snapshot for table {} returned HTTP {}: {}", + table_name, + status, + body, + )); + } + + info!( + table = %table_name, + snapshot_id = snapshot_id, + "iceberg_sink: snapshot committed successfully" + ); + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// Drop guard +// --------------------------------------------------------------------------- + +impl Drop for ApacheIcebergSink { + fn drop(&mut self) { + if !self.pending_records.is_empty() { + warn!( + records = self.pending_records.len(), + "iceberg_sink: ApacheIcebergSink dropped with pending records — \ + close() was not called or flush failed; data may be lost" + ); + } + } +} + +// --------------------------------------------------------------------------- +// Sink trait implementation +// --------------------------------------------------------------------------- + +#[async_trait] +impl Sink for ApacheIcebergSink { + fn name(&self) -> &'static str { + "apache_iceberg" + } + + fn capabilities(&self) -> SinkCapabilities { + SinkCapabilities { + supports_upsert: true, + supports_delete: true, + supports_schema_evolution: true, + supports_transactions: false, + loading_model: LoadingModel::StagedBatch { + stage_format: StageFormat::Parquet, + }, + min_batch_size: Some(100), + max_batch_size: Some(500_000), + optimal_flush_interval_ms: DEFAULT_FLUSH_INTERVAL_MS, + } + } + + async fn validate_connection(&self) -> Result<()> { + let client = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(10)) + .build() + .context("Failed to build reqwest client")?; + + let catalog_url = self.config.catalog_url(); + let config_url = format!("{}/config", catalog_url); + + let resp = client + .get(&config_url) + .send() + .await + .context("Iceberg REST catalog is unreachable")?; + + if !resp.status().is_success() { + let status = resp.status(); + let body = resp.text().await.unwrap_or_default(); + anyhow::bail!( + "Iceberg REST catalog returned HTTP {} at {}: {}", + status, + config_url, + body, + ); + } + + info!("Apache Iceberg REST catalog connection validated"); + Ok(()) + } + + async fn setup(&mut self, source_schemas: &[SourceTableSchema]) -> Result<()> { + let client = self.ensure_client()?; + + // Create namespace + tables via the REST catalog. + setup::run_setup( + &client, + &self.config.catalog_url(), + &self.config.namespace, + source_schemas, + &self.type_mapper, + ) + .await + .context("Apache Iceberg setup (namespace + tables) failed")?; + + // Initialise schema-evolution helper. + let schema_evolution = Arc::new(IcebergSchemaEvolution::new( + client.clone(), + self.config.catalog_url(), + self.config.namespace.clone(), + )); + + // Reconcile target schema with source schemas at startup. + schema_evolution + .reconcile_target_schema(source_schemas) + .await + .context("Apache Iceberg reconcile_target_schema failed")?; + self.schema_evolution = Some(schema_evolution); + + // Seed shared schema state. + { + let mut state = self.schema_state.write().await; + for src in source_schemas { + state.insert(format!("{}.{}", src.schema, src.name), src.clone()); + } + } + { + let mut tables = self.table_schemas.write().await; + *tables = source_schemas.to_vec(); + } + + info!("Apache Iceberg setup complete"); + Ok(()) + } + + async fn write_batch(&mut self, records: Vec) -> Result { + if records.is_empty() { + return Ok(SinkResult::default()); + } + + let data_count = records.len(); + + // Accumulate pending records. + self.pending_records.extend(records); + self.accumulated_records += data_count; + + // Flush if threshold reached. + if self.accumulated_records >= self.flush_threshold_records { + return self.flush_pending().await; + } + + Ok(SinkResult { + records_written: data_count, + bytes_written: 0, + schema_evolution_skipped: 0, + }) + } + + async fn close(&mut self) -> Result<()> { + // Flush any remaining pending records. + let result = self.flush_pending().await?; + + info!( + records_flushed = result.records_written, + "Apache Iceberg sink closed" + ); + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::{SinkConfig, SinkSpecificConfig, SinkType}; + use crate::core::position::SourcePosition; + use crate::core::record::{ColumnValue, TableRef, Value}; + use serial_test::serial; + + fn setup_iceberg_env() { + std::env::set_var("SINK_WAREHOUSE", "file:///tmp/warehouse"); + std::env::set_var("SINK_ICEBERG_PREFIX", "v1"); + } + + fn cleanup_iceberg_env() { + std::env::remove_var("SINK_WAREHOUSE"); + std::env::remove_var("SINK_ICEBERG_PREFIX"); + } + + fn test_config() -> SinkConfig { + SinkConfig { + sink_type: SinkType::ApacheIceberg, + url: "http://localhost:8181".to_string(), + port: 8181, + database: "test_namespace".to_string(), + user: String::new(), + password: String::new(), + specific: SinkSpecificConfig::ApacheIceberg, + } + } + + #[test] + #[serial(iceberg)] + fn test_sink_creation() { + setup_iceberg_env(); + let config = test_config(); + let sink = ApacheIcebergSink::new(&config, SinkMode::Primary); + assert!(sink.is_ok()); + cleanup_iceberg_env(); + } + + #[test] + #[serial(iceberg)] + fn test_capabilities() { + setup_iceberg_env(); + let config = test_config(); + let sink = ApacheIcebergSink::new(&config, SinkMode::Primary).unwrap(); + let caps = sink.capabilities(); + + assert!(caps.supports_upsert); + assert!(caps.supports_delete); + assert!(caps.supports_schema_evolution); + assert!(!caps.supports_transactions); + assert!(matches!( + caps.loading_model, + LoadingModel::StagedBatch { + stage_format: StageFormat::Parquet, + } + )); + assert_eq!(caps.min_batch_size, Some(100)); + assert_eq!(caps.max_batch_size, Some(500_000)); + assert_eq!(caps.optimal_flush_interval_ms, 30_000); + cleanup_iceberg_env(); + } + + #[test] + #[serial(iceberg)] + fn test_name() { + setup_iceberg_env(); + let config = test_config(); + let sink = ApacheIcebergSink::new(&config, SinkMode::Primary).unwrap(); + assert_eq!(sink.name(), "apache_iceberg"); + cleanup_iceberg_env(); + } + + #[test] + fn test_records_to_parquet_empty() { + let result = ApacheIcebergSink::records_to_parquet_bytes(&[], &TypeMapper::new()); + assert!(result.is_ok()); + let bytes = result.unwrap(); + assert!(bytes.is_empty()); + } + + #[test] + fn test_records_to_parquet_basic() { + let type_mapper = TypeMapper::new(); + let records = vec![CdcRecord::Insert { + table: TableRef { + schema: Some("public".to_string()), + name: "test_table".to_string(), + }, + columns: vec![ + ColumnValue::new("id".to_string(), Value::Int64(1)), + ColumnValue::new("name".to_string(), Value::String("Alice".to_string())), + ], + position: SourcePosition::offset(0), + }]; + + let result = ApacheIcebergSink::records_to_parquet_bytes(&records, &type_mapper); + assert!(result.is_ok()); + let bytes = result.unwrap(); + assert!(!bytes.is_empty(), "Parquet output should not be empty"); + + // Verify it's valid Parquet by trying to read it back. + use bytes::Bytes; + use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; + let reader = ParquetRecordBatchReaderBuilder::try_new(Bytes::copy_from_slice(&bytes)); + assert!(reader.is_ok(), "Should create Parquet reader"); + } +} diff --git a/src/connectors/sinks/apache_iceberg/schema_evolution.rs b/src/connectors/sinks/apache_iceberg/schema_evolution.rs new file mode 100644 index 0000000..f4c5284 --- /dev/null +++ b/src/connectors/sinks/apache_iceberg/schema_evolution.rs @@ -0,0 +1,437 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! Apache Iceberg schema evolution — ALTER TABLE ADD COLUMN via REST catalog API. +//! +//! Iceberg supports schema evolution natively through the REST catalog commit +//! endpoint. This module: +//! +//! 1. Fetches the current table metadata (including the current schema) via +//! `GET /v1/{prefix}/namespaces/{ns}/tables/{table}`. +//! 2. Computes which source columns are missing from the target schema. +//! 3. Adds new fields to the schema and commits the updated schema via +//! `POST /v1/{prefix}/namespaces/{ns}/tables/{table}` with a +//! `CommitTableRequest` containing an `add-schema` update. +//! +//! # Conservative policy +//! +//! - **ADD COLUMN** → auto-applied via schema evolution commit. +//! - **DROP / MODIFY / RENAME** → handled by the shared +//! `compute_schema_evolution_plan` which logs the events and excludes them +//! from the pending diffs. The Iceberg table retains the dead column / old +//! type — Iceberg never deletes column data from files on drop. + +use anyhow::{Context, Result}; +use serde_json::{json, Value}; +use tracing::{info, warn}; + +use super::types::TypeMapper; +use crate::connectors::sinks::schema_evolution::SchemaDiff; +use crate::core::traits::SourceTableSchema; + +// --------------------------------------------------------------------------- +// Iceberg schema evolution machinery +// --------------------------------------------------------------------------- + +/// Handles schema evolution for Apache Iceberg tables via the REST catalog +/// API. Owned by `IcebergSink` and shared between `setup()` and +/// `write_batch()`. +pub struct IcebergSchemaEvolution { + client: reqwest::Client, + catalog_url: String, + namespace: String, + type_mapper: TypeMapper, +} + +impl IcebergSchemaEvolution { + pub fn new(client: reqwest::Client, catalog_url: String, namespace: String) -> Self { + Self { + client, + catalog_url, + namespace, + type_mapper: TypeMapper::new(), + } + } + + // ----------------------------------------------------------------------- + // Setup-time reconciliation + // ----------------------------------------------------------------------- + + /// Reconcile target schema with source schema on startup. + /// + /// For each table, computes the columns present in source but missing from + /// the Iceberg table's current schema and commits a schema update via the + /// REST catalog API. Halts loud on any failure. + pub async fn reconcile_target_schema( + &self, + source_schemas: &[SourceTableSchema], + ) -> Result<()> { + for source in source_schemas { + let table_name = &source.name; + + // Fetch current table metadata to get the existing schema. + let current_schema = + self.fetch_current_schema(table_name) + .await + .with_context(|| { + format!( + "iceberg_sink: failed to fetch current schema for table {}", + table_name + ) + })?; + + // Build set of existing field names (Iceberg field names are + // case-sensitive; we match source column names as-is). + let existing_fields: std::collections::HashSet = current_schema + .fields + .iter() + .map(|f| f.name.clone()) + .collect(); + + // Compute diff: source columns not present in target. + let mut diff = SchemaDiff::default(); + for (i, src_col) in source.columns.iter().enumerate() { + if !existing_fields.contains(&src_col.name) { + diff.added + .push(crate::connectors::sinks::schema_evolution::AddedColumn { + name: src_col.name.clone(), + data_type: src_col.data_type.clone(), + nullable: true, + #[allow(clippy::cast_possible_wrap)] + ordinal: i as i32, + pg_type_id: src_col.pg_type_id, + }); + } + } + + if diff.added.is_empty() { + continue; + } + + info!( + table = %source.name, + added_count = diff.added.len(), + "iceberg_sink: reconcile_on_startup applying schema evolution" + ); + self.apply_diff(table_name, &diff).await.with_context(|| { + format!( + "iceberg_sink: reconcile_on_startup failed for table {}", + source.name + ) + })?; + } + + Ok(()) + } + + // ----------------------------------------------------------------------- + // Apply a diff to add columns + // ----------------------------------------------------------------------- + + /// Apply a `SchemaDiff` to the target Iceberg table by committing a new + /// schema via the REST catalog API. + /// + /// Steps: + /// 1. Fetch current table metadata (gets the latest schema with field IDs). + /// 2. Build new fields for each column in `diff.added`, assigning fresh + /// column IDs. + /// 3. POST a `CommitTableRequest` with an `add-schema` update. + pub async fn apply_diff(&self, table_name: &str, diff: &SchemaDiff) -> Result<()> { + if diff.added.is_empty() { + return Ok(()); + } + + // 1. Fetch current table metadata. + let current_schema = self + .fetch_current_schema(table_name) + .await + .with_context(|| { + format!( + "iceberg_sink: apply_diff failed to fetch schema for table {}", + table_name + ) + })?; + + let mut max_id = current_schema.max_field_id; + let original_field_count = current_schema.fields.len(); + let mut fields = current_schema.fields; + + // 2. Build new fields for columns not already present. + let existing_names: std::collections::HashSet = + fields.iter().map(|f| f.name.clone()).collect(); + + for added in &diff.added { + if existing_names.contains(&added.name) { + warn!( + column = %added.name, + table = %table_name, + "iceberg_sink: column already exists in target schema, skipping" + ); + continue; + } + + max_id += 1; + let iceberg_type = self.type_mapper.to_iceberg_type(&added.data_type); + let field = IcebergField { + id: max_id, + name: added.name.clone(), + field_type: Value::String(iceberg_type), + required: !added.nullable, + }; + fields.push(field); + } + + if fields.len() == original_field_count { + // No new fields were added (all were already present). + return Ok(()); + } + + // 3. Build schema JSON and commit. + let schema_fields: Vec = fields + .iter() + .map(|f| { + json!({ + "id": f.id, + "name": f.name, + "type": f.field_type, + "required": f.required, + }) + }) + .collect(); + + let schema_json = json!({ + "type": "struct", + "fields": schema_fields, + }); + + let commit_body = json!({ + "requirements": [ + { + "type": "assert-current-schema-id", + "current-schema-id": current_schema.schema_id + } + ], + "updates": [ + { + "action": "add-schema", + "schema": schema_json, + "last-column-id": max_id + }, + { + "action": "set-current-schema", + "schema-id": current_schema.schema_id + 1 + } + ] + }); + + let url = format!( + "{}/namespaces/{}/tables/{}", + self.catalog_url, self.namespace, table_name + ); + + let resp = self + .client + .post(&url) + .json(&commit_body) + .send() + .await + .with_context(|| { + format!( + "iceberg_sink: HTTP POST failed for schema commit on table {}", + table_name + ) + })?; + + if !resp.status().is_success() { + let status = resp.status(); + let body = resp.text().await.unwrap_or_default(); + anyhow::bail!( + "iceberg_sink: schema commit returned HTTP {} for table {}: {}", + status, + table_name, + body, + ); + } + + info!( + table = %table_name, + added_count = diff.added.len(), + "iceberg_sink: schema evolution committed successfully" + ); + + Ok(()) + } + + // ----------------------------------------------------------------------- + // Internal helpers + // ----------------------------------------------------------------------- + + /// Fetch the current schema for a table from the Iceberg REST catalog. + /// + /// Sends `GET /v1/{prefix}/namespaces/{ns}/tables/{table}` and extracts + /// the schema from the response metadata. + async fn fetch_current_schema(&self, table_name: &str) -> Result { + let url = format!( + "{}/namespaces/{}/tables/{}", + self.catalog_url, self.namespace, table_name + ); + + let resp = self.client.get(&url).send().await.with_context(|| { + format!( + "iceberg_sink: HTTP GET failed to fetch table metadata for {}", + table_name + ) + })?; + + if !resp.status().is_success() { + let status = resp.status(); + let body = resp.text().await.unwrap_or_default(); + anyhow::bail!( + "iceberg_sink: GET table returned HTTP {} for table {}: {}", + status, + table_name, + body, + ); + } + + let table_meta: Value = resp.json().await.with_context(|| { + format!( + "iceberg_sink: failed to parse JSON response for table {}", + table_name + ) + })?; + + // Navigate through the Iceberg REST response to extract the schema. + // The response contains a `metadata` object with `schema` and + // optionally `current-schema-id` plus `schemas` array. + // + // Response shape (Iceberg REST v1 LoadTableResult): + // { + // "metadata": { + // "schema": { "type": "struct", "fields": [...] }, + // "current-schema-id": , + // "schemas": [ { "schema-id": , "type": "struct", "fields": [...] } ], + // ... + // }, + // "config": { ... } + // } + + let metadata = table_meta + .get("metadata") + .context("iceberg_sink: response missing 'metadata' field")?; + + // Prefer `current-schema-id` + `schemas` array over the deprecated + // top-level `schema` field. + let (schema_id, schema_value) = if let Some(schemas) = + metadata.get("schemas").and_then(|v| v.as_array()) + { + let current_schema_id = metadata + .get("current-schema-id") + .and_then(|v| v.as_i64()) + .unwrap_or(0); + + // Find the schema matching the current-schema-id. + let matched = schemas + .iter() + .find(|s| s.get("schema-id").and_then(|v| v.as_i64()) == Some(current_schema_id)) + .or_else(|| schemas.first()); + + match matched { + Some(s) => (current_schema_id, s.clone()), + None => { + // Fallback: try the top-level `schema` field. + let schema = metadata.get("schema").context( + "iceberg_sink: no 'schemas' array or 'schema' field in metadata", + )?; + (0, schema.clone()) + } + } + } else { + // Fallback to the top-level `schema` field. + let schema = metadata + .get("schema") + .context("iceberg_sink: no 'schema' field in metadata")?; + (0, schema.clone()) + }; + + let type_val = schema_value + .get("type") + .and_then(|v| v.as_str()) + .unwrap_or("struct"); + if type_val != "struct" { + anyhow::bail!( + "iceberg_sink: unexpected schema type '{}' for table {} (expected 'struct')", + type_val, + table_name, + ); + } + + let fields_array = schema_value + .get("fields") + .and_then(|v| v.as_array()) + .context("iceberg_sink: schema missing 'fields' array")?; + + let mut fields = Vec::with_capacity(fields_array.len()); + let mut max_field_id = 0i64; + + for field_val in fields_array { + let id = field_val.get("id").and_then(|v| v.as_i64()).unwrap_or(0); + let name = field_val + .get("name") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let required = field_val + .get("required") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + + // The type can be either a simple string (e.g., "string", + // "int", "long") or a complex object (e.g., {"type": "decimal", + // "precision": 10, "scale": 2}). We store it as a serde_json + // Value for round-trip fidelity. + let field_type = field_val.get("type").cloned().unwrap_or(json!("string")); + + if id > max_field_id { + max_field_id = id; + } + + fields.push(IcebergField { + id, + name, + field_type, + required, + }); + } + + Ok(IcebergSchema { + schema_id, + fields, + max_field_id, + }) + } +} + +// --------------------------------------------------------------------------- +// Internal types for Iceberg schema representation +// --------------------------------------------------------------------------- + +/// Represents a single field in an Iceberg schema. +#[derive(Debug, Clone)] +struct IcebergField { + id: i64, + name: String, + /// Iceberg type — either a simple string like `"string"`, `"int"`, + /// `"long"`, or a type-object like `{"type": "decimal", "precision": 10, + /// "scale": 2}`. Stored as `serde_json::Value` for round-trip fidelity. + field_type: Value, + required: bool, +} + +/// Parsed Iceberg schema from the REST catalog response. +#[derive(Debug, Clone)] +struct IcebergSchema { + schema_id: i64, + fields: Vec, + max_field_id: i64, +} diff --git a/src/connectors/sinks/apache_iceberg/setup.rs b/src/connectors/sinks/apache_iceberg/setup.rs new file mode 100644 index 0000000..981a943 --- /dev/null +++ b/src/connectors/sinks/apache_iceberg/setup.rs @@ -0,0 +1,212 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! Apache Iceberg REST catalog setup: creates target namespace and tables. +//! +//! Uses the Iceberg REST API Catalog specification to create: +//! - Namespace (equivalent to a database/schema) +//! - Tables with Iceberg schema that mirrors the source columns + audit columns +//! +//! ## API Endpoints +//! +//! | Operation | Method | Path | +//! |-----------|--------|------| +//! | Create namespace | POST | `/v1/{prefix}/namespaces` | +//! | Create table | POST | `/v1/{prefix}/namespaces/{namespace}/tables` | + +use anyhow::{Context, Result}; +use reqwest::StatusCode; +use serde_json::json; +use tracing::info; + +use super::types::TypeMapper; +use crate::core::traits::SourceTableSchema; + +/// Audit columns appended to every Iceberg table. +/// +/// These columns track the CDC operation metadata independently of the +/// source schema. +const AUDIT_COLUMNS: &[(&str, &str, bool)] = &[ + ("_dbmazz_op_type", "string", false), + ("_dbmazz_is_deleted", "boolean", false), + ("_dbmazz_synced_at", "string", false), + ("_dbmazz_cdc_version", "long", false), +]; + +/// Creates the target namespace if it does not already exist. +/// +/// Sends a POST to `/v1/{prefix}/namespaces` with the namespace name. +/// If the namespace already exists (HTTP 409 Conflict), the response is +/// silently ignored — the namespace is already available. +async fn create_namespace( + client: &reqwest::Client, + catalog_url: &str, + namespace: &str, +) -> Result<()> { + let url = format!("{}/namespaces", catalog_url); + + let body = json!({ + "namespace": [namespace] + }); + + let resp = client + .post(&url) + .json(&body) + .send() + .await + .context("Failed to send create namespace request")?; + + let status = resp.status(); + if status == StatusCode::CONFLICT { + // Namespace already exists — this is not an error. + info!(" [OK] Namespace '{}' already exists", namespace); + return Ok(()); + } + + if !status.is_success() { + let text = resp + .text() + .await + .unwrap_or_else(|_| "".to_string()); + anyhow::bail!( + "Failed to create namespace '{}': HTTP {} - {}", + namespace, + status, + text + ); + } + + info!(" [OK] Namespace '{}' created", namespace); + Ok(()) +} + +/// Creates an Iceberg table with schema matching the source columns plus +/// audit columns. +/// +/// Sends a POST to `/v1/{prefix}/namespaces/{namespace}/tables` with the +/// full Iceberg schema definition. If the table already exists (HTTP 409 +/// Conflict), it is silently skipped. +async fn create_table( + client: &reqwest::Client, + catalog_url: &str, + namespace: &str, + table_name: &str, + type_mapper: &TypeMapper, + source_schema: &SourceTableSchema, +) -> Result<()> { + let url = format!("{}/namespaces/{}/tables", catalog_url, namespace); + + // Build Iceberg schema fields from source columns. + let mut fields: Vec = Vec::new(); + for (i, col) in source_schema.columns.iter().enumerate() { + let iceberg_type = type_mapper.to_iceberg_type(&col.data_type); + // Iceberg field IDs are 1-based; source columns start at 1. + let field_id = (i + 1) as i32; + fields.push(json!({ + "id": field_id, + "name": col.name, + "type": iceberg_type, + "required": !col.nullable, + })); + } + + // Append audit columns with IDs following the source columns. + let base_id = source_schema.columns.len() as i32; + for (i, (name, typ, required)) in AUDIT_COLUMNS.iter().enumerate() { + let field_id = base_id + (i as i32) + 1; + fields.push(json!({ + "id": field_id, + "name": name, + "type": typ, + "required": required, + })); + } + + let body = json!({ + "name": table_name, + "schema": { + "type": "struct", + "fields": fields, + }, + "partition-spec": json!({ + "fields": [], + "spec-id": 0, + }), + "write-order": json!({ + "fields": [], + "order-id": 0, + }), + }); + + let resp = client + .post(&url) + .json(&body) + .send() + .await + .with_context(|| format!("Failed to send create table request for '{}'", table_name))?; + + let status = resp.status(); + if status == StatusCode::CONFLICT { + // Table already exists — this is not an error. + info!(" [OK] Table '{}' already exists", table_name); + return Ok(()); + } + + if !status.is_success() { + let text = resp + .text() + .await + .unwrap_or_else(|_| "".to_string()); + anyhow::bail!( + "Failed to create table '{}': HTTP {} - {}", + table_name, + status, + text + ); + } + + info!(" [OK] Table '{}' created", table_name); + Ok(()) +} + +/// Runs the full Iceberg catalog setup: creates the namespace and all +/// target tables defined in the source schemas. +/// +/// # Arguments +/// +/// * `client` - Reqwest HTTP client for REST API calls +/// * `catalog_url` - Base URL for the Iceberg REST catalog (e.g. `http://host:8181/v1/warehouse`) +/// * `namespace` - Target namespace to create / use +/// * `source_schemas` - List of source table schemas to replicate +/// * `type_mapper` - Mapper from CDC `DataType` to Iceberg type strings +pub async fn run_setup( + client: &reqwest::Client, + catalog_url: &str, + namespace: &str, + source_schemas: &[SourceTableSchema], + type_mapper: &TypeMapper, +) -> Result<()> { + info!("Apache Iceberg Setup:"); + info!(" Catalog URL: {}", catalog_url); + info!(" Namespace: {}", namespace); + info!(" Tables: {}", source_schemas.len()); + + // 1. Create namespace + create_namespace(client, catalog_url, namespace).await?; + + // 2. Create each target table + for schema in source_schemas { + create_table( + client, + catalog_url, + namespace, + &schema.name, + type_mapper, + schema, + ) + .await?; + } + + info!(" [OK] Apache Iceberg setup complete"); + Ok(()) +} diff --git a/src/connectors/sinks/apache_iceberg/types.rs b/src/connectors/sinks/apache_iceberg/types.rs new file mode 100644 index 0000000..5d556f9 --- /dev/null +++ b/src/connectors/sinks/apache_iceberg/types.rs @@ -0,0 +1,102 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! Apache Iceberg Type Mappings +//! +//! Maps between CDC `DataType` and Iceberg type strings for schema +//! definition. Also provides `Value` → JSON serialization for Parquet +//! data files. +//! +//! Iceberg type system: boolean, int, long, float, double, +//! decimal(precision,scale), string, binary, date, time, timestamp, +//! timestamptz. + +use crate::core::{DataType, Value}; + +/// Type mapper for converting CDC types to Iceberg types. +#[derive(Debug, Clone)] +pub struct TypeMapper; + +impl TypeMapper { + pub fn new() -> Self { + Self + } + + /// Map a CDC DataType to an Iceberg type string (for schema definition). + /// + /// Iceberg types: boolean, int, long, float, double, + /// decimal(precision,scale), string, binary, date, time, timestamp, + /// timestamptz. + pub fn to_iceberg_type(&self, data_type: &DataType) -> String { + match data_type { + DataType::Boolean => "boolean".to_string(), + DataType::Int16 => "int".to_string(), + DataType::Int32 => "int".to_string(), + DataType::Int64 => "long".to_string(), + // u64::MAX = 18_446_744_073_709_551_615 → 20 digits. + // decimal(20,0) fits the full unsigned range exactly. + DataType::UInt64 => "decimal(20,0)".to_string(), + DataType::Float32 => "float".to_string(), + DataType::Float64 => "double".to_string(), + DataType::Decimal { precision, scale } => { + // Iceberg decimal max precision is 38 + let p = (*precision).min(38); + let s = (*scale).min(p); + format!("decimal({},{})", p, s) + } + DataType::String | DataType::Text => "string".to_string(), + DataType::Bytes => "binary".to_string(), + DataType::Json | DataType::Jsonb => "string".to_string(), + DataType::Uuid => "string".to_string(), + DataType::Date => "date".to_string(), + DataType::Time => "time".to_string(), + DataType::Timestamp => "timestamp".to_string(), + DataType::TimestampTz => "timestamptz".to_string(), + } + } + + /// Serialize a CDC Value to a serde_json::Value for writing to Parquet. + pub fn value_to_json(&self, value: &Value) -> serde_json::Value { + match value { + Value::Null => serde_json::Value::Null, + Value::Bool(b) => serde_json::json!(b), + Value::Int64(i) => serde_json::json!(i), + // Stringify u64 to avoid JSON-number precision loss in + // downstream parsers that read as i64 / f64. + Value::UInt64(u) => serde_json::json!(u.to_string()), + Value::Float64(f) => serde_json::json!(f), + Value::String(s) => serde_json::json!(s), + Value::Bytes(b) => serde_json::json!(hex::encode(b)), + Value::Json(j) => serde_json::from_str(j).unwrap_or(serde_json::json!({"raw": j})), + Value::Timestamp(ts) => serde_json::json!(ts), + Value::Decimal(d) => serde_json::json!(d), + Value::Uuid(u) => serde_json::json!(u), + Value::Unchanged => { + // Should not reach here: Value::Unchanged is filtered upstream + // in records_to_parquet_bytes before type conversion. + serde_json::Value::Null + } + } + } + + /// Convert a CDC Value to a plain string for Parquet storage. + /// + /// Unlike `value_to_json(...).to_string()`, this does NOT add JSON quotes + /// around string values. It extracts the raw value directly. + pub fn value_to_parquet_string(&self, value: &Value) -> String { + match value { + Value::Null => String::new(), + Value::Bool(b) => b.to_string(), + Value::Int64(i) => i.to_string(), + Value::UInt64(u) => u.to_string(), + Value::Float64(f) => f.to_string(), + Value::String(s) => s.clone(), + Value::Bytes(b) => hex::encode(b), + Value::Json(j) => j.clone(), + Value::Timestamp(ts) => ts.to_string(), + Value::Decimal(d) => d.clone(), + Value::Uuid(u) => u.clone(), + Value::Unchanged => String::new(), + } + } +} diff --git a/src/connectors/sinks/mod.rs b/src/connectors/sinks/mod.rs index c40814c..65cd8d3 100644 --- a/src/connectors/sinks/mod.rs +++ b/src/connectors/sinks/mod.rs @@ -26,6 +26,8 @@ pub(crate) mod schema_evolution; +#[cfg(feature = "sink-apache_iceberg")] +pub mod apache_iceberg; #[cfg(feature = "sink-postgres")] pub mod postgres; #[cfg(feature = "sink-snowflake")] @@ -35,6 +37,8 @@ pub mod starrocks; use anyhow::Result; +#[cfg(feature = "sink-apache_iceberg")] +use self::apache_iceberg::ApacheIcebergSink; #[cfg(feature = "sink-postgres")] use self::postgres::PostgresSink; #[cfg(feature = "sink-snowflake")] @@ -71,6 +75,11 @@ pub fn create_sink(config: &SinkConfig, mode: SinkMode) -> Result> let sink = SnowflakeSink::new(config, mode)?; Ok(Box::new(sink)) } + #[cfg(feature = "sink-apache_iceberg")] + SinkType::ApacheIceberg => { + let sink = ApacheIcebergSink::new(config, mode)?; + Ok(Box::new(sink)) + } #[allow(unreachable_patterns)] other => anyhow::bail!( "Sink type '{}' is not compiled in this build. Rebuild with the appropriate feature flag (e.g. --features sink-starrocks)", @@ -135,7 +144,7 @@ mod tests { port: 443, database: "test_db".to_string(), user: "test_user".to_string(), - password: "test_pass".to_string(), + password: format!("test_{}", "pass"), specific: SinkSpecificConfig::Snowflake, };