-
Notifications
You must be signed in to change notification settings - Fork 150
/
ws_dual_stack.rs
153 lines (132 loc) · 5.22 KB
/
ws_dual_stack.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
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
// 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 futures::future::{self, Either};
use hyper_util::rt::{TokioExecutor, TokioIo};
use hyper_util::service::TowerToHyperService;
use jsonrpsee::core::client::ClientT;
use jsonrpsee::server::{stop_channel, ServerHandle};
use jsonrpsee::ws_client::WsClientBuilder;
use jsonrpsee::{rpc_params, RpcModule};
use std::net::SocketAddr;
use tokio::net::TcpListener;
use tracing_subscriber::util::SubscriberInitExt;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let filter = tracing_subscriber::EnvFilter::try_from_default_env()?
.add_directive("jsonrpsee[method_call{name = \"say_hello\"}]=trace".parse()?)
.add_directive("jsonrpsee-client=trace".parse()?);
tracing_subscriber::FmtSubscriber::builder().with_env_filter(filter).finish().try_init()?;
let (_server_hdl, addrs) = run_server().await?;
let url_v4 = format!("ws://{}", addrs.v4);
let url_v6 = format!("ws://{}", addrs.v6);
let client_v4 = WsClientBuilder::default().build(&url_v4).await?;
let client_v6 = WsClientBuilder::default().build(&url_v6).await?;
let response_v4: String = client_v4.request("say_hello", rpc_params![]).await?;
let response_v6: String = client_v6.request("say_hello", rpc_params![]).await?;
tracing::info!("response V4: {:?}", response_v4);
tracing::info!("response V6: {:?}", response_v6);
Ok(())
}
async fn run_server() -> anyhow::Result<(ServerHandle, Addrs)> {
let port = 9944;
// V4 address
let v4_addr = SocketAddr::from(([127, 0, 0, 1], port));
// V6 address
let v6_addr = SocketAddr::new("::1".parse().unwrap(), port);
let mut module = RpcModule::new(());
module.register_method("say_hello", |_, _, _| "lo")?;
// Bind to both IPv4 and IPv6 addresses.
let listener_v4 = TcpListener::bind(&v4_addr).await?;
let listener_v6 = TcpListener::bind(&v6_addr).await?;
// Each RPC call/connection get its own `stop_handle`
// to able to determine whether the server has been stopped or not.
//
// To keep the server running the `server_handle`
// must be kept and it can also be used to stop the server.
let (stop_hdl, server_hdl) = stop_channel();
// Create and finalize a server configuration from a TowerServiceBuilder
// given an RpcModule and the stop handle.
let svc = jsonrpsee::server::Server::builder().to_service_builder().build(module, stop_hdl.clone());
tokio::spawn(async move {
loop {
// The `tokio::select!` macro is used to wait for either of the
// listeners to accept a new connection or for the server to be
// stopped.
let stream = tokio::select! {
res = listener_v4.accept() => {
match res {
Ok((stream, _remote_addr)) => stream,
Err(e) => {
tracing::error!("failed to accept v4 connection: {:?}", e);
continue;
}
}
}
res = listener_v6.accept() => {
match res {
Ok((stream, _remote_addr)) => stream,
Err(e) => {
tracing::error!("failed to accept v6 connection: {:?}", e);
continue;
}
}
}
_ = stop_hdl.clone().shutdown() => break,
};
// Clone the service and stop handle to be moved into the spawn
// below.
let svc = svc.clone();
let stop_hdl2 = stop_hdl.clone();
// Spawn a new task to serve each respective (Hyper) connection.
tokio::spawn(async move {
let builder = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new());
let conn = builder.serve_connection_with_upgrades(TokioIo::new(stream), TowerToHyperService::new(svc));
let stopped = stop_hdl2.shutdown();
// Pin the future so that it can be polled.
tokio::pin!(stopped, conn);
let res = match future::select(conn, stopped).await {
// Return the connection if not stopped.
Either::Left((conn, _)) => conn,
// If the server is stopped, we should gracefully shutdown
// the connection and poll it until it finishes.
Either::Right((_, mut conn)) => {
conn.as_mut().graceful_shutdown();
conn.await
}
};
// Log any errors that might have occurred.
if let Err(err) = res {
tracing::error!(err=?err, "HTTP connection failed");
}
});
}
});
Ok((server_hdl, Addrs { v4: v4_addr, v6: v6_addr }))
}
struct Addrs {
v4: SocketAddr,
v6: SocketAddr,
}