tonic-rpc
is a macro that generates the traits and stubs used by tonic
from Rust definitions instead of proto
files.
This means that you can get all the benefits
of tonic
while using regular Rust types and without needing to use proto
files or build scripts.
Of course, this comes at the sacrifice of interoperability.
Alternatives
tarpc
is an excellent RPC library that also defines services
as a Rust trait.
Required dependencies
= "0.8.3"
= { = "0.2.1", = [ <enabled-codecs> ] }
Example
Instead of defining a proto
file, define a service as a trait:
The attribute #[tonic_rpc(json)]
indicates that this service
will serialize the requests and responses using json
.
Other encodings are available
.
The arguments and return values for each function must implement
serde::Serialize
and serde::Deserialize
.
The service can be implemented by defining an impl
:
;
And a server and client can be run:
async
The full example is available here. Further examples are available in the tests folder.
Encodings
Multiple codecs are available for serializing the RPC request/response types. Each codec is enabled by a feature flag. At least one of these features must be enabled.
bincode
- usingbincode
cbor
- usingserde_cbor
json
- usingserde_json
messagepack
- usingrmp-serde
E.g. To use the encode using cbor
, use the attribute
and include
= { = "0.2.1", = [ "cbor" ]}
in Cargo.toml
.
Streaming
Streaming can be added on the client or server side by adding the attributes
#[client_streaming]
or #[server_streaming]
to a function in the service trait.
These behave the same as if the stream
keyword were added to a proto
definition.
Examples that use streaming can be found in the tests folder.
Request/Response types
The traits and functions generated by tonic-rpc
will be transformations
of the methods defined in the tonic_rpc
trait that have been modified to
add handling of gRPC
request/response types, async, and streaming.
This is a summary of how signatures are transformed:
Arguments
..
becomes
async ..
Return value
becomes
async
Streaming arguments
..
becomes
async ..
Streaming return value
becomes
type FStream: ;
async