-
Notifications
You must be signed in to change notification settings - Fork 89
download a stream of bytes, not single byte #123
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kosta
wants to merge
1
commit into
ThouCheese:master
Choose a base branch
from
kosta:streaming-bytes
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
|
|
@@ -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, | ||
|
|
@@ -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()?) | ||
| } | ||
| } | ||
|
|
||
| /// 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()) | ||
| } | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
|
|
@@ -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() | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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_responseto unify the common download code paths. I also noticed checking forStatusCode::NOT_FOUNDwas only done fordownload, notdownload_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?