Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
toy-rpc
A async RPC crate that mimics the golang
's net/rpc
package and supports both async-std
and tokio
.
This crate aims at providing an easy-to-use RPC that is similar to golang
's
net/rpc
.
The usage is similar to that of golang
's net/rpc
with functions sharing similar
names and functionalities. Certain function names are changed to be more "rusty".
Because rust
doesn't have reflection, attribute macros are used to make certain
method "exported".
Content
Breaking Changes
The most recent breaking changes will be reflected here.
Version 0.6.0-beta
- Re-defined the custom
Error
type - Fixed bug where client does not interpret error message correctly
Version 0.6.0-alpha
- In short, this update makes the crate resemble closer to the usage of
go
'snet/rpc
package - Service registration is simplified to
Server::builder().register(foo_service).build()
. The examples will be updated accordingly. Thusservice!()
macro will be deprecatedregister
function now takes only one argument, which is the instance of the service- on the client side, the service name will just be the name of the struct. for example,
to call a RPC method on
struct Foo { }
service, the client simply uses.async_call("Foo.<method>").await
where<method>
should be replaced with the RPC method - you can still register multiple services on the same server. However, only one object of the same type can be registered on the same server. Multiple servers are needed to have multiple objects of the same type.
Crate Feature Flags
The feature flags can be put into two categories.
Choice of serialization/deserialzation
serde_bincode
: the default codec will usebincode
for serialization/deserializationserde_json
: the default codec will useserde_json
forjson
serialization/deserializationserde_cbor
: the default codec will useserde_cbor
for serialization/deserializationserde_rmp
: the default codec will usermp-serde
for serialization/deserialization
Choice of runtime
async_std_runtime
: supports usage withasync-std
tokio_runtime
: supports usage withtokio
http_tide
: enablestide
integration on the server side. This also enablesasync_std_runtime
http_actix_web
: enablesactix-web
integration on the server side. This also enablestokio_runtime
http_warp
: enables integration withwarp
on the server side. This also enablestokio_runtime
Other trivial feature flags are listed below, and they are likely of no actual usage for you.
docs
std
:serde/std
. There is no actual usage right now.
Default Features
[]
= [
"serde_bincode",
"async_std_runtime"
]
Documentation
The following documentation is adapted based on golang
's documentation.
This crate provides access to the methods marked with #[export_impl]
and #[export_method]
of an object across a network connection. A server
registers an object, making it visible as a service with a name provided by the user.
After the registration, the "exported" methods will be accessible remotely.
A server may register multiple objects as multiple services, and multiple
objects of different types could be registered on the same
Server
object. Only one object(service) of the same type can be registered on
one server; multiple servers are needed for multiple objects of the same type.
To export a method, use #[export_method]
attribute in an impl block marked with
#[export_impl]
attribute. This crate currently only
support using #[export_impl]
attribute
on one
impl block per type.
The methods to export must meet the following criteria on the server side
-
the method resides in an impl block marked with
#[export_impl]
-
the method is marked with
#[export_method]
attribute -
the method takes one argument other than
&self
and returns aResult<T, E>
- the argument must implement trait
serde::Deserialize
- the
Ok
typeT
of the result must implement traitserde::Serialize
- the
Err
typeE
of the result must implement traitToString
- the argument must implement trait
-
the method is essentially in the form
Req
and Res
are marshaled/unmarshaled (serialized/deserialized) by serde
.
Realistically the Req
and Res
type must also be marshaled/unmarshaled on
the client side, and thus Req
and Res
must both implement both
serde::Serialize
and serde::Deserialize
.
The method's argument reprements the argument provided by the client caller,
and the Ok
type of result represents success parameters to be returned to
the client caller. The Err
type of result is passed back to the client as
a String
.
The server may handle requests on a single connection by calling serve_conn
,
and it may handle multiple connections by creating a async_std::net::TcpListener
and call accept
. Integration with HTTP currently only supports tide
by calling
into_endpoint
.
A client wishing to use the service establishes a async_std::net::TcpStream
connection
and then creates Client
over the connection. The convenience function dial
performs
this step for raw TCP socket connection, and dial_http
performs this for an HTTP
connection. A Client
with HTTP connection or socket connection has three methods, call
, async_call
,
and spawn_task
, to specify the service and method to call and the argument. Please note that
the service and method name is case sensitive, and following Rust's naming convention,
the service name should be in CamelCase, for example, if a service is defined as pub struct Foo {}
,
the client needs to use async_call("Foo.echo").await
to make the remote call.
call
method is synchronous and waits for the remote call to complete and then returns the result in a blocking manner.async_call
is theasync
versions ofcall
andcall_http
, respectively. Because they areasync
functions, they must be called with.await
to be executed.spawn_task
method spawns anasync
task and returns aJoinHandle
. The result can be obtained using theJoinHandle
. Please note thatasync_std::task::JoinHandle
andtokio::task::JoinHandle
behave slightly different. Executing.await
onasync_std::task::JoinHandle
returnsResult<Res, toy_rpc::error::Error>
. However, executing.await
ontokio::task::JoinHandle
returns `Result<Result<Res, toy_rpc::error::Error>, tokio::task::JoinError>.- A client stub trait is generated automatically which allows usage such as
client.foo().echo("data").await
wherefoo()
represents a call to theFoo{}
service whileecho()
represents the RPC method for theFoo{}
service. More details can be found below
Unless an explicity codec is set up (with serve_codec
method, HTTP is NOT supported yet),
the default codec specified by one of the following features tags (serde_bincode
, serde_json
serde_cbor
, serde_rmp
) will be used to transport data.
async-std
and tokio
Starting from version 0.5.0-beta.2
, you can use toy-rpc
with either runtime by choosing
the corresponding feature flag (async_std_runtime
, tokio_runtime
).
HTTP integrations
Similar to choosing the runtimes, toy-rpc
supports integration with actix-web
, tide
,
and warp
by choosing the corresponding feature flag (http_tide
, http_actix_web
http_warp
). Starting from version 0.5.0-beta.0
the integration is implemented using
WebSocket as the transport protocol, and the DEFAULT_RPC_SERVER=_rpc_
is appended to the path you
supply to the HTTP framework. The client side support is not based on async_tungstenite
and removed usage of surf
. Thus versions >=0.5.0-beta.0
are NOT compatible
with versions <0.5.0-beta.0
. The examples below are also updated to reflect
the changes.
Client Stub
The #[export_impl]
macro now also generates client stubs that internally uses async_call
.
For example, if the Example {}
service is registered on the server as "example_service"
.
If you want to call the echo(&self, arg: u32)
RPC method on the Example {}
service, you
can conveniently use client.example().echo(3).await.unwrap()
. The generated stub follows the
snake case, for example
- if a service is defined as pub struct Foo {}
, the generated stub will be foo()
- if a service is defined as pub struct FooBar {}
, the generated stub will be foo_bar()
- if a service is defined asx pub struct FooBarService {}
, the generated stub will be foo_bar_service()
// import everything from the `rpc` mod to include generated client stub
use *;
async
Examples
A few simple examples are shown below. More examples can be found in the examples
directory in the repo. All examples here will assume the follwing
RPC service definition below.
The examples here will also need some other dependencies
[]
# you may need to change feature flags for different examples
= { = "0.6.0-beta" }
# optional depending on the choice of runtime or http framework for different examples
= { = "1.9.0", = ["attributes"] }
= { = "1.2.0", = ["rt", "rt-multi-thread", "macros", "net", "sync"] }
= "0.16.0"
= "3.3.2"
= "0.3.0"
# other dependencies needed for the examples here
= "0.1.42"
= "0.8.2"
= "0.4.14"
= { = "1.0.123", = ["derive"] }
Example Service Definition
RPC over TCP with async-std
This example will assume the RPC service defined above,
and you may need to uncomment the line use async_std::sync::Mutex;
in the RPC service definition
for this example.
The default feature flags will work with the example below.
server.rs
use TcpListener;
use ;
use task;
use service;
use Server;
use crate rpc; // assume the rpc module can be found here
async
client.rs
use Client;
use Error;
// import everything from the `rpc` mod to include generated client stub
use crate*; // assume the rpc module can be found here
async
RPC over TCP with tokio
This example will assume the RPC service defined above
and you may need to uncomment the line use tokio::sync::Mutex;
in the RPC service definition
for this example.
The default feature flags will NOT work for this example, and you need to change the feature flags.
=
toy_rpc
server.rs
use Arc;
use TcpListener;
use Mutex;
use task;
use service;
use Server;
use crate rpc; // assume the rpc module can be found here
async
client.rs
use Client;
use Error;
// import everything from the `rpc` mod to include generated client stub
use crate*; // assume the rpc module can be found here
async
HTTP integration with tide
This example will assume the RPC service defined above
and you may need to uncomment the line use async_std::sync::Mutex;
in the RPC service definition
for this example.
An example client to use with HTTP can be found in a separate example here. The default feature flags will NOT work with this example, and you need to change the feature flags.
= { = "0.6.0-beta", = false, = ["serde_bincode", "http_tide"] }
server.rs
use ;
use service;
use Server;
use crate rpc; // assume the rpc module can be found here
async
HTTP integration with actix-web
This example will assume the RPC service defined above
and you may need to uncomment the line use tokio::sync::Mutex;
in the RPC service definition
for this example.
An example client to use with HTTP can be found in a another example here. The default feature flags will NOT work with this example, and you need to change the feature flags.
= { = "0.6.0-beta", = false, = ["serde_bincode", "http_actix_web"] }
server.rs
use Arc;
use Mutex;
use ;
use service;
use Server;
use crate rpc; // assume the rpc module can be found here
async
HTTP integration with warp
This example will assume the RPC service defined above
and you may need to uncomment the line use tokio::sync::Mutex;
in the RPC service definition
for this example.
An example client to use with HTTP can be found in a another example here. The default feature flags will NOT work with this example, and you need to change the feature flags.
= { = "0.6.0-beta", = false, = ["serde_bincode", "http_warp"] }
server.rs
use Filter;
use Arc;
use Mutex;
use service;
use Server;
use crate rpc; // assume the rpc module can be found here
async
RPC client for HTTP
This example will assume the RPC service defined above. The default feature flags will work with this example. However, you may also use client with any runtime or http feature flag.
All HTTP examples assumes that the RPC server is found at "127.0.0.1/rpc/" endpoint.
use Client;
use Error;
use crate rpc; // assume the rpc module can be found here
// choose the runtime attribute accordingly
//#[tokio::main]
async
Change Log
0.6.0-beta
- Re-defined the custom
Error
type - Fixed bug where client does not interpret error message correctly
0.6.0-alpha
- In short, this update makes the crate resemble closer to the usage of
go
'snet/rpc
package - Service registration is simplified to
Server::builder().register(foo_service).build()
. The examples will be updated accordingly. Thusservice!()
macro will be deprecatedregister
function now takes only one argument, which is the instance of the service- on the client side, the service name will just be the name of the struct. for example,
to call a RPC method on
struct Foo { }
service, the client simply uses.async_call("Foo.<method>").await
where<method>
should be replaced with the RPC method - you can still register multiple services on the same server. However, only one object of the same type can be registered on the same server. Multiple servers are needed to have multiple objects of the same type.
0.5.4
- Handlers are now stored as a
fn
pointer as opposed to a trait object.
0.5.3
- The
#[export_impl]
macro now generates client stub functions by generating a new trait fortoy_rpc::Client
.
0.5.0
Breaking changes
- HTTP integration is now accomplished using WebSocket with
async_tungstenite
, and thus HTTP connections of versions <0.5.0 are not compatible with versions >=0.5.0. - The custom binary transport protocol now includes a magic byte at the beginning, making versions <0.5.0 NOT compatible with versions >= 0.5.0;
toy_rpc::error::Error
changed from struct-like variants to simple enum variants- Changes to feature flags
- "logging" feature flag is removed
- "surf" feature flag is removed
- "tide" is changed to "http_tide"
- "actix-web" is changed to "http_actix_web"
- added "http_warp" feature flag
- added "async_std_runtime"
- added "tokio_runtime"
Non-breaking changes
- Removed
Stream
andSink
impl from the custom binary transport protocolFrame
0.4.5
- Added
Sink
implementation for the custom binary transport protocolFrame
0.4.4
- Modified traits
CodecRead
,CodecWrite
,ServerCodec
,ClientCodec
to no longer return number of bytes written - The number of bytes written for header and body will be logged separately
0.4.3
- Removed previously unused NoneError
- Unified
call
,async_call
andspawn_task
for socket client and HTTP client. Thecall_http
,async_call_http
, andspawn_task_http
methods are kept for compatibility.
0.4.2
- Temporary fix of
spawn_task()
andspawn_task_http()
withArc<Mutex<_>>
until lifetime with async task is figured out. As a result,Client
no longer needs to be declaredmut
.
0.4.1
- Updated documentation
0.4.0
- Added
actix-web
feature flag to support integration withactix-web
0.3.1
- Added
serde_rmp
features flag - Updated and corrected examples in the documentation
0.3.0
- Added
serde_cbor
feature flag - Changed
bincode
feature flag toserde_bincode
Future Plan
The following items are in no particular order.
- improve error handling
- improve logging message
- support other I/O connection
- more tests
License: MIT/Apache-2.0