Introduction
The Google Cloud Client Libraries for Rust is a collection of Rust crates to interact with Google Cloud Services.
This guide is organized as a series of small tutorials showing how to perform specific actions with the client libraries. Most Google Cloud services follow a series of guidelines, collectively known as the AIPs. This makes the client libraries more consistent from one service to the next. The functions to delete or list resources almost always have the same interface.
Audience
This guide is intended for Rust developers who are familiar with the language and the Rust ecosystem. This guide assumes you know how to use Rust and its supporting toolchain.
At the risk of being repetitive, most of the guides do not assume you have used any Google Service or client library before (in Rust or other language). However, the guides will refer you to service specific tutorials to initialize their projects and services.
Service specific documentation
These guides are not intended as tutorials for each service or as extended guides on how to design Rust applications to work on Google Cloud. They are starting points to get you productive with the client libraries for Rust.
We recommend you read the service documentation at https://cloud.google.com to learn more about each service. If you need guidance on how to design your application for Google Cloud, the Cloud Architecture Center may have what you are looking for.
Reporting bugs
Bug reports about the client libraries or their documentation are welcome. Use GitHub Issues.
License
The client libraries source and their documentation are release under the Apache License, Version 2.0.
Using Google Cloud Storage
Google Cloud Storage is a managed service for storing unstructured data.
The Rust client library provides an idiomatic API to access this service. The client library resumes interrupted downloads and uploads, and automatically performs integrity checks on the data. For metadata operations, the client library can retry failed requests, and automatically poll long-running operations.
Quickstart
This guide will show you how to create a Cloud Storage bucket, upload an object to this bucket, and then read the object back.
Prerequisites
The guide assumes you have an existing Google Cloud project with billing enabled.
Add the client library as a dependency
cargo add google-cloud-storage
Create a storage bucket
The client to perform operations on buckets and object metadata is called
StorageControl:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
pub async fn sample(project_id: &str, bucket_id: &str) -> anyhow::Result<()> {
use google_cloud_storage as gcs;
use google_cloud_storage::client::StorageControl;
let control = StorageControl::builder().build().await?;
let bucket = control
.create_bucket()
.set_parent("projects/_")
.set_bucket_id(bucket_id)
.set_bucket(
gcs::model::Bucket::new()
.set_project(format!("projects/{project_id}"))
.set_iam_config(
gcs::model::bucket::IamConfig::new().set_uniform_bucket_level_access(
gcs::model::bucket::iam_config::UniformBucketLevelAccess::new()
.set_enabled(true),
),
),
)
.send()
.await?;
println!("bucket successfully created {bucket:?}");
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let object = client
.write_object(&bucket.name, "hello.txt", "Hello World!")
.send_buffered()
.await?;
println!("object successfully uploaded {object:?}");
let mut reader = client.read_object(&bucket.name, "hello.txt").send().await?;
let mut contents = Vec::new();
while let Some(chunk) = reader.next().await.transpose()? {
contents.extend_from_slice(&chunk);
}
println!(
"object contents successfully downloaded {:?}",
bytes::Bytes::from_owner(contents)
);
control
.delete_object()
.set_bucket(&bucket.name)
.set_object(&object.name)
.set_generation(object.generation)
.send()
.await?;
control
.delete_bucket()
.set_name(&bucket.name)
.send()
.await?;
Ok(())
}
To create a bucket you must provide the project name and the desired bucket id:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
pub async fn sample(project_id: &str, bucket_id: &str) -> anyhow::Result<()> {
use google_cloud_storage as gcs;
use google_cloud_storage::client::StorageControl;
let control = StorageControl::builder().build().await?;
let bucket = control
.create_bucket()
.set_parent("projects/_")
.set_bucket_id(bucket_id)
.set_bucket(
gcs::model::Bucket::new()
.set_project(format!("projects/{project_id}"))
.set_iam_config(
gcs::model::bucket::IamConfig::new().set_uniform_bucket_level_access(
gcs::model::bucket::iam_config::UniformBucketLevelAccess::new()
.set_enabled(true),
),
),
)
.send()
.await?;
println!("bucket successfully created {bucket:?}");
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let object = client
.write_object(&bucket.name, "hello.txt", "Hello World!")
.send_buffered()
.await?;
println!("object successfully uploaded {object:?}");
let mut reader = client.read_object(&bucket.name, "hello.txt").send().await?;
let mut contents = Vec::new();
while let Some(chunk) = reader.next().await.transpose()? {
contents.extend_from_slice(&chunk);
}
println!(
"object contents successfully downloaded {:?}",
bytes::Bytes::from_owner(contents)
);
control
.delete_object()
.set_bucket(&bucket.name)
.set_object(&object.name)
.set_generation(object.generation)
.send()
.await?;
control
.delete_bucket()
.set_name(&bucket.name)
.send()
.await?;
Ok(())
}
You can also provide other attributes for the bucket. For example, if you want all objects in the bucket to use the same permissions, you can enable Uniform bucket-level access:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
pub async fn sample(project_id: &str, bucket_id: &str) -> anyhow::Result<()> {
use google_cloud_storage as gcs;
use google_cloud_storage::client::StorageControl;
let control = StorageControl::builder().build().await?;
let bucket = control
.create_bucket()
.set_parent("projects/_")
.set_bucket_id(bucket_id)
.set_bucket(
gcs::model::Bucket::new()
.set_project(format!("projects/{project_id}"))
.set_iam_config(
gcs::model::bucket::IamConfig::new().set_uniform_bucket_level_access(
gcs::model::bucket::iam_config::UniformBucketLevelAccess::new()
.set_enabled(true),
),
),
)
.send()
.await?;
println!("bucket successfully created {bucket:?}");
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let object = client
.write_object(&bucket.name, "hello.txt", "Hello World!")
.send_buffered()
.await?;
println!("object successfully uploaded {object:?}");
let mut reader = client.read_object(&bucket.name, "hello.txt").send().await?;
let mut contents = Vec::new();
while let Some(chunk) = reader.next().await.transpose()? {
contents.extend_from_slice(&chunk);
}
println!(
"object contents successfully downloaded {:?}",
bytes::Bytes::from_owner(contents)
);
control
.delete_object()
.set_bucket(&bucket.name)
.set_object(&object.name)
.set_generation(object.generation)
.send()
.await?;
control
.delete_bucket()
.set_name(&bucket.name)
.send()
.await?;
Ok(())
}
Then send this request and wait for the response:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
pub async fn sample(project_id: &str, bucket_id: &str) -> anyhow::Result<()> {
use google_cloud_storage as gcs;
use google_cloud_storage::client::StorageControl;
let control = StorageControl::builder().build().await?;
let bucket = control
.create_bucket()
.set_parent("projects/_")
.set_bucket_id(bucket_id)
.set_bucket(
gcs::model::Bucket::new()
.set_project(format!("projects/{project_id}"))
.set_iam_config(
gcs::model::bucket::IamConfig::new().set_uniform_bucket_level_access(
gcs::model::bucket::iam_config::UniformBucketLevelAccess::new()
.set_enabled(true),
),
),
)
.send()
.await?;
println!("bucket successfully created {bucket:?}");
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let object = client
.write_object(&bucket.name, "hello.txt", "Hello World!")
.send_buffered()
.await?;
println!("object successfully uploaded {object:?}");
let mut reader = client.read_object(&bucket.name, "hello.txt").send().await?;
let mut contents = Vec::new();
while let Some(chunk) = reader.next().await.transpose()? {
contents.extend_from_slice(&chunk);
}
println!(
"object contents successfully downloaded {:?}",
bytes::Bytes::from_owner(contents)
);
control
.delete_object()
.set_bucket(&bucket.name)
.set_object(&object.name)
.set_generation(object.generation)
.send()
.await?;
control
.delete_bucket()
.set_name(&bucket.name)
.send()
.await?;
Ok(())
}
Upload an object
The client to perform operations on object data is called Storage:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
pub async fn sample(project_id: &str, bucket_id: &str) -> anyhow::Result<()> {
use google_cloud_storage as gcs;
use google_cloud_storage::client::StorageControl;
let control = StorageControl::builder().build().await?;
let bucket = control
.create_bucket()
.set_parent("projects/_")
.set_bucket_id(bucket_id)
.set_bucket(
gcs::model::Bucket::new()
.set_project(format!("projects/{project_id}"))
.set_iam_config(
gcs::model::bucket::IamConfig::new().set_uniform_bucket_level_access(
gcs::model::bucket::iam_config::UniformBucketLevelAccess::new()
.set_enabled(true),
),
),
)
.send()
.await?;
println!("bucket successfully created {bucket:?}");
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let object = client
.write_object(&bucket.name, "hello.txt", "Hello World!")
.send_buffered()
.await?;
println!("object successfully uploaded {object:?}");
let mut reader = client.read_object(&bucket.name, "hello.txt").send().await?;
let mut contents = Vec::new();
while let Some(chunk) = reader.next().await.transpose()? {
contents.extend_from_slice(&chunk);
}
println!(
"object contents successfully downloaded {:?}",
bytes::Bytes::from_owner(contents)
);
control
.delete_object()
.set_bucket(&bucket.name)
.set_object(&object.name)
.set_generation(object.generation)
.send()
.await?;
control
.delete_bucket()
.set_name(&bucket.name)
.send()
.await?;
Ok(())
}
In this case, create an object called hello.txt, with the traditional greeting
for a programming tutorial:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
pub async fn sample(project_id: &str, bucket_id: &str) -> anyhow::Result<()> {
use google_cloud_storage as gcs;
use google_cloud_storage::client::StorageControl;
let control = StorageControl::builder().build().await?;
let bucket = control
.create_bucket()
.set_parent("projects/_")
.set_bucket_id(bucket_id)
.set_bucket(
gcs::model::Bucket::new()
.set_project(format!("projects/{project_id}"))
.set_iam_config(
gcs::model::bucket::IamConfig::new().set_uniform_bucket_level_access(
gcs::model::bucket::iam_config::UniformBucketLevelAccess::new()
.set_enabled(true),
),
),
)
.send()
.await?;
println!("bucket successfully created {bucket:?}");
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let object = client
.write_object(&bucket.name, "hello.txt", "Hello World!")
.send_buffered()
.await?;
println!("object successfully uploaded {object:?}");
let mut reader = client.read_object(&bucket.name, "hello.txt").send().await?;
let mut contents = Vec::new();
while let Some(chunk) = reader.next().await.transpose()? {
contents.extend_from_slice(&chunk);
}
println!(
"object contents successfully downloaded {:?}",
bytes::Bytes::from_owner(contents)
);
control
.delete_object()
.set_bucket(&bucket.name)
.set_object(&object.name)
.set_generation(object.generation)
.send()
.await?;
control
.delete_bucket()
.set_name(&bucket.name)
.send()
.await?;
Ok(())
}
Download an object
To download the contents of an object use read_object():
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
pub async fn sample(project_id: &str, bucket_id: &str) -> anyhow::Result<()> {
use google_cloud_storage as gcs;
use google_cloud_storage::client::StorageControl;
let control = StorageControl::builder().build().await?;
let bucket = control
.create_bucket()
.set_parent("projects/_")
.set_bucket_id(bucket_id)
.set_bucket(
gcs::model::Bucket::new()
.set_project(format!("projects/{project_id}"))
.set_iam_config(
gcs::model::bucket::IamConfig::new().set_uniform_bucket_level_access(
gcs::model::bucket::iam_config::UniformBucketLevelAccess::new()
.set_enabled(true),
),
),
)
.send()
.await?;
println!("bucket successfully created {bucket:?}");
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let object = client
.write_object(&bucket.name, "hello.txt", "Hello World!")
.send_buffered()
.await?;
println!("object successfully uploaded {object:?}");
let mut reader = client.read_object(&bucket.name, "hello.txt").send().await?;
let mut contents = Vec::new();
while let Some(chunk) = reader.next().await.transpose()? {
contents.extend_from_slice(&chunk);
}
println!(
"object contents successfully downloaded {:?}",
bytes::Bytes::from_owner(contents)
);
control
.delete_object()
.set_bucket(&bucket.name)
.set_object(&object.name)
.set_generation(object.generation)
.send()
.await?;
control
.delete_bucket()
.set_name(&bucket.name)
.send()
.await?;
Ok(())
}
Cleanup
Finally, remove the object and bucket to cleanup all the resources used in this guide:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
pub async fn sample(project_id: &str, bucket_id: &str) -> anyhow::Result<()> {
use google_cloud_storage as gcs;
use google_cloud_storage::client::StorageControl;
let control = StorageControl::builder().build().await?;
let bucket = control
.create_bucket()
.set_parent("projects/_")
.set_bucket_id(bucket_id)
.set_bucket(
gcs::model::Bucket::new()
.set_project(format!("projects/{project_id}"))
.set_iam_config(
gcs::model::bucket::IamConfig::new().set_uniform_bucket_level_access(
gcs::model::bucket::iam_config::UniformBucketLevelAccess::new()
.set_enabled(true),
),
),
)
.send()
.await?;
println!("bucket successfully created {bucket:?}");
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let object = client
.write_object(&bucket.name, "hello.txt", "Hello World!")
.send_buffered()
.await?;
println!("object successfully uploaded {object:?}");
let mut reader = client.read_object(&bucket.name, "hello.txt").send().await?;
let mut contents = Vec::new();
while let Some(chunk) = reader.next().await.transpose()? {
contents.extend_from_slice(&chunk);
}
println!(
"object contents successfully downloaded {:?}",
bytes::Bytes::from_owner(contents)
);
control
.delete_object()
.set_bucket(&bucket.name)
.set_object(&object.name)
.set_generation(object.generation)
.send()
.await?;
control
.delete_bucket()
.set_name(&bucket.name)
.send()
.await?;
Ok(())
}
Next steps
Full program
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
pub async fn sample(project_id: &str, bucket_id: &str) -> anyhow::Result<()> {
use google_cloud_storage as gcs;
use google_cloud_storage::client::StorageControl;
let control = StorageControl::builder().build().await?;
let bucket = control
.create_bucket()
.set_parent("projects/_")
.set_bucket_id(bucket_id)
.set_bucket(
gcs::model::Bucket::new()
.set_project(format!("projects/{project_id}"))
.set_iam_config(
gcs::model::bucket::IamConfig::new().set_uniform_bucket_level_access(
gcs::model::bucket::iam_config::UniformBucketLevelAccess::new()
.set_enabled(true),
),
),
)
.send()
.await?;
println!("bucket successfully created {bucket:?}");
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let object = client
.write_object(&bucket.name, "hello.txt", "Hello World!")
.send_buffered()
.await?;
println!("object successfully uploaded {object:?}");
let mut reader = client.read_object(&bucket.name, "hello.txt").send().await?;
let mut contents = Vec::new();
while let Some(chunk) = reader.next().await.transpose()? {
contents.extend_from_slice(&chunk);
}
println!(
"object contents successfully downloaded {:?}",
bytes::Bytes::from_owner(contents)
);
control
.delete_object()
.set_bucket(&bucket.name)
.set_object(&object.name)
.set_generation(object.generation)
.send()
.await?;
control
.delete_bucket()
.set_name(&bucket.name)
.send()
.await?;
Ok(())
}
Use errors to terminate object writes
In this guide you will learn how to use errors and custom data sources to terminate an object write before it is finalized. This is useful when applications want to stop the client library from finalizing the object creation if there is some error condition.
Prerequisites
The guide assumes you have an existing Google Cloud project with billing enabled, and a Cloud Storage bucket in that project.
The tutorial assumes you are familiar with the basics of using the client library. If not, you may want to read the quickstart guide first.
Add the client library as a dependency
cargo add google-cloud-storage
Overview
The client library creates objects from any type implementing the
StreamingSource trait. The client library pulls data from implementations of
the trait. The library terminates the object write on the first error.
In this guide you will build a custom implementation of StreamingSource that
returns some data and then stops on an error. You will verify that an object
write using this custom data source returns an error.
Create a custom error type
To terminate an object write without finalizing it, your StreamingSource must return an error. In this example you will create a simple error type, in your application code you can use any existing error type:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
#[derive(Debug)]
pub enum MyError {
ExpectedProblem,
OhNoes,
}
impl std::error::Error for MyError {}
impl std::fmt::Display for MyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ExpectedProblem => write!(f, "this kind of thing happens"),
Self::OhNoes => write!(f, "oh noes! something terrible happened"),
}
}
}
#[derive(Debug, Default)]
struct MySource(u32);
impl google_cloud_storage::streaming_source::StreamingSource for MySource {
type Error = MyError;
async fn next(&mut self) -> Option<Result<bytes::Bytes, Self::Error>> {
self.0 += 1;
match self.0 {
42 => Some(Err(MyError::ExpectedProblem)),
n if n > 42 => None,
n => Some(Ok(bytes::Bytes::from_owner(format!(
"test data for the example {n}\n"
)))),
}
}
}
pub async fn attempt_upload(bucket_name: &str) -> anyhow::Result<()> {
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let upload = client
.write_object(bucket_name, "expect-error", MySource::default())
.send_buffered()
.await;
println!("Upload result {upload:?}");
let err = upload.expect_err("the source is supposed to terminate the upload");
assert!(err.is_serialization(), "{err:?}");
use std::error::Error as _;
assert!(err.source().is_some_and(|e| e.is::<MyError>()), "{err:?}");
Ok(())
}
The client library requires that your custom error type implements the standard Error trait:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
#[derive(Debug)]
pub enum MyError {
ExpectedProblem,
OhNoes,
}
impl std::error::Error for MyError {}
impl std::fmt::Display for MyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ExpectedProblem => write!(f, "this kind of thing happens"),
Self::OhNoes => write!(f, "oh noes! something terrible happened"),
}
}
}
#[derive(Debug, Default)]
struct MySource(u32);
impl google_cloud_storage::streaming_source::StreamingSource for MySource {
type Error = MyError;
async fn next(&mut self) -> Option<Result<bytes::Bytes, Self::Error>> {
self.0 += 1;
match self.0 {
42 => Some(Err(MyError::ExpectedProblem)),
n if n > 42 => None,
n => Some(Ok(bytes::Bytes::from_owner(format!(
"test data for the example {n}\n"
)))),
}
}
}
pub async fn attempt_upload(bucket_name: &str) -> anyhow::Result<()> {
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let upload = client
.write_object(bucket_name, "expect-error", MySource::default())
.send_buffered()
.await;
println!("Upload result {upload:?}");
let err = upload.expect_err("the source is supposed to terminate the upload");
assert!(err.is_serialization(), "{err:?}");
use std::error::Error as _;
assert!(err.source().is_some_and(|e| e.is::<MyError>()), "{err:?}");
Ok(())
}
As you may recall, that requires implementing Display too:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
#[derive(Debug)]
pub enum MyError {
ExpectedProblem,
OhNoes,
}
impl std::error::Error for MyError {}
impl std::fmt::Display for MyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ExpectedProblem => write!(f, "this kind of thing happens"),
Self::OhNoes => write!(f, "oh noes! something terrible happened"),
}
}
}
#[derive(Debug, Default)]
struct MySource(u32);
impl google_cloud_storage::streaming_source::StreamingSource for MySource {
type Error = MyError;
async fn next(&mut self) -> Option<Result<bytes::Bytes, Self::Error>> {
self.0 += 1;
match self.0 {
42 => Some(Err(MyError::ExpectedProblem)),
n if n > 42 => None,
n => Some(Ok(bytes::Bytes::from_owner(format!(
"test data for the example {n}\n"
)))),
}
}
}
pub async fn attempt_upload(bucket_name: &str) -> anyhow::Result<()> {
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let upload = client
.write_object(bucket_name, "expect-error", MySource::default())
.send_buffered()
.await;
println!("Upload result {upload:?}");
let err = upload.expect_err("the source is supposed to terminate the upload");
assert!(err.is_serialization(), "{err:?}");
use std::error::Error as _;
assert!(err.source().is_some_and(|e| e.is::<MyError>()), "{err:?}");
Ok(())
}
Create a custom StreamingSource
Create a type that generates the data for your object. In this example you will use synthetic data using a counter:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
#[derive(Debug)]
pub enum MyError {
ExpectedProblem,
OhNoes,
}
impl std::error::Error for MyError {}
impl std::fmt::Display for MyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ExpectedProblem => write!(f, "this kind of thing happens"),
Self::OhNoes => write!(f, "oh noes! something terrible happened"),
}
}
}
#[derive(Debug, Default)]
struct MySource(u32);
impl google_cloud_storage::streaming_source::StreamingSource for MySource {
type Error = MyError;
async fn next(&mut self) -> Option<Result<bytes::Bytes, Self::Error>> {
self.0 += 1;
match self.0 {
42 => Some(Err(MyError::ExpectedProblem)),
n if n > 42 => None,
n => Some(Ok(bytes::Bytes::from_owner(format!(
"test data for the example {n}\n"
)))),
}
}
}
pub async fn attempt_upload(bucket_name: &str) -> anyhow::Result<()> {
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let upload = client
.write_object(bucket_name, "expect-error", MySource::default())
.send_buffered()
.await;
println!("Upload result {upload:?}");
let err = upload.expect_err("the source is supposed to terminate the upload");
assert!(err.is_serialization(), "{err:?}");
use std::error::Error as _;
assert!(err.source().is_some_and(|e| e.is::<MyError>()), "{err:?}");
Ok(())
}
Implement the streaming source trait for your type:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
#[derive(Debug)]
pub enum MyError {
ExpectedProblem,
OhNoes,
}
impl std::error::Error for MyError {}
impl std::fmt::Display for MyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ExpectedProblem => write!(f, "this kind of thing happens"),
Self::OhNoes => write!(f, "oh noes! something terrible happened"),
}
}
}
#[derive(Debug, Default)]
struct MySource(u32);
impl google_cloud_storage::streaming_source::StreamingSource for MySource {
type Error = MyError;
async fn next(&mut self) -> Option<Result<bytes::Bytes, Self::Error>> {
self.0 += 1;
match self.0 {
42 => Some(Err(MyError::ExpectedProblem)),
n if n > 42 => None,
n => Some(Ok(bytes::Bytes::from_owner(format!(
"test data for the example {n}\n"
)))),
}
}
}
pub async fn attempt_upload(bucket_name: &str) -> anyhow::Result<()> {
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let upload = client
.write_object(bucket_name, "expect-error", MySource::default())
.send_buffered()
.await;
println!("Upload result {upload:?}");
let err = upload.expect_err("the source is supposed to terminate the upload");
assert!(err.is_serialization(), "{err:?}");
use std::error::Error as _;
assert!(err.source().is_some_and(|e| e.is::<MyError>()), "{err:?}");
Ok(())
}
// ... more details below ...
}
Define the error type:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
#[derive(Debug)]
pub enum MyError {
ExpectedProblem,
OhNoes,
}
impl std::error::Error for MyError {}
impl std::fmt::Display for MyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ExpectedProblem => write!(f, "this kind of thing happens"),
Self::OhNoes => write!(f, "oh noes! something terrible happened"),
}
}
}
#[derive(Debug, Default)]
struct MySource(u32);
impl google_cloud_storage::streaming_source::StreamingSource for MySource {
type Error = MyError;
async fn next(&mut self) -> Option<Result<bytes::Bytes, Self::Error>> {
self.0 += 1;
match self.0 {
42 => Some(Err(MyError::ExpectedProblem)),
n if n > 42 => None,
n => Some(Ok(bytes::Bytes::from_owner(format!(
"test data for the example {n}\n"
)))),
}
}
}
pub async fn attempt_upload(bucket_name: &str) -> anyhow::Result<()> {
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let upload = client
.write_object(bucket_name, "expect-error", MySource::default())
.send_buffered()
.await;
println!("Upload result {upload:?}");
let err = upload.expect_err("the source is supposed to terminate the upload");
assert!(err.is_serialization(), "{err:?}");
use std::error::Error as _;
assert!(err.source().is_some_and(|e| e.is::<MyError>()), "{err:?}");
Ok(())
}
And implement the main function in this trait. Note how this function will (eventually) return the error type you defined above:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
#[derive(Debug)]
pub enum MyError {
ExpectedProblem,
OhNoes,
}
impl std::error::Error for MyError {}
impl std::fmt::Display for MyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ExpectedProblem => write!(f, "this kind of thing happens"),
Self::OhNoes => write!(f, "oh noes! something terrible happened"),
}
}
}
#[derive(Debug, Default)]
struct MySource(u32);
impl google_cloud_storage::streaming_source::StreamingSource for MySource {
type Error = MyError;
async fn next(&mut self) -> Option<Result<bytes::Bytes, Self::Error>> {
self.0 += 1;
match self.0 {
42 => Some(Err(MyError::ExpectedProblem)),
n if n > 42 => None,
n => Some(Ok(bytes::Bytes::from_owner(format!(
"test data for the example {n}\n"
)))),
}
}
}
pub async fn attempt_upload(bucket_name: &str) -> anyhow::Result<()> {
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let upload = client
.write_object(bucket_name, "expect-error", MySource::default())
.send_buffered()
.await;
println!("Upload result {upload:?}");
let err = upload.expect_err("the source is supposed to terminate the upload");
assert!(err.is_serialization(), "{err:?}");
use std::error::Error as _;
assert!(err.source().is_some_and(|e| e.is::<MyError>()), "{err:?}");
Ok(())
}
Create the object
You will need a client to interact with Cloud Storage:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
#[derive(Debug)]
pub enum MyError {
ExpectedProblem,
OhNoes,
}
impl std::error::Error for MyError {}
impl std::fmt::Display for MyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ExpectedProblem => write!(f, "this kind of thing happens"),
Self::OhNoes => write!(f, "oh noes! something terrible happened"),
}
}
}
#[derive(Debug, Default)]
struct MySource(u32);
impl google_cloud_storage::streaming_source::StreamingSource for MySource {
type Error = MyError;
async fn next(&mut self) -> Option<Result<bytes::Bytes, Self::Error>> {
self.0 += 1;
match self.0 {
42 => Some(Err(MyError::ExpectedProblem)),
n if n > 42 => None,
n => Some(Ok(bytes::Bytes::from_owner(format!(
"test data for the example {n}\n"
)))),
}
}
}
pub async fn attempt_upload(bucket_name: &str) -> anyhow::Result<()> {
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let upload = client
.write_object(bucket_name, "expect-error", MySource::default())
.send_buffered()
.await;
println!("Upload result {upload:?}");
let err = upload.expect_err("the source is supposed to terminate the upload");
assert!(err.is_serialization(), "{err:?}");
use std::error::Error as _;
assert!(err.source().is_some_and(|e| e.is::<MyError>()), "{err:?}");
Ok(())
}
Use the custom type to create the object:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
#[derive(Debug)]
pub enum MyError {
ExpectedProblem,
OhNoes,
}
impl std::error::Error for MyError {}
impl std::fmt::Display for MyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ExpectedProblem => write!(f, "this kind of thing happens"),
Self::OhNoes => write!(f, "oh noes! something terrible happened"),
}
}
}
#[derive(Debug, Default)]
struct MySource(u32);
impl google_cloud_storage::streaming_source::StreamingSource for MySource {
type Error = MyError;
async fn next(&mut self) -> Option<Result<bytes::Bytes, Self::Error>> {
self.0 += 1;
match self.0 {
42 => Some(Err(MyError::ExpectedProblem)),
n if n > 42 => None,
n => Some(Ok(bytes::Bytes::from_owner(format!(
"test data for the example {n}\n"
)))),
}
}
}
pub async fn attempt_upload(bucket_name: &str) -> anyhow::Result<()> {
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let upload = client
.write_object(bucket_name, "expect-error", MySource::default())
.send_buffered()
.await;
println!("Upload result {upload:?}");
let err = upload.expect_err("the source is supposed to terminate the upload");
assert!(err.is_serialization(), "{err:?}");
use std::error::Error as _;
assert!(err.source().is_some_and(|e| e.is::<MyError>()), "{err:?}");
Ok(())
}
As expected, this object write fails. You can inspect the error details:
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
#[derive(Debug)]
pub enum MyError {
ExpectedProblem,
OhNoes,
}
impl std::error::Error for MyError {}
impl std::fmt::Display for MyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ExpectedProblem => write!(f, "this kind of thing happens"),
Self::OhNoes => write!(f, "oh noes! something terrible happened"),
}
}
}
#[derive(Debug, Default)]
struct MySource(u32);
impl google_cloud_storage::streaming_source::StreamingSource for MySource {
type Error = MyError;
async fn next(&mut self) -> Option<Result<bytes::Bytes, Self::Error>> {
self.0 += 1;
match self.0 {
42 => Some(Err(MyError::ExpectedProblem)),
n if n > 42 => None,
n => Some(Ok(bytes::Bytes::from_owner(format!(
"test data for the example {n}\n"
)))),
}
}
}
pub async fn attempt_upload(bucket_name: &str) -> anyhow::Result<()> {
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let upload = client
.write_object(bucket_name, "expect-error", MySource::default())
.send_buffered()
.await;
println!("Upload result {upload:?}");
let err = upload.expect_err("the source is supposed to terminate the upload");
assert!(err.is_serialization(), "{err:?}");
use std::error::Error as _;
assert!(err.source().is_some_and(|e| e.is::<MyError>()), "{err:?}");
Ok(())
}
Next Steps
Full Program
// Copyright 2025 Google LLC
//
// Licensed 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
//
// https://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.
#[derive(Debug)]
pub enum MyError {
ExpectedProblem,
OhNoes,
}
impl std::error::Error for MyError {}
impl std::fmt::Display for MyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ExpectedProblem => write!(f, "this kind of thing happens"),
Self::OhNoes => write!(f, "oh noes! something terrible happened"),
}
}
}
#[derive(Debug, Default)]
struct MySource(u32);
impl google_cloud_storage::streaming_source::StreamingSource for MySource {
type Error = MyError;
async fn next(&mut self) -> Option<Result<bytes::Bytes, Self::Error>> {
self.0 += 1;
match self.0 {
42 => Some(Err(MyError::ExpectedProblem)),
n if n > 42 => None,
n => Some(Ok(bytes::Bytes::from_owner(format!(
"test data for the example {n}\n"
)))),
}
}
}
pub async fn attempt_upload(bucket_name: &str) -> anyhow::Result<()> {
use google_cloud_storage::client::Storage;
let client = Storage::builder().build().await?;
let upload = client
.write_object(bucket_name, "expect-error", MySource::default())
.send_buffered()
.await;
println!("Upload result {upload:?}");
let err = upload.expect_err("the source is supposed to terminate the upload");
assert!(err.is_serialization(), "{err:?}");
use std::error::Error as _;
assert!(err.source().is_some_and(|e| e.is::<MyError>()), "{err:?}");
Ok(())
}
Working with enums
This guide will show you how to use enumerations in the Google Cloud client libraries for Rust, including working with enumeration values introduced after the library was released.
Background
Google Cloud services use enumerations for fields that only accept or provide a discrete and limited set of values. While at any point in time the set of allowed values is known, this list may change over time.
The client libraries are prepared to receive and send enumerations, and support working with values introduced after the library release.
Prerequisites
This guide does not make any calls to Google Cloud services. You can run the examples without having a project or account in Google Cloud. The guide will use the client library for Secret Manager. The same principles apply to any other enumeration in any other client library.
Dependencies
As it is usual with Rust, you must declare the dependency in your Cargo.toml
file. You can use:
cargo add google-cloud-secretmanager-v1 serde_json
Handling known values
When using known values, you can use the enumeration as usual:
use google_cloud_secretmanager_v1::model::secret_version::State;
let enabled = State::Enabled;
println!("State::Enabled = {enabled}");
assert_eq!(enabled.value(), Some(1));
assert_eq!(enabled.name(), Some("ENABLED"));
let state = State::from(1);
println!("state = {state}");
assert_eq!(state.value(), Some(1));
assert_eq!(state.name(), Some("ENABLED"));
let state = State::from("ENABLED");
println!("state = {state}");
assert_eq!(state.value(), Some(1));
assert_eq!(state.name(), Some("ENABLED"));
println!("json = {}", serde_json::to_value(&state)?);
Handling unknown values
When using unknown string values, the .value() function return None, but
everything else works as normal:
use google_cloud_secretmanager_v1::model::secret_version::State;
use serde_json::json;
let state = State::from("STATE_NAME_FROM_THE_FUTURE");
println!("state = {state}");
assert_eq!(state.value(), None);
assert_eq!(state.name(), Some("STATE_NAME_FROM_THE_FUTURE"));
println!("json = {}", serde_json::to_value(&state)?);
let u = serde_json::from_value::<State>(json!("STATE_NAME_FROM_THE_FUTURE"))?;
assert_eq!(state, u);
The same principle applies to unknown integer values:
use google_cloud_secretmanager_v1::model::secret_version::State;
use serde_json::json;
const MAGIC_INT_FROM_THE_FUTURE: i32 = 17;
let state = State::from(MAGIC_INT_FROM_THE_FUTURE);
println!("state = {state}");
assert_eq!(state.value(), Some(17));
assert_eq!(state.name(), None);
println!("json = {}", serde_json::to_value(&state)?);
let s2 = serde_json::from_value::<State>(json!(17))?;
assert_eq!(state, s2);
Preparing for upgrades
As previously mentioned, the Rust enumerations in the client libraries may gain
new variants in future releases. To avoid breaking applications, these
enumerations are marked as #[non_exhaustive].
If you use a match expression for non-exhaustive enumerations then you must include the wildcard pattern in your match. This maintains backward compatibility when new variants are added to the enumeration.
use google_cloud_secretmanager_v1::model::secret_version::State;
fn match_with_wildcard(state: State) -> anyhow::Result<()> {
use anyhow::Error;
match state {
State::Unspecified => {
return Err(Error::msg("the documentation says this is never used"));
}
State::Enabled => println!("the secret is enabled and can be accessed"),
State::Disabled => {
println!("the secret version is not accessible until it is enabled")
}
State::Destroyed => {
println!("the secret is destroyed, the data is no longer accessible")
}
State::UnknownValue(u) => {
println!("unknown State variant ({u:?}) time to update the library")
}
_ => return Err(Error::msg("unexpected value, update this code")),
};
Ok(())
}
Nevertheless, you may want a warning or error if new variants appear, at least
so you can examine the code and decide if it must be updated. If that is the
case, consider using the wildcard_enum_match_arm clippy warning:
use google_cloud_secretmanager_v1::model::secret_version::State;
fn match_with_warnings(state: State) -> anyhow::Result<()> {
use anyhow::Error;
#[warn(clippy::wildcard_enum_match_arm)]
match state {
State::Unspecified => {
return Err(Error::msg("the documentation says this is never used"));
}
State::Enabled => println!("the secret is enabled and can be accessed"),
State::Disabled => {
println!("the secret version is not accessible until it is enabled")
}
State::Destroyed => {
println!("the secret is destroyed, the data is no longer accessible")
}
State::UnknownValue(u) => {
println!("unknown State variant ({u:?}) time to update the library")
}
_ => {
// *If* your CI includes treating clippy warnings as errors,
// consider using `unreachable!()`.
return Err(Error::msg("unexpected value, update this code"));
}
};
Ok(())
}
You may also consider the (currently unstable)
non_exhaustive_omitted_patterns lint.
Troubleshoot the Google Cloud Rust Client Library
Debug logging
The best way to troubleshoot is by enabling logging. See Enabling Logging for more information.
How can I trace gRPC issues?
Clients that use gRPC use tonic for the underlying transport. The
primary method for debugging gRPC calls in Rust is using the tracing
subscriber filters. You can target specific gRPC crates to see underlying
transport details.
NOTE: The tracing crate requires that you first initialize a
tracing_subscriber.
For example, setting the RUST_LOG environment variable to include
tonic=debug or h2=debug will dump a lot of information regarding the gRPC
and HTTP/2 layers.
RUST_LOG=debug,tonic=debug,h2=debug cargo run --example your_program
How can I diagnose proxy issues?
See Client Configuration: Configuring a Proxy.
Reporting a problem
If your issue is still not resolved, ask for help. If you have a support contract with Google, create an issue in the support console instead of filing on GitHub. This will ensure a timely response.
Otherwise, file an issue on GitHub. Although there are multiple GitHub repositories associated with the Google Cloud Libraries, we recommend filing an issue in https://github.com/googleapis/google-cloud-rust unless you are certain that it belongs elsewhere. The maintainers may move it to a different repository where appropriate, but you will be notified of this using the email associated with your GitHub account.