Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit a527da9

Browse files
committed
add backwards compability
1 parent 0ef7b68 commit a527da9

File tree

3 files changed

+58
-25
lines changed

3 files changed

+58
-25
lines changed

bin/node/cli/tests/common.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -163,14 +163,14 @@ pub fn find_ws_url_from_output(read: impl Read + Send) -> (String, String) {
163163
data.push_str(&line);
164164

165165
// does the line contain our port (we expect this specific output from substrate).
166-
let sock_addr = match line.split_once("Running JSON-RPC server: addr=") {
166+
let sock_addr = match line.split_once("Running JSON-RPC WS server: addr=") {
167167
None => return None,
168168
Some((_, after)) => after.split_once(",").unwrap().0,
169169
};
170170

171171
Some(format!("ws://{}", sock_addr))
172172
})
173-
.expect("We should get an address");
173+
.expect("We should get a WebSocket address");
174174

175175
(ws_url, data)
176176
}

client/rpc-servers/src/lib.rs

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ impl Config {
8080
}
8181
}
8282

83-
/// Start WS server listening on given address.
83+
/// Start JSON-RPC server listening on given address.
8484
pub async fn start_server<M: Send + Sync + 'static>(
8585
addrs: [SocketAddr; 2],
8686
cors: Option<&Vec<String>>,
@@ -89,20 +89,23 @@ pub async fn start_server<M: Send + Sync + 'static>(
8989
rpc_api: RpcModule<M>,
9090
rt: tokio::runtime::Handle,
9191
id_provider: Option<Box<dyn IdProvider>>,
92+
transport_label: &str,
9293
) -> Result<ServerHandle, Box<dyn StdError + Send + Sync>> {
9394
let (max_payload_in, max_payload_out, max_connections, max_subs_per_conn) =
9495
config.deconstruct();
9596

96-
let (allow_hosts, cors) = {
97+
let host_filter = hosts_filter(cors.is_some(), &addrs);
98+
99+
let cors = {
97100
if let Some(cors) = cors {
98101
let mut list = Vec::new();
99102
for origin in cors {
100103
list.push(HeaderValue::from_str(origin.as_str())?);
101104
}
102-
(allowed_hosts(&addrs), CorsLayer::new().allow_origin(AllowOrigin::list(list)))
105+
CorsLayer::new().allow_origin(AllowOrigin::list(list))
103106
} else {
104107
// allow all cors
105-
(AllowHosts::Any, CorsLayer::permissive())
108+
CorsLayer::permissive()
106109
}
107110
};
108111

@@ -117,7 +120,7 @@ pub async fn start_server<M: Send + Sync + 'static>(
117120
.max_connections(max_connections)
118121
.max_subscriptions_per_connection(max_subs_per_conn)
119122
.ping_interval(std::time::Duration::from_secs(30))
120-
.set_host_filtering(allow_hosts)
123+
.set_host_filtering(host_filter)
121124
.set_middleware(middleware)
122125
.custom_tokio_runtime(rt);
123126

@@ -140,23 +143,15 @@ pub async fn start_server<M: Send + Sync + 'static>(
140143
};
141144

142145
log::info!(
143-
"Running JSON-RPC server: addr={}, cors={:?}",
146+
"Running JSON-RPC {} server: addr={}, cors={:?}",
147+
transport_label,
144148
addr.map_or_else(|_| "unknown".to_string(), |a| a.to_string()),
145149
cors
146150
);
147151

148152
Ok(handle)
149153
}
150154

