Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[proc macros] force proc macro api to return Result #435

Merged
merged 19 commits into from
Aug 18, 2021
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions benches/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use futures_channel::oneshot;
use futures_util::future::FutureExt;
use jsonrpsee::{
http_server::HttpServerBuilder,
types::Error,
ws_server::{RpcModule, WsServerBuilder},
};

Expand All @@ -17,8 +18,8 @@ pub async fn http_server() -> String {
let server =
HttpServerBuilder::default().max_request_body_size(u32::MAX).build("127.0.0.1:0".parse().unwrap()).unwrap();
let mut module = RpcModule::new(());
module.register_method(SYNC_METHOD_NAME, |_, _| Ok("lo")).unwrap();
module.register_async_method(ASYNC_METHOD_NAME, |_, _| (async { Ok("lo") }).boxed()).unwrap();
module.register_method::<_, _, Error>(SYNC_METHOD_NAME, |_, _| Ok("lo")).unwrap();
module.register_async_method::<_, _, Error>(ASYNC_METHOD_NAME, |_, _| (async { Ok("lo") }).boxed()).unwrap();
server_started_tx.send(server.local_addr().unwrap()).unwrap();
server.start(module).await
});
Expand All @@ -31,8 +32,8 @@ pub async fn ws_server() -> String {
tokio::spawn(async move {
let server = WsServerBuilder::default().build("127.0.0.1:0").await.unwrap();
let mut module = RpcModule::new(());
module.register_method(SYNC_METHOD_NAME, |_, _| Ok("lo")).unwrap();
module.register_async_method(ASYNC_METHOD_NAME, |_, _| (async { Ok("lo") }).boxed()).unwrap();
module.register_method::<_, _, Error>(SYNC_METHOD_NAME, |_, _| Ok("lo")).unwrap();
module.register_async_method::<_, _, Error>(ASYNC_METHOD_NAME, |_, _| (async { Ok("lo") }).boxed()).unwrap();
module
.register_subscription(SUB_METHOD_NAME, UNSUB_METHOD_NAME, |_params, mut sink, _ctx| {
let x = "Hello";
Expand Down
3 changes: 2 additions & 1 deletion examples/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use jsonrpsee::{
http_client::HttpClientBuilder,
http_server::{HttpServerBuilder, RpcModule},
types::Error,
types::{traits::Client, JsonValue},
};
use std::net::SocketAddr;
Expand All @@ -50,7 +51,7 @@ async fn main() -> anyhow::Result<()> {
async fn run_server() -> anyhow::Result<SocketAddr> {
let server = HttpServerBuilder::default().build("127.0.0.1:0".parse()?)?;
let mut module = RpcModule::new(());
module.register_method("say_hello", |_, _| Ok("lo"))?;
module.register_method::<_, _, Error>("say_hello", |_, _| Ok("lo"))?;

let addr = server.local_addr()?;
tokio::spawn(server.start(module));
Expand Down
12 changes: 6 additions & 6 deletions examples/proc_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,17 @@

use jsonrpsee::{
proc_macros::rpc,
types::async_trait,
types::{async_trait, error::Error},
ws_client::WsClientBuilder,
ws_server::{RpcModule, SubscriptionSink, WsServerBuilder},
};
use std::net::SocketAddr;

#[rpc(client, server, namespace = "state")]
#[rpc(server, client, namespace = "state")]
pub trait Rpc {
/// Async method call example.
#[method(name = "getPairs")]
async fn storage_pairs(&self, prefix: usize, hash: Option<u128>) -> Vec<usize>;
async fn storage_pairs(&self, prefix: usize, hash: Option<u128>) -> Result<Vec<usize>, Error>;

/// Subscription that take `Option<Vec<u8>>` as input and produces output `Vec<usize>`.
#[subscription(name = "subscribeStorage", unsub = "unsubscribeStorage", item = Vec<usize>)]
Expand All @@ -47,8 +47,8 @@ pub struct RpcServerImpl;

#[async_trait]
impl RpcServer for RpcServerImpl {
async fn storage_pairs(&self, _prefix: usize, _hash: Option<u128>) -> Vec<usize> {
vec![1, 2, 3, 4]
async fn storage_pairs(&self, _prefix: usize, _hash: Option<u128>) -> Result<Vec<usize>, Error> {
Ok(vec![1, 2, 3, 4])
}

fn subscribe_storage(&self, mut sink: SubscriptionSink, keys: Option<Vec<u8>>) {
Expand All @@ -75,7 +75,7 @@ async fn main() -> anyhow::Result<()> {
async fn run_server() -> anyhow::Result<SocketAddr> {
let server = WsServerBuilder::default().build("127.0.0.1:0").await?;
let mut module = RpcModule::new(());
module.register_method("state_getPairs", |_, _| Ok(vec![1, 2, 3]))?;
module.register_method::<_, _, Error>("state_getPairs", |_, _| Ok(vec![1, 2, 3]))?;

let addr = server.local_addr()?;
tokio::spawn(async move { server.start(RpcServerImpl.into_rpc()).await });
Expand Down
4 changes: 2 additions & 2 deletions examples/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
// DEALINGS IN THE SOFTWARE.

use jsonrpsee::{
types::{traits::Client, v2::params::JsonRpcParams},
types::{traits::Client, v2::params::JsonRpcParams, Error},
ws_client::WsClientBuilder,
ws_server::{RpcModule, WsServerBuilder},
};
Expand All @@ -47,7 +47,7 @@ async fn main() -> anyhow::Result<()> {
async fn run_server() -> anyhow::Result<SocketAddr> {
let server = WsServerBuilder::default().build("127.0.0.1:0").await?;
let mut module = RpcModule::new(());
module.register_method("say_hello", |_, _| Ok("lo"))?;
module.register_method::<_, _, Error>("say_hello", |_, _| Ok("lo"))?;
let addr = server.local_addr()?;
tokio::spawn(server.start(module));
Ok(addr)
Expand Down
24 changes: 12 additions & 12 deletions http-server/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,38 +47,38 @@ async fn server_with_handles() -> (SocketAddr, JoinHandle<Result<(), Error>>, St
let ctx = TestContext;
let mut module = RpcModule::new(ctx);
let addr = server.local_addr().unwrap();
module.register_method("say_hello", |_, _| Ok("lo")).unwrap();
module.register_async_method("say_hello_async", |_, _| async move { Ok("lo") }.boxed()).unwrap();
module.register_method::<_, _, Error>("say_hello", |_, _| Ok("lo")).unwrap();
module.register_async_method::<_, _, Error>("say_hello_async", |_, _| async move { Ok("lo") }.boxed()).unwrap();
module
.register_method("add", |params, _| {
.register_method::<_, _, Error>("add", |params, _| {
let params: Vec<u64> = params.parse()?;
let sum: u64 = params.into_iter().sum();
Ok(sum)
})
.unwrap();
module
.register_method("multiparam", |params, _| {
.register_method::<_, _, Error>("multiparam", |params, _| {
let params: (String, String, Vec<u8>) = params.parse()?;
let r = format!("string1={}, string2={}, vec={}", params.0.len(), params.1.len(), params.2.len());
Ok(r)
})
.unwrap();
module.register_method("notif", |_, _| Ok("")).unwrap();
module.register_method::<_, _, Error>("notif", |_, _| Ok("")).unwrap();
module
.register_method("should_err", |_, ctx| {
.register_method::<_, _, Error>("should_err", |_, ctx| {
let _ = ctx.err().map_err(|e| CallError::Failed(e.into()))?;
Ok("err")
})
.unwrap();

module
.register_method("should_ok", |_, ctx| {
.register_method::<_, _, Error>("should_ok", |_, ctx| {
let _ = ctx.ok().map_err(|e| CallError::Failed(e.into()))?;
Ok("ok")
})
.unwrap();
module
.register_async_method("should_ok_async", |_p, ctx| {
.register_async_method::<_, _, Error>("should_ok_async", |_p, ctx| {
async move {
let _ = ctx.ok().map_err(|e| CallError::Failed(e.into()))?;
Ok("ok")
Expand Down Expand Up @@ -369,12 +369,12 @@ async fn can_register_modules() {
let mut mod2 = RpcModule::new(cx2);

assert_eq!(mod1.method_names().count(), 0);
mod1.register_method("bla", |_, cx| Ok(format!("Gave me {}", cx))).unwrap();
mod1.register_method("bla2", |_, cx| Ok(format!("Gave me {}", cx))).unwrap();
mod2.register_method("yada", |_, cx| Ok(format!("Gave me {:?}", cx))).unwrap();
mod1.register_method::<_, _, Error>("bla", |_, cx| Ok(format!("Gave me {}", cx))).unwrap();
mod1.register_method::<_, _, Error>("bla2", |_, cx| Ok(format!("Gave me {}", cx))).unwrap();
mod2.register_method::<_, _, Error>("yada", |_, cx| Ok(format!("Gave me {:?}", cx))).unwrap();

// Won't register, name clashes
mod2.register_method("bla", |_, cx| Ok(format!("Gave me {:?}", cx))).unwrap();
mod2.register_method::<_, _, Error>("bla", |_, cx| Ok(format!("Gave me {:?}", cx))).unwrap();

assert_eq!(mod1.method_names().count(), 2);

Expand Down
14 changes: 7 additions & 7 deletions proc-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,16 +198,16 @@ mod new;
///
/// // RPC is moved into a separate module to clearly show names of generated entities.
/// mod rpc_impl {
/// use jsonrpsee::{proc_macros::rpc, types::async_trait, ws_server::SubscriptionSink};
/// use jsonrpsee::{proc_macros::rpc, types::{async_trait, JsonRpcResult}, ws_server::SubscriptionSink};
///
/// // Generate both server and client implementations, prepend all the methods with `foo_` prefix.
/// #[rpc(client, server, namespace = "foo")]
/// pub trait Rpc {
/// #[method(name = "foo")]
/// async fn async_method(&self, param_a: u8, param_b: String) -> u16;
/// async fn async_method(&self, param_a: u8, param_b: String) -> JsonRpcResult<u16>;
///
/// #[method(name = "bar")]
/// fn sync_method(&self) -> u16;
/// fn sync_method(&self) -> JsonRpcResult<u16>;
///
/// #[subscription(name = "sub", unsub = "unsub", item = String)]
/// fn sub(&self);
Expand All @@ -220,12 +220,12 @@ mod new;
/// // Note that the trait name we use is `RpcServer`, not `Rpc`!
/// #[async_trait]
/// impl RpcServer for RpcServerImpl {
/// async fn async_method(&self, _param_a: u8, _param_b: String) -> u16 {
/// 42u16
/// async fn async_method(&self, _param_a: u8, _param_b: String) -> JsonRpcResult<u16> {
/// Ok(42u16)
/// }
///
/// fn sync_method(&self) -> u16 {
/// 10u16
/// fn sync_method(&self) -> JsonRpcResult<u16> {
/// Ok(10u16)
/// }
///
/// // We could've spawned a `tokio` future that yields values while our program works,
Expand Down
2 changes: 1 addition & 1 deletion proc-macros/src/new/render_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ impl RpcDescription {
// `returns` represent the return type of the *rust method* (`Result< <..>, jsonrpsee::Error`).
let (called_method, returns) = if let Some(returns) = &method.returns {
let called_method = quote::format_ident!("request");
let returns = quote! { Result<#returns, #jrps_error> };
let returns = quote! { #returns };

(called_method, returns)
} else {
Expand Down
10 changes: 4 additions & 6 deletions proc-macros/src/new/render_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ impl RpcDescription {
}
};

// panic!("{}", trait_impl);

Ok(trait_impl)
}

Expand Down Expand Up @@ -72,7 +70,7 @@ impl RpcDescription {
let rpc_method_name = self.rpc_identifier(&method.name);
// `parsing` is the code associated with parsing structure from the
// provided `RpcParams` object.
// `params_seq` is the comma-delimited sequence of parametsrs.
// `params_seq` is the comma-delimited sequence of parameters.
let (parsing, params_seq) = self.render_params_decoding(&method.params);

check_name(rpc_method_name.clone(), rust_method_name.span());
Expand All @@ -82,7 +80,7 @@ impl RpcDescription {
rpc.register_async_method(#rpc_method_name, |params, context| {
let fut = async move {
#parsing
Ok(context.as_ref().#rust_method_name(#params_seq).await)
context.as_ref().#rust_method_name(#params_seq).await
};
Box::pin(fut)
})?;
Expand All @@ -91,7 +89,7 @@ impl RpcDescription {
quote! {
rpc.register_method(#rpc_method_name, |params, context| {
#parsing
Ok(context.#rust_method_name(#params_seq))
context.#rust_method_name(#params_seq)
})?;
}
}
Expand All @@ -110,7 +108,7 @@ impl RpcDescription {
let rpc_unsub_name = self.rpc_identifier(&sub.unsub_method);
// `parsing` is the code associated with parsing structure from the
// provided `RpcParams` object.
// `params_seq` is the comma-delimited sequence of parametsrs.
// `params_seq` is the comma-delimited sequence of parameters.
let (parsing, params_seq) = self.render_params_decoding(&sub.params);

check_name(rpc_sub_name.clone(), rust_method_name.span());
Expand Down
5 changes: 3 additions & 2 deletions proc-macros/tests/rpc_example.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
//! Example of using proc macro to generate working client and server.

use jsonrpsee::types::Error;
use jsonrpsee_proc_macros::rpc;
use std::borrow::Cow;

#[rpc(client, server, namespace = "foo")]
pub trait Rpc {
#[method(name = "foo")]
async fn async_method(&self, param_a: u8, param_b: Option<Cow<'_, str>>) -> u16;
async fn async_method(&self, param_a: u8, param_b: Option<Cow<'_, str>>) -> Result<u16, Error>;

#[method(name = "bar")]
fn sync_method(&self) -> u16;
fn sync_method(&self) -> Result<u16, Error>;

#[subscription(name = "sub", unsub = "unsub", item = String)]
fn sub(&self);
Expand Down
14 changes: 7 additions & 7 deletions proc-macros/tests/ui/correct/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use jsonrpsee::{
proc_macros::rpc,
types::async_trait,
types::{async_trait, JsonRpcResult},
ws_client::*,
ws_server::{SubscriptionSink, WsServerBuilder},
};
Expand All @@ -11,10 +11,10 @@ use std::{net::SocketAddr, sync::mpsc::channel};
#[rpc(client, server, namespace = "foo")]
pub trait Rpc {
#[method(name = "foo")]
async fn async_method(&self, param_a: u8, param_b: String) -> u16;
async fn async_method(&self, param_a: u8, param_b: String) -> JsonRpcResult<u16>;

#[method(name = "bar")]
fn sync_method(&self) -> u16;
fn sync_method(&self) -> JsonRpcResult<u16>;

#[subscription(name = "sub", unsub = "unsub", item = String)]
fn sub(&self);
Expand All @@ -27,12 +27,12 @@ pub struct RpcServerImpl;

#[async_trait]
impl RpcServer for RpcServerImpl {
async fn async_method(&self, _param_a: u8, _param_b: String) -> u16 {
42u16
async fn async_method(&self, _param_a: u8, _param_b: String) -> JsonRpcResult<u16> {
Ok(42u16)
}

fn sync_method(&self) -> u16 {
10u16
fn sync_method(&self) -> JsonRpcResult<u16> {
Ok(10u16)
}

fn sub(&self, mut sink: SubscriptionSink) {
Expand Down
6 changes: 3 additions & 3 deletions proc-macros/tests/ui/correct/only_client.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
//! Example of using proc macro to generate working client and server.

use jsonrpsee::proc_macros::rpc;
use jsonrpsee::{proc_macros::rpc, types::JsonRpcResult};

#[rpc(client)]
pub trait Rpc {
#[method(name = "foo")]
async fn async_method(&self, param_a: u8, param_b: String) -> u16;
async fn async_method(&self, param_a: u8, param_b: String) -> JsonRpcResult<u16>;

#[method(name = "bar")]
fn sync_method(&self) -> u16;
fn sync_method(&self) -> JsonRpcResult<u16>;

#[subscription(name = "sub", unsub = "unsub", item = String)]
fn sub(&self);
Expand Down
14 changes: 7 additions & 7 deletions proc-macros/tests/ui/correct/only_server.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
use jsonrpsee::{
proc_macros::rpc,
types::async_trait,
types::{async_trait, JsonRpcResult},
ws_server::{SubscriptionSink, WsServerBuilder},
};
use std::{net::SocketAddr, sync::mpsc::channel};

#[rpc(server)]
pub trait Rpc {
#[method(name = "foo")]
async fn async_method(&self, param_a: u8, param_b: String) -> u16;
async fn async_method(&self, param_a: u8, param_b: String) -> JsonRpcResult<u16>;

#[method(name = "bar")]
fn sync_method(&self) -> u16;
fn sync_method(&self) -> JsonRpcResult<u16>;

#[subscription(name = "sub", unsub = "unsub", item = String)]
fn sub(&self);
Expand All @@ -21,12 +21,12 @@ pub struct RpcServerImpl;

#[async_trait]
impl RpcServer for RpcServerImpl {
async fn async_method(&self, _param_a: u8, _param_b: String) -> u16 {
42u16
async fn async_method(&self, _param_a: u8, _param_b: String) -> JsonRpcResult<u16> {
Ok(42u16)
}

fn sync_method(&self) -> u16 {
10u16
fn sync_method(&self) -> JsonRpcResult<u16> {
Ok(10u16)
}

fn sub(&self, mut sink: SubscriptionSink) {
Expand Down
2 changes: 1 addition & 1 deletion proc-macros/tests/ui/incorrect/method/method_no_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use jsonrpsee::proc_macros::rpc;
#[rpc(client, server)]
pub trait NoMethodName {
#[method()]
async fn async_method(&self) -> u8;
async fn async_method(&self) -> jsonrpsee::types::JsonRpcResult<u8>;
}

fn main() {}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use jsonrpsee::proc_macros::rpc;
#[rpc(client, server)]
pub trait UnexpectedField {
#[method(name = "foo", magic = false)]
async fn async_method(&self) -> u8;
async fn async_method(&self) -> jsonrpsee::types::JsonRpcResult<u8>;
}

fn main() {}
Loading