Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 61 additions & 32 deletions src/client/object.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use futures_util::{stream, Stream, TryStream};
use reqwest::StatusCode;
use futures_util::{stream, Stream, StreamExt, TryStream, TryStreamExt};
use reqwest::{Response, StatusCode};

use crate::{
error::GoogleResponse,
Expand Down Expand Up @@ -262,20 +262,7 @@ impl<'a> ObjectClient<'a> {
}
}

/// Download the content of the object with the specified name in the specified bucket.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::Client;
/// use cloud_storage::Object;
///
/// let client = Client::default();
/// let bytes = client.object().download("my_bucket", "path/to/my/file.png").await?;
/// # Ok(())
/// # }
/// ```
pub async fn download(&self, bucket: &str, file_name: &str) -> crate::Result<Vec<u8>> {
async fn download_response(&self, bucket: &str, file_name: &str) -> crate::Result<Response> {
let url = format!(
"{}/b/{}/o/{}?alt=media",
crate::BASE_URL,
Expand All @@ -289,13 +276,68 @@ impl<'a> ObjectClient<'a> {
.headers(self.0.get_headers().await?)
.send()
.await?;

if resp.status() == StatusCode::NOT_FOUND {
Err(crate::Error::Other(resp.text().await?))
} else {
Ok(resp.error_for_status()?.bytes().await?.to_vec())
Ok(resp.error_for_status()?)
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I created a non-pub helper function download_response to unify the common download code paths. I also noticed checking for StatusCode::NOT_FOUND was only done for download, not download_streamed. I think it makes more sense to have that unified here, but it might be a breaking change?

Up for you to decide, I'm happy to move that error handling around.

Usability note: Often the google error responses include helpful content that is being discarded here. I think on http status errors, we should actually try to convert it into an Error::Google(GoogleErrorResponse). Maybe in a separate MR?

}

/// Download the content of the object with the specified name in the specified bucket.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::Client;
/// use cloud_storage::Object;
///
/// let client = Client::default();
/// let bytes = client.object().download("my_bucket", "path/to/my/file.png").await?;
/// # Ok(())
/// # }
/// ```
pub async fn download(&self, bucket: &str, file_name: &str) -> crate::Result<Vec<u8>> {
Ok(self
.download_response(bucket, file_name)
.await?
.bytes()
.await?
.into())
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The actual methods are now very straightfoward


/// Download the content of the object with the specified name in the specified bucket, without
/// allocating the whole file into a vector.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::Client;
/// use cloud_storage::Object;
/// use futures_util::stream::StreamExt;
/// use tokio::fs::File;
/// use tokio::io::{AsyncWriteExt, BufWriter};
///
/// let client = Client::default();
/// let mut stream = client.object().download_bytes_stream("my_bucket", "path/to/my/file.png").await?;
/// let mut file = BufWriter::new(File::create("file.png").await?);
/// while let Some(bytes) = stream.next().await {
/// file.write_all(&bytes?).await?;
/// }
/// file.flush().await?;
/// # Ok(())
/// # }
/// ```
pub async fn download_bytes_stream(
&self,
bucket: &str,
file_name: &str,
) -> crate::Result<impl Stream<Item = crate::Result<crate::Bytes>> + Unpin> {
let response = self.download_response(bucket, file_name).await?;
let bytes = response.bytes_stream().map_err(crate::Error::from);
Ok(bytes)
}

/// Download the content of the object with the specified name in the specified bucket, without
/// allocating the whole file into a vector.
/// ### Example
Expand All @@ -318,26 +360,13 @@ impl<'a> ObjectClient<'a> {
/// # Ok(())
/// # }
/// ```
#[deprecated = "Streaming u8 is inefficient, use download_bytes_stream instead"]
pub async fn download_streamed(
&self,
bucket: &str,
file_name: &str,
) -> crate::Result<impl Stream<Item = crate::Result<u8>> + Unpin> {
use futures_util::{StreamExt, TryStreamExt};
let url = format!(
"{}/b/{}/o/{}?alt=media",
crate::BASE_URL,
percent_encode(bucket),
percent_encode(file_name),
);
let response = self
.0
.client
.get(&url)
.headers(self.0.get_headers().await?)
.send()
.await?
.error_for_status()?;
let response = self.download_response(bucket, file_name).await?;
let size = response.content_length();
let bytes = response
.bytes_stream()
Expand Down
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ mod error;
mod resources;
mod token;

/// re-exported type that appears in public api
pub use bytes::Bytes;

use crate::resources::service_account::ServiceAccount;
pub use crate::{
client::Client,
Expand Down
32 changes: 32 additions & 0 deletions src/resources/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -449,16 +449,48 @@ impl Object {
/// # }
/// ```
#[cfg(feature = "global-client")]
#[deprecated = "Streaming u8 is inefficient, use download_bytes_stream instead"]
pub async fn download_streamed(
bucket: &str,
file_name: &str,
) -> crate::Result<impl Stream<Item = crate::Result<u8>> + Unpin> {
#[allow(deprecated)] // this calling function is deprecated as well
crate::CLOUD_CLIENT
.object()
.download_streamed(bucket, file_name)
.await
}

/// Download the content of the object with the specified name in the specified bucket, without
/// allocating the whole file into a vector.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::Object;
/// use futures_util::stream::StreamExt;
/// use std::fs::File;
/// use std::io::{BufWriter, Write};
///
/// let mut stream = Object::download_bytes_stream("my_bucket", "path/to/my/file.png").await?;
/// let mut file = BufWriter::new(File::create("file.png")?);
/// while let Some(bytes) = stream.next().await {
/// file.write_all(&bytes?)?;
/// }
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "global-client")]
pub async fn download_bytes_stream(
bucket: &str,
file_name: &str,
) -> crate::Result<impl Stream<Item = crate::Result<crate::Bytes>> + Unpin> {
crate::CLOUD_CLIENT
.object()
.download_bytes_stream(bucket, file_name)
.await
}

/// Obtains a single object with the specified name in the specified bucket.
/// ### Example
/// ```no_run
Expand Down