Electron's Super Simple RPC (ESSRPC) is a lightweight RPC library which aims to enable RPC calls as transparently as possible through calls to ordinary trait methods.
The magic is performed by the essrpc
attribute macro which may
be applied to any trait whose functions each meet the following conditions:
- Returns a
Result
whose error type implementsFrom<RPCError>
. - Uses only parameter and returns types which implement
Serialize
- Is not unsafe
The essrpc
macro generates for a trait an RPC client and a
server. For a trait named Foo
, the macro will generate
FooRPCClient
which implements both
RPCClient and Foo
as well as
FooRPCServer
which implements RPCServer.
Examples
A trait can apply the essrpc
attribute like this.
#[essrpc]
pub trait Foo {
fn bar(&self, a: String, b: i32) -> Result<String, SomeError>;
}
For example purposes, assume we're using a unix socket to
communicate between a parent and child process. Anything else
implementing Read+Write
would work just as well.
# use std::os::unix::net::UnixStream;
let (s1, s2) = UnixStream::pair().unwrap();
We can spin up a server like this
let mut s = FooRPCServer::new(FooImpl::new(), BincodeTransport::new(s2));
s.serve()
Then, if we have some type FooImpl
which implements Foo
, we can do RPC like this.
let client = FooRPCClient::new(BincodeTransport::new(s1));
match client.bar("the answer".to_string(), 42) {
Ok(result) => assert_eq!("the answer is 42", result),
Err(e) => panic!("error: {:?}", e)
}
Asynchronous Clients
By default, the #[essrpc]
attribute generates a synchronous
client. Asynchronous clients can be generated via
#[essrpc(async)]
, or #[essrpc(sync, async)]
if both
synchronous and asynchronous clients are needed. For asynchronous,
the macro generates a new trait, suffixed with Async
for which
every method returns a boxed Future
instead of a Result
, with
the same success and error types, and a type implementing
AsyncRPCClient
. For example,
#[essrpc(async)]
pub trait Foo {
fn bar(&self, a: String, b: i32) -> Result<String, SomeError>;
}
Would generate a FooAsync
trait with a bar
method returning
Box<Future<Item=String, Error=SomeError>>
and a
FooAsyncRPCClient
struct implementing both FooAsync
and
AsyncRPCClient.