risingwave_connector/sink/iceberg/
mod.rs1#[cfg(test)]
16mod test;
17
18mod commit;
19pub mod commit_retry;
20mod config;
21mod create_table;
22#[cfg(any(test, madsim))]
23pub mod mock_v3_catalog_registry;
24mod prometheus;
25mod writer;
26
27use std::collections::BTreeMap;
28use std::fmt::Debug;
29use std::num::NonZeroU64;
30
31use anyhow::{Context, anyhow};
32pub use commit::*;
33pub use config::*;
34pub use create_table::*;
35use iceberg::table::Table;
36use risingwave_common::bail;
37use tokio::sync::mpsc::UnboundedSender;
38pub use writer::*;
39
40use super::{
41 GLOBAL_SINK_METRICS, SINK_TYPE_APPEND_ONLY, SINK_TYPE_OPTION, SINK_TYPE_UPSERT, Sink,
42 SinkError, SinkWriterParam,
43};
44use crate::connector_common::{IcebergCatalogKind, IcebergSinkCompactionUpdate};
45use crate::enforce_secret::EnforceSecret;
46use crate::sink::coordinate::CoordinatedLogSinker;
47use crate::sink::{Result, SinkCommitCoordinator, SinkParam};
48
49pub const ICEBERG_SINK: &str = "iceberg";
50
51pub struct IcebergSink {
52 pub config: IcebergConfig,
53 param: SinkParam,
54 upsert_primary_key_column_names: Option<Vec<String>>,
56}
57
58impl EnforceSecret for IcebergSink {
59 fn enforce_secret<'a>(
60 prop_iter: impl Iterator<Item = &'a str>,
61 ) -> crate::error::ConnectorResult<()> {
62 for prop in prop_iter {
63 IcebergConfig::enforce_one(prop)?;
64 }
65 Ok(())
66 }
67}
68
69impl TryFrom<SinkParam> for IcebergSink {
70 type Error = SinkError;
71
72 fn try_from(param: SinkParam) -> std::result::Result<Self, Self::Error> {
73 let config = IcebergConfig::from_btreemap(param.properties.clone())?;
74 IcebergSink::new(config, param)
75 }
76}
77
78impl Debug for IcebergSink {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 f.debug_struct("IcebergSink")
81 .field("config", &self.config)
82 .finish()
83 }
84}
85
86impl IcebergSink {
87 pub async fn create_and_validate_table(&self) -> Result<Table> {
88 create_and_validate_table_impl(&self.config, &self.param).await
89 }
90
91 pub async fn create_table_if_not_exists(&self) -> Result<()> {
92 create_table_if_not_exists_impl(&self.config, &self.param).await
93 }
94
95 pub fn new(config: IcebergConfig, param: SinkParam) -> Result<Self> {
96 if let Some(order_key) = &config.order_key {
97 validate_order_key_columns(
98 order_key,
99 param.columns.iter().map(|column| column.name.as_str()),
100 )
101 .context("invalid order_key")
102 .map_err(SinkError::Config)?;
103 }
104
105 let upsert_primary_key_column_names =
106 if config.r#type == SINK_TYPE_UPSERT && !config.force_append_only {
107 let pk_indices = param
108 .downstream_pk
109 .as_ref()
110 .filter(|pk| !pk.is_empty())
111 .ok_or_else(|| {
112 SinkError::Config(anyhow!(
113 "primary key must be specified for upsert iceberg sink"
114 ))
115 })?;
116 Some(
117 pk_indices
118 .iter()
119 .map(|&idx| {
120 param
121 .columns
122 .get(idx)
123 .map(|column| column.name.clone())
124 .ok_or_else(|| {
125 SinkError::Config(anyhow!(
126 "primary key column index {} out of range in sink schema",
127 idx
128 ))
129 })
130 })
131 .collect::<Result<Vec<_>>>()?,
132 )
133 } else {
134 None
135 };
136 Ok(Self {
137 config,
138 param,
139 upsert_primary_key_column_names,
140 })
141 }
142}
143
144impl Sink for IcebergSink {
145 type LogSinker = CoordinatedLogSinker<IcebergSinkWriter>;
146
147 const SINK_NAME: &'static str = ICEBERG_SINK;
148
149 async fn validate(&self) -> Result<()> {
150 let catalog_kind = self.config.catalog_kind()?;
151 if matches!(catalog_kind, IcebergCatalogKind::Snowflake) {
152 bail!("Snowflake catalog only supports iceberg sources");
153 }
154
155 if matches!(catalog_kind, IcebergCatalogKind::Glue(_)) {
156 risingwave_common::license::Feature::IcebergSinkWithGlue
157 .check_available()
158 .map_err(|e| anyhow::anyhow!(e))?;
159 }
160
161 IcebergConfig::validate_append_only_write_mode(
163 &self.config.r#type,
164 self.config.write_mode,
165 )?;
166
167 let compaction_type = self.config.compaction_type();
169
170 if self.config.write_mode == IcebergWriteMode::CopyOnWrite
173 && compaction_type != CompactionType::Full
174 {
175 bail!(
176 "'copy-on-write' mode only supports 'full' compaction type, got: '{}'",
177 compaction_type
178 );
179 }
180
181 match compaction_type {
182 CompactionType::SmallFiles => {
183 risingwave_common::license::Feature::IcebergCompaction
185 .check_available()
186 .map_err(|e| anyhow::anyhow!(e))?;
187
188 if self.config.write_mode != IcebergWriteMode::MergeOnRead {
190 bail!(
191 "'small-files' compaction type only supports 'merge-on-read' write mode, got: '{}'",
192 self.config.write_mode
193 );
194 }
195
196 if self.config.delete_files_count_threshold.is_some() {
198 bail!(
199 "`compaction.delete-files-count-threshold` is not supported for 'small-files' compaction type"
200 );
201 }
202 }
203 CompactionType::FilesWithDelete => {
204 risingwave_common::license::Feature::IcebergCompaction
206 .check_available()
207 .map_err(|e| anyhow::anyhow!(e))?;
208
209 if self.config.write_mode != IcebergWriteMode::MergeOnRead {
211 bail!(
212 "'files-with-delete' compaction type only supports 'merge-on-read' write mode, got: '{}'",
213 self.config.write_mode
214 );
215 }
216
217 if self.config.small_files_threshold_mb.is_some() {
219 bail!(
220 "`compaction.small-files-threshold-mb` must not be set for 'files-with-delete' compaction type"
221 );
222 }
223 }
224 CompactionType::Full => {
225 }
227 }
228
229 let _ = self.create_and_validate_table().await?;
230 Ok(())
231 }
232
233 fn support_schema_change() -> bool {
234 true
235 }
236
237 fn validate_alter_config(config: &BTreeMap<String, String>) -> Result<()> {
238 let iceberg_config = IcebergConfig::from_btreemap(config.clone())?;
239
240 if let Some(compaction_interval) = iceberg_config.compaction_interval_sec {
242 if iceberg_config.enable_compaction && compaction_interval == 0 {
243 bail!(
244 "`compaction-interval-sec` must be greater than 0 when `enable-compaction` is true"
245 );
246 }
247
248 tracing::info!(
249 "Alter config compaction_interval set to {} seconds",
250 compaction_interval
251 );
252 }
253
254 if let Some(max_snapshots) = iceberg_config.max_snapshots_num_before_compaction
256 && max_snapshots < 1
257 {
258 bail!(
259 "`compaction.max_snapshots_num` must be greater than 0, got: {}",
260 max_snapshots
261 );
262 }
263
264 if let Some(target_file_size_mb) = iceberg_config.target_file_size_mb
266 && target_file_size_mb == 0
267 {
268 bail!("`compaction.target_file_size_mb` must be greater than 0");
269 }
270
271 if let Some(max_row_group_rows) = iceberg_config.write_parquet_max_row_group_rows
273 && max_row_group_rows == 0
274 {
275 bail!("`compaction.write_parquet_max_row_group_rows` must be greater than 0");
276 }
277
278 if let Some(max_row_group_bytes) = iceberg_config.write_parquet_max_row_group_bytes
280 && max_row_group_bytes == 0
281 {
282 bail!("`compaction.write_parquet_max_row_group_bytes` must be greater than 0");
283 }
284
285 if let Some(ref compression) = iceberg_config.write_parquet_compression {
287 let valid_codecs = [
288 "uncompressed",
289 "snappy",
290 "gzip",
291 "lzo",
292 "brotli",
293 "lz4",
294 "zstd",
295 ];
296 if !valid_codecs.contains(&compression.to_lowercase().as_str()) {
297 bail!(
298 "`compaction.write_parquet_compression` must be one of {:?}, got: {}",
299 valid_codecs,
300 compression
301 );
302 }
303 }
304
305 Ok(())
306 }
307
308 async fn new_log_sinker(&self, writer_param: SinkWriterParam) -> Result<Self::LogSinker> {
309 let writer = IcebergSinkWriter::new(
310 self.config.clone(),
311 self.param.clone(),
312 writer_param.clone(),
313 self.upsert_primary_key_column_names.clone(),
314 );
315
316 let commit_checkpoint_interval =
317 NonZeroU64::new(self.config.commit_checkpoint_interval).expect(
318 "commit_checkpoint_interval should be greater than 0, and it should be checked in config validation",
319 );
320 let log_sinker = CoordinatedLogSinker::new(
321 &writer_param,
322 self.param.clone(),
323 writer,
324 commit_checkpoint_interval,
325 )
326 .await?;
327
328 Ok(log_sinker)
329 }
330
331 fn is_coordinated_sink(&self) -> bool {
332 true
333 }
334
335 async fn new_coordinator(
336 &self,
337 iceberg_compact_stat_sender: Option<UnboundedSender<IcebergSinkCompactionUpdate>>,
338 ) -> Result<SinkCommitCoordinator> {
339 let catalog = self.config.create_catalog().await?;
340 let table = self.create_and_validate_table().await?;
341 let coordinator = IcebergSinkCommitter {
342 catalog,
343 table,
344 last_commit_epoch: 0,
345 sink_id: self.param.sink_id,
346 config: self.config.clone(),
347 param: self.param.clone(),
348 commit_retry_num: self.config.commit_retry_num,
349 iceberg_compact_stat_sender,
350 };
351 if self.config.is_exactly_once.unwrap_or_default() {
352 Ok(SinkCommitCoordinator::TwoPhase(Box::new(coordinator)))
353 } else {
354 Ok(SinkCommitCoordinator::SinglePhase(Box::new(coordinator)))
355 }
356 }
357}