151-
fn allowed_hosts(addrs: &[SocketAddr]) -> AllowHosts {
152-
let mut hosts = Vec::with_capacity(addrs.len() * 2);
153-
for addr in addrs {
154-
hosts.push(format!("localhost:{}", addr.port()).into());
155-
hosts.push(format!("127.0.0.1:{}", addr.port()).into());
156-
}
157-
AllowHosts::Only(hosts)
158-
}
159-
160155
fn build_rpc_api<M: Send + Sync + 'static>(mut rpc_api: RpcModule<M>) -> RpcModule<M> {
161156
let mut available_methods = rpc_api.method_names().collect::<Vec<_>>();
162157
available_methods.sort();
@@ -175,3 +170,17 @@ fn build_rpc_api<M: Send + Sync + 'static>(mut rpc_api: RpcModule<M>) -> RpcModu
175170
fn payload_size_or_default(size_mb: Option<usize>) -> usize {
176171
size_mb.map_or(RPC_MAX_PAYLOAD_DEFAULT, |mb| mb.saturating_mul(MEGABYTE))
177172
}
173+
174+
fn hosts_filter(enabled: bool, addrs: &[SocketAddr]) -> AllowHosts {
175+
if enabled {
176+
// NOTE The listening addresses are whitelisted by default.
177+
let mut hosts = Vec::with_capacity(addrs.len() * 2);
178+
for addr in addrs {
179+
hosts.push(format!("localhost:{}", addr.port()).into());
180+
hosts.push(format!("127.0.0.1:{}", addr.port()).into());
181+
}
182+
AllowHosts::Only(hosts)
183+
} else {
184+
AllowHosts::Any
185+
}
186+
}

client/service/src/lib.rs

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -329,10 +329,15 @@ where
329329
addr
330330
};
331331

332-
let addr = config
332+
let ws_addr = config
333333
.rpc_ws
334334
.unwrap_or_else(|| "127.0.0.1:9944".parse().expect("valid sockaddr; qed"));
335-
let addr2 = random_port(addr);
335+
let ws_addr2 = random_port(ws_addr);
336+
337+
let http_addr = config
338+
.rpc_http
339+
.unwrap_or_else(|| "127.0.0.1:9933".parse().expect("valid sockaddr; qed"));
340+
let http_addr2 = random_port(http_addr);
336341

337342
let metrics = sc_rpc_server::RpcMetrics::new(config.prometheus_registry())?;
338343

@@ -343,18 +348,37 @@ where
343348
max_subs_per_conn: config.rpc_max_subs_per_conn,
344349
};
345350

346-
let server_fut = sc_rpc_server::start_server(
347-
[addr, addr2],
351+
let ws_fut = sc_rpc_server::start_server(
352+
[ws_addr, ws_addr2],
353+
config.rpc_cors.as_ref(),
354+
server_config.clone(),
355+
metrics.clone(),
356+
gen_rpc_module(deny_unsafe(ws_addr, &config.rpc_methods))?,
357+
config.tokio_handle.clone(),
358+
rpc_id_provider,
359+
"WS",
360+
);
361+
362+
let http_fut = sc_rpc_server::start_server(
363+
[http_addr, http_addr2],
348364
config.rpc_cors.as_ref(),
349365
server_config,
350366
metrics,
351-
gen_rpc_module(deny_unsafe(addr, &config.rpc_methods))?,
367+
gen_rpc_module(deny_unsafe(http_addr, &config.rpc_methods))?,
352368
config.tokio_handle.clone(),
353-
rpc_id_provider,
369+
// NOTE: this is hack to be backwards compatible because the `RpcSubscriptionIdProvider`
370+
// isn't cloneable and we don't expect ws connections to the old http server.
371+
//
372+
// The only downside to that is if one configures a custom subscription ID generator
373+
// then this will use the default one.
374+
None,
375+
"HTTP",
354376
);
355377

356-
match tokio::task::block_in_place(|| config.tokio_handle.block_on(server_fut)) {
357-
Ok(server) => Ok(Box::new(waiting::Server(Some(server)))),
378+
match tokio::task::block_in_place(|| {
379+
config.tokio_handle.block_on(futures::future::try_join(http_fut, ws_fut))
380+
}) {
381+
Ok((http, ws)) => Ok(Box::new((waiting::Server(Some(http)), waiting::Server(Some(ws))))),
358382
Err(e) => Err(Error::Application(e)),
359383
}
360384
}

0 commit comments

Comments
 (0)