Skip to content

add readme file #1387

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
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
212 changes: 212 additions & 0 deletions tutorial.md
Copy link
Collaborator

Choose a reason for hiding this comment

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

Let's move this file to guide/src/. I think we will need to break this down, you are covering too much ground for a single document.

First, the initialization of a simple client is already covered in "Setting up your development environment". We can probably skip that.

Second, the long running operations are already covered too, we can skip that.

We should use your example of how to initialize using service account credentials into a new chapter titled "Using service account credentials" (or something similar).

We should break the section on error handling to its own chapter also.


You will need to use mdformat to fix a number of formatting issues:

https://github.com/googleapis/google-cloud-rust/actions/runs/13572960728/job/38427364311?pr=1387

And need to rebase to get the latest build scripts going.

Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
# Google Cloud Client Libraries for Rust

This guide explains how to use the Google Cloud Client Libraries for Rust to interact with Google Cloud services in your applications.

> **Note**: These libraries are currently in development and not recommended for production use.

## Before you begin

1. [Install Rust](https://www.rust-lang.org/tools/install)
2. [Set up a Google Cloud project](https://cloud.google.com/resource-manager/docs/creating-managing-projects)
3. [Install and initialize the Google Cloud CLI](https://cloud.google.com/sdk/docs/install)

## Installing the client libraries

Add the required dependencies to your `Cargo.toml`:

```toml
[dependencies]
google-cloud-secretmanager-v1 = { version = "0.1", features = ["unstable-stream"] }
tokio = { version = "1.0", features = ["macros", "rt-multi-thread"] }
```

## Authenticating

### Using Application Default Credentials (Recommended)

```rust
use google_cloud_secretmanager_v1::client::SecretManagerServiceClient;

async fn init_client() -> Result<SecretManagerServiceClient, Box<dyn std::error::Error>> {
// Creates a client using Application Default Credentials
let client = SecretManagerServiceClient::new().await?;
Ok(client)
}
```

### Using Service Account Keys

```rust
use google_cloud_auth::credentials::CredentialsFile;
use google_cloud_secretmanager_v1::client::SecretManagerServiceClient;

async fn init_client_with_credentials() -> Result<SecretManagerServiceClient, Box<dyn std::error::Error>> {
// Load credentials from a service account key file
let credentials = CredentialsFile::new_from_file(
"/path/to/service-account-key.json"
).await?;

// Initialize client with explicit credentials
let client = SecretManagerServiceClient::builder()
.with_credentials(credentials)
.build()
.await?;

Ok(client)
}
```

## Using the client libraries

### Basic operations

#### Listing secrets

```rust
use google_cloud_secretmanager_v1::client::SecretManagerServiceClient;
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think the client name is simply SecretManagerService. This is why we write the code samples as actual code in guide/samples/* and embed the code using {{#include }} to ensure the code actually compiles.

Please refactor all the code compilable code samples.


async fn list_secrets(project_id: &str) -> Result<(), Box<dyn std::error::Error>> {
// Initialize the client
let client = SecretManagerServiceClient::new().await?;

// Format the parent resource name
let parent = format!("projects/{}", project_id);

// List all secrets in the project
let response = client
.list_secrets()
.set_parent(parent)
.send()
.await?;

// Process the response
for secret in response.secrets {
println!("Secret: {}", secret.name);
}

Ok(())
}
```

### Working with long-running operations
Copy link
Collaborator

Choose a reason for hiding this comment

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


Some Google Cloud operations may take a long time to complete. Here's how to handle them:

```rust
use google_cloud_speech_v2::client::SpeechClient;
Copy link
Collaborator

Choose a reason for hiding this comment

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

The name of this client is incorrect again.

use google_cloud_gax::retry::ExponentialBackoff;
use std::time::Duration;

async fn handle_long_running_operation(
project_id: &str
) -> Result<(), Box<dyn std::error::Error>> {
// Initialize client with custom polling policy
let backoff = ExponentialBackoff::new(
Duration::from_secs(1), // Initial delay
Duration::from_secs(60), // Maximum delay
1.5, // Multiplier
);

let client = SpeechClient::builder()
.with_polling_backoff_policy(backoff)
.build()
.await?;

// Start a long-running operation
let operation = client
.create_recognizer()
.set_parent(format!("projects/{}/locations/global", project_id))
.set_recognizer_id("my-recognizer")
.send()
.await?;

// Wait for completion
let result = operation.await_complete().await?;
Copy link
Collaborator

Choose a reason for hiding this comment

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

I do not think this would compile.


Ok(())
}
```

### Error handling

Handle errors appropriately to ensure your application is robust:

```rust
use google_cloud_gax::error::{Code, ServiceError};

async fn robust_error_handling(
project_id: &str
) -> Result<(), Box<dyn std::error::Error>> {
let client = match SecretManagerServiceClient::new().await {
Ok(client) => client,
Err(e) => {
eprintln!("Failed to initialize client: {}", e);
return Err(e.into());
}
};

let secret_name = format!("projects/{}/secrets/my-secret", project_id);

match client.get_secret().set_name(secret_name).send().await {
Ok(secret) => {
println!("Retrieved secret: {}", secret.name);
Ok(())
}
Err(e) => {
if let Some(status) = e.downcast_ref::<ServiceError>() {
Copy link
Collaborator

Choose a reason for hiding this comment

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

The type of status would be ServiceError, but you are using it as if it was Status.... does this code compile?

match status.code() {
Code::NotFound => {
println!("Secret not found");
Ok(())
}
Code::PermissionDenied => {
eprintln!("Permission denied");
Err(e)
}
_ => {
eprintln!("Service error: {}", status);
Err(e)
}
}
} else {
eprintln!("Unknown error: {}", e);
Err(e)
}
}
}
}
```

## Troubleshooting

### Common issues

Comment on lines +180 to +183
Copy link
Collaborator

Choose a reason for hiding this comment

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

This is a really good idea.

1. **Authentication errors**
- Ensure you've run `gcloud auth application-default login`
- Verify your service account has the necessary permissions

2. **API not enabled**
- Enable the required APIs in your project:
```bash
gcloud services enable secretmanager.googleapis.com
Copy link
Collaborator

Choose a reason for hiding this comment

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

You are missing some APIs used above, like speech.googleapis.com. Keeping the tutorial focused on one topic makes it easier to catch these problems.

```

3. **Permission denied**
- Grant the necessary IAM roles to your account:
```bash
gcloud projects add-iam-policy-binding PROJECT_ID \
--member=user:EMAIL \
--role=roles/secretmanager.admin
```

## Next steps

- Explore the [Google Cloud documentation](https://cloud.google.com/docs)
- View the [API reference](https://docs.rs/google-cloud-secretmanager-v1)
- Check out [sample applications](https://github.com/googleapis/google-cloud-rust)

## Additional resources

- [Rust Programming Language](https://www.rust-lang.org/)
- [Google Cloud Platform Console](https://console.cloud.google.com/)
- [Google Cloud CLI documentation](https://cloud.google.com/sdk/docs)
Loading