Skip to content

Commit be29025

Browse files
committed
Add optional attributes to RPC impl macros to change the service name and the method names .
1 parent 3b89022 commit be29025

File tree

9 files changed

+260
-78
lines changed

9 files changed

+260
-78
lines changed

jsonrpc/README.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,18 +32,20 @@ use smol::stream::StreamExt;
3232

3333
use karyon_jsonrpc::{
3434
error::RPCError, server::{Server, ServerBuilder, Channel}, client::ClientBuilder,
35-
rpc_impl, rpc_pubsub_impl, message::SubscriptionID,
35+
rpc_impl, rpc_pubsub_impl, rpc_method, message::SubscriptionID,
3636
};
3737

3838
struct HelloWorld {}
3939

40+
// It is possible to change the service name by adding a `name` attribute
4041
#[rpc_impl]
4142
impl HelloWorld {
4243
async fn say_hello(&self, params: Value) -> Result<Value, RPCError> {
4344
let msg: String = serde_json::from_value(params)?;
4445
Ok(serde_json::json!(format!("Hello {msg}!")))
4546
}
4647

48+
#[rpc_method(name = "foo_method")]
4749
async fn foo(&self, params: Value) -> Result<Value, RPCError> {
4850
Ok(serde_json::json!("foo!"))
4951
}
@@ -53,6 +55,8 @@ impl HelloWorld {
5355
}
5456
}
5557

