Xuanwo commented on code in PR #78: URL: https://github.com/apache/iceberg-rust/pull/78#discussion_r1357725856
########## crates/iceberg/src/catalog/rest.rs: ########## @@ -0,0 +1,912 @@ +// 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. + +//! This module contains rest catalog implementation. + +use std::collections::HashMap; + +use async_trait::async_trait; +use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue}; +use reqwest::{Client, Request}; +use serde::de::DeserializeOwned; +use urlencoding::encode; + +use crate::error::Result; +use crate::table::Table; +use crate::{ + Catalog, Error, ErrorKind, Namespace, NamespaceIdent, TableCommit, TableCreation, TableIdent, +}; + +use self::_serde::{ + CatalogConfig, ErrorModel, ErrorResponse, ListNamespaceResponse, ListTableResponse, + NamespaceSerde, RenameTableRequest, NO_CONTENT, OK, +}; + +const ICEBERG_REST_SPEC_VERSION: &str = "0.14.1"; +const PATH_V1: &str = "v1"; + +#[derive(Debug, Builder)] +pub struct RestCatalogConfig { + uri: String, + #[builder(default)] + warehouse: Option<String>, + + #[builder(default)] + props: HashMap<String, String>, +} + +impl RestCatalogConfig { + fn config_endpoint(&self) -> String { + [&self.uri, PATH_V1, "config"].join("/") + } + + fn namespaces_endpoint(&self) -> String { + [&self.uri, PATH_V1, "namespaces"].join("/") + } + + fn namespace_endpoint(&self, ns: &NamespaceIdent) -> Result<String> { + Ok([&self.uri, PATH_V1, "namespaces", &ns.encode_in_url()?].join("/")) + } + + fn tables_endpoint(&self, ns: &NamespaceIdent) -> Result<String> { + Ok([ + &self.uri, + PATH_V1, + "namespaces", + &ns.encode_in_url()?, + "tables", + ] + .join("/")) + } + + fn rename_table_endpoint(&self) -> Result<String> { + Ok([&self.uri, PATH_V1, "tables", "rename"].join("/")) + } + + fn table_endpoint(&self, table: &TableIdent) -> Result<String> { + Ok([ + &self.uri, + PATH_V1, + "namespaces", + &table.namespace.encode_in_url()?, + "tables", + encode(&table.name).as_ref(), + ] + .join("/")) + } + + fn try_create_rest_client(&self) -> Result<HttpClient> { + //TODO: We will add oauth, ssl config, sigv4 later + let mut headers = HeaderMap::new(); + headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + headers.insert( + HeaderName::from_static("x-client-version"), + HeaderValue::from_static(ICEBERG_REST_SPEC_VERSION), + ); + headers.insert( + header::USER_AGENT, + HeaderValue::from_str(&format!("iceberg-rs/{}", env!("CARGO_PKG_VERSION"))).unwrap(), + ); + + Ok(HttpClient( + Client::builder().default_headers(headers).build()?, + )) + } +} + +impl NamespaceIdent { + /// Returns url encoded format. + pub fn encode_in_url(&self) -> Result<String> { + if self.0.is_empty() { Review Comment: It's better to ensure that `NamespaceIdent` is valid so that we don't have to check it when using it. This change can removes a lot of `Result<T>` in related APIs. ########## crates/iceberg/src/catalog/rest.rs: ########## @@ -0,0 +1,912 @@ +// 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. + +//! This module contains rest catalog implementation. + +use std::collections::HashMap; + +use async_trait::async_trait; +use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue}; +use reqwest::{Client, Request}; +use serde::de::DeserializeOwned; +use urlencoding::encode; + +use crate::error::Result; +use crate::table::Table; +use crate::{ + Catalog, Error, ErrorKind, Namespace, NamespaceIdent, TableCommit, TableCreation, TableIdent, +}; + +use self::_serde::{ + CatalogConfig, ErrorModel, ErrorResponse, ListNamespaceResponse, ListTableResponse, + NamespaceSerde, RenameTableRequest, NO_CONTENT, OK, +}; + +const ICEBERG_REST_SPEC_VERSION: &str = "0.14.1"; +const PATH_V1: &str = "v1"; + +#[derive(Debug, Builder)] +pub struct RestCatalogConfig { + uri: String, + #[builder(default)] + warehouse: Option<String>, + + #[builder(default)] + props: HashMap<String, String>, +} + +impl RestCatalogConfig { + fn config_endpoint(&self) -> String { + [&self.uri, PATH_V1, "config"].join("/") + } + + fn namespaces_endpoint(&self) -> String { + [&self.uri, PATH_V1, "namespaces"].join("/") + } + + fn namespace_endpoint(&self, ns: &NamespaceIdent) -> Result<String> { + Ok([&self.uri, PATH_V1, "namespaces", &ns.encode_in_url()?].join("/")) + } + + fn tables_endpoint(&self, ns: &NamespaceIdent) -> Result<String> { + Ok([ + &self.uri, + PATH_V1, + "namespaces", + &ns.encode_in_url()?, + "tables", + ] + .join("/")) + } + + fn rename_table_endpoint(&self) -> Result<String> { + Ok([&self.uri, PATH_V1, "tables", "rename"].join("/")) + } + + fn table_endpoint(&self, table: &TableIdent) -> Result<String> { + Ok([ + &self.uri, + PATH_V1, + "namespaces", + &table.namespace.encode_in_url()?, + "tables", + encode(&table.name).as_ref(), + ] + .join("/")) + } + + fn try_create_rest_client(&self) -> Result<HttpClient> { + //TODO: We will add oauth, ssl config, sigv4 later + let mut headers = HeaderMap::new(); + headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + headers.insert( + HeaderName::from_static("x-client-version"), + HeaderValue::from_static(ICEBERG_REST_SPEC_VERSION), + ); + headers.insert( + header::USER_AGENT, + HeaderValue::from_str(&format!("iceberg-rs/{}", env!("CARGO_PKG_VERSION"))).unwrap(), + ); + + Ok(HttpClient( + Client::builder().default_headers(headers).build()?, + )) + } +} + +impl NamespaceIdent { + /// Returns url encoded format. + pub fn encode_in_url(&self) -> Result<String> { + if self.0.is_empty() { + return Err(Error::new( + ErrorKind::DataInvalid, + "Can't encode empty namespace in url!", + )); + } + + Ok(encode(&self.0.join("\u{1F}")).to_string()) + } +} + +struct HttpClient(Client); + +impl HttpClient { + async fn execute< + R: DeserializeOwned, + E: DeserializeOwned + Into<Error>, + const SUCCESS_CODE: u16, + >( + &self, + request: Request, + ) -> Result<R> { + let resp = self.0.execute(request).await?; + + if resp.status().as_u16() == SUCCESS_CODE { + let text = resp.text().await?; + log::debug!("Response text is: {text}"); + Ok(serde_json::from_slice::<R>(text.as_bytes()).map_err(|e| { + Error::new( + ErrorKind::Unexpected, + "Failed to parse response from rest catalog server!", + ) + .with_context("json", text) + .with_source(e) + })?) + } else { + let text = resp.text().await?; + log::debug!("Response text is: {text}"); + let e = serde_json::from_slice::<E>(text.as_bytes()).map_err(|e| { + Error::new( + ErrorKind::Unexpected, + "Failed to parse response from rest catalog server!", + ) + .with_context("json", text) + .with_source(e) + })?; + Err(e.into()) + } + } + + async fn execute2<E: DeserializeOwned + Into<Error>, const SUCCESS_CODE: u16>( + &self, + request: Request, + ) -> Result<()> { + let resp = self.0.execute(request).await?; + + if resp.status().as_u16() == SUCCESS_CODE { + Ok(()) + } else { + let text = resp.text().await?; + log::debug!("Response text is: {text}"); + let e = serde_json::from_slice::<E>(text.as_bytes()).map_err(|e| { + Error::new( + ErrorKind::Unexpected, + "Failed to parse response from rest catalog server!", + ) + .with_context("json", text) + .with_source(e) + })?; + Err(e.into()) + } + } +} + +pub struct RestCatalog { + config: RestCatalogConfig, + client: HttpClient, +} + +#[async_trait] +impl Catalog for RestCatalog { + /// List namespaces from table. + async fn list_namespaces( + &self, + parent: Option<&NamespaceIdent>, + ) -> Result<Vec<NamespaceIdent>> { + let mut request = self.client.0.get(self.config.namespaces_endpoint()); + if let Some(ns) = parent { + request = request.query(&[("parent", ns.encode_in_url()?)]); + } + + let resp = self + .client + .execute::<ListNamespaceResponse, ErrorModel, OK>(request.build()?) + .await?; + + Ok(resp + .namespaces + .into_iter() + .map(NamespaceIdent::from_vec) Review Comment: from_vec should returns `Result<T>` to make sure `NamespaceIdent` is valid. ########## crates/iceberg/Cargo.toml: ########## @@ -41,20 +41,24 @@ either = "1" futures = "0.3" itertools = "0.11" lazy_static = "1" +log = "^0.4" murmur3 = "0.5.2" once_cell = "1" opendal = "0.40" ordered-float = "4.0.0" +reqwest = { version = "^0.11", features = ["json"] } Review Comment: Do we need to put rest catalog in a new crate? I'm guessing not all iceberg users need this. ########## crates/iceberg/src/catalog/rest.rs: ########## @@ -0,0 +1,912 @@ +// 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. + +//! This module contains rest catalog implementation. + +use std::collections::HashMap; + +use async_trait::async_trait; +use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue}; +use reqwest::{Client, Request}; +use serde::de::DeserializeOwned; +use urlencoding::encode; + +use crate::error::Result; +use crate::table::Table; +use crate::{ + Catalog, Error, ErrorKind, Namespace, NamespaceIdent, TableCommit, TableCreation, TableIdent, +}; + +use self::_serde::{ + CatalogConfig, ErrorModel, ErrorResponse, ListNamespaceResponse, ListTableResponse, + NamespaceSerde, RenameTableRequest, NO_CONTENT, OK, +}; + +const ICEBERG_REST_SPEC_VERSION: &str = "0.14.1"; +const PATH_V1: &str = "v1"; + +#[derive(Debug, Builder)] +pub struct RestCatalogConfig { + uri: String, + #[builder(default)] + warehouse: Option<String>, + + #[builder(default)] + props: HashMap<String, String>, +} + +impl RestCatalogConfig { + fn config_endpoint(&self) -> String { + [&self.uri, PATH_V1, "config"].join("/") + } + + fn namespaces_endpoint(&self) -> String { + [&self.uri, PATH_V1, "namespaces"].join("/") + } + + fn namespace_endpoint(&self, ns: &NamespaceIdent) -> Result<String> { + Ok([&self.uri, PATH_V1, "namespaces", &ns.encode_in_url()?].join("/")) + } + + fn tables_endpoint(&self, ns: &NamespaceIdent) -> Result<String> { + Ok([ + &self.uri, + PATH_V1, + "namespaces", + &ns.encode_in_url()?, + "tables", + ] + .join("/")) + } + + fn rename_table_endpoint(&self) -> Result<String> { + Ok([&self.uri, PATH_V1, "tables", "rename"].join("/")) + } + + fn table_endpoint(&self, table: &TableIdent) -> Result<String> { + Ok([ + &self.uri, + PATH_V1, + "namespaces", + &table.namespace.encode_in_url()?, + "tables", + encode(&table.name).as_ref(), + ] + .join("/")) + } + + fn try_create_rest_client(&self) -> Result<HttpClient> { + //TODO: We will add oauth, ssl config, sigv4 later + let mut headers = HeaderMap::new(); + headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + headers.insert( + HeaderName::from_static("x-client-version"), + HeaderValue::from_static(ICEBERG_REST_SPEC_VERSION), + ); + headers.insert( + header::USER_AGENT, + HeaderValue::from_str(&format!("iceberg-rs/{}", env!("CARGO_PKG_VERSION"))).unwrap(), + ); + + Ok(HttpClient( + Client::builder().default_headers(headers).build()?, + )) + } +} + +impl NamespaceIdent { + /// Returns url encoded format. + pub fn encode_in_url(&self) -> Result<String> { + if self.0.is_empty() { + return Err(Error::new( + ErrorKind::DataInvalid, + "Can't encode empty namespace in url!", + )); + } + + Ok(encode(&self.0.join("\u{1F}")).to_string()) + } +} + +struct HttpClient(Client); + +impl HttpClient { + async fn execute< + R: DeserializeOwned, + E: DeserializeOwned + Into<Error>, + const SUCCESS_CODE: u16, + >( + &self, + request: Request, + ) -> Result<R> { + let resp = self.0.execute(request).await?; + + if resp.status().as_u16() == SUCCESS_CODE { + let text = resp.text().await?; Review Comment: Using `resp.bytes()` here to avoid not need UTC-8 checks. -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
