GCP Rust Tools
A comprehensive Rust toolset for Google Cloud Platform, combining simplified Observability (Logs, Metrics, Traces) with robust Pub/Sub wrappers.
Builder notes
This crate was developed by Santiago Amoretti in the context of the development of Genevabm(https://genevabm.com).
Features
- π Pub/Sub Integration: Easy wrapper around official Google Cloud Pub/Sub crates.
- π Cloud Logging: Send structured logs to Google Cloud Logging.
- π Cloud Monitoring: Create custom metrics in Google Cloud Monitoring.
- π Cloud Trace: Create distributed traces in Google Cloud Trace.
- β‘ High Performance: Designed for efficiency.
- π‘οΈ Error Resilient: Automatic retry logic.
Installation
Add this to your Cargo.toml:
[]
= "0.2.4"
= { = "1", = ["rt-multi-thread", "macros"] }
Prerequisites
-
Google Cloud Project with APIs enabled:
- Cloud Logging API
- Cloud Monitoring API
- Cloud Trace API
- Pub/Sub API
-
Service Account JSON with roles:
roles/logging.logWriterroles/monitoring.metricWriterroles/cloudtrace.agentroles/pubsub.publisher(for publishing)roles/pubsub.subscriber(for pulling/streaming subscriptions)
-
gcloud CLI (automatically installed if missing)
Architecture
The library uses a channel-based architecture for optimal performance:
βββββββββββββββ βββββββββββ ββββββββββββββββ
β Your App ββββββββββΆβ Channel ββββββββββΆβ Worker Threadβ
β (main) β queue β (1027) β process β (async ops) β
βββββββββββββββ βββββββββββ ββββββββββββββββ
β
βΌ
ββββββββββββββββ
β GCP APIs β
ββββββββββββββββ
Quick Start
Fire-and-Forget (Recommended)
use ;
use HashMap;
use ;
async
Async (Wait for Completion)
When you need confirmation that an operation succeeded:
// Wait for operation to complete
client.send_log_async.await?;
client.send_metric_async.await?;
client.send_trace_async.await?;
Using Convenience Macros
use ;
gcp_info!?;
gcp_warn!?;
gcp_error!?;
API Reference
ObservabilityClient
Initialization
new(project_id, service_account_path)βResult<Self, ObservabilityError>- Creates and authenticates a new client
- Starts background worker thread
Fire-and-Forget Methods
send_log(log_entry: LogEntry)βResult<(), ObservabilityError>send_metric(metric_data: MetricData)βResult<(), ObservabilityError>send_trace(trace_span: TraceSpan)βResult<(), ObservabilityError>
Async Methods (Wait for Completion)
send_log_async(log_entry: LogEntry)βFuture<Result<(), ObservabilityError>>send_metric_async(metric_data: MetricData)βFuture<Result<(), ObservabilityError>>send_trace_async(trace_span: TraceSpan)βFuture<Result<(), ObservabilityError>>
Utility Methods
generate_trace_id()βString- Generate a 32-character hex trace IDgenerate_span_id()βString- Generate a 16-character hex span ID
Data Structures
LogEntry
new
MetricData
new
TraceSpan
new
Convenience Macros
gcp_info!(client, "message")- Send an INFO log (fire-and-forget)gcp_warn!(client, "message")- Send a WARNING log (fire-and-forget)gcp_error!(client, "message")- Send an ERROR log (fire-and-forget)gcp_log!(client, "LEVEL", "message")- Send a log with custom severity
Error Handling
The library provides comprehensive error handling:
Error Types
AuthenticationError- Failed to authenticate with gcloudApiError- Google Cloud API request failedSetupError- Failed to setup/install gcloud CLIShutdown- Special internal error for worker shutdown
Token Expiration
The library automatically handles token expiration:
- Detects expired tokens (401/403 HTTP responses)
- Re-authenticates using your service account
- Retries the failed operation with a fresh token
- All happens transparently in the background
Silent Failures
Background operations fail silently to avoid disrupting your application. If you need error feedback, use the async methods:
match client.send_log_async.await
Pub/Sub
This crate includes a small convenience wrapper over the official google-cloud-pubsub client.
Naming conventions
- Topics passed in
topicsare expanded to:projects/{project_id}/topics/{name}-{instance_id} - Subscriptions passed in
subsare expanded to:projects/{project_id}/subscriptions/{name}
Publish (fire-and-forget)
use create_pubsub_client;
use Arc;
async
Notes:
publish_fire_and_forgetintentionally does not surface publish errors; it spawns a task and logs failures vialog.- Subscriptions are currently treated primarily as lookups (and may need to exist already in GCP with the correct topic binding).
Performance
Characteristics
- Non-blocking: Fire-and-forget operations return immediately
- Bounded Channel: 1027-item buffer prevents memory overflow
- Single Worker: One background thread prevents API rate limiting
- No Synchronization Overhead: Minimal locking and contention
- Fast Compilation: No heavy protobuf or gRPC dependencies
Benchmarks
On a typical development machine:
- Fire-and-forget operation: < 1Β΅s
- Background processing: ~50-200ms per operation (network dependent)
- Channel capacity: 1027 items before blocking
Features
[]
= { = "0.2.4", = ["logging", "monitoring"] }
Available features:
logging- Cloud Logging functionalitymonitoring- Cloud Monitoring functionalitytracing- Cloud Trace functionalitydefault- Includes all features
Examples
Run the example:
# Set your project ID and service account path
Architecture
This library uses a unique approach that balances simplicity with performance:
- Lightweight: No heavy protobuf or gRPC dependencies
- Simple: Uses standard HTTP/REST APIs via curl
- Reliable: Leverages battle-tested gcloud CLI for authentication
- Fast: Minimal overhead and fast compilation times
- Resilient: Automatic token refresh and retry logic
Background Worker
The single-threaded worker model provides natural rate limiting:
- One thread processes all operations sequentially
- Prevents overwhelming GCP APIs
- No complex rate limiting logic needed
- Predictable memory usage
Troubleshooting
Authentication Issues
# Verify gcloud is installed
# Verify service account works
API Not Enabled
Enable required APIs in your GCP project:
Permission Issues
Ensure your service account has the required roles:
roles/logging.logWriterroles/monitoring.metricWriterroles/cloudtrace.agent
License
Licensed under the Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0).
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.