luoyuxia commented on code in PR #160:
URL: https://github.com/apache/paimon-rust/pull/160#discussion_r3015514817


##########
crates/integration_tests/Cargo.toml:
##########
@@ -28,3 +28,7 @@ paimon = { path = "../paimon" }
 arrow-array = { workspace = true }
 tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
 futures = "0.3"
+serde_json = "1"

Review Comment:
   can be removed?



##########
crates/integration_tests/tests/read_tables.rs:
##########
@@ -438,3 +445,169 @@ async fn test_read_projection_duplicate_column() {
         "Expected ConfigInvalid for duplicate projection, got: {err:?}"
     );
 }
+
+// ======================= REST Catalog read tests 
===============================
+
+/// Build a simple test schema matching the Spark-provisioned tables (id INT, 
name VARCHAR).
+fn simple_log_schema() -> Schema {
+    Schema::builder()
+        .column("id", DataType::Int(IntType::new()))
+        .column("name", DataType::VarChar(VarCharType::string_type()))
+        .build()
+        .expect("Failed to build schema")
+}
+
+/// Build a DV-enabled primary key schema (id INT NOT NULL as PK, name 
VARCHAR).
+fn simple_dv_pk_schema() -> Schema {
+    Schema::builder()
+        .column("id", DataType::Int(IntType::with_nullable(false)))
+        .column("name", DataType::VarChar(VarCharType::string_type()))
+        .primary_key(["id"])
+        .option("deletion-vectors.enabled", "true")
+        .build()
+        .expect("Failed to build schema")
+}
+
+/// Start a mock REST server backed by Spark-provisioned data on disk,
+/// register the given tables, and return a connected `RESTCatalog`.
+async fn setup_rest_catalog_with_tables(
+    table_configs: &[(&str, &str, Schema)],
+) -> (mock_server::RESTServer, RESTCatalog) {
+    let catalog_path = get_test_warehouse();
+    // Use a simple warehouse name (no slashes) to avoid URL-encoding issues
+    let warehouse_name = "test_warehouse";
+    let prefix = "mock-test";
+    let mut defaults = HashMap::new();
+    defaults.insert("prefix".to_string(), prefix.to_string());
+    let config = ConfigResponse::new(defaults);
+
+    let server = start_mock_server(
+        warehouse_name.to_string(),
+        catalog_path.clone(),
+        config,
+        vec!["default".to_string()],
+    )
+    .await;
+
+    // Register each table with its schema and the real on-disk path
+    for (database, table_name, schema) in table_configs {
+        let table_path = format!("{}/{}.db/{}", catalog_path, database, 
table_name);
+        server.add_table_with_schema(database, table_name, schema.clone(), 
&table_path);
+    }
+
+    let url = server.url().expect("Failed to get server URL");
+    let mut options = Options::new();
+    options.set("uri", &url);
+    options.set("warehouse", warehouse_name);
+    options.set("token.provider", "bear");
+    options.set("token", "test_token");
+
+    let catalog = RESTCatalog::new(options, true)
+        .await
+        .expect("Failed to create RESTCatalog");
+
+    (server, catalog)
+}
+
+/// Test reading an append-only (log) table via REST catalog backed by mock 
server.
+///
+/// The mock server returns table metadata pointing to Spark-provisioned data 
on disk.
+#[tokio::test]
+async fn test_rest_catalog_read_append_table() {

Review Comment:
   is there any difference between log table and dv table regarding to rest 
catalog?
   If not, I think we just need to keep only one test.



##########
crates/paimon/examples/rest_catalog_example.rs:
##########
@@ -0,0 +1,177 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Example: REST Catalog Operations
+//!
+//! This example demonstrates how to use `RESTCatalog` for database and table 
operations
+//! via the Paimon REST catalog API.
+//!
+//! # Usage
+//! ```bash
+//! # With DLF authentication:
+//! DLF_ACCESS_KEY_ID=xxx DLF_ACCESS_KEY_SECRET=yyy \
+//!   cargo run -p paimon --example rest_catalog_example
+//!
+//! # With Bearer token authentication:
+//! PAIMON_REST_TOKEN=zzz \
+//!   cargo run -p paimon --example rest_catalog_example
+//! ```
+
+use std::collections::HashMap;
+
+use paimon::catalog::{Catalog, Identifier, RESTCatalog};
+use paimon::common::{CatalogOptions, Options};
+use paimon::spec::{DataType, IntType, Schema, VarCharType};
+
+/// Create a simple test schema with `id` (INT) and `name` (VARCHAR) columns.
+fn create_test_schema() -> Schema {
+    Schema::builder()
+        .column("id", DataType::Int(IntType::new()))
+        .column("name", DataType::VarChar(VarCharType::new(255).unwrap()))
+        .build()
+        .expect("Failed to build schema")
+}
+
+#[tokio::main]
+async fn main() {

Review Comment:
   can these two example combine to single one example? 



##########
crates/paimon/src/catalog/rest/rest_catalog.rs:
##########
@@ -0,0 +1,371 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! REST catalog implementation for Apache Paimon.
+//!
+//! This module provides a REST-based catalog that communicates with
+//! a Paimon REST catalog server for database and table CRUD operations.
+
+use std::collections::HashMap;
+
+use async_trait::async_trait;
+
+use crate::api::rest_api::RESTApi;
+use crate::api::rest_error::RestError;
+use crate::api::PagedList;
+use crate::catalog::{Catalog, Database, Identifier, DB_LOCATION_PROP};
+use crate::common::{CatalogOptions, Options};
+use crate::error::Error;
+use crate::io::FileIO;
+use crate::spec::{Schema, SchemaChange, TableSchema};
+use crate::table::Table;
+use crate::Result;
+
+use super::rest_token_file_io::RESTTokenFileIO;
+
+/// REST catalog implementation.
+///
+/// This catalog communicates with a Paimon REST catalog server
+/// for all metadata operations (database and table CRUD).
+///
+/// Corresponds to Python `RESTCatalog` in 
`pypaimon/catalog/rest/rest_catalog.py`.
+pub struct RESTCatalog {
+    /// The REST API client.
+    api: RESTApi,
+    /// Catalog configuration options.
+    options: Options,
+    /// Warehouse path.
+    warehouse: String,
+    /// Whether data token is enabled for FileIO construction.
+    data_token_enabled: bool,
+}
+
+impl RESTCatalog {
+    /// Create a new REST catalog.
+    ///
+    /// # Arguments
+    /// * `options` - Configuration options containing URI, warehouse, etc.
+    /// * `config_required` - Whether to fetch config from server and merge 
with options.
+    ///
+    /// # Errors
+    /// Returns an error if required options are missing or if initialization 
fails.
+    pub async fn new(options: Options, config_required: bool) -> Result<Self> {
+        let warehouse = options
+            .get(CatalogOptions::WAREHOUSE)
+            .cloned()
+            .unwrap_or_default();

Review Comment:
   return error instead of default?



##########
crates/paimon/src/catalog/rest/rest_catalog.rs:
##########
@@ -0,0 +1,371 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! REST catalog implementation for Apache Paimon.
+//!
+//! This module provides a REST-based catalog that communicates with
+//! a Paimon REST catalog server for database and table CRUD operations.
+
+use std::collections::HashMap;
+
+use async_trait::async_trait;
+
+use crate::api::rest_api::RESTApi;
+use crate::api::rest_error::RestError;
+use crate::api::PagedList;
+use crate::catalog::{Catalog, Database, Identifier, DB_LOCATION_PROP};
+use crate::common::{CatalogOptions, Options};
+use crate::error::Error;
+use crate::io::FileIO;
+use crate::spec::{Schema, SchemaChange, TableSchema};
+use crate::table::Table;
+use crate::Result;
+
+use super::rest_token_file_io::RESTTokenFileIO;
+
+/// REST catalog implementation.
+///
+/// This catalog communicates with a Paimon REST catalog server
+/// for all metadata operations (database and table CRUD).
+///
+/// Corresponds to Python `RESTCatalog` in 
`pypaimon/catalog/rest/rest_catalog.py`.
+pub struct RESTCatalog {
+    /// The REST API client.
+    api: RESTApi,
+    /// Catalog configuration options.
+    options: Options,
+    /// Warehouse path.
+    warehouse: String,
+    /// Whether data token is enabled for FileIO construction.
+    data_token_enabled: bool,
+}
+
+impl RESTCatalog {
+    /// Create a new REST catalog.
+    ///
+    /// # Arguments
+    /// * `options` - Configuration options containing URI, warehouse, etc.
+    /// * `config_required` - Whether to fetch config from server and merge 
with options.
+    ///
+    /// # Errors
+    /// Returns an error if required options are missing or if initialization 
fails.
+    pub async fn new(options: Options, config_required: bool) -> Result<Self> {
+        let warehouse = options
+            .get(CatalogOptions::WAREHOUSE)
+            .cloned()
+            .unwrap_or_default();
+
+        let api = RESTApi::new(options.clone(), config_required).await?;
+
+        let data_token_enabled = api
+            .options()
+            .get(CatalogOptions::DATA_TOKEN_ENABLED)
+            .map(|v| v.eq_ignore_ascii_case("true"))
+            .unwrap_or(false);
+
+        let api_options = api.options().clone();
+
+        Ok(Self {
+            api,
+            options: api_options,
+            warehouse,
+            data_token_enabled,
+        })
+    }
+
+    /// Get the warehouse path.
+    pub fn warehouse(&self) -> &str {
+        &self.warehouse
+    }
+
+    /// Get the catalog options.
+    pub fn options(&self) -> &Options {
+        &self.options
+    }
+
+    /// Whether data token is enabled.
+    pub fn data_token_enabled(&self) -> bool {
+        self.data_token_enabled
+    }
+
+    /// List databases with pagination.
+    pub async fn list_databases_paged(
+        &self,
+        max_results: Option<u32>,
+        page_token: Option<&str>,
+        database_name_pattern: Option<&str>,
+    ) -> Result<PagedList<String>> {
+        self.api
+            .list_databases_paged(max_results, page_token, 
database_name_pattern)
+            .await
+    }
+}
+
+// ============================================================================
+// Catalog trait implementation
+// ============================================================================
+
+#[async_trait]
+impl Catalog for RESTCatalog {
+    // ======================= database methods ===============================
+
+    async fn list_databases(&self) -> Result<Vec<String>> {
+        self.api.list_databases().await
+    }
+
+    async fn create_database(
+        &self,
+        name: &str,
+        ignore_if_exists: bool,
+        properties: HashMap<String, String>,
+    ) -> Result<()> {
+        let result = self
+            .api
+            .create_database(name, Some(properties))
+            .await
+            .map_err(|e| map_rest_error_for_database(e, name));
+        ignore_error_if(result, |e| {
+            ignore_if_exists && matches!(e, Error::DatabaseAlreadyExist { .. })
+        })
+    }
+
+    async fn get_database(&self, name: &str) -> Result<Database> {
+        let response = self
+            .api
+            .get_database(name)
+            .await
+            .map_err(|e| map_rest_error_for_database(e, name))?;
+
+        let mut options = response.options;
+        if let Some(location) = response.location {
+            options.insert(DB_LOCATION_PROP.to_string(), location);
+        }
+
+        Ok(Database::new(name.to_string(), options, None))
+    }
+
+    async fn drop_database(
+        &self,
+        name: &str,
+        ignore_if_not_exists: bool,
+        cascade: bool,
+    ) -> Result<()> {
+        // If not cascade, check if database is empty first
+        if !cascade {
+            let tables = match self.api.list_tables(name).await {
+                Ok(tables) => tables,
+                Err(err) => {
+                    return 
ignore_error_if(Err(map_rest_error_for_database(err, name)), |e| {
+                        ignore_if_not_exists && matches!(e, 
Error::DatabaseNotExist { .. })
+                    });
+                }
+            };
+            if !tables.is_empty() {
+                return Err(Error::DatabaseNotEmpty {
+                    database: name.to_string(),
+                });
+            }
+        }
+
+        let result = self
+            .api
+            .drop_database(name)
+            .await
+            .map_err(|e| map_rest_error_for_database(e, name));
+        ignore_error_if(result, |e| {
+            ignore_if_not_exists && matches!(e, Error::DatabaseNotExist { .. })
+        })
+    }
+
+    // ======================= table methods ===============================
+
+    async fn get_table(&self, identifier: &Identifier) -> Result<Table> {
+        let response = self
+            .api
+            .get_table(identifier)
+            .await
+            .map_err(|e| map_rest_error_for_table(e, identifier))?;
+
+        // Extract schema from response
+        let schema = response.schema.ok_or_else(|| Error::DataInvalid {
+            message: format!("Table {} response missing schema", 
identifier.full_name()),
+            source: None,
+        })?;
+
+        let schema_id = response.schema_id.unwrap_or(0);
+        let table_schema = TableSchema::new(schema_id, &schema);
+
+        // Extract table path from response
+        let table_path = response.path.ok_or_else(|| Error::DataInvalid {
+            message: format!("Table {} response missing path", 
identifier.full_name()),
+            source: None,
+        })?;
+
+        // Check if the table is external
+        let is_external = response.is_external.unwrap_or(false);
+
+        // Build FileIO based on data_token_enabled and is_external
+        let file_io = if self.data_token_enabled && !is_external {
+            // Use RESTTokenFileIO to get token-based FileIO
+            let token_file_io =
+                RESTTokenFileIO::new(identifier.clone(), table_path.clone(), 
self.options.clone());
+            token_file_io.build_file_io().await?
+        } else {
+            // Use standard FileIO from path
+            FileIO::from_path(&table_path)?.build()?

Review Comment:
   seems here we don't pass any option like ak/sk to it. How it can access 
oss/s3?



##########
crates/paimon/src/catalog/rest/rest_token_file_io.rs:
##########
@@ -0,0 +1,183 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! REST token-based FileIO for Apache Paimon.
+//!
+//! This module provides a FileIO wrapper that supports getting data access
+//! tokens from a REST Server. It handles token caching, expiration detection,
+//! and automatic refresh.
+
+use std::collections::HashMap;
+
+use tokio::sync::{Mutex, RwLock};
+
+use crate::api::rest_api::RESTApi;
+use crate::api::rest_util::RESTUtil;
+use crate::catalog::Identifier;
+use crate::common::{CatalogOptions, Options};
+use crate::io::storage_oss::OSS_ENDPOINT;
+use crate::io::FileIO;
+use crate::Result;
+
+use super::rest_token::RESTToken;
+
+/// Safe time margin (in milliseconds) before token expiration to trigger 
refresh.
+const TOKEN_EXPIRATION_SAFE_TIME_MILLIS: i64 = 3_600_000;
+
+/// A FileIO wrapper that supports getting data access tokens from a REST 
Server.
+///
+/// This struct handles:
+/// - Token caching with expiration detection
+/// - Automatic token refresh via `RESTApi::load_table_token`
+/// - Merging token credentials into catalog options to build the underlying 
`FileIO`
+pub struct RESTTokenFileIO {
+    /// Table identifier for token requests.
+    identifier: Identifier,
+    /// Table path (e.g. "oss://bucket/warehouse/db.db/table").
+    path: String,
+    /// Catalog options used to build FileIO and create RESTApi.
+    catalog_options: Options,
+    /// Lazily-initialized REST API client for token refresh.
+    /// Created on first token refresh and reused for subsequent refreshes.
+    api: Mutex<Option<RESTApi>>,
+    /// Cached token with RwLock for concurrent access.
+    token: RwLock<Option<RESTToken>>,
+}
+
+impl RESTTokenFileIO {
+    /// Create a new RESTTokenFileIO.
+    ///
+    /// # Arguments
+    /// * `identifier` - Table identifier for token requests.
+    /// * `path` - Table path for FileIO construction.
+    /// * `catalog_options` - Catalog options for RESTApi and FileIO.
+    pub fn new(identifier: Identifier, path: String, catalog_options: Options) 
-> Self {
+        Self {
+            identifier,
+            path,
+            catalog_options,
+            api: Mutex::new(None),
+            token: RwLock::new(None),
+        }
+    }
+
+    /// Build a `FileIO` instance with the current token merged into options.
+    ///
+    /// This method:
+    /// 1. Refreshes the token if expired or not yet obtained.
+    /// 2. Merges token credentials into catalog options.
+    /// 3. Builds a `FileIO` from the merged options.
+    ///
+    /// This method builds a FileIO with the current token,
+    /// which can be passed to `Table::new`. If the token expires, a new
+    /// `get_table` call is needed.
+    pub async fn build_file_io(&self) -> Result<FileIO> {
+        // Ensure token is fresh
+        self.try_to_refresh_token().await?;
+
+        let token_guard = self.token.read().await;
+        match token_guard.as_ref() {
+            Some(token) => {
+                // Merge catalog options (base) with token credentials 
(override)
+                let merged_props =
+                    RESTUtil::merge(Some(self.catalog_options.to_map()), 
Some(&token.token));
+                // Build FileIO with merged properties
+                let mut builder = FileIO::from_path(&self.path)?;
+                builder = builder.with_props(merged_props);
+                builder.build()
+            }
+            None => {
+                // No token available, build FileIO from path only
+                FileIO::from_path(&self.path)?.build()
+            }
+        }
+    }
+
+    /// Try to refresh the token if it is expired or not yet obtained.
+    async fn try_to_refresh_token(&self) -> Result<()> {
+        // Fast path: check if token is still valid under read lock
+        {
+            let token_guard = self.token.read().await;
+            if let Some(token) = token_guard.as_ref() {
+                if !Self::is_token_expired(token) {
+                    return Ok(());
+                }
+            }
+        }
+
+        // Slow path: acquire write lock and refresh
+        let mut token_guard = self.token.write().await;
+
+        // Double-check after acquiring write lock (another task may have 
refreshed)
+        if let Some(token) = token_guard.as_ref() {
+            if !Self::is_token_expired(token) {
+                return Ok(());
+            }
+        }
+
+        // Refresh the token
+        let new_token = self.refresh_token().await?;

Review Comment:
   please don't hold lock across `.await` points, it may well cause dead lock



##########
crates/paimon/src/catalog/rest/rest_token_file_io.rs:
##########
@@ -0,0 +1,183 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! REST token-based FileIO for Apache Paimon.
+//!
+//! This module provides a FileIO wrapper that supports getting data access
+//! tokens from a REST Server. It handles token caching, expiration detection,
+//! and automatic refresh.
+
+use std::collections::HashMap;
+
+use tokio::sync::{Mutex, RwLock};
+
+use crate::api::rest_api::RESTApi;
+use crate::api::rest_util::RESTUtil;
+use crate::catalog::Identifier;
+use crate::common::{CatalogOptions, Options};
+use crate::io::storage_oss::OSS_ENDPOINT;
+use crate::io::FileIO;
+use crate::Result;
+
+use super::rest_token::RESTToken;
+
+/// Safe time margin (in milliseconds) before token expiration to trigger 
refresh.
+const TOKEN_EXPIRATION_SAFE_TIME_MILLIS: i64 = 3_600_000;
+
+/// A FileIO wrapper that supports getting data access tokens from a REST 
Server.
+///
+/// This struct handles:
+/// - Token caching with expiration detection
+/// - Automatic token refresh via `RESTApi::load_table_token`
+/// - Merging token credentials into catalog options to build the underlying 
`FileIO`
+pub struct RESTTokenFileIO {
+    /// Table identifier for token requests.
+    identifier: Identifier,
+    /// Table path (e.g. "oss://bucket/warehouse/db.db/table").
+    path: String,
+    /// Catalog options used to build FileIO and create RESTApi.
+    catalog_options: Options,
+    /// Lazily-initialized REST API client for token refresh.
+    /// Created on first token refresh and reused for subsequent refreshes.
+    api: Mutex<Option<RESTApi>>,

Review Comment:
   can it also use RwLock?
   Also, we tend to use parking_lot::RwLock



##########
crates/paimon/src/catalog/rest/rest_catalog.rs:
##########
@@ -0,0 +1,371 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! REST catalog implementation for Apache Paimon.
+//!
+//! This module provides a REST-based catalog that communicates with
+//! a Paimon REST catalog server for database and table CRUD operations.
+
+use std::collections::HashMap;
+
+use async_trait::async_trait;
+
+use crate::api::rest_api::RESTApi;
+use crate::api::rest_error::RestError;
+use crate::api::PagedList;
+use crate::catalog::{Catalog, Database, Identifier, DB_LOCATION_PROP};
+use crate::common::{CatalogOptions, Options};
+use crate::error::Error;
+use crate::io::FileIO;
+use crate::spec::{Schema, SchemaChange, TableSchema};
+use crate::table::Table;
+use crate::Result;
+
+use super::rest_token_file_io::RESTTokenFileIO;
+
+/// REST catalog implementation.
+///
+/// This catalog communicates with a Paimon REST catalog server
+/// for all metadata operations (database and table CRUD).
+///
+/// Corresponds to Python `RESTCatalog` in 
`pypaimon/catalog/rest/rest_catalog.py`.
+pub struct RESTCatalog {
+    /// The REST API client.
+    api: RESTApi,
+    /// Catalog configuration options.
+    options: Options,
+    /// Warehouse path.
+    warehouse: String,
+    /// Whether data token is enabled for FileIO construction.
+    data_token_enabled: bool,
+}
+
+impl RESTCatalog {
+    /// Create a new REST catalog.
+    ///
+    /// # Arguments
+    /// * `options` - Configuration options containing URI, warehouse, etc.
+    /// * `config_required` - Whether to fetch config from server and merge 
with options.
+    ///
+    /// # Errors
+    /// Returns an error if required options are missing or if initialization 
fails.
+    pub async fn new(options: Options, config_required: bool) -> Result<Self> {
+        let warehouse = options
+            .get(CatalogOptions::WAREHOUSE)
+            .cloned()
+            .unwrap_or_default();
+
+        let api = RESTApi::new(options.clone(), config_required).await?;
+
+        let data_token_enabled = api
+            .options()
+            .get(CatalogOptions::DATA_TOKEN_ENABLED)
+            .map(|v| v.eq_ignore_ascii_case("true"))
+            .unwrap_or(false);
+
+        let api_options = api.options().clone();
+
+        Ok(Self {
+            api,
+            options: api_options,
+            warehouse,
+            data_token_enabled,
+        })
+    }
+
+    /// Get the warehouse path.
+    pub fn warehouse(&self) -> &str {
+        &self.warehouse
+    }
+
+    /// Get the catalog options.
+    pub fn options(&self) -> &Options {
+        &self.options
+    }
+
+    /// Whether data token is enabled.
+    pub fn data_token_enabled(&self) -> bool {
+        self.data_token_enabled
+    }
+
+    /// List databases with pagination.
+    pub async fn list_databases_paged(
+        &self,
+        max_results: Option<u32>,
+        page_token: Option<&str>,
+        database_name_pattern: Option<&str>,
+    ) -> Result<PagedList<String>> {
+        self.api
+            .list_databases_paged(max_results, page_token, 
database_name_pattern)
+            .await
+    }
+}
+
+// ============================================================================
+// Catalog trait implementation
+// ============================================================================
+
+#[async_trait]
+impl Catalog for RESTCatalog {
+    // ======================= database methods ===============================
+
+    async fn list_databases(&self) -> Result<Vec<String>> {
+        self.api.list_databases().await
+    }
+
+    async fn create_database(
+        &self,
+        name: &str,
+        ignore_if_exists: bool,
+        properties: HashMap<String, String>,
+    ) -> Result<()> {
+        let result = self
+            .api
+            .create_database(name, Some(properties))
+            .await
+            .map_err(|e| map_rest_error_for_database(e, name));
+        ignore_error_if(result, |e| {
+            ignore_if_exists && matches!(e, Error::DatabaseAlreadyExist { .. })
+        })
+    }
+
+    async fn get_database(&self, name: &str) -> Result<Database> {
+        let response = self
+            .api
+            .get_database(name)
+            .await
+            .map_err(|e| map_rest_error_for_database(e, name))?;
+
+        let mut options = response.options;
+        if let Some(location) = response.location {
+            options.insert(DB_LOCATION_PROP.to_string(), location);
+        }
+
+        Ok(Database::new(name.to_string(), options, None))
+    }
+
+    async fn drop_database(
+        &self,
+        name: &str,
+        ignore_if_not_exists: bool,
+        cascade: bool,
+    ) -> Result<()> {
+        // If not cascade, check if database is empty first
+        if !cascade {
+            let tables = match self.api.list_tables(name).await {
+                Ok(tables) => tables,
+                Err(err) => {
+                    return 
ignore_error_if(Err(map_rest_error_for_database(err, name)), |e| {
+                        ignore_if_not_exists && matches!(e, 
Error::DatabaseNotExist { .. })
+                    });
+                }
+            };
+            if !tables.is_empty() {
+                return Err(Error::DatabaseNotEmpty {
+                    database: name.to_string(),
+                });
+            }
+        }
+
+        let result = self
+            .api
+            .drop_database(name)
+            .await
+            .map_err(|e| map_rest_error_for_database(e, name));
+        ignore_error_if(result, |e| {
+            ignore_if_not_exists && matches!(e, Error::DatabaseNotExist { .. })
+        })
+    }
+
+    // ======================= table methods ===============================
+
+    async fn get_table(&self, identifier: &Identifier) -> Result<Table> {
+        let response = self
+            .api
+            .get_table(identifier)
+            .await
+            .map_err(|e| map_rest_error_for_table(e, identifier))?;
+
+        // Extract schema from response
+        let schema = response.schema.ok_or_else(|| Error::DataInvalid {
+            message: format!("Table {} response missing schema", 
identifier.full_name()),
+            source: None,
+        })?;
+
+        let schema_id = response.schema_id.unwrap_or(0);

Review Comment:
   is it expected it didn't return schema id and just use 0?



##########
crates/paimon/src/io/file_io.rs:
##########
@@ -122,18 +122,21 @@ impl FileIO {
         // use normalize_root to make sure it end with `/`.
         let list_path = normalize_root(relative_path);
 
-        // Request ContentLength and LastModified so accessing 
meta.content_length() / last_modified()
-        let entries = op
-            .list_with(&list_path)
-            .metakey(Metakey::ContentLength | Metakey::LastModified)
-            .await
-            .context(IoUnexpectedSnafu {
-                message: format!("Failed to list files in '{path}'"),
-            })?;
+        let entries = op.list_with(&list_path).await.context(IoUnexpectedSnafu 
{
+            message: format!("Failed to list files in '{path}'"),
+        })?;
 
         let mut statuses = Vec::new();
-
+        let list_path_normalized = list_path.trim_start_matches('/');
         for entry in entries {
+            // opendal list_with includes the root directory itself as the 
first entry.

Review Comment:
   is it true?



##########
crates/paimon/src/io/file_io.rs:
##########
@@ -122,18 +122,21 @@ impl FileIO {
         // use normalize_root to make sure it end with `/`.
         let list_path = normalize_root(relative_path);
 
-        // Request ContentLength and LastModified so accessing 
meta.content_length() / last_modified()
-        let entries = op
-            .list_with(&list_path)
-            .metakey(Metakey::ContentLength | Metakey::LastModified)
-            .await
-            .context(IoUnexpectedSnafu {
-                message: format!("Failed to list files in '{path}'"),
-            })?;
+        let entries = op.list_with(&list_path).await.context(IoUnexpectedSnafu 
{

Review Comment:
   why change this?



##########
crates/paimon/src/io/file_io.rs:
##########
@@ -122,18 +122,21 @@ impl FileIO {
         // use normalize_root to make sure it end with `/`.
         let list_path = normalize_root(relative_path);
 
-        // Request ContentLength and LastModified so accessing 
meta.content_length() / last_modified()
-        let entries = op
-            .list_with(&list_path)
-            .metakey(Metakey::ContentLength | Metakey::LastModified)
-            .await
-            .context(IoUnexpectedSnafu {
-                message: format!("Failed to list files in '{path}'"),
-            })?;
+        let entries = op.list_with(&list_path).await.context(IoUnexpectedSnafu 
{
+            message: format!("Failed to list files in '{path}'"),
+        })?;
 
         let mut statuses = Vec::new();
-
+        let list_path_normalized = list_path.trim_start_matches('/');
         for entry in entries {
+            // opendal list_with includes the root directory itself as the 
first entry.

Review Comment:
   Why does it work before?



##########
crates/paimon/src/api/auth/dlf_provider.rs:
##########
@@ -244,7 +244,7 @@ const TOKEN_EXPIRATION_SAFE_TIME_MILLIS: i64 = 3_600_000;
 /// (ROA v2 HMAC-SHA1).
 pub struct DLFAuthProvider {
     uri: String,
-    token: Option<DLFToken>,
+    token: tokio::sync::Mutex<Option<DLFToken>>,

Review Comment:
   nit:
   use parking_lot::RwLock
   ```
   RwLock<Option<DLFToken>>,
   ```
   



##########
crates/integration_tests/tests/read_tables.rs:
##########
@@ -438,3 +445,169 @@ async fn test_read_projection_duplicate_column() {
         "Expected ConfigInvalid for duplicate projection, got: {err:?}"
     );
 }
+
+// ======================= REST Catalog read tests 
===============================
+
+/// Build a simple test schema matching the Spark-provisioned tables (id INT, 
name VARCHAR).
+fn simple_log_schema() -> Schema {
+    Schema::builder()
+        .column("id", DataType::Int(IntType::new()))
+        .column("name", DataType::VarChar(VarCharType::string_type()))
+        .build()
+        .expect("Failed to build schema")
+}
+
+/// Build a DV-enabled primary key schema (id INT NOT NULL as PK, name 
VARCHAR).
+fn simple_dv_pk_schema() -> Schema {
+    Schema::builder()
+        .column("id", DataType::Int(IntType::with_nullable(false)))
+        .column("name", DataType::VarChar(VarCharType::string_type()))
+        .primary_key(["id"])
+        .option("deletion-vectors.enabled", "true")
+        .build()
+        .expect("Failed to build schema")
+}
+
+/// Start a mock REST server backed by Spark-provisioned data on disk,
+/// register the given tables, and return a connected `RESTCatalog`.
+async fn setup_rest_catalog_with_tables(
+    table_configs: &[(&str, &str, Schema)],
+) -> (mock_server::RESTServer, RESTCatalog) {
+    let catalog_path = get_test_warehouse();
+    // Use a simple warehouse name (no slashes) to avoid URL-encoding issues
+    let warehouse_name = "test_warehouse";
+    let prefix = "mock-test";
+    let mut defaults = HashMap::new();
+    defaults.insert("prefix".to_string(), prefix.to_string());
+    let config = ConfigResponse::new(defaults);
+
+    let server = start_mock_server(
+        warehouse_name.to_string(),
+        catalog_path.clone(),
+        config,
+        vec!["default".to_string()],
+    )
+    .await;
+
+    // Register each table with its schema and the real on-disk path
+    for (database, table_name, schema) in table_configs {
+        let table_path = format!("{}/{}.db/{}", catalog_path, database, 
table_name);
+        server.add_table_with_schema(database, table_name, schema.clone(), 
&table_path);
+    }
+
+    let url = server.url().expect("Failed to get server URL");
+    let mut options = Options::new();
+    options.set("uri", &url);
+    options.set("warehouse", warehouse_name);
+    options.set("token.provider", "bear");
+    options.set("token", "test_token");
+
+    let catalog = RESTCatalog::new(options, true)
+        .await
+        .expect("Failed to create RESTCatalog");
+
+    (server, catalog)
+}
+
+/// Test reading an append-only (log) table via REST catalog backed by mock 
server.
+///
+/// The mock server returns table metadata pointing to Spark-provisioned data 
on disk.
+#[tokio::test]
+async fn test_rest_catalog_read_append_table() {

Review Comment:
   Also, i think you can reuse `scan_and_read_with_projection`. Pass a catalog 
trait to it. It should works for both filesystem catalog and rest catalog.



##########
crates/paimon/src/catalog/rest/rest_token_file_io.rs:
##########
@@ -0,0 +1,183 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! REST token-based FileIO for Apache Paimon.
+//!
+//! This module provides a FileIO wrapper that supports getting data access
+//! tokens from a REST Server. It handles token caching, expiration detection,
+//! and automatic refresh.
+
+use std::collections::HashMap;
+
+use tokio::sync::{Mutex, RwLock};
+
+use crate::api::rest_api::RESTApi;
+use crate::api::rest_util::RESTUtil;
+use crate::catalog::Identifier;
+use crate::common::{CatalogOptions, Options};
+use crate::io::storage_oss::OSS_ENDPOINT;
+use crate::io::FileIO;
+use crate::Result;
+
+use super::rest_token::RESTToken;
+
+/// Safe time margin (in milliseconds) before token expiration to trigger 
refresh.
+const TOKEN_EXPIRATION_SAFE_TIME_MILLIS: i64 = 3_600_000;
+
+/// A FileIO wrapper that supports getting data access tokens from a REST 
Server.
+///
+/// This struct handles:
+/// - Token caching with expiration detection
+/// - Automatic token refresh via `RESTApi::load_table_token`
+/// - Merging token credentials into catalog options to build the underlying 
`FileIO`
+pub struct RESTTokenFileIO {
+    /// Table identifier for token requests.
+    identifier: Identifier,
+    /// Table path (e.g. "oss://bucket/warehouse/db.db/table").
+    path: String,
+    /// Catalog options used to build FileIO and create RESTApi.
+    catalog_options: Options,
+    /// Lazily-initialized REST API client for token refresh.
+    /// Created on first token refresh and reused for subsequent refreshes.
+    api: Mutex<Option<RESTApi>>,
+    /// Cached token with RwLock for concurrent access.
+    token: RwLock<Option<RESTToken>>,
+}
+
+impl RESTTokenFileIO {
+    /// Create a new RESTTokenFileIO.
+    ///
+    /// # Arguments
+    /// * `identifier` - Table identifier for token requests.
+    /// * `path` - Table path for FileIO construction.
+    /// * `catalog_options` - Catalog options for RESTApi and FileIO.
+    pub fn new(identifier: Identifier, path: String, catalog_options: Options) 
-> Self {
+        Self {
+            identifier,
+            path,
+            catalog_options,
+            api: Mutex::new(None),
+            token: RwLock::new(None),
+        }
+    }
+
+    /// Build a `FileIO` instance with the current token merged into options.
+    ///
+    /// This method:
+    /// 1. Refreshes the token if expired or not yet obtained.
+    /// 2. Merges token credentials into catalog options.
+    /// 3. Builds a `FileIO` from the merged options.
+    ///
+    /// This method builds a FileIO with the current token,
+    /// which can be passed to `Table::new`. If the token expires, a new
+    /// `get_table` call is needed.
+    pub async fn build_file_io(&self) -> Result<FileIO> {
+        // Ensure token is fresh
+        self.try_to_refresh_token().await?;
+
+        let token_guard = self.token.read().await;
+        match token_guard.as_ref() {
+            Some(token) => {
+                // Merge catalog options (base) with token credentials 
(override)
+                let merged_props =
+                    RESTUtil::merge(Some(self.catalog_options.to_map()), 
Some(&token.token));
+                // Build FileIO with merged properties
+                let mut builder = FileIO::from_path(&self.path)?;
+                builder = builder.with_props(merged_props);
+                builder.build()
+            }
+            None => {
+                // No token available, build FileIO from path only
+                FileIO::from_path(&self.path)?.build()
+            }
+        }
+    }
+
+    /// Try to refresh the token if it is expired or not yet obtained.
+    async fn try_to_refresh_token(&self) -> Result<()> {
+        // Fast path: check if token is still valid under read lock
+        {
+            let token_guard = self.token.read().await;
+            if let Some(token) = token_guard.as_ref() {
+                if !Self::is_token_expired(token) {
+                    return Ok(());
+                }
+            }
+        }
+
+        // Slow path: acquire write lock and refresh
+        let mut token_guard = self.token.write().await;
+
+        // Double-check after acquiring write lock (another task may have 
refreshed)
+        if let Some(token) = token_guard.as_ref() {
+            if !Self::is_token_expired(token) {
+                return Ok(());
+            }
+        }
+
+        // Refresh the token
+        let new_token = self.refresh_token().await?;
+        *token_guard = Some(new_token);
+        Ok(())
+    }
+
+    /// Refresh the token by calling `RESTApi::load_table_token`.
+    ///
+    /// Lazily creates a `RESTApi` instance on first call and reuses it
+    /// for subsequent refreshes.
+    async fn refresh_token(&self) -> Result<RESTToken> {
+        let mut api_guard = self.api.lock().await;
+        let api = match api_guard.as_ref() {
+            Some(existing) => existing,
+            None => {
+                let new_api = RESTApi::new(self.catalog_options.clone(), 
false).await?;

Review Comment:
   dito:
   please don't hold lock across .await points, it may well cause dead lock



##########
crates/paimon/src/catalog/filesystem.rs:
##########
@@ -121,9 +121,16 @@ impl FileSystemCatalog {
     /// List directories in the given path.
     async fn list_directories(&self, path: &str) -> Result<Vec<String>> {
         let statuses = self.file_io.list_status(path).await?;
+        // Normalize the listed path for comparison: strip trailing slash
+        let normalized_path = path.trim_end_matches('/');
         let mut dirs = Vec::new();
         for status in statuses {
             if status.is_dir {
+                // Skip the directory itself (opendal list_with includes the 
root entry)

Review Comment:
   is that true?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to