capnp-rpc-rust
This is a level one implementation of the Cap'n Proto remote procedure call protocol. It is a fairly direct translation of the original C++ implementation.
Defining an interface
First, make sure that the
capnp executable
is installed on your system,
and that you have the capnpc crate
in the build-dependencies section of your Cargo.toml.
Then, in a file named foo.capnp, define your interface:
@0xa7ed6c5c8a98ca40;
interface Bar {
baz @0 (x :Int32) -> (y :Int32);
}
interface Qux {
quux @0 (bar :Bar) -> (y :Int32);
}
Now you can invoke the schema compiler in a
build.rs file, like this:
Such a command generates a foo_capnp.rs file in the OUT_DIR
directory provided by cargo.
To import the generated code, add a line like this at the root of your crate:
generated_code!
(If you want to import the code at a non-toplevel module location, then you will
need to use the $Rust.parentModule annotation, defined in rust.capnp.)
Calling methods on an RPC object
For each defined interface, the generated code includes a Client struct
that can be used to call the interface's methods. For example, the following
code calls the Bar.baz() method:
A bar::Client is a reference to a possibly-remote Bar object.
The Cap'n Proto RPC runtime tracks the number of such references
that are live at any given time and automatically drops the
object when none are left.
Implementing an interface
The generated code also includes a Server trait for each of your interfaces.
To create an RPC-enabled object, you must implement that trait.
Then you can convert your object into a capability client like this:
let client: Client = new_client;
This new client can now be sent across the network.
You can use it as the bootstrap capability when you construct an RpcSystem,
and you can pass it in RPC method arguments and results.
Async methods
The methods of the generated Server traits return
a value of type impl Future<Output = Result<(), ::capnp::Error>>.
These can be implented as async fn methods returning Result<(), ::capnp::Error>.
The response will be sent back to the method's caller once two things have happened:
- The
Resultsstruct has been dropped. - The returned
Futurehas resolved.
Usually (1) happens before (2).
Here's an example of a method implementation that does not return immediately:
It's possible for multiple calls of quux() to be active at the same time
on the same object, and they do not need to return in the same order
as they were called.
Further reading
- The hello world example demonstrates a basic request/reply pattern.
- The calculator example demonstrates how to use promise pipelining.
- The pubsub example shows how even an interface with no methods can be useful.
- The Sandstorm raw API example app shows how Sandstorm lets you write web apps using Cap'n Proto instead of HTTP.