58+
59+
// It is possible to change the service name by adding a `name` attribute
5660
#[rpc_pubsub_impl]
5761
impl HelloWorld {
5862
async fn log_subscribe(&self, chan: Arc<Channel>, method: String, _params: Value) -> Result<Value, RPCError> {
@@ -112,6 +116,10 @@ async {
112116
.await
113117
.expect("send a request");
114118

119+
let result: String = client.call("HelloWorld.foo_method", ())
120+
.await
121+
.expect("send a request");
122+
115123
let sub = client
116124
.subscribe("HelloWorld.log_subscribe", ())
117125
.await

jsonrpc/examples/client.py

Lines changed: 0 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,30 +8,6 @@
88
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
99
s.connect((HOST, PORT))
1010

11-
req = {
12-
"jsonrpc": "2.0",
13-
"id": str(random.randint(0, 1000)),
14-
"method": "Calc.add",
15-
"params": {"x": 4, "y": 3},
16-
}
17-
print("Send: ", req)
18-
s.sendall((json.dumps(req)).encode())
19-
res = s.recv(1024)
20-
res = json.loads(res)
21-
print("Received: ", res)
22-
23-
req = {
24-
"jsonrpc": "2.0",
25-
"id": str(random.randint(0, 1000)),
26-
"method": "Calc.sub",
27-
"params": {"x": 4, "y": 3},
28-
}
29-
print("Send: ", req)
30-
s.sendall((json.dumps(req)).encode())
31-
res = s.recv(1024)
32-
res = json.loads(res)
33-
print("Received: ", res)
34-
3511
req = {
3612
"jsonrpc": "2.0",
3713
"id": str(random.randint(0, 1000)),

jsonrpc/examples/client.rs

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,20 +24,6 @@ fn main() {
2424
.await
2525
.expect("Create rpc client");
2626

27-
let params = Req { x: 10, y: 7 };
28-
let result: u32 = client
29-
.call("Calc.add", params)
30-
.await
31-
.expect("Call Calc.add method");
32-
info!("Add result: {result}");
33-
34-
let params = Req { x: 10, y: 7 };
35-
let result: u32 = client
36-
.call("Calc.sub", params)
37-
.await
38-
.expect("Call Calc.sub method");
39-
info!("Sub result: {result}");
40-
4127
let result: String = client
4228
.call("Calc.version", ())
4329
.await

jsonrpc/examples/client_derive.rs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
use std::time::Duration;
2+
3+
use log::info;
4+
use serde::{Deserialize, Serialize};
5+
use smol::Timer;
6+
7+
use karyon_jsonrpc::client::ClientBuilder;
8+
9+
#[derive(Deserialize, Serialize)]
10+
struct Req {
11+
x: u32,
12+
y: u32,
13+
}
14+
15+
#[derive(Deserialize, Serialize, Debug)]
16+
struct Pong {}
17+
18+
fn main() {
19+
env_logger::init();
20+
smol::future::block_on(async {
21+
let client = ClientBuilder::new("tcp://127.0.0.1:6000")
22+
.expect("Create client builder")
23+
.build()
24+
.await
25+
.expect("Create rpc client");
26+
27+
let params = Req { x: 10, y: 7 };
28+
let result: u32 = client
29+
.call("calculator.math.add", params)
30+
.await
31+
.expect("Call calculator.math.add method");
32+
info!("Add result: {result}");
33+
34+
let params = Req { x: 10, y: 7 };
35+
let result: u32 = client
36+
.call("calculator.math.sub", params)
37+
.await
38+
.expect("Call calculator.math.sub method");
39+
info!("Sub result: {result}");
40+
41+
let result: String = client
42+
.call("calculator.version", ())
43+
.await
44+
.expect("Call calculator.version method");
45+
info!("Version result: {result}");
46+
47+
loop {
48+
Timer::after(Duration::from_millis(100)).await;
49+
let result: Pong = client
50+
.call("calculator.ping", ())
51+
.await
52+
.expect("Call calculator.ping method");
53+
info!("Ping result: {:?}", result);
54+
}
55+
});
56+
}

jsonrpc/examples/server.rs

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ use serde::{Deserialize, Serialize};
44
use serde_json::Value;
55

66
use karyon_core::async_util::sleep;
7-
use karyon_jsonrpc::{error::RPCError, rpc_impl, server::ServerBuilder};
7+
use karyon_jsonrpc::{
8+
error::RPCError,
9+
server::{RPCMethod, RPCService, ServerBuilder},
10+
};
811

912
struct Calc {
1013
version: String,
@@ -19,20 +22,25 @@ struct Req {
1922
#[derive(Deserialize, Serialize)]
2023
struct Pong {}
2124

22-
#[rpc_impl]
23-
impl Calc {
24-
async fn ping(&self, _params: Value) -> Result<Value, RPCError> {
25-
Ok(serde_json::json!(Pong {}))
25+
impl RPCService for Calc {
26+
fn get_method(&self, name: &str) -> Option<RPCMethod> {
27+
match name {
28+
"ping" => Some(Box::new(move |params: Value| Box::pin(self.ping(params)))),
29+
"version" => Some(Box::new(move |params: Value| {
30+
Box::pin(self.version(params))
31+
})),
32+
_ => unimplemented!(),
33+
}
2634
}
2735

28-
async fn add(&self, params: Value) -> Result<Value, RPCError> {
29-
let params: Req = serde_json::from_value(params)?;
30-
Ok(serde_json::json!(params.x + params.y))
36+
fn name(&self) -> String {
37+
"Calc".to_string()
3138
}
39+
}
3240

33-
async fn sub(&self, params: Value) -> Result<Value, RPCError> {
34-
let params: Req = serde_json::from_value(params)?;
35-
Ok(serde_json::json!(params.x - params.y))
41+
impl Calc {
42+
async fn ping(&self, _params: Value) -> Result<Value, RPCError> {
43+
Ok(serde_json::json!(Pong {}))
3644
}
3745

3846
async fn version(&self, _params: Value) -> Result<Value, RPCError> {

jsonrpc/examples/server_derive.rs

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
use std::{sync::Arc, time::Duration};
2+
3+
use serde::{Deserialize, Serialize};
4+
use serde_json::Value;
5+
6+
use karyon_core::async_util::sleep;
7+
use karyon_jsonrpc::{error::RPCError, rpc_impl, rpc_method, server::ServerBuilder};
8+
9+
struct Calc {
10+
version: String,
11+
}
12+
13+
#[derive(Deserialize, Serialize)]
14+
struct Req {
15+
x: u32,
16+
y: u32,
17+
}
18+
19+
#[derive(Deserialize, Serialize)]
20+
struct Pong {}
21+
22+
#[rpc_impl(name = "calculator")]
23+
impl Calc {
24+
async fn ping(&self, _params: Value) -> Result<Value, RPCError> {
25+
Ok(serde_json::json!(Pong {}))
26+
}
27+
28+
#[rpc_method(name = "math.add")]
29+
async fn add(&self, params: Value) -> Result<Value, RPCError> {
30+
let params: Req = serde_json::from_value(params)?;
31+
Ok(serde_json::json!(params.x + params.y))
32+
}
33+
34+
#[rpc_method(name = "math.sub")]
35+
async fn sub(&self, params: Value) -> Result<Value, RPCError> {
36+
let params: Req = serde_json::from_value(params)?;
37+
Ok(serde_json::json!(params.x - params.y))
38+
}
39+
40+
async fn version(&self, _params: Value) -> Result<Value, RPCError> {
41+
Ok(serde_json::json!(self.version))
42+
}
43+
}
44+
45+
fn main() {
46+
env_logger::init();
47+
smol::block_on(async {
48+
// Register the Calc service
49+
let calc = Calc {
50+
version: String::from("0.1"),
51+
};
52+
53+
// Creates a new server
54+
let server = ServerBuilder::new("tcp://127.0.0.1:6000")
55+
.expect("Create a new server builder")
56+
.service(Arc::new(calc))
57+
.build()
58+
.await
59+
.expect("start a new server");
60+
61+
// Start the server
62+
server.start();
63+
64+
sleep(Duration::MAX).await;
65+
});
66+
}

0 commit comments

Comments
 (0)