plusplusjiajia commented on code in PR #2651:
URL: https://github.com/apache/iceberg-rust/pull/2651#discussion_r4456455887


##########
crates/storage/opendal/src/prefixed.rs:
##########
@@ -0,0 +1,379 @@
+// 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.
+
+//! Storage that serves each location with its prefix's credential.
+
+use std::collections::HashMap;
+use std::fmt::{self, Debug};
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use bytes::Bytes;
+use futures::StreamExt;
+use futures::stream::{self, BoxStream};
+use iceberg::Result;
+use iceberg::io::{
+    FileMetadata, FileRead, FileWrite, InputFile, OutputFile, Storage, 
StorageConfig,
+};
+use serde::{Deserialize, Serialize};
+
+/// Per-prefix batch size of `delete_stream`, as in Java's 
`S3FileIO.deleteFiles`.
+const DELETE_BATCH_SIZE: usize = 1000;
+
+/// Serves each path with the credential of its longest matching prefix, as
+/// Java's `S3FileIO.clientForStoragePath` does, else without credentials.
+#[derive(Serialize, Deserialize)]
+pub(crate) struct PrefixedStorage {
+    default: Arc<dyn Storage>,
+    /// Longest prefix first.
+    prefixed: Vec<(String, Arc<dyn Storage>)>,
+}
+
+impl PrefixedStorage {
+    /// Builds the storage for `config` with `build`, which is passed configs
+    /// without storage credentials.
+    pub(crate) fn build(
+        config: &StorageConfig,
+        build: impl Fn(&StorageConfig) -> Result<Arc<dyn Storage>>,
+    ) -> Result<Arc<dyn Storage>> {
+        if config.storage_credentials().is_empty() {
+            return build(config);
+        }
+        Ok(Arc::new(Self::new(config, build)?))
+    }
+
+    fn new(
+        config: &StorageConfig,
+        build: impl Fn(&StorageConfig) -> Result<Arc<dyn Storage>>,
+    ) -> Result<Self> {
+        let base = StorageConfig::from_props(config.props().clone());
+        // The last credential for a prefix wins, as in Java's 
`clientByPrefix`.
+        let credentials: HashMap<&str, &HashMap<String, String>> = config
+            .storage_credentials()
+            .iter()
+            .filter(|credential| !credential.prefix().is_empty())

Review Comment:
   Done, `StorageCredential::new` and its deserialization now reject an empty 
prefix.



##########
crates/storage/opendal/src/prefixed.rs:
##########
@@ -0,0 +1,379 @@
+// 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.
+
+//! Storage that serves each location with its prefix's credential.
+
+use std::collections::HashMap;
+use std::fmt::{self, Debug};
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use bytes::Bytes;
+use futures::StreamExt;
+use futures::stream::{self, BoxStream};
+use iceberg::Result;
+use iceberg::io::{
+    FileMetadata, FileRead, FileWrite, InputFile, OutputFile, Storage, 
StorageConfig,
+};
+use serde::{Deserialize, Serialize};
+
+/// Per-prefix batch size of `delete_stream`, as in Java's 
`S3FileIO.deleteFiles`.
+const DELETE_BATCH_SIZE: usize = 1000;
+
+/// Serves each path with the credential of its longest matching prefix, as
+/// Java's `S3FileIO.clientForStoragePath` does, else without credentials.
+#[derive(Serialize, Deserialize)]
+pub(crate) struct PrefixedStorage {
+    default: Arc<dyn Storage>,
+    /// Longest prefix first.
+    prefixed: Vec<(String, Arc<dyn Storage>)>,
+}
+
+impl PrefixedStorage {
+    /// Builds the storage for `config` with `build`, which is passed configs
+    /// without storage credentials.
+    pub(crate) fn build(
+        config: &StorageConfig,
+        build: impl Fn(&StorageConfig) -> Result<Arc<dyn Storage>>,
+    ) -> Result<Arc<dyn Storage>> {
+        if config.storage_credentials().is_empty() {
+            return build(config);
+        }
+        Ok(Arc::new(Self::new(config, build)?))
+    }
+
+    fn new(
+        config: &StorageConfig,
+        build: impl Fn(&StorageConfig) -> Result<Arc<dyn Storage>>,
+    ) -> Result<Self> {
+        let base = StorageConfig::from_props(config.props().clone());
+        // The last credential for a prefix wins, as in Java's 
`clientByPrefix`.
+        let credentials: HashMap<&str, &HashMap<String, String>> = config
+            .storage_credentials()
+            .iter()
+            .filter(|credential| !credential.prefix().is_empty())
+            .map(|credential| (credential.prefix(), credential.config()))
+            .collect();
+        let mut prefixed = credentials
+            .into_iter()
+            .map(|(prefix, credential)| {
+                let config = base.clone().with_props(credential.clone());
+                Ok((prefix.to_string(), build(&config)?))
+            })
+            .collect::<Result<Vec<_>>>()?;
+        prefixed.sort_by_key(|(prefix, _)| std::cmp::Reverse(prefix.len()));
+        Ok(Self {
+            default: build(&base)?,
+            prefixed,
+        })
+    }
+
+    /// Matches raw strings, as Java does: `s3://b/data` covers 
`s3://b/database`.
+    fn prefix_index(&self, path: &str) -> Option<usize> {
+        self.prefixed
+            .iter()
+            .position(|(prefix, _)| path.starts_with(prefix.as_str()))
+    }
+
+    fn storage_at(&self, index: Option<usize>) -> &dyn Storage {
+        match index {
+            Some(index) => self.prefixed[index].1.as_ref(),
+            None => self.default.as_ref(),
+        }
+    }
+
+    fn storage_for(&self, path: &str) -> &dyn Storage {
+        self.storage_at(self.prefix_index(path))
+    }
+}
+
+// A backend's Debug may print the credentials it was built with.
+impl Debug for PrefixedStorage {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        let prefixes = fmt::from_fn(|f| {
+            f.debug_list()
+                .entries(self.prefixed.iter().map(|(prefix, _)| prefix))
+                .finish()
+        });
+        f.debug_struct("PrefixedStorage")
+            .field("default", &self.default)
+            .field("prefixes", &prefixes)
+            .finish_non_exhaustive()

Review Comment:
   The per-prefix storages' `Debug` would print their vended credentials, so 
they're left out.



-- 
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]

Reply via email to