Skip to content

gRPC Fundamentals & Contracts ​

Sword uses tonic as the foundation for gRPC controllers. Contracts are written in .proto files, which are not read at runtime: they are compiled and generate the Rust code for the service, the message types and, optionally, a descriptor for reflection.

Protocol Buffers ​

Protocol Buffers is an extensible, language- and platform-neutral mechanism, developed by Google, for serializing structured data.

.proto files define how data is structured once. The code generated at compile time is then used to write and read that structured data across different data streams, in different programming languages.

RPC types ​

A service defined in .proto can expose several RPC types, depending on the shape of requests and responses:

  • Unary: one request → one response. It is the most common type.
  • Server streaming: the client sends one request and the server responds with a stream of messages.
  • Client streaming: the client sends a stream of requests and the server responds with a single message.
  • Bidirectional streaming: both sides send and receive streams concurrently.

In the contract they are declared like this:

proto
syntax = "proto3";

package users;

service UserGrpcService {
  rpc GetUser (GetUserRequest) returns (GetUserResponse);          // unary
  rpc StreamUsers (StreamUsersRequest) returns (stream UserItem);  // server streaming
  rpc UploadUsers (stream UserItem) returns (UploadReply);          // client streaming
  rpc Chat (stream ChatMessage) returns (stream ChatReply);         // bidi streaming
}

Recommendations and Naming Conventions

These rules aim to avoid ambiguity with your application's internal services and keep clear contracts for external clients.

We recommend keeping the .proto files in config/proto/, or in shared/proto/ if it is a contract shared across several services.

This helps you:

  • maintain a predictable structure across projects,
  • reuse the same pattern in build.rs,
  • separate transport contracts from the rest of the application code.

Services ​

Use the GrpcService suffix in proto services, because business services with similar names can coexist in your application.

proto
service UserGrpcService {
  rpc GetUser (GetUserRequest) returns (GetUserResponse);
}
proto
service UserService {
  rpc GetUser (GetUserRequest) returns (GetUserResponse);
}

RPC methods ​

Name methods by intent (Get, List, Create, Update, Delete, Stream) so the contract is self-explanatory for whoever consumes it.

proto
rpc GetUser (GetUserRequest) returns (GetUserResponse);
rpc ListUsers (ListUsersRequest) returns (ListUsersResponse);
rpc StreamUsers (StreamUsersRequest) returns (stream User);
proto
rpc UserGet (GetUserRequest) returns (GetUserResponse);
rpc DoUserAction (ListUsersRequest) returns (ListUsersResponse);

Messages ​

Avoid technical prefixes/suffixes such as Grpc in message. In public contracts, it is better to use neutral, domain-oriented names.

proto
message GetUserRequest {
  string id = 1;
}

message GetUserResponse {
  User user = 1;
}
proto
message GetUserGrpcRequest {
  string id = 1;
}

message GetUserGrpcResponse {
  UserGrpcModel user = 1;
}

Build dependencies ​

To compile the .proto files you need tonic-prost-build as a build dependency, plus prost (serialization) and tonic-prost (codec) as project dependencies.

Minimum dependencies ​

toml
[dependencies]
sword = { version = "0.7", features = ["grpc"] }
tonic = "x.y.z"
prost = "x.y.z"
prost-types = "x.y.z"
tonic-prost = "x.y.z"

[build-dependencies]
tonic-prost-build = "x.y.z"

Why is sword with its grpc feature not enough?

When .proto files are compiled, they depend directly on prost and tonic-prost in the final client, meaning these crates need to be in the project's Cargo.toml. It is not enough for sword to re-export them.

Advanced types with the 'prost-types' crate ​

If your contract uses protobuf well-known types (google.protobuf.Timestamp, Duration, Any, etc.), you also need the prost-types crate in the project.

proto
import "google/protobuf/timestamp.proto";

message UserItem {
  string id = 1;
  string username = 2;
  google.protobuf.Timestamp created_at = 3;
}
rust
pub struct UserItem {
    pub id: String,
    pub username: String,
    pub created_at: prost_types::Timestamp,
}

Compiling '.proto' files in 'build.rs' ​

Any project using gRPC controllers needs a build.rs file that compiles the .proto files with tonic_prost_build, plus the matching build dependency.

toml
[build-dependencies]
tonic-prost-build = { workspace = true }
rust
fn main() -> Result<(), Box<dyn std::error::Error>> {
    tonic_prost_build::configure()
        .compile_protos(&["config/proto/users.proto"], &["config/proto"])?;

    Ok(())
}

What does compiling a '.proto' file generate? ​

When you compile a .proto file with tonic-prost-build, it generates:

  • A trait for the defined service (for example UserGrpcService),
  • A server to register the service (for example UserGrpcServiceServer<T>),
  • A client to invoke the service (for example UserGrpcServiceClient<T>),
  • Request/response types and enums defined in the contract.

Re-exporting the generated types ​

The types generated after compilation must be imported using Tonic's include_proto! macro. However, that produces imports with submodules, which can be tedious, so it is recommended to declare a proto submodule per contract that calls include_proto! and re-exports the server and the client at a single level:

rust
mod controller;
mod dtos;
mod entity;
mod repository;
mod service;

pub mod proto {
    tonic::include_proto!("users");

    pub use user_grpc_service_client::*;
    pub use user_grpc_service_server::*;
}

use sword::prelude::*;

use self::controller::UsersController;

pub use self::dtos::{CreateUserDto, UpdateUserDto};
pub use self::entity::{User, UserView};
pub use self::repository::UserRepository;
pub use self::service::UserService;

pub struct UsersModule;

impl Module for UsersModule {
    fn register_components(components: &ComponentRegistry) {
        components.register::<UserRepository>();
        components.register::<UserService>();
    }

    fn register_controllers(controllers: &ControllerRegistry) {
        controllers.register::<UsersController>();
    }
}
rust
use super::proto::*;

#[controller(kind = Controller::Grpc, server = UserGrpcServiceServer)]
pub struct UsersController;

impl UserGrpcService for UsersController { ... }

Reflection ​

If you enable the grpc-reflection feature, you must generate the reflection descriptor. This lets Sword register reflection automatically and expose it to clients such as grpcurl.

toml
[dependencies]
sword = { version = "0.7", features = ["grpc", "grpc-reflection"] }
rust
use std::{env, path::PathBuf};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let out_dir = PathBuf::from(env::var("OUT_DIR")?); 
    let descriptor_path = out_dir.join("sword_descriptor_set.bin"); 

    tonic_prost_build::configure()
        .file_descriptor_set_path(&descriptor_path) 
        .compile_protos(&["config/proto/users.proto"], &["config/proto"])?;

    Ok(())
}