alamb commented on code in PR #5538:
URL: https://github.com/apache/arrow-rs/pull/5538#discussion_r1561270810


##########
object_store/src/payload.rs:
##########
@@ -0,0 +1,298 @@
+// 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.
+
+use bytes::Bytes;
+use std::sync::Arc;
+
+/// A cheaply cloneable, ordered collection of [`Bytes`]
+#[derive(Debug, Clone)]
+pub struct PutPayload(Arc<[Bytes]>);
+
+impl Default for PutPayload {
+    fn default() -> Self {
+        Self(Arc::new([]))
+    }
+}
+
+impl PutPayload {
+    /// Create a new empty [`PutPayload`]
+    pub fn new() -> Self {
+        Self::default()
+    }
+
+    /// Creates a [`PutPayload`] from a static slice
+    pub fn from_static(s: &'static [u8]) -> Self {
+        s.into()
+    }
+
+    /// Creates a [`PutPayload`] from a [`Bytes`]
+    pub fn from_bytes(s: Bytes) -> Self {
+        s.into()
+    }
+
+    #[cfg(feature = "cloud")]
+    pub(crate) fn body(&self) -> reqwest::Body {
+        reqwest::Body::wrap_stream(futures::stream::iter(
+            self.clone().into_iter().map(Ok::<_, crate::Error>),
+        ))
+    }
+
+    /// Returns the total length of the [`Bytes`] in this payload
+    pub fn content_length(&self) -> usize {
+        self.0.iter().map(|b| b.len()).sum()
+    }
+
+    /// Returns an iterator over the [`Bytes`] in this payload
+    pub fn iter(&self) -> PutPayloadIter<'_> {
+        PutPayloadIter(self.0.iter())
+    }
+}
+
+impl AsRef<[Bytes]> for PutPayload {
+    fn as_ref(&self) -> &[Bytes] {
+        self.0.as_ref()
+    }
+}
+
+impl<'a> IntoIterator for &'a PutPayload {
+    type Item = &'a Bytes;
+    type IntoIter = PutPayloadIter<'a>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        self.iter()
+    }
+}
+
+impl IntoIterator for PutPayload {
+    type Item = Bytes;
+    type IntoIter = PutPayloadIntoIter;
+
+    fn into_iter(self) -> Self::IntoIter {
+        PutPayloadIntoIter {
+            payload: self,
+            idx: 0,
+        }
+    }
+}
+
+/// An iterator over [`PutPayload`]
+#[derive(Debug)]
+pub struct PutPayloadIter<'a>(std::slice::Iter<'a, Bytes>);
+
+impl<'a> Iterator for PutPayloadIter<'a> {
+    type Item = &'a Bytes;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        self.0.next()
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.0.size_hint()
+    }
+}
+
+/// An owning iterator of [`PutPayload`]
+#[derive(Debug)]
+pub struct PutPayloadIntoIter {
+    payload: PutPayload,
+    idx: usize,
+}
+
+impl Iterator for PutPayloadIntoIter {
+    type Item = Bytes;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        let p = self.payload.0.get(self.idx)?.clone();
+        self.idx += 1;
+        Some(p)
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        let l = self.payload.0.len() - self.idx;
+        (l, Some(l))
+    }
+}
+
+impl From<Bytes> for PutPayload {
+    fn from(value: Bytes) -> Self {
+        Self(Arc::new([value]))
+    }
+}
+
+impl From<Vec<u8>> for PutPayload {
+    fn from(value: Vec<u8>) -> Self {
+        Self(Arc::new([value.into()]))
+    }
+}
+
+impl From<&'static str> for PutPayload {
+    fn from(value: &'static str) -> Self {
+        Bytes::from(value).into()
+    }
+}
+
+impl From<&'static [u8]> for PutPayload {
+    fn from(value: &'static [u8]) -> Self {
+        Bytes::from(value).into()
+    }
+}
+
+impl From<String> for PutPayload {
+    fn from(value: String) -> Self {
+        Bytes::from(value).into()
+    }
+}
+
+impl FromIterator<u8> for PutPayload {
+    fn from_iter<T: IntoIterator<Item = u8>>(iter: T) -> Self {
+        Bytes::from_iter(iter).into()
+    }
+}
+
+impl FromIterator<Bytes> for PutPayload {
+    fn from_iter<T: IntoIterator<Item = Bytes>>(iter: T) -> Self {
+        Self(iter.into_iter().collect())
+    }
+}
+
+impl From<PutPayload> for Bytes {
+    fn from(value: PutPayload) -> Self {
+        match value.0.len() {
+            0 => Self::new(),
+            1 => value.0[0].clone(),
+            _ => {
+                let mut buf = Vec::with_capacity(value.content_length());
+                value.iter().for_each(|x| buf.extend_from_slice(x));
+                buf.into()
+            }
+        }
+    }
+}
+
+/// A builder for [`PutPayload`] that allocates memory in chunks
+#[derive(Debug)]
+pub struct PutPayloadMut {
+    len: usize,
+    completed: Vec<Bytes>,
+    in_progress: Vec<u8>,
+    block_size: usize,
+}
+
+impl Default for PutPayloadMut {
+    fn default() -> Self {
+        Self {
+            len: 0,
+            completed: vec![],
+            in_progress: vec![],
+
+            block_size: 8 * 1024,
+        }
+    }
+}
+
+impl PutPayloadMut {
+    /// Create a new [`PutPayloadMut`]
+    pub fn new() -> Self {
+        Self::default()
+    }
+
+    /// Allocate data in chunks of `block_size`
+    ///
+    /// Defaults to 8KB
+    pub fn with_block_size(self, block_size: usize) -> Self {
+        Self { block_size, ..self }
+    }
+
+    /// Write bytes into this [`PutPayloadMut`]
+    pub fn extend_from_slice(&mut self, slice: &[u8]) {
+        let remaining = self.in_progress.capacity() - self.in_progress.len();
+        let to_copy = remaining.min(slice.len());
+
+        self.in_progress.extend_from_slice(&slice[..to_copy]);
+        if self.in_progress.capacity() == self.in_progress.len() {
+            let new_cap = self.block_size.max(slice.len() - to_copy);
+            let completed = std::mem::replace(&mut self.in_progress, 
Vec::with_capacity(new_cap));
+            if !completed.is_empty() {
+                self.completed.push(completed.into())
+            }
+            self.in_progress.extend_from_slice(&slice[to_copy..])
+        }
+        self.len += slice.len();
+    }
+
+    /// Append a [`Bytes`] to this [`PutPayloadMut`]
+    pub fn push(&mut self, bytes: Bytes) {

Review Comment:
   Can you please document that this is a zero copy API -- specifically that 
the  progress is closed off and the underlying data is not copied. 



##########
object_store/src/client/retry.rs:
##########
@@ -166,26 +166,54 @@ impl Default for RetryConfig {
     }
 }
 
-fn send_retry_impl(
-    builder: reqwest::RequestBuilder,
-    config: &RetryConfig,
-    is_idempotent: Option<bool>,
-) -> BoxFuture<'static, Result<Response>> {
-    let mut backoff = Backoff::new(&config.backoff);
-    let max_retries = config.max_retries;
-    let retry_timeout = config.retry_timeout;
+pub struct RetryableRequest {
+    client: Client,
+    request: Request,
 
-    let (client, req) = builder.build_split();
-    let req = req.expect("request must be valid");
-    let is_idempotent = is_idempotent.unwrap_or(req.method().is_safe());
+    max_retries: usize,
+    retry_timeout: Duration,
+    backoff: Backoff,
 
-    async move {
+    idempotent: Option<bool>,
+    payload: Option<PutPayload>,
+}
+
+impl RetryableRequest {
+    /// Set whether this request is idempotent
+    pub fn idempotent(self, idempotent: bool) -> Self {
+        Self {
+            idempotent: Some(idempotent),
+            ..self
+        }
+    }
+
+    /// Provide a [`PutPayload`]
+    pub fn payload(self, payload: Option<PutPayload>) -> Self {
+        Self { payload, ..self }
+    }
+
+    pub async fn send(self) -> Result<Response> {
+        let max_retries = self.max_retries;
+        let retry_timeout = self.retry_timeout;
         let mut retries = 0;
         let now = Instant::now();
 
+        let mut backoff = self.backoff;
+        let is_idempotent = self
+            .idempotent
+            .unwrap_or_else(|| self.request.method().is_safe());
+
         loop {
-            let s = req.try_clone().expect("request body must be cloneable");
-            match client.execute(s).await {
+            let mut s = self

Review Comment:
   I know you like brevity but one character variable names that are different 
than the first letter of the things they are holding are pretty hard for me to 
grok. (I realize you can't use `r` b/c there is another variable below named 
`r`). 
   
   How about we rename `s` to `request` and `x` to `payload`?



##########
object_store/src/payload.rs:
##########
@@ -0,0 +1,298 @@
+// 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.
+
+use bytes::Bytes;
+use std::sync::Arc;
+
+/// A cheaply cloneable, ordered collection of [`Bytes`]
+#[derive(Debug, Clone)]
+pub struct PutPayload(Arc<[Bytes]>);
+
+impl Default for PutPayload {
+    fn default() -> Self {
+        Self(Arc::new([]))
+    }
+}
+
+impl PutPayload {
+    /// Create a new empty [`PutPayload`]
+    pub fn new() -> Self {
+        Self::default()
+    }
+
+    /// Creates a [`PutPayload`] from a static slice
+    pub fn from_static(s: &'static [u8]) -> Self {
+        s.into()
+    }
+
+    /// Creates a [`PutPayload`] from a [`Bytes`]
+    pub fn from_bytes(s: Bytes) -> Self {
+        s.into()
+    }
+
+    #[cfg(feature = "cloud")]
+    pub(crate) fn body(&self) -> reqwest::Body {
+        reqwest::Body::wrap_stream(futures::stream::iter(
+            self.clone().into_iter().map(Ok::<_, crate::Error>),
+        ))
+    }
+
+    /// Returns the total length of the [`Bytes`] in this payload
+    pub fn content_length(&self) -> usize {
+        self.0.iter().map(|b| b.len()).sum()
+    }
+
+    /// Returns an iterator over the [`Bytes`] in this payload
+    pub fn iter(&self) -> PutPayloadIter<'_> {
+        PutPayloadIter(self.0.iter())
+    }
+}
+
+impl AsRef<[Bytes]> for PutPayload {
+    fn as_ref(&self) -> &[Bytes] {
+        self.0.as_ref()
+    }
+}
+
+impl<'a> IntoIterator for &'a PutPayload {
+    type Item = &'a Bytes;
+    type IntoIter = PutPayloadIter<'a>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        self.iter()
+    }
+}
+
+impl IntoIterator for PutPayload {
+    type Item = Bytes;
+    type IntoIter = PutPayloadIntoIter;
+
+    fn into_iter(self) -> Self::IntoIter {
+        PutPayloadIntoIter {
+            payload: self,
+            idx: 0,
+        }
+    }
+}
+
+/// An iterator over [`PutPayload`]
+#[derive(Debug)]
+pub struct PutPayloadIter<'a>(std::slice::Iter<'a, Bytes>);
+
+impl<'a> Iterator for PutPayloadIter<'a> {
+    type Item = &'a Bytes;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        self.0.next()
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.0.size_hint()
+    }
+}
+
+/// An owning iterator of [`PutPayload`]
+#[derive(Debug)]
+pub struct PutPayloadIntoIter {
+    payload: PutPayload,
+    idx: usize,
+}
+
+impl Iterator for PutPayloadIntoIter {
+    type Item = Bytes;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        let p = self.payload.0.get(self.idx)?.clone();
+        self.idx += 1;
+        Some(p)
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        let l = self.payload.0.len() - self.idx;
+        (l, Some(l))
+    }
+}
+
+impl From<Bytes> for PutPayload {
+    fn from(value: Bytes) -> Self {
+        Self(Arc::new([value]))
+    }
+}
+
+impl From<Vec<u8>> for PutPayload {
+    fn from(value: Vec<u8>) -> Self {
+        Self(Arc::new([value.into()]))
+    }
+}
+
+impl From<&'static str> for PutPayload {
+    fn from(value: &'static str) -> Self {
+        Bytes::from(value).into()
+    }
+}
+
+impl From<&'static [u8]> for PutPayload {
+    fn from(value: &'static [u8]) -> Self {
+        Bytes::from(value).into()
+    }
+}
+
+impl From<String> for PutPayload {
+    fn from(value: String) -> Self {
+        Bytes::from(value).into()
+    }
+}
+
+impl FromIterator<u8> for PutPayload {
+    fn from_iter<T: IntoIterator<Item = u8>>(iter: T) -> Self {
+        Bytes::from_iter(iter).into()
+    }
+}
+
+impl FromIterator<Bytes> for PutPayload {
+    fn from_iter<T: IntoIterator<Item = Bytes>>(iter: T) -> Self {
+        Self(iter.into_iter().collect())
+    }
+}
+
+impl From<PutPayload> for Bytes {
+    fn from(value: PutPayload) -> Self {
+        match value.0.len() {
+            0 => Self::new(),
+            1 => value.0[0].clone(),
+            _ => {
+                let mut buf = Vec::with_capacity(value.content_length());
+                value.iter().for_each(|x| buf.extend_from_slice(x));
+                buf.into()
+            }
+        }
+    }
+}
+
+/// A builder for [`PutPayload`] that allocates memory in chunks
+#[derive(Debug)]
+pub struct PutPayloadMut {
+    len: usize,
+    completed: Vec<Bytes>,
+    in_progress: Vec<u8>,
+    block_size: usize,
+}
+
+impl Default for PutPayloadMut {
+    fn default() -> Self {
+        Self {
+            len: 0,
+            completed: vec![],
+            in_progress: vec![],
+
+            block_size: 8 * 1024,
+        }
+    }
+}
+
+impl PutPayloadMut {
+    /// Create a new [`PutPayloadMut`]
+    pub fn new() -> Self {
+        Self::default()
+    }
+
+    /// Allocate data in chunks of `block_size`
+    ///
+    /// Defaults to 8KB
+    pub fn with_block_size(self, block_size: usize) -> Self {
+        Self { block_size, ..self }
+    }
+
+    /// Write bytes into this [`PutPayloadMut`]
+    pub fn extend_from_slice(&mut self, slice: &[u8]) {
+        let remaining = self.in_progress.capacity() - self.in_progress.len();
+        let to_copy = remaining.min(slice.len());
+
+        self.in_progress.extend_from_slice(&slice[..to_copy]);
+        if self.in_progress.capacity() == self.in_progress.len() {
+            let new_cap = self.block_size.max(slice.len() - to_copy);
+            let completed = std::mem::replace(&mut self.in_progress, 
Vec::with_capacity(new_cap));
+            if !completed.is_empty() {
+                self.completed.push(completed.into())
+            }
+            self.in_progress.extend_from_slice(&slice[to_copy..])
+        }
+        self.len += slice.len();
+    }
+
+    /// Append a [`Bytes`] to this [`PutPayloadMut`]
+    pub fn push(&mut self, bytes: Bytes) {
+        if !self.in_progress.is_empty() {
+            let completed = std::mem::take(&mut self.in_progress);
+            self.completed.push(completed.into())
+        }
+        self.completed.push(bytes)
+    }
+
+    /// Returns `true` if this [`PutPayloadMut`] contains no bytes
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len == 0
+    }
+
+    /// Returns the total length of the [`Bytes`] in this payload
+    #[inline]
+    pub fn content_length(&self) -> usize {
+        self.len
+    }
+
+    /// Convert into [`PutPayload`]
+    pub fn freeze(mut self) -> PutPayload {
+        if !self.in_progress.is_empty() {
+            let completed = std::mem::take(&mut self.in_progress).into();
+            self.completed.push(completed);
+        }
+        PutPayload(self.completed.into())
+    }
+}
+
+impl From<PutPayloadMut> for PutPayload {
+    fn from(value: PutPayloadMut) -> Self {
+        value.freeze()
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use crate::PutPayloadMut;
+
+    #[test]
+    fn test_put_payload() {
+        let mut chunk = PutPayloadMut::new().with_block_size(23);
+        chunk.extend_from_slice(&[1; 16]);

Review Comment:
   I recommend also testing a slice of 0 length



##########
object_store/src/client/retry.rs:
##########
@@ -166,26 +166,54 @@ impl Default for RetryConfig {
     }
 }
 
-fn send_retry_impl(
-    builder: reqwest::RequestBuilder,
-    config: &RetryConfig,
-    is_idempotent: Option<bool>,
-) -> BoxFuture<'static, Result<Response>> {
-    let mut backoff = Backoff::new(&config.backoff);
-    let max_retries = config.max_retries;
-    let retry_timeout = config.retry_timeout;
+pub struct RetryableRequest {
+    client: Client,
+    request: Request,
 
-    let (client, req) = builder.build_split();
-    let req = req.expect("request must be valid");
-    let is_idempotent = is_idempotent.unwrap_or(req.method().is_safe());
+    max_retries: usize,
+    retry_timeout: Duration,
+    backoff: Backoff,
 
-    async move {
+    idempotent: Option<bool>,
+    payload: Option<PutPayload>,
+}
+
+impl RetryableRequest {
+    /// Set whether this request is idempotent
+    pub fn idempotent(self, idempotent: bool) -> Self {
+        Self {
+            idempotent: Some(idempotent),
+            ..self
+        }
+    }
+
+    /// Provide a [`PutPayload`]
+    pub fn payload(self, payload: Option<PutPayload>) -> Self {
+        Self { payload, ..self }
+    }
+
+    pub async fn send(self) -> Result<Response> {
+        let max_retries = self.max_retries;
+        let retry_timeout = self.retry_timeout;
         let mut retries = 0;
         let now = Instant::now();
 
+        let mut backoff = self.backoff;
+        let is_idempotent = self
+            .idempotent
+            .unwrap_or_else(|| self.request.method().is_safe());
+
         loop {
-            let s = req.try_clone().expect("request body must be cloneable");
-            match client.execute(s).await {
+            let mut s = self
+                .request
+                .try_clone()
+                .expect("request body must be cloneable");
+
+            if let Some(x) = &self.payload {
+                *s.body_mut() = Some(x.body());

Review Comment:
   Maybe a function call like  `s.set_body(Some(x.body())` instead might be 
easier to understand the intent



##########
object_store/src/aws/client.rs:
##########
@@ -266,7 +270,8 @@ pub(crate) struct Request<'a> {
     path: &'a Path,
     config: &'a S3Config,
     builder: RequestBuilder,
-    payload_sha256: Option<Vec<u8>>,
+    payload_sha256: Option<digest::Digest>,

Review Comment:
   These are unrelated cleanups right? Or is there a reason `digest::Digest` is 
preferred over `Vec<u8>`?



##########
object_store/src/payload.rs:
##########
@@ -0,0 +1,298 @@
+// 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.
+
+use bytes::Bytes;
+use std::sync::Arc;
+
+/// A cheaply cloneable, ordered collection of [`Bytes`]
+#[derive(Debug, Clone)]
+pub struct PutPayload(Arc<[Bytes]>);
+
+impl Default for PutPayload {
+    fn default() -> Self {
+        Self(Arc::new([]))
+    }
+}
+
+impl PutPayload {
+    /// Create a new empty [`PutPayload`]
+    pub fn new() -> Self {
+        Self::default()
+    }
+
+    /// Creates a [`PutPayload`] from a static slice
+    pub fn from_static(s: &'static [u8]) -> Self {
+        s.into()
+    }
+
+    /// Creates a [`PutPayload`] from a [`Bytes`]
+    pub fn from_bytes(s: Bytes) -> Self {
+        s.into()
+    }
+
+    #[cfg(feature = "cloud")]
+    pub(crate) fn body(&self) -> reqwest::Body {
+        reqwest::Body::wrap_stream(futures::stream::iter(
+            self.clone().into_iter().map(Ok::<_, crate::Error>),
+        ))
+    }
+
+    /// Returns the total length of the [`Bytes`] in this payload
+    pub fn content_length(&self) -> usize {
+        self.0.iter().map(|b| b.len()).sum()
+    }
+
+    /// Returns an iterator over the [`Bytes`] in this payload
+    pub fn iter(&self) -> PutPayloadIter<'_> {
+        PutPayloadIter(self.0.iter())
+    }
+}
+
+impl AsRef<[Bytes]> for PutPayload {
+    fn as_ref(&self) -> &[Bytes] {
+        self.0.as_ref()
+    }
+}
+
+impl<'a> IntoIterator for &'a PutPayload {
+    type Item = &'a Bytes;
+    type IntoIter = PutPayloadIter<'a>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        self.iter()
+    }
+}
+
+impl IntoIterator for PutPayload {
+    type Item = Bytes;
+    type IntoIter = PutPayloadIntoIter;
+
+    fn into_iter(self) -> Self::IntoIter {
+        PutPayloadIntoIter {
+            payload: self,
+            idx: 0,
+        }
+    }
+}
+
+/// An iterator over [`PutPayload`]
+#[derive(Debug)]
+pub struct PutPayloadIter<'a>(std::slice::Iter<'a, Bytes>);
+
+impl<'a> Iterator for PutPayloadIter<'a> {
+    type Item = &'a Bytes;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        self.0.next()
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.0.size_hint()
+    }
+}
+
+/// An owning iterator of [`PutPayload`]
+#[derive(Debug)]
+pub struct PutPayloadIntoIter {
+    payload: PutPayload,
+    idx: usize,
+}
+
+impl Iterator for PutPayloadIntoIter {
+    type Item = Bytes;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        let p = self.payload.0.get(self.idx)?.clone();
+        self.idx += 1;
+        Some(p)
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        let l = self.payload.0.len() - self.idx;
+        (l, Some(l))
+    }
+}
+
+impl From<Bytes> for PutPayload {
+    fn from(value: Bytes) -> Self {
+        Self(Arc::new([value]))
+    }
+}
+
+impl From<Vec<u8>> for PutPayload {
+    fn from(value: Vec<u8>) -> Self {
+        Self(Arc::new([value.into()]))
+    }
+}
+
+impl From<&'static str> for PutPayload {
+    fn from(value: &'static str) -> Self {
+        Bytes::from(value).into()
+    }
+}
+
+impl From<&'static [u8]> for PutPayload {
+    fn from(value: &'static [u8]) -> Self {
+        Bytes::from(value).into()
+    }
+}
+
+impl From<String> for PutPayload {
+    fn from(value: String) -> Self {
+        Bytes::from(value).into()
+    }
+}
+
+impl FromIterator<u8> for PutPayload {
+    fn from_iter<T: IntoIterator<Item = u8>>(iter: T) -> Self {
+        Bytes::from_iter(iter).into()
+    }
+}
+
+impl FromIterator<Bytes> for PutPayload {
+    fn from_iter<T: IntoIterator<Item = Bytes>>(iter: T) -> Self {
+        Self(iter.into_iter().collect())
+    }
+}
+
+impl From<PutPayload> for Bytes {
+    fn from(value: PutPayload) -> Self {
+        match value.0.len() {
+            0 => Self::new(),
+            1 => value.0[0].clone(),
+            _ => {
+                let mut buf = Vec::with_capacity(value.content_length());
+                value.iter().for_each(|x| buf.extend_from_slice(x));
+                buf.into()
+            }
+        }
+    }
+}
+
+/// A builder for [`PutPayload`] that allocates memory in chunks
+#[derive(Debug)]
+pub struct PutPayloadMut {
+    len: usize,
+    completed: Vec<Bytes>,
+    in_progress: Vec<u8>,
+    block_size: usize,
+}
+
+impl Default for PutPayloadMut {
+    fn default() -> Self {
+        Self {
+            len: 0,
+            completed: vec![],
+            in_progress: vec![],
+
+            block_size: 8 * 1024,
+        }
+    }
+}
+
+impl PutPayloadMut {
+    /// Create a new [`PutPayloadMut`]
+    pub fn new() -> Self {
+        Self::default()
+    }
+
+    /// Allocate data in chunks of `block_size`
+    ///
+    /// Defaults to 8KB
+    pub fn with_block_size(self, block_size: usize) -> Self {
+        Self { block_size, ..self }
+    }
+
+    /// Write bytes into this [`PutPayloadMut`]
+    pub fn extend_from_slice(&mut self, slice: &[u8]) {
+        let remaining = self.in_progress.capacity() - self.in_progress.len();
+        let to_copy = remaining.min(slice.len());
+
+        self.in_progress.extend_from_slice(&slice[..to_copy]);
+        if self.in_progress.capacity() == self.in_progress.len() {
+            let new_cap = self.block_size.max(slice.len() - to_copy);
+            let completed = std::mem::replace(&mut self.in_progress, 
Vec::with_capacity(new_cap));
+            if !completed.is_empty() {
+                self.completed.push(completed.into())
+            }
+            self.in_progress.extend_from_slice(&slice[to_copy..])
+        }
+        self.len += slice.len();
+    }
+
+    /// Append a [`Bytes`] to this [`PutPayloadMut`]
+    pub fn push(&mut self, bytes: Bytes) {
+        if !self.in_progress.is_empty() {
+            let completed = std::mem::take(&mut self.in_progress);
+            self.completed.push(completed.into())
+        }
+        self.completed.push(bytes)
+    }
+
+    /// Returns `true` if this [`PutPayloadMut`] contains no bytes
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len == 0
+    }
+
+    /// Returns the total length of the [`Bytes`] in this payload
+    #[inline]
+    pub fn content_length(&self) -> usize {
+        self.len
+    }
+
+    /// Convert into [`PutPayload`]
+    pub fn freeze(mut self) -> PutPayload {
+        if !self.in_progress.is_empty() {
+            let completed = std::mem::take(&mut self.in_progress).into();
+            self.completed.push(completed);
+        }
+        PutPayload(self.completed.into())
+    }
+}
+
+impl From<PutPayloadMut> for PutPayload {
+    fn from(value: PutPayloadMut) -> Self {
+        value.freeze()
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use crate::PutPayloadMut;
+
+    #[test]
+    fn test_put_payload() {
+        let mut chunk = PutPayloadMut::new().with_block_size(23);
+        chunk.extend_from_slice(&[1; 16]);
+        chunk.extend_from_slice(&[2; 32]);
+        chunk.extend_from_slice(&[2; 5]);
+        chunk.extend_from_slice(&[2; 21]);
+        chunk.extend_from_slice(&[2; 40]);
+        let payload = chunk.freeze();
+        assert_eq!(payload.content_length(), 114);
+
+        let chunks = payload.as_ref();
+        assert_eq!(chunks.len(), 5);
+
+        assert_eq!(chunks[0].len(), 23);
+        assert_eq!(chunks[1].len(), 25); // 32 - (23 - 16)
+        assert_eq!(chunks[2].len(), 23);
+        assert_eq!(chunks[3].len(), 23);
+        assert_eq!(chunks[4].len(), 20);
+    }
+}

Review Comment:
   It would be good to add a test for `push` as well (esp to document the non 
copying behavior)



##########
object_store/src/lib.rs:
##########
@@ -532,14 +574,20 @@ pub trait ObjectStore: std::fmt::Display + Send + Sync + 
Debug + 'static {
     /// Save the provided bytes to the specified location
     ///
     /// The operation is guaranteed to be atomic, it will either successfully
-    /// write the entirety of `bytes` to `location`, or fail. No clients
+    /// write the entirety of `payload` to `location`, or fail. No clients
     /// should be able to observe a partially written object
-    async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
-        self.put_opts(location, bytes, PutOptions::default()).await
+    async fn put(&self, location: &Path, payload: PutPayload) -> 
Result<PutResult> {

Review Comment:
   For anyone else reviewing this PR. I think this is an (and the key) API 
change -- to take a slice of `[Bytes]` bytes rather than a `Bytes` directly
   
   
   
   



##########
object_store/src/upload.rs:
##########
@@ -157,19 +159,34 @@ impl WriteMultipart {
     /// [`Self::wait_for_capacity`] prior to calling this method
     pub fn write(&mut self, mut buf: &[u8]) {
         while !buf.is_empty() {
-            let capacity = self.buffer.capacity();
-            let remaining = capacity - self.buffer.len();
+            let remaining = self.chunk_size - self.buffer.content_length();
             let to_read = buf.len().min(remaining);
             self.buffer.extend_from_slice(&buf[..to_read]);
             if to_read == remaining {
-                let part = std::mem::replace(&mut self.buffer, 
Vec::with_capacity(capacity));
-                self.put_part(part.into())
+                let buffer = std::mem::take(&mut self.buffer);
+                self.put_part(buffer.into())
             }
             buf = &buf[to_read..]
         }
     }
 
-    fn put_part(&mut self, part: Bytes) {
+    /// Put a chunk of data into this [`WriteMultipart`]
+    ///
+    /// See [`Self::write`] for information on backpressure
+    pub fn put(&mut self, mut bytes: Bytes) {

Review Comment:
   If we are changing the API anyways, is there a reason to keep both` write` 
and `put`? As in why not change `write` to take a `Bytes` as one can could then 
call `write` via `write(my_payload.into())` 🤔 



##########
object_store/src/aws/client.rs:
##########
@@ -438,16 +443,8 @@ impl S3Client {
 
         let mut builder = self.client.request(Method::POST, url);
 
-        // Compute checksum - S3 *requires* this for DeleteObjects requests, 
so we default to

Review Comment:
   (and to be clear for anyone else reading this PR -- this code is not exposed 
publicly so it can be changed in the future if needed as well)



##########
object_store/src/client/retry.rs:
##########
@@ -166,26 +166,54 @@ impl Default for RetryConfig {
     }
 }
 
-fn send_retry_impl(
-    builder: reqwest::RequestBuilder,
-    config: &RetryConfig,
-    is_idempotent: Option<bool>,
-) -> BoxFuture<'static, Result<Response>> {
-    let mut backoff = Backoff::new(&config.backoff);
-    let max_retries = config.max_retries;
-    let retry_timeout = config.retry_timeout;
+pub struct RetryableRequest {
+    client: Client,
+    request: Request,
 
-    let (client, req) = builder.build_split();
-    let req = req.expect("request must be valid");
-    let is_idempotent = is_idempotent.unwrap_or(req.method().is_safe());
+    max_retries: usize,
+    retry_timeout: Duration,
+    backoff: Backoff,
 
-    async move {
+    idempotent: Option<bool>,
+    payload: Option<PutPayload>,
+}
+
+impl RetryableRequest {
+    /// Set whether this request is idempotent

Review Comment:
   Can we document what `idempotent` means in this context? Like it means the 
entire request can be retried?



##########
object_store/src/payload.rs:
##########
@@ -0,0 +1,298 @@
+// 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.
+
+use bytes::Bytes;
+use std::sync::Arc;
+
+/// A cheaply cloneable, ordered collection of [`Bytes`]
+#[derive(Debug, Clone)]
+pub struct PutPayload(Arc<[Bytes]>);
+
+impl Default for PutPayload {
+    fn default() -> Self {
+        Self(Arc::new([]))
+    }
+}
+
+impl PutPayload {
+    /// Create a new empty [`PutPayload`]
+    pub fn new() -> Self {
+        Self::default()
+    }
+
+    /// Creates a [`PutPayload`] from a static slice
+    pub fn from_static(s: &'static [u8]) -> Self {
+        s.into()
+    }
+
+    /// Creates a [`PutPayload`] from a [`Bytes`]
+    pub fn from_bytes(s: Bytes) -> Self {
+        s.into()
+    }
+
+    #[cfg(feature = "cloud")]
+    pub(crate) fn body(&self) -> reqwest::Body {
+        reqwest::Body::wrap_stream(futures::stream::iter(
+            self.clone().into_iter().map(Ok::<_, crate::Error>),
+        ))
+    }
+
+    /// Returns the total length of the [`Bytes`] in this payload
+    pub fn content_length(&self) -> usize {
+        self.0.iter().map(|b| b.len()).sum()
+    }
+
+    /// Returns an iterator over the [`Bytes`] in this payload
+    pub fn iter(&self) -> PutPayloadIter<'_> {
+        PutPayloadIter(self.0.iter())
+    }
+}
+
+impl AsRef<[Bytes]> for PutPayload {
+    fn as_ref(&self) -> &[Bytes] {
+        self.0.as_ref()
+    }
+}
+
+impl<'a> IntoIterator for &'a PutPayload {
+    type Item = &'a Bytes;
+    type IntoIter = PutPayloadIter<'a>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        self.iter()
+    }
+}
+
+impl IntoIterator for PutPayload {
+    type Item = Bytes;
+    type IntoIter = PutPayloadIntoIter;
+
+    fn into_iter(self) -> Self::IntoIter {
+        PutPayloadIntoIter {
+            payload: self,
+            idx: 0,
+        }
+    }
+}
+
+/// An iterator over [`PutPayload`]
+#[derive(Debug)]
+pub struct PutPayloadIter<'a>(std::slice::Iter<'a, Bytes>);
+
+impl<'a> Iterator for PutPayloadIter<'a> {
+    type Item = &'a Bytes;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        self.0.next()
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.0.size_hint()
+    }
+}
+
+/// An owning iterator of [`PutPayload`]
+#[derive(Debug)]
+pub struct PutPayloadIntoIter {
+    payload: PutPayload,
+    idx: usize,
+}
+
+impl Iterator for PutPayloadIntoIter {
+    type Item = Bytes;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        let p = self.payload.0.get(self.idx)?.clone();
+        self.idx += 1;
+        Some(p)
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        let l = self.payload.0.len() - self.idx;
+        (l, Some(l))
+    }
+}
+
+impl From<Bytes> for PutPayload {
+    fn from(value: Bytes) -> Self {
+        Self(Arc::new([value]))
+    }
+}
+
+impl From<Vec<u8>> for PutPayload {
+    fn from(value: Vec<u8>) -> Self {
+        Self(Arc::new([value.into()]))
+    }
+}
+
+impl From<&'static str> for PutPayload {
+    fn from(value: &'static str) -> Self {
+        Bytes::from(value).into()
+    }
+}
+
+impl From<&'static [u8]> for PutPayload {
+    fn from(value: &'static [u8]) -> Self {
+        Bytes::from(value).into()
+    }
+}
+
+impl From<String> for PutPayload {
+    fn from(value: String) -> Self {
+        Bytes::from(value).into()
+    }
+}
+
+impl FromIterator<u8> for PutPayload {
+    fn from_iter<T: IntoIterator<Item = u8>>(iter: T) -> Self {
+        Bytes::from_iter(iter).into()
+    }
+}
+
+impl FromIterator<Bytes> for PutPayload {
+    fn from_iter<T: IntoIterator<Item = Bytes>>(iter: T) -> Self {
+        Self(iter.into_iter().collect())
+    }
+}
+
+impl From<PutPayload> for Bytes {
+    fn from(value: PutPayload) -> Self {
+        match value.0.len() {
+            0 => Self::new(),
+            1 => value.0[0].clone(),
+            _ => {
+                let mut buf = Vec::with_capacity(value.content_length());
+                value.iter().for_each(|x| buf.extend_from_slice(x));
+                buf.into()
+            }
+        }
+    }
+}
+
+/// A builder for [`PutPayload`] that allocates memory in chunks
+#[derive(Debug)]
+pub struct PutPayloadMut {
+    len: usize,
+    completed: Vec<Bytes>,
+    in_progress: Vec<u8>,
+    block_size: usize,
+}
+
+impl Default for PutPayloadMut {
+    fn default() -> Self {
+        Self {
+            len: 0,
+            completed: vec![],
+            in_progress: vec![],
+
+            block_size: 8 * 1024,
+        }
+    }
+}
+
+impl PutPayloadMut {
+    /// Create a new [`PutPayloadMut`]
+    pub fn new() -> Self {
+        Self::default()
+    }
+
+    /// Allocate data in chunks of `block_size`
+    ///
+    /// Defaults to 8KB
+    pub fn with_block_size(self, block_size: usize) -> Self {
+        Self { block_size, ..self }
+    }
+
+    /// Write bytes into this [`PutPayloadMut`]
+    pub fn extend_from_slice(&mut self, slice: &[u8]) {
+        let remaining = self.in_progress.capacity() - self.in_progress.len();
+        let to_copy = remaining.min(slice.len());
+
+        self.in_progress.extend_from_slice(&slice[..to_copy]);
+        if self.in_progress.capacity() == self.in_progress.len() {
+            let new_cap = self.block_size.max(slice.len() - to_copy);
+            let completed = std::mem::replace(&mut self.in_progress, 
Vec::with_capacity(new_cap));
+            if !completed.is_empty() {
+                self.completed.push(completed.into())
+            }
+            self.in_progress.extend_from_slice(&slice[to_copy..])
+        }
+        self.len += slice.len();
+    }
+
+    /// Append a [`Bytes`] to this [`PutPayloadMut`]
+    pub fn push(&mut self, bytes: Bytes) {
+        if !self.in_progress.is_empty() {
+            let completed = std::mem::take(&mut self.in_progress);
+            self.completed.push(completed.into())
+        }
+        self.completed.push(bytes)
+    }
+
+    /// Returns `true` if this [`PutPayloadMut`] contains no bytes
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len == 0
+    }
+
+    /// Returns the total length of the [`Bytes`] in this payload
+    #[inline]
+    pub fn content_length(&self) -> usize {
+        self.len
+    }
+
+    /// Convert into [`PutPayload`]
+    pub fn freeze(mut self) -> PutPayload {
+        if !self.in_progress.is_empty() {
+            let completed = std::mem::take(&mut self.in_progress).into();
+            self.completed.push(completed);
+        }
+        PutPayload(self.completed.into())

Review Comment:
   nit: I think you can save typing and  allocating another Vec with something 
like
   
   ```suggestion
           let Self { in_progress, completed, ..} = self;
           
           if !in_progress.is_empty() {
               completed.push(in_progress);
           }
           PutPayload(completed.into())
   ```



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