Newer
Older
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
use jsonrpsee::{
http_client::HttpClientBuilder,
http_server::HttpServerBuilder,
proc_macros::rpc,
types::{traits::Client, v2::ParamsSer, Error},
ws_client::WsClientBuilder,
ws_server::{WsServerBuilder, WsStopHandle},
RpcModule,
};
use tokio::time::sleep;
use std::net::SocketAddr;
use std::time::Duration;
fn module_manual() -> Result<RpcModule<()>, Error> {
let mut module = RpcModule::new(());
module.register_async_method("say_hello", |_, _| async move {
sleep(Duration::from_millis(50)).await;
Ok("hello")
})?;
module
.register_async_method("expensive_call", |_, _| async move {
sleep(Duration::from_millis(50)).await;
Ok("hello expensive call")
})?
.resource("CPU", 3)?;
module
.register_async_method("memory_hog", |_, _| async move {
sleep(Duration::from_millis(50)).await;
Ok("hello memory hog")
})?
.resource("CPU", 0)?
.resource("MEM", 8)?;
Ok(module)
}
fn module_macro() -> RpcModule<()> {
#[rpc(server)]
pub trait Rpc {
#[method(name = "say_hello")]
async fn hello(&self) -> Result<&'static str, Error> {
sleep(Duration::from_millis(50)).await;
Ok("hello")
}
#[method(name = "expensive_call", resources("CPU" = 3))]
async fn expensive(&self) -> Result<&'static str, Error> {
sleep(Duration::from_millis(50)).await;
Ok("hello expensive call")
}
#[method(name = "memory_hog", resources("CPU" = 0, "MEM" = 8))]
async fn memory(&self) -> Result<&'static str, Error> {
sleep(Duration::from_millis(50)).await;
Ok("hello memory hog")
}
}
impl RpcServer for () {}
().into_rpc()
}
async fn websocket_server(module: RpcModule<()>) -> Result<(SocketAddr, WsStopHandle), Error> {
let server = WsServerBuilder::default()
.register_resource("CPU", 6, 2)?
.register_resource("MEM", 10, 1)?
.build("127.0.0.1:0")
.await?;
let addr = server.local_addr()?;
let handle = server.start(module)?;
Ok((addr, handle))
}
async fn http_server(module: RpcModule<()>) -> Result<SocketAddr, Error> {
let server = HttpServerBuilder::default()
.register_resource("CPU", 6, 2)?
.register_resource("MEM", 10, 1)?
.build("127.0.0.1:0".parse().unwrap())?;
let addr = server.local_addr()?;
tokio::spawn(server.start(module));
Ok(addr)
}
fn assert_server_busy(fail: Result<String, Error>) {
match fail {
Err(Error::Request(msg)) => {
let err: serde_json::Value = serde_json::from_str(&msg).unwrap();
assert_eq!(err["error"]["code"], -32604);
assert_eq!(err["error"]["message"], "Server is busy, try again later");
}
fail => panic!("Expected error, got: {:?}", fail),
}
}
async fn run_tests_on_ws_server(server_addr: SocketAddr, stop_handle: WsStopHandle) {
let server_url = format!("ws://{}", server_addr);
let client = WsClientBuilder::default().build(&server_url).await.unwrap();
// 2 CPU units (default) per call, so 4th call exceeds cap
let (pass1, pass2, pass3, fail) = tokio::join!(
client.request::<String>("say_hello", ParamsSer::NoParams),
client.request::<String>("say_hello", ParamsSer::NoParams),
client.request::<String>("say_hello", ParamsSer::NoParams),
client.request::<String>("say_hello", ParamsSer::NoParams),
);
assert!(pass1.is_ok());
assert!(pass2.is_ok());
assert!(pass3.is_ok());
assert_server_busy(fail);
// 3 CPU units per call, so 3rd call exceeds CPU cap, but we can still get on MEM
let (pass_cpu1, pass_cpu2, fail_cpu, pass_mem, fail_mem) = tokio::join!(
client.request::<String>("expensive_call", ParamsSer::NoParams),
client.request::<String>("expensive_call", ParamsSer::NoParams),
client.request::<String>("expensive_call", ParamsSer::NoParams),
client.request::<String>("memory_hog", ParamsSer::NoParams),
client.request::<String>("memory_hog", ParamsSer::NoParams),
);
assert!(pass_cpu1.is_ok());
assert!(pass_cpu2.is_ok());
assert_server_busy(fail_cpu);
assert!(pass_mem.is_ok());
assert_server_busy(fail_mem);
// Client being active prevents the server from shutting down?!
drop(client);
stop_handle.stop().unwrap().await;
}
async fn run_tests_on_http_server(server_addr: SocketAddr) {
let server_url = format!("http://{}", server_addr);
let client = HttpClientBuilder::default().build(&server_url).unwrap();
// 2 CPU units (default) per call, so 4th call exceeds cap
let (a, b, c, d) = tokio::join!(
client.request::<String>("say_hello", ParamsSer::NoParams),
client.request::<String>("say_hello", ParamsSer::NoParams),
client.request::<String>("say_hello", ParamsSer::NoParams),
client.request::<String>("say_hello", ParamsSer::NoParams),
);
// HTTP does not guarantee ordering
let mut passes = 0;
for result in [a, b, c, d] {
if result.is_ok() {
passes += 1;
} else {
assert_server_busy(result);
}
}
assert_eq!(passes, 3);
}
#[tokio::test]
async fn ws_server_with_manual_module() {
let (server_addr, stop_handle) = websocket_server(module_manual().unwrap()).await.unwrap();
run_tests_on_ws_server(server_addr, stop_handle).await;
}
#[tokio::test]
async fn ws_server_with_macro_module() {
let (server_addr, stop_handle) = websocket_server(module_macro()).await.unwrap();
run_tests_on_ws_server(server_addr, stop_handle).await;
}
#[tokio::test]
async fn http_server_with_manual_module() {
let server_addr = http_server(module_manual().unwrap()).await.unwrap();
run_tests_on_http_server(server_addr).await;
}
#[tokio::test]
async fn http_server_with_macro_module() {
let server_addr = http_server(module_macro()).await.unwrap();
run_tests_on_http_server(server_addr).await;
}