risingwave_connector/connector_common/iceberg/
mod.rs

1// Copyright 2024 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15pub mod compaction;
16mod jni_catalog;
17mod mock_catalog;
18mod storage_catalog;
19
20use std::collections::HashMap;
21use std::sync::{Arc, LazyLock};
22
23use ::iceberg::io::{
24    S3_ACCESS_KEY_ID, S3_ASSUME_ROLE_ARN, S3_ENDPOINT, S3_REGION, S3_SECRET_ACCESS_KEY,
25};
26use ::iceberg::table::Table;
27use ::iceberg::{Catalog, CatalogBuilder, TableIdent};
28use anyhow::{Context, anyhow};
29use iceberg::io::object_cache::ObjectCache;
30use iceberg::io::{
31    ADLS_ACCOUNT_KEY, ADLS_ACCOUNT_NAME, AZBLOB_ACCOUNT_KEY, AZBLOB_ACCOUNT_NAME, AZBLOB_ENDPOINT,
32    GCS_CREDENTIALS_JSON, GCS_DISABLE_CONFIG_LOAD, S3_DISABLE_CONFIG_LOAD, S3_PATH_STYLE_ACCESS,
33};
34use iceberg_catalog_glue::{AWS_ACCESS_KEY_ID, AWS_REGION_NAME, AWS_SECRET_ACCESS_KEY};
35use moka::future::Cache as MokaCache;
36use phf::{Set, phf_set};
37use risingwave_common::bail;
38use risingwave_common::error::IcebergError;
39use risingwave_common::util::deployment::Deployment;
40use risingwave_common::util::env_var::env_var_is_true;
41use serde::Deserialize;
42use serde_with::serde_as;
43use url::Url;
44use uuid::Uuid;
45use with_options::WithOptions;
46
47use crate::connector_common::common::DISABLE_DEFAULT_CREDENTIAL;
48use crate::connector_common::iceberg::storage_catalog::StorageCatalogConfig;
49use crate::deserialize_optional_bool_from_string;
50use crate::enforce_secret::EnforceSecret;
51use crate::error::ConnectorResult;
52
53#[serde_as]
54#[derive(Debug, Clone, PartialEq, Eq, Deserialize, WithOptions)]
55pub struct IcebergCommon {
56    // Catalog type supported by iceberg, such as "storage", "rest".
57    // If not set, we use "storage" as default.
58    #[serde(rename = "catalog.type")]
59    pub catalog_type: Option<String>,
60    #[serde(rename = "s3.region")]
61    pub s3_region: Option<String>,
62    #[serde(rename = "s3.endpoint")]
63    pub s3_endpoint: Option<String>,
64    #[serde(rename = "s3.access.key")]
65    pub s3_access_key: Option<String>,
66    #[serde(rename = "s3.secret.key")]
67    pub s3_secret_key: Option<String>,
68    #[serde(rename = "s3.iam_role_arn")]
69    pub s3_iam_role_arn: Option<String>,
70
71    #[serde(rename = "glue.access.key")]
72    pub glue_access_key: Option<String>,
73    #[serde(rename = "glue.secret.key")]
74    pub glue_secret_key: Option<String>,
75    #[serde(rename = "glue.iam_role_arn")]
76    pub glue_iam_role_arn: Option<String>,
77    #[serde(rename = "glue.region")]
78    pub glue_region: Option<String>,
79    /// AWS Client id, can be omitted for storage catalog or when
80    /// caller's AWS account ID matches glue id
81    #[serde(rename = "glue.id")]
82    pub glue_id: Option<String>,
83
84    #[serde(rename = "gcs.credential")]
85    pub gcs_credential: Option<String>,
86
87    #[serde(rename = "azblob.account_name")]
88    pub azblob_account_name: Option<String>,
89    #[serde(rename = "azblob.account_key")]
90    pub azblob_account_key: Option<String>,
91    #[serde(rename = "azblob.endpoint_url")]
92    pub azblob_endpoint_url: Option<String>,
93
94    #[serde(rename = "adlsgen2.account_name")]
95    pub adlsgen2_account_name: Option<String>,
96    #[serde(rename = "adlsgen2.account_key")]
97    pub adlsgen2_account_key: Option<String>,
98    #[serde(rename = "adlsgen2.endpoint")]
99    pub adlsgen2_endpoint: Option<String>,
100
101    /// Path of iceberg warehouse.
102    #[serde(rename = "warehouse.path")]
103    pub warehouse_path: Option<String>,
104    /// Catalog name, default value is risingwave.
105    #[serde(rename = "catalog.name")]
106    pub catalog_name: Option<String>,
107    /// URI of iceberg catalog, only applicable in rest catalog.
108    #[serde(rename = "catalog.uri")]
109    pub catalog_uri: Option<String>,
110    /// Credential for accessing iceberg catalog, only applicable in rest catalog.
111    /// A credential to exchange for a token in the `OAuth2` client credentials flow.
112    #[serde(rename = "catalog.credential")]
113    pub catalog_credential: Option<String>,
114    /// token for accessing iceberg catalog, only applicable in rest catalog.
115    /// A Bearer token which will be used for interaction with the server.
116    #[serde(rename = "catalog.token")]
117    pub catalog_token: Option<String>,
118    /// `oauth2_server_uri` for accessing iceberg catalog, only applicable in rest catalog.
119    /// Token endpoint URI to fetch token from if the Rest Catalog is not the authorization server.
120    #[serde(rename = "catalog.oauth2_server_uri")]
121    pub catalog_oauth2_server_uri: Option<String>,
122    /// scope for accessing iceberg catalog, only applicable in rest catalog.
123    /// Additional scope for `OAuth2`.
124    #[serde(rename = "catalog.scope")]
125    pub catalog_scope: Option<String>,
126
127    /// The signing region to use when signing requests to the REST catalog.
128    #[serde(rename = "catalog.rest.signing_region")]
129    pub rest_signing_region: Option<String>,
130
131    /// The signing name to use when signing requests to the REST catalog.
132    #[serde(rename = "catalog.rest.signing_name")]
133    pub rest_signing_name: Option<String>,
134
135    /// Whether to use `SigV4` for signing requests to the REST catalog.
136    #[serde(
137        rename = "catalog.rest.sigv4_enabled",
138        default,
139        deserialize_with = "deserialize_optional_bool_from_string"
140    )]
141    pub rest_sigv4_enabled: Option<bool>,
142
143    #[serde(
144        rename = "s3.path.style.access",
145        default,
146        deserialize_with = "deserialize_optional_bool_from_string"
147    )]
148    pub s3_path_style_access: Option<bool>,
149    /// Enable config load. This parameter set to true will load warehouse credentials from the environment. Only allowed to be used in a self-hosted environment.
150    #[serde(default, deserialize_with = "deserialize_optional_bool_from_string")]
151    pub enable_config_load: Option<bool>,
152
153    /// This is only used by iceberg engine to enable the hosted catalog.
154    #[serde(
155        rename = "hosted_catalog",
156        default,
157        deserialize_with = "deserialize_optional_bool_from_string"
158    )]
159    pub hosted_catalog: Option<bool>,
160
161    /// The http header to be used in the catalog requests.
162    /// Example:
163    /// `catalog.header = "key1=value1;key2=value2;key3=value3"`
164    /// explain the format of the header:
165    /// - Each header is a key-value pair, separated by an '='.
166    /// - Multiple headers can be specified, separated by a ';'.
167    #[serde(rename = "catalog.header")]
168    pub catalog_header: Option<String>,
169
170    /// Enable vended credentials for iceberg REST catalog.
171    #[serde(default, deserialize_with = "deserialize_optional_bool_from_string")]
172    pub vended_credentials: Option<bool>,
173
174    /// Security type for REST catalog authentication.
175    /// Supported values: `none`, `oauth2`, `google`.
176    /// When set to `google`, uses Iceberg's `GoogleAuthManager` (requires Iceberg 1.10+)
177    /// for authentication using Google Application Default Credentials (ADC).
178    #[serde(rename = "catalog.security")]
179    pub catalog_security: Option<String>,
180
181    /// OAuth-based scopes for Google authentication.
182    /// Comma-separated list of OAuth-based scopes to request.
183    /// Only applicable when `catalog.security` is set to `google`.
184    /// Default: <https://www.googleapis.com/auth/cloud-platform>
185    #[serde(rename = "gcp.auth.scopes")]
186    pub gcp_auth_scopes: Option<String>,
187
188    /// Custom `FileIO` implementation class for the Iceberg catalog.
189    /// Allows specifying a custom `FileIO` implementation instead of the default.
190    /// Examples:
191    /// - `org.apache.iceberg.aws.s3.S3FileIO` for Amazon S3 (default)
192    /// - `org.apache.iceberg.gcp.gcs.GCSFileIO` for Google Cloud Storage
193    /// - `org.apache.iceberg.azure.adlsv2.ADLSFileIO` for Azure Data Lake Storage Gen2
194    #[serde(rename = "catalog.io_impl")]
195    pub catalog_io_impl: Option<String>,
196}
197
198// Matches iceberg::io::object_cache default size (32MB).
199// TODO: change it after object cache get refactored.
200const DEFAULT_OBJECT_CACHE_SIZE_BYTES: u64 = 32 * 1024 * 1024;
201const SHARED_OBJECT_CACHE_BUDGET_BYTES: u64 = 512 * 1024 * 1024;
202const SHARED_OBJECT_CACHE_MAX_TABLES: u64 =
203    SHARED_OBJECT_CACHE_BUDGET_BYTES / DEFAULT_OBJECT_CACHE_SIZE_BYTES;
204
205impl EnforceSecret for IcebergCommon {
206    const ENFORCE_SECRET_PROPERTIES: Set<&'static str> = phf_set! {
207        "s3.access.key",
208        "s3.secret.key",
209        "gcs.credential",
210        "catalog.credential",
211        "catalog.token",
212        "catalog.oauth2_server_uri",
213        "adlsgen2.account_key",
214        "adlsgen2.client_secret",
215        "glue.access.key",
216        "glue.secret.key",
217    };
218}
219
220#[serde_as]
221#[derive(Debug, Clone, PartialEq, Eq, Deserialize, WithOptions)]
222#[serde(deny_unknown_fields)]
223pub struct IcebergTableIdentifier {
224    #[serde(rename = "database.name")]
225    pub database_name: Option<String>,
226    /// Full name of table, must include schema name when database is provided.
227    #[serde(rename = "table.name")]
228    pub table_name: String,
229}
230
231impl IcebergTableIdentifier {
232    pub fn database_name(&self) -> Option<&str> {
233        self.database_name.as_deref()
234    }
235
236    pub fn table_name(&self) -> &str {
237        &self.table_name
238    }
239
240    pub fn to_table_ident(&self) -> ConnectorResult<TableIdent> {
241        let ret = if let Some(database_name) = &self.database_name {
242            TableIdent::from_strs(vec![database_name, &self.table_name])
243        } else {
244            TableIdent::from_strs(vec![&self.table_name])
245        };
246
247        Ok(ret.context("Failed to create table identifier")?)
248    }
249}
250
251impl IcebergCommon {
252    pub fn catalog_type(&self) -> &str {
253        let catalog_type: &str = self.catalog_type.as_deref().unwrap_or("storage");
254        if self.vended_credentials() && catalog_type == "rest" {
255            "rest_rust"
256        } else {
257            catalog_type
258        }
259    }
260
261    pub fn vended_credentials(&self) -> bool {
262        self.vended_credentials.unwrap_or(false)
263    }
264
265    fn glue_access_key(&self) -> Option<&str> {
266        self.glue_access_key
267            .as_deref()
268            .or(self.s3_access_key.as_deref())
269    }
270
271    fn glue_secret_key(&self) -> Option<&str> {
272        self.glue_secret_key
273            .as_deref()
274            .or(self.s3_secret_key.as_deref())
275    }
276
277    fn glue_region(&self) -> Option<&str> {
278        self.glue_region.as_deref().or(self.s3_region.as_deref())
279    }
280
281    pub fn catalog_name(&self) -> String {
282        self.catalog_name
283            .as_ref()
284            .cloned()
285            .unwrap_or_else(|| "risingwave".to_owned())
286    }
287
288    pub fn headers(&self) -> ConnectorResult<HashMap<String, String>> {
289        let mut headers = HashMap::new();
290        let user_agent = match Deployment::current() {
291            Deployment::Ci => "RisingWave(CI)".to_owned(),
292            Deployment::Cloud => "RisingWave(Cloud)".to_owned(),
293            Deployment::Other => "RisingWave(OSS)".to_owned(),
294        };
295        if self.vended_credentials() {
296            headers.insert(
297                "X-Iceberg-Access-Delegation".to_owned(),
298                "vended-credentials".to_owned(),
299            );
300        }
301        headers.insert("User-Agent".to_owned(), user_agent);
302        if let Some(header) = &self.catalog_header {
303            for pair in header.split(';') {
304                let mut parts = pair.split('=');
305                if let (Some(key), Some(value)) = (parts.next(), parts.next()) {
306                    headers.insert(key.to_owned(), value.to_owned());
307                } else {
308                    bail!("Invalid header format: {}", pair);
309                }
310            }
311        }
312        Ok(headers)
313    }
314
315    pub fn enable_config_load(&self) -> bool {
316        // If the env var is set to true, we disable the default config load. (Cloud environment)
317        if env_var_is_true(DISABLE_DEFAULT_CREDENTIAL) {
318            if matches!(self.enable_config_load, Some(true)) {
319                tracing::warn!(
320                    "`enable_config_load` can't be enabled in SaaS environment, the behavior might be unexpected"
321                );
322            }
323            return false;
324        }
325        self.enable_config_load.unwrap_or(false)
326    }
327
328    /// For both V1 and V2.
329    fn build_jni_catalog_configs(
330        &self,
331        java_catalog_props: &HashMap<String, String>,
332    ) -> ConnectorResult<(HashMap<String, String>, HashMap<String, String>)> {
333        let mut iceberg_configs = HashMap::new();
334        let enable_config_load = self.enable_config_load();
335        let file_io_props = {
336            let catalog_type = self.catalog_type().to_owned();
337
338            if let Some(region) = &self.s3_region {
339                // iceberg-rust
340                iceberg_configs.insert(S3_REGION.to_owned(), region.clone());
341            }
342
343            if let Some(endpoint) = &self.s3_endpoint {
344                // iceberg-rust
345                iceberg_configs.insert(S3_ENDPOINT.to_owned(), endpoint.clone());
346            }
347
348            // iceberg-rust
349            if let Some(access_key) = &self.s3_access_key {
350                iceberg_configs.insert(S3_ACCESS_KEY_ID.to_owned(), access_key.clone());
351            }
352            if let Some(secret_key) = &self.s3_secret_key {
353                iceberg_configs.insert(S3_SECRET_ACCESS_KEY.to_owned(), secret_key.clone());
354            }
355            if let Some(role_arn) = &self.s3_iam_role_arn {
356                iceberg_configs.insert(S3_ASSUME_ROLE_ARN.to_owned(), role_arn.clone());
357            }
358            if let Some(gcs_credential) = &self.gcs_credential {
359                iceberg_configs.insert(GCS_CREDENTIALS_JSON.to_owned(), gcs_credential.clone());
360                if catalog_type != "rest" && catalog_type != "rest_rust" {
361                    bail!("gcs unsupported in {} catalog", &catalog_type);
362                }
363            }
364
365            if let (
366                Some(azblob_account_name),
367                Some(azblob_account_key),
368                Some(azblob_endpoint_url),
369            ) = (
370                &self.azblob_account_name,
371                &self.azblob_account_key,
372                &self.azblob_endpoint_url,
373            ) {
374                iceberg_configs.insert(AZBLOB_ACCOUNT_NAME.to_owned(), azblob_account_name.clone());
375                iceberg_configs.insert(AZBLOB_ACCOUNT_KEY.to_owned(), azblob_account_key.clone());
376                iceberg_configs.insert(AZBLOB_ENDPOINT.to_owned(), azblob_endpoint_url.clone());
377
378                if catalog_type != "rest" && catalog_type != "rest_rust" {
379                    bail!("azblob unsupported in {} catalog", &catalog_type);
380                }
381            }
382
383            if let (Some(account_name), Some(account_key)) = (
384                self.adlsgen2_account_name.as_ref(),
385                self.adlsgen2_account_key.as_ref(),
386            ) {
387                iceberg_configs.insert(ADLS_ACCOUNT_NAME.to_owned(), account_name.clone());
388                iceberg_configs.insert(ADLS_ACCOUNT_KEY.to_owned(), account_key.clone());
389                if catalog_type != "rest" && catalog_type != "rest_rust" {
390                    bail!("adlsgen2 unsupported in {} catalog", &catalog_type);
391                }
392            }
393
394            match &self.warehouse_path {
395                Some(warehouse_path) => {
396                    let (bucket, _) = {
397                        let is_s3_tables = warehouse_path.starts_with("arn:aws:s3tables");
398                        // BigLake catalog federation uses bq:// prefix for BigQuery-managed Iceberg tables
399                        let is_bq_catalog_federation = warehouse_path.starts_with("bq://");
400                        let url = Url::parse(warehouse_path);
401                        if (url.is_err() || is_s3_tables || is_bq_catalog_federation)
402                            && (catalog_type == "rest" || catalog_type == "rest_rust")
403                        {
404                            // If the warehouse path is not a valid URL, it could be:
405                            // - A warehouse name in REST catalog
406                            // - An S3 Tables path (arn:aws:s3tables:...)
407                            // - A BigLake path (bq://projects/...) for Google Cloud BigQuery integration
408                            // We allow these to pass through for REST catalogs.
409                            (None, None)
410                        } else {
411                            let url = url.with_context(|| {
412                                format!("Invalid warehouse path: {}", warehouse_path)
413                            })?;
414                            let bucket = url
415                                .host_str()
416                                .with_context(|| {
417                                    format!(
418                                        "Invalid s3 path: {}, bucket is missing",
419                                        warehouse_path
420                                    )
421                                })?
422                                .to_owned();
423                            let root = url.path().trim_start_matches('/').to_owned();
424                            (Some(bucket), Some(root))
425                        }
426                    };
427
428                    if let Some(bucket) = bucket {
429                        iceberg_configs.insert("iceberg.table.io.bucket".to_owned(), bucket);
430                    }
431                }
432                None => {
433                    if catalog_type != "rest" && catalog_type != "rest_rust" {
434                        bail!("`warehouse.path` must be set in {} catalog", &catalog_type);
435                    }
436                }
437            }
438            iceberg_configs.insert(
439                S3_DISABLE_CONFIG_LOAD.to_owned(),
440                (!enable_config_load).to_string(),
441            );
442
443            iceberg_configs.insert(
444                GCS_DISABLE_CONFIG_LOAD.to_owned(),
445                (!enable_config_load).to_string(),
446            );
447
448            if let Some(path_style_access) = self.s3_path_style_access {
449                iceberg_configs.insert(
450                    S3_PATH_STYLE_ACCESS.to_owned(),
451                    path_style_access.to_string(),
452                );
453            }
454
455            iceberg_configs
456        };
457
458        // Prepare jni configs, for details please see https://iceberg.apache.org/docs/latest/aws/
459        let mut java_catalog_configs = HashMap::new();
460        {
461            if let Some(uri) = self.catalog_uri.as_deref() {
462                java_catalog_configs.insert("uri".to_owned(), uri.to_owned());
463            }
464
465            if let Some(warehouse_path) = &self.warehouse_path {
466                java_catalog_configs.insert("warehouse".to_owned(), warehouse_path.clone());
467            }
468            java_catalog_configs.extend(java_catalog_props.clone());
469
470            // Set io-impl: use custom io-impl if provided, otherwise default to S3FileIO
471            let io_impl = self
472                .catalog_io_impl
473                .clone()
474                .unwrap_or_else(|| "org.apache.iceberg.aws.s3.S3FileIO".to_owned());
475            java_catalog_configs.insert("io-impl".to_owned(), io_impl);
476
477            // suppress log of FileIO like: Unclosed FileIO instance created by...
478            java_catalog_configs.insert("init-creation-stacktrace".to_owned(), "false".to_owned());
479
480            if let Some(region) = &self.s3_region {
481                java_catalog_configs.insert("client.region".to_owned(), region.clone());
482            }
483            if let Some(endpoint) = &self.s3_endpoint {
484                java_catalog_configs.insert("s3.endpoint".to_owned(), endpoint.clone());
485            }
486
487            if let Some(access_key) = &self.s3_access_key {
488                java_catalog_configs.insert("s3.access-key-id".to_owned(), access_key.clone());
489            }
490            if let Some(secret_key) = &self.s3_secret_key {
491                java_catalog_configs.insert("s3.secret-access-key".to_owned(), secret_key.clone());
492            }
493
494            if let Some(path_style_access) = &self.s3_path_style_access {
495                java_catalog_configs.insert(
496                    "s3.path-style-access".to_owned(),
497                    path_style_access.to_string(),
498                );
499            }
500
501            let headers = self.headers()?;
502            for (header_name, header_value) in headers {
503                java_catalog_configs.insert(format!("header.{}", header_name), header_value);
504            }
505
506            match self.catalog_type() {
507                "rest" => {
508                    // Handle security type for REST catalog (Iceberg 1.10+)
509                    if let Some(security) = &self.catalog_security {
510                        match security.to_lowercase().as_str() {
511                            "google" => {
512                                // Google AuthManager (Iceberg 1.10+) - uses Google ADC
513                                java_catalog_configs.insert(
514                                    "rest.auth.type".to_owned(),
515                                    "org.apache.iceberg.gcp.auth.GoogleAuthManager".to_owned(),
516                                );
517                                // Set GCP auth scopes if provided
518                                if let Some(gcp_auth_scopes) = &self.gcp_auth_scopes {
519                                    java_catalog_configs.insert(
520                                        "gcp.auth.scopes".to_owned(),
521                                        gcp_auth_scopes.clone(),
522                                    );
523                                }
524                            }
525                            "oauth2" => {
526                                // Standard OAuth2 authentication
527                                if let Some(credential) = &self.catalog_credential {
528                                    java_catalog_configs
529                                        .insert("credential".to_owned(), credential.clone());
530                                }
531                                if let Some(token) = &self.catalog_token {
532                                    java_catalog_configs.insert("token".to_owned(), token.clone());
533                                }
534                                if let Some(oauth2_server_uri) = &self.catalog_oauth2_server_uri {
535                                    java_catalog_configs.insert(
536                                        "oauth2-server-uri".to_owned(),
537                                        oauth2_server_uri.clone(),
538                                    );
539                                }
540                                if let Some(scope) = &self.catalog_scope {
541                                    java_catalog_configs.insert("scope".to_owned(), scope.clone());
542                                }
543                            }
544                            "none" | "" => {
545                                // No authentication
546                            }
547                            _ => {
548                                tracing::warn!(
549                                    "Unknown catalog.security value: {}. Supported values: none, oauth2, google",
550                                    security
551                                );
552                            }
553                        }
554                    } else {
555                        // Legacy behavior: use individual OAuth2 properties if security type not specified
556                        if let Some(credential) = &self.catalog_credential {
557                            java_catalog_configs
558                                .insert("credential".to_owned(), credential.clone());
559                        }
560                        if let Some(token) = &self.catalog_token {
561                            java_catalog_configs.insert("token".to_owned(), token.clone());
562                        }
563                        if let Some(oauth2_server_uri) = &self.catalog_oauth2_server_uri {
564                            java_catalog_configs
565                                .insert("oauth2-server-uri".to_owned(), oauth2_server_uri.clone());
566                        }
567                        if let Some(scope) = &self.catalog_scope {
568                            java_catalog_configs.insert("scope".to_owned(), scope.clone());
569                        }
570                    }
571                    if let Some(rest_signing_region) = &self.rest_signing_region {
572                        java_catalog_configs.insert(
573                            "rest.signing-region".to_owned(),
574                            rest_signing_region.clone(),
575                        );
576                    }
577                    if let Some(rest_signing_name) = &self.rest_signing_name {
578                        java_catalog_configs
579                            .insert("rest.signing-name".to_owned(), rest_signing_name.clone());
580                    }
581                    if let Some(rest_sigv4_enabled) = self.rest_sigv4_enabled {
582                        java_catalog_configs.insert(
583                            "rest.sigv4-enabled".to_owned(),
584                            rest_sigv4_enabled.to_string(),
585                        );
586
587                        if let Some(access_key) = &self.s3_access_key {
588                            java_catalog_configs
589                                .insert("rest.access-key-id".to_owned(), access_key.clone());
590                        }
591
592                        if let Some(secret_key) = &self.s3_secret_key {
593                            java_catalog_configs
594                                .insert("rest.secret-access-key".to_owned(), secret_key.clone());
595                        }
596                    }
597                }
598                "glue" => {
599                    let glue_access_key = self.glue_access_key();
600                    let glue_secret_key = self.glue_secret_key();
601                    let has_glue_credentials =
602                        glue_access_key.is_some() && glue_secret_key.is_some();
603                    let should_configure_glue_provider = !enable_config_load
604                        || has_glue_credentials
605                        || self.glue_iam_role_arn.is_some();
606
607                    if should_configure_glue_provider {
608                        java_catalog_configs.insert(
609                            "client.credentials-provider".to_owned(),
610                            "com.risingwave.connector.catalog.GlueCredentialProvider".to_owned(),
611                        );
612                        if let Some(region) = self.glue_region() {
613                            java_catalog_configs.insert(
614                                "client.credentials-provider.glue.region".to_owned(),
615                                region.to_owned(),
616                            );
617                        }
618                        if let Some(access_key) = glue_access_key {
619                            java_catalog_configs.insert(
620                                "client.credentials-provider.glue.access-key-id".to_owned(),
621                                access_key.to_owned(),
622                            );
623                        }
624                        if let Some(secret_key) = glue_secret_key {
625                            java_catalog_configs.insert(
626                                "client.credentials-provider.glue.secret-access-key".to_owned(),
627                                secret_key.to_owned(),
628                            );
629                        }
630                        if let Some(role_arn) = self.glue_iam_role_arn.as_deref() {
631                            java_catalog_configs.insert(
632                                "client.credentials-provider.glue.iam-role-arn".to_owned(),
633                                role_arn.to_owned(),
634                            );
635                        }
636                        if enable_config_load && !has_glue_credentials {
637                            java_catalog_configs.insert(
638                                "client.credentials-provider.glue.use-default-credential-chain"
639                                    .to_owned(),
640                                "true".to_owned(),
641                            );
642                        }
643                    }
644
645                    if let Some(region) = self.glue_region() {
646                        java_catalog_configs.insert("client.region".to_owned(), region.to_owned());
647                        java_catalog_configs.insert(
648                            "glue.endpoint".to_owned(),
649                            format!("https://glue.{}.amazonaws.com", region),
650                        );
651                    }
652
653                    if let Some(glue_id) = self.glue_id.as_deref() {
654                        java_catalog_configs.insert("glue.id".to_owned(), glue_id.to_owned());
655                    }
656                }
657                "jdbc" => {
658                    if let Some(iam_role_arn) = &self.s3_iam_role_arn {
659                        java_catalog_configs
660                            .insert("client.assume-role.arn".to_owned(), iam_role_arn.clone());
661                        java_catalog_configs.insert(
662                            "client.factory".to_owned(),
663                            "org.apache.iceberg.aws.AssumeRoleAwsClientFactory".to_owned(),
664                        );
665                        if let Some(region) = &self.s3_region {
666                            java_catalog_configs
667                                .insert("client.assume-role.region".to_owned(), region.clone());
668                        }
669                    }
670                }
671                _ => {}
672            }
673        }
674
675        Ok((file_io_props, java_catalog_configs))
676    }
677}
678
679impl IcebergCommon {
680    /// TODO: remove the arguments and put them into `IcebergCommon`. Currently the handling in source and sink are different, so pass them separately to be safer.
681    pub async fn create_catalog(
682        &self,
683        java_catalog_props: &HashMap<String, String>,
684    ) -> ConnectorResult<Arc<dyn Catalog>> {
685        match self.catalog_type() {
686            "storage" => {
687                let warehouse = self
688                    .warehouse_path
689                    .clone()
690                    .ok_or_else(|| anyhow!("`warehouse.path` must be set in storage catalog"))?;
691                let url = Url::parse(warehouse.as_ref())
692                    .map_err(|_| anyhow!("Invalid warehouse path: {}", warehouse))?;
693
694                let config = match url.scheme() {
695                    "s3" | "s3a" => StorageCatalogConfig::S3(
696                        storage_catalog::StorageCatalogS3Config::builder()
697                            .warehouse(warehouse)
698                            .access_key(self.s3_access_key.clone())
699                            .secret_key(self.s3_secret_key.clone())
700                            .region(self.s3_region.clone())
701                            .endpoint(self.s3_endpoint.clone())
702                            .path_style_access(self.s3_path_style_access)
703                            .enable_config_load(Some(self.enable_config_load()))
704                            .build(),
705                    ),
706                    "gs" | "gcs" => StorageCatalogConfig::Gcs(
707                        storage_catalog::StorageCatalogGcsConfig::builder()
708                            .warehouse(warehouse)
709                            .credential(self.gcs_credential.clone())
710                            .enable_config_load(Some(self.enable_config_load()))
711                            .build(),
712                    ),
713                    "azblob" => StorageCatalogConfig::Azblob(
714                        storage_catalog::StorageCatalogAzblobConfig::builder()
715                            .warehouse(warehouse)
716                            .account_name(self.azblob_account_name.clone())
717                            .account_key(self.azblob_account_key.clone())
718                            .endpoint(self.azblob_endpoint_url.clone())
719                            .build(),
720                    ),
721                    scheme => bail!("Unsupported warehouse scheme: {}", scheme),
722                };
723
724                let catalog = storage_catalog::StorageCatalog::new(config)?;
725                Ok(Arc::new(catalog))
726            }
727            "rest_rust" => {
728                let mut iceberg_configs = HashMap::new();
729
730                // check gcs credential or s3 access key and secret key
731                if let Some(gcs_credential) = &self.gcs_credential {
732                    iceberg_configs.insert(GCS_CREDENTIALS_JSON.to_owned(), gcs_credential.clone());
733                } else {
734                    if let Some(region) = &self.s3_region {
735                        iceberg_configs.insert(S3_REGION.to_owned(), region.clone());
736                    }
737                    if let Some(endpoint) = &self.s3_endpoint {
738                        iceberg_configs.insert(S3_ENDPOINT.to_owned(), endpoint.clone());
739                    }
740                    if let Some(access_key) = &self.s3_access_key {
741                        iceberg_configs.insert(S3_ACCESS_KEY_ID.to_owned(), access_key.clone());
742                    }
743                    if let Some(secret_key) = &self.s3_secret_key {
744                        iceberg_configs.insert(S3_SECRET_ACCESS_KEY.to_owned(), secret_key.clone());
745                    }
746                    if let Some(path_style_access) = &self.s3_path_style_access {
747                        iceberg_configs.insert(
748                            S3_PATH_STYLE_ACCESS.to_owned(),
749                            path_style_access.to_string(),
750                        );
751                    }
752                };
753
754                if let Some(credential) = &self.catalog_credential {
755                    iceberg_configs.insert("credential".to_owned(), credential.clone());
756                }
757                if let Some(token) = &self.catalog_token {
758                    iceberg_configs.insert("token".to_owned(), token.clone());
759                }
760                if let Some(oauth2_server_uri) = &self.catalog_oauth2_server_uri {
761                    iceberg_configs
762                        .insert("oauth2-server-uri".to_owned(), oauth2_server_uri.clone());
763                }
764                if let Some(scope) = &self.catalog_scope {
765                    iceberg_configs.insert("scope".to_owned(), scope.clone());
766                }
767
768                let headers = self.headers()?;
769                for (header_name, header_value) in headers {
770                    iceberg_configs.insert(format!("header.{}", header_name), header_value);
771                }
772
773                iceberg_configs.insert(
774                    iceberg_catalog_rest::REST_CATALOG_PROP_URI.to_owned(),
775                    self.catalog_uri
776                        .clone()
777                        .with_context(|| "`catalog.uri` must be set in rest catalog".to_owned())?,
778                );
779                if let Some(warehouse_path) = &self.warehouse_path {
780                    iceberg_configs.insert(
781                        iceberg_catalog_rest::REST_CATALOG_PROP_WAREHOUSE.to_owned(),
782                        warehouse_path.clone(),
783                    );
784                }
785                let catalog = iceberg_catalog_rest::RestCatalogBuilder::default()
786                    .load("rest", iceberg_configs)
787                    .await
788                    .map_err(|e| anyhow!(IcebergError::from(e)))?;
789                Ok(Arc::new(catalog))
790            }
791            "glue_rust" => {
792                let mut iceberg_configs = HashMap::new();
793                // glue
794                if let Some(region) = self.glue_region() {
795                    iceberg_configs.insert(AWS_REGION_NAME.to_owned(), region.to_owned());
796                }
797                if let Some(access_key) = self.glue_access_key() {
798                    iceberg_configs.insert(AWS_ACCESS_KEY_ID.to_owned(), access_key.to_owned());
799                }
800                if let Some(secret_key) = self.glue_secret_key() {
801                    iceberg_configs.insert(AWS_SECRET_ACCESS_KEY.to_owned(), secret_key.to_owned());
802                }
803                // s3
804                if let Some(region) = &self.s3_region {
805                    iceberg_configs.insert(S3_REGION.to_owned(), region.clone());
806                }
807                if let Some(endpoint) = &self.s3_endpoint {
808                    iceberg_configs.insert(S3_ENDPOINT.to_owned(), endpoint.clone());
809                }
810                if let Some(access_key) = &self.s3_access_key {
811                    iceberg_configs.insert(S3_ACCESS_KEY_ID.to_owned(), access_key.clone());
812                }
813                if let Some(secret_key) = &self.s3_secret_key {
814                    iceberg_configs.insert(S3_SECRET_ACCESS_KEY.to_owned(), secret_key.clone());
815                }
816                if let Some(role_arn) = &self.s3_iam_role_arn {
817                    iceberg_configs.insert(S3_ASSUME_ROLE_ARN.to_owned(), role_arn.clone());
818                }
819                if let Some(path_style_access) = &self.s3_path_style_access {
820                    iceberg_configs.insert(
821                        S3_PATH_STYLE_ACCESS.to_owned(),
822                        path_style_access.to_string(),
823                    );
824                }
825                iceberg_configs.insert(
826                    iceberg_catalog_glue::GLUE_CATALOG_PROP_WAREHOUSE.to_owned(),
827                    self.warehouse_path
828                        .clone()
829                        .ok_or_else(|| anyhow!("`warehouse.path` must be set in glue catalog"))?,
830                );
831                if let Some(uri) = self.catalog_uri.as_deref() {
832                    iceberg_configs.insert(
833                        iceberg_catalog_glue::GLUE_CATALOG_PROP_URI.to_owned(),
834                        uri.to_owned(),
835                    );
836                }
837                let catalog = iceberg_catalog_glue::GlueCatalogBuilder::default()
838                    .load("glue", iceberg_configs)
839                    .await
840                    .map_err(|e| anyhow!(IcebergError::from(e)))?;
841                Ok(Arc::new(catalog))
842            }
843            catalog_type
844                if catalog_type == "hive"
845                    || catalog_type == "snowflake"
846                    || catalog_type == "jdbc"
847                    || catalog_type == "rest"
848                    || catalog_type == "glue" =>
849            {
850                // Create java catalog
851                let (file_io_props, java_catalog_props) =
852                    self.build_jni_catalog_configs(java_catalog_props)?;
853                let catalog_impl = match catalog_type {
854                    "hive" => "org.apache.iceberg.hive.HiveCatalog",
855                    "jdbc" => "org.apache.iceberg.jdbc.JdbcCatalog",
856                    "snowflake" => "org.apache.iceberg.snowflake.SnowflakeCatalog",
857                    "rest" => "org.apache.iceberg.rest.RESTCatalog",
858                    "glue" => "org.apache.iceberg.aws.glue.GlueCatalog",
859                    _ => unreachable!(),
860                };
861
862                jni_catalog::JniCatalog::build_catalog(
863                    file_io_props,
864                    self.catalog_name(),
865                    catalog_impl,
866                    java_catalog_props,
867                )
868            }
869            "mock" => Ok(Arc::new(mock_catalog::MockCatalog {})),
870            _ => {
871                bail!(
872                    "Unsupported catalog type: {}, only support `storage`, `rest`, `hive`, `jdbc`, `glue`, `snowflake`",
873                    self.catalog_type()
874                )
875            }
876        }
877    }
878
879    /// TODO: remove the arguments and put them into `IcebergCommon`. Currently the handling in source and sink are different, so pass them separately to be safer.
880    pub async fn load_table(
881        &self,
882        table: &IcebergTableIdentifier,
883        java_catalog_props: &HashMap<String, String>,
884    ) -> ConnectorResult<Table> {
885        let catalog = self
886            .create_catalog(java_catalog_props)
887            .await
888            .context("Unable to load iceberg catalog")?;
889
890        let table_id = table
891            .to_table_ident()
892            .context("Unable to parse table name")?;
893
894        let table = catalog.load_table(&table_id).await?;
895        Ok(rebuild_table_with_shared_cache(table).await)
896    }
897}
898
899/// Get a globally shared object cache keyed by table UUID to avoid reuse after drop & recreate.
900pub(crate) async fn shared_object_cache(
901    init_object_cache: Arc<ObjectCache>,
902    table_uuid: Uuid,
903) -> Arc<ObjectCache> {
904    static CACHE: LazyLock<MokaCache<Uuid, Arc<ObjectCache>>> = LazyLock::new(|| {
905        MokaCache::builder()
906            .max_capacity(SHARED_OBJECT_CACHE_MAX_TABLES)
907            .build()
908    });
909
910    CACHE
911        .get_with(table_uuid, async { init_object_cache })
912        .await
913}
914
915pub async fn rebuild_table_with_shared_cache(table: Table) -> Table {
916    let table_uuid = table.metadata().uuid();
917    let init_object_cache = table.object_cache();
918    let object_cache = shared_object_cache(init_object_cache, table_uuid).await;
919    table.with_object_cache(object_cache)
920}