-
Notifications
You must be signed in to change notification settings - Fork 0
/
add.rs
69 lines (56 loc) · 1.72 KB
/
add.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use std::future::Future;
use std::pin::Pin;
use std::sync::{mpsc, OnceLock};
struct Message {
uri: &'static str,
payload: Vec<u8>,
response_channel: mpsc::Sender<Vec<u8>>,
}
static QUEUE: OnceLock<mpsc::SyncSender<Message>> = OnceLock::new();
struct Service;
impl marpc::RpcService for Service {
type Format = marpc::Json;
}
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 {
let (send, recv) = mpsc::channel();
let message = Message {
uri,
payload: payload.to_owned(),
response_channel: send,
};
// Send the rpc call to the "server"
QUEUE.get().unwrap().send(message).unwrap();
// Wait for a response
Ok(recv.recv().unwrap())
})
}
}
marpc::register_service!(Service);
#[marpc::rpc(MyTest, uri = "/api/add", service = Service)]
async fn test(a: i32, b: i32) -> Result<i32, ()> {
Ok(a + b)
}
fn main() {
let (send, recv) = mpsc::sync_channel(1);
QUEUE.set(send).unwrap();
std::thread::spawn(move || {
pollster::block_on(async move {
while let Ok(message) = recv.recv() {
let res = marpc::handle_rpc::<Service>(message.uri, (), &message.payload)
.await
.unwrap();
message.response_channel.send(res).unwrap();
}
});
});
pollster::block_on(async {
let res = test(5, 6).await;
println!("Res: {:?}", res);
});
}