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

Modules

Macros

Enums

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

Traits

Functions

Type Definitions

Attribute Macros

  • Define a rpc function.