Skip to main content

gcp_common/
client.rs

1//! Helper functions to create GCP SDK clients from configuration.
2
3use crate::config::GcpConfig;
4use gcloud_auth::credentials::CredentialsFile;
5use gcloud_pubsub::client::{Client as PubSubClient, ClientConfig as PubSubClientConfig};
6use gcloud_storage::client::{Client as StorageClient, ClientConfig as StorageClientConfig};
7
8/// Creates a GCS Storage client.
9pub async fn create_storage_client(config: &GcpConfig) -> anyhow::Result<StorageClient> {
10    let mut storage_config = StorageClientConfig::default();
11
12    if let Some(project_id) = &config.project_id {
13        storage_config.project_id = Some(project_id.clone());
14    }
15
16    // Authentication
17    if let Some(json) = &config.credentials_json {
18        let creds = CredentialsFile::new_from_str(json).await?;
19        storage_config = storage_config.with_credentials(creds).await?;
20    } else if let Some(path) = &config.credentials_file {
21        let creds = CredentialsFile::new_from_file(path.clone()).await?;
22        storage_config = storage_config.with_credentials(creds).await?;
23    } else {
24        storage_config = storage_config.with_auth().await?;
25    }
26
27    Ok(StorageClient::new(storage_config))
28}
29
30/// Creates a Pub/Sub client.
31pub async fn create_pubsub_client(config: &GcpConfig) -> anyhow::Result<PubSubClient> {
32    let mut pubsub_config = PubSubClientConfig::default();
33
34    // Authentication
35    if let Some(json) = &config.credentials_json {
36        let creds = CredentialsFile::new_from_str(json).await?;
37        pubsub_config = pubsub_config.with_credentials(creds).await?;
38    } else if let Some(path) = &config.credentials_file {
39        let creds = CredentialsFile::new_from_file(path.clone()).await?;
40        pubsub_config = pubsub_config.with_credentials(creds).await?;
41    } else {
42        pubsub_config = pubsub_config.with_auth().await?;
43    }
44
45    if let Some(project_id) = &config.project_id {
46        pubsub_config.project_id = Some(project_id.clone());
47    }
48
49    PubSubClient::new(pubsub_config)
50        .await
51        .map_err(|e| anyhow::anyhow!("Failed to create Pub/Sub client: {}", e))
52}