gRPC Clients
Sword lets you consume a remote gRPC service as an injectable dependency, through the same mechanism it uses for its other providers.
Configuration
Each client is declared in a [grpc.clients.<name>] section:
| Key | Type | Default | Description |
|---|---|---|---|
url | String | — | Remote service address |
connect | eager | lazy | lazy | Channel connection policy |
timeout | TimeConfig | 5s | Per-request timeout |
toml
[grpc.clients.users]
url = "http://users-service:50051"
connect = "lazy"
timeout = "5s"API Reference: Client configuration
The 'client' method
rust
pub fn client(&self, name: &str) -> Option<&GrpcClientConfig>Returns
- The client configuration, or
Noneif the[grpc.clients.<name>]section is not declared.
When to use it
- When a missing client is an expected case and you want to handle it without aborting.
The 'expect_client' method
rust
pub fn expect_client(&self, name: &str) -> &GrpcClientConfigReturns
- The client configuration.
When to use it
- When the client is required: it panics if the
[grpc.clients.<name>]section is not declared.
Registering in a module
The channel is built with Channel::from_config and registered as a provider:
rust
use sword::grpc::*;
use sword::prelude::*;
use crate::users::proto::*;
pub struct UsersModule;
impl Module for UsersModule {
async fn register_providers(config: &Config, providers: &ProviderRegistry) {
let grpc = config.get_or_default::<GrpcApplicationConfig>();
let channel = Channel::from_config(grpc.expect_client("users"))
.await
.expect("valid gRPC client channel");
providers.register(UserGrpcServiceClient::new(channel));
}
}Using it from a component
The client is injected into any component:
rust
use std::sync::Arc;
use sword::grpc::*;
use crate::users::proto::*;
#[injectable]
pub struct UsersService {
client: Arc<UserGrpcServiceClient<Channel>>,
}
impl UsersService {
pub async fn list(&self) -> Result<Vec<UserItem>, Status> {
let mut client = self.client.as_ref().clone();
let response = client.list_users(Request::new(ListUsersRequest {})).await?;
let users = response.into_inner().users;
Ok(users)
}
}Connection policies
lazy: connects on first use and retries if the service is unavailable. This is the default.eager: connects while the application starts and fails early if the service is down.

