tustvold commented on code in PR #3329:
URL: https://github.com/apache/arrow-rs/pull/3329#discussion_r1045837038


##########
object_store/src/prefix.rs:
##########
@@ -0,0 +1,291 @@
+// 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.
+
+//! An object store wrapper handling a constant path prefix
+use bytes::Bytes;
+use futures::{stream::BoxStream, StreamExt, TryStreamExt};
+use std::ops::Range;
+use tokio::io::AsyncWrite;
+
+use crate::path::{Path, DELIMITER};
+use crate::{
+    GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore,
+    Result as ObjectStoreResult,
+};
+
+/// Store wrapper that applies a constant prefix to all paths handled by the 
store.
+#[derive(Debug, Clone)]
+pub struct PrefixObjectStore<T: ObjectStore> {
+    prefix: Path,
+    inner: T,
+}
+
+impl<T: ObjectStore> std::fmt::Display for PrefixObjectStore<T> {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "PrefixObjectStore({})", self.prefix.as_ref())
+    }
+}
+
+impl<T: ObjectStore> PrefixObjectStore<T> {
+    /// Create a new instance of [`PrefixObjectStore`]
+    pub fn new(store: T, prefix: impl Into<Path>) -> Self {
+        Self {
+            prefix: prefix.into(),
+            inner: store,
+        }
+    }
+
+    /// Create the full path from a path relative to prefix
+    fn full_path(&self, location: &Path) -> ObjectStoreResult<Path> {
+        let path: &str = location.as_ref();
+        let stripped = match self.prefix.as_ref() {
+            "" => path.to_string(),
+            p => format!("{}/{}", p, path),
+        };
+        Ok(Path::parse(stripped.trim_end_matches(DELIMITER))?)
+    }
+
+    /// Strip the constant prefix from a given path
+    fn strip_prefix(&self, path: &Path) -> Option<Path> {
+        let path: &str = path.as_ref();
+        let stripped = match self.prefix.as_ref() {
+            "" => path,
+            p => path.strip_prefix(p)?.strip_prefix(DELIMITER)?,
+        };
+        Path::parse(stripped).ok()
+    }
+}
+
+#[async_trait::async_trait]
+impl<T: ObjectStore> ObjectStore for PrefixObjectStore<T> {
+    /// Save the provided bytes to the specified location.
+    async fn put(&self, location: &Path, bytes: Bytes) -> 
ObjectStoreResult<()> {
+        let full_path = self.full_path(location)?;
+        self.inner.put(&full_path, bytes).await
+    }
+
+    /// Return the bytes that are stored at the specified location.
+    async fn get(&self, location: &Path) -> ObjectStoreResult<GetResult> {
+        let full_path = self.full_path(location)?;
+        self.inner.get(&full_path).await
+    }
+
+    /// Return the bytes that are stored at the specified location
+    /// in the given byte range
+    async fn get_range(
+        &self,
+        location: &Path,
+        range: Range<usize>,
+    ) -> ObjectStoreResult<Bytes> {
+        let full_path = self.full_path(location)?;
+        self.inner.get_range(&full_path, range).await
+    }
+
+    /// Return the metadata for the specified location
+    async fn head(&self, location: &Path) -> ObjectStoreResult<ObjectMeta> {
+        let full_path = self.full_path(location)?;
+        self.inner.head(&full_path).await.map(|meta| ObjectMeta {
+            last_modified: meta.last_modified,
+            size: meta.size,
+            location: 
self.strip_prefix(&meta.location).unwrap_or(meta.location),
+        })
+    }
+
+    /// Delete the object at the specified location.
+    async fn delete(&self, location: &Path) -> ObjectStoreResult<()> {
+        let full_path = self.full_path(location)?;
+        self.inner.delete(&full_path).await
+    }
+
+    /// List all the objects with the given prefix.
+    ///
+    /// Prefixes are evaluated on a path segment basis, i.e. `foo/bar/` is a 
prefix of `foo/bar/x` but not of
+    /// `foo/bar_baz/x`.
+    async fn list(
+        &self,
+        prefix: Option<&Path>,
+    ) -> ObjectStoreResult<BoxStream<'_, ObjectStoreResult<ObjectMeta>>> {
+        let prefix = prefix.and_then(|p| self.full_path(p).ok());
+        Ok(self
+            .inner
+            .list(Some(&prefix.unwrap_or_else(|| self.prefix.clone())))

Review Comment:
   Oh I see what complicates this - suggestion in 
https://github.com/apache/arrow-rs/pull/3329/files#r1045836725



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