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
#![warn(missing_docs)]
mod middleware;
use jsonrpc_core::{IoHandlerExtension, MetaIoHandler};
use log::error;
use pubsub::PubSubMetadata;
use std::io;
const MEGABYTE: usize = 1024 * 1024;
pub const RPC_MAX_PAYLOAD_DEFAULT: usize = 15 * MEGABYTE;
const WS_MAX_CONNECTIONS: usize = 100;
const HTTP_THREADS: usize = 4;
pub type RpcHandler<T> = pubsub::PubSubHandler<T, RpcMiddleware>;
pub use self::inner::*;
pub use middleware::{RpcMetrics, RpcMiddleware};
pub fn rpc_handler<M: PubSubMetadata>(
extension: impl IoHandlerExtension<M>,
rpc_middleware: RpcMiddleware,
) -> RpcHandler<M> {
let io_handler = MetaIoHandler::with_middleware(rpc_middleware);
let mut io = pubsub::PubSubHandler::new(io_handler);
extension.augment(&mut io);
let mut methods = io.iter().map(|x| x.0.clone()).collect::<Vec<String>>();
io.add_method("rpc_methods", {
methods.sort();
let methods = serde_json::to_value(&methods)
.expect("Serialization of Vec<String> is infallible; qed");
move |_| {
Ok(serde_json::json!({
"version": 1,
"methods": methods.clone(),
}))
}
});
io
}
#[cfg(not(target_os = "unknown"))]
mod inner {
use super::*;
pub type IpcServer = ipc::Server;
pub type HttpServer = http::Server;
pub type WsServer = ws::Server;
pub fn start_http<M: pubsub::PubSubMetadata + Default>(
addr: &std::net::SocketAddr,
thread_pool_size: Option<usize>,
cors: Option<&Vec<String>>,
io: RpcHandler<M>,
maybe_max_payload_mb: Option<usize>,
) -> io::Result<http::Server> {
let max_request_body_size = maybe_max_payload_mb
.map(|mb| mb.saturating_mul(MEGABYTE))
.unwrap_or(RPC_MAX_PAYLOAD_DEFAULT);
http::ServerBuilder::new(io)
.threads(thread_pool_size.unwrap_or(HTTP_THREADS))
.health_api(("/health", "system_health"))
.allowed_hosts(hosts_filtering(cors.is_some()))
.rest_api(if cors.is_some() { http::RestApi::Secure } else { http::RestApi::Unsecure })
.cors(map_cors::<http::AccessControlAllowOrigin>(cors))
.max_request_body_size(max_request_body_size)
.start_http(addr)
}
pub fn start_ipc<M: pubsub::PubSubMetadata + Default>(
addr: &str,
io: RpcHandler<M>,
) -> io::Result<ipc::Server> {
let builder = ipc::ServerBuilder::new(io);
#[cfg(target_os = "unix")]
builder.set_security_attributes({
let security_attributes = ipc::SecurityAttributes::empty();
security_attributes.set_mode(0o600)?;
security_attributes
});
builder.start(addr)
}
pub fn start_ws<
M: pubsub::PubSubMetadata + From<jsonrpc_core::futures::sync::mpsc::Sender<String>>,
>(
addr: &std::net::SocketAddr,
max_connections: Option<usize>,
cors: Option<&Vec<String>>,
io: RpcHandler<M>,
maybe_max_payload_mb: Option<usize>,
) -> io::Result<ws::Server> {
let rpc_max_payload = maybe_max_payload_mb
.map(|mb| mb.saturating_mul(MEGABYTE))
.unwrap_or(RPC_MAX_PAYLOAD_DEFAULT);
ws::ServerBuilder::with_meta_extractor(io, |context: &ws::RequestContext| {
context.sender().into()
})
.max_payload(rpc_max_payload)
.max_connections(max_connections.unwrap_or(WS_MAX_CONNECTIONS))
.allowed_origins(map_cors(cors))
.allowed_hosts(hosts_filtering(cors.is_some()))
.start(addr)
.map_err(|err| match err {
ws::Error::Io(io) => io,
ws::Error::ConnectionClosed => io::ErrorKind::BrokenPipe.into(),
e => {
error!("{}", e);
io::ErrorKind::Other.into()
},
})
}
fn map_cors<T: for<'a> From<&'a str>>(
cors: Option<&Vec<String>>,
) -> http::DomainsValidation<T> {
cors.map(|x| x.iter().map(AsRef::as_ref).map(Into::into).collect::<Vec<_>>())
.into()
}
fn hosts_filtering(enable: bool) -> http::DomainsValidation<http::Host> {
if enable {
http::DomainsValidation::AllowOnly(vec![])
} else {
http::DomainsValidation::Disabled
}
}
}
#[cfg(target_os = "unknown")]
mod inner {}