Crate marpc

Source
Expand description

§MARPC - simple macro-based and boilerplate-free rpc library

§Usage

  • You start by creating a rpc service type that implements RpcService. This defines what format will be used for rpc transactions. This type needs to be accessible to both your client code and server code.
  • The on the client you implement ClientRpcService for this type. This allows you to define a client handler, that is the function that sends the rpc request to the server and recieves a response.
  • On the server you register your service type with register_service!. This allows find_rpc_handler handle_rpc to find your rpc handler. It also allows you to specify a server state type.
  • Finally you can define rpc functions with the #[rpc] macro. Use the client and server feature flags to control whether to generate code for the client or server in the #[rpc] macro.
  • On the client you can simply call yout rpc functions as they where normal functions.
  • On the server use handle_rpc to handle any incomming rpc requests.

§Example

use std::future::Future;
use std::pin::Pin;

struct Service;

impl marpc::RpcService for Service {
    type Format = marpc::Json;
}

#[cfg(feature = "client")]
impl marpc::ClientRpcService for Service {
    type ClientError = Box<dyn std::error::Error>;

    fn handle<'a>(
        uri: &'static str,
        payload: &'a [u8],
    ) -> Pin<Box<dyn 'a + Future<Output = Result<Vec<u8>, Self::ClientError>>>> {
        Box::pin(async move {
            Ok(marpc::handle_rpc::<Service>(uri, (), payload).await?)
        })
    }
}

#[cfg(feature = "server")]
marpc::register_service!(Service);

#[marpc::rpc(AddRpc, uri = "/api/add", service = Service)]
async fn add(a: i32, b: i32) -> Result<i32, ()> {
    Ok(a + b)
}

let res = add(5, 6).await;
assert_eq!(res.unwrap(), 11);

Re-exports§

pub use formats::Json;
pub use inventory;server
pub use serde;

Modules§

formats
internal

Macros§

register_serviceserver
Register a rpc service.

Enums§

ClientRpcError
The set of rpc errors that the client can observe.
RpcError
The rpc errors that can happen on the server and that are sent to the client.

Traits§

ClientRpcService
The client defintion of a rpc service.
RpcFormat
A format for (de)serializing rpc messages.
RpcMethod
An rpc method definition.
RpcService
A rpc service.

Functions§

find_rpc_handlerserver
Find a matching rpc handler given a rpc service and uri.
handle_rpcserver
Handle a rpc call on the server.

Type Aliases§

RpcResult

Attribute Macros§

rpc
Define a rpc function.