Skip to content

Commit

Permalink
fix: Print correct port for spawned server (#513)
Browse files Browse the repository at this point in the history
  • Loading branch information
popzxc authored Jan 7, 2025
1 parent 43e544f commit b21c489
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
18 changes: 15 additions & 3 deletions crates/api_server/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,22 +87,34 @@ impl NodeServerBuilder {
.set_rpc_middleware(RpcServiceBuilder::new().rpc_logger(100));

let server = server_builder.build(addr).await.unwrap();
let local_addr = server.local_addr().unwrap();
let rpc = Self::default_rpc(self.node);
// `jsonrpsee` does `tokio::spawn` within `start` method, so we cannot invoke it here, as this method
// should only build the server. This way we delay the launch until the `NodeServer::run` is invoked.
NodeServer(Box::new(move || server.start(rpc)))
NodeServer {
local_addr,
run_fn: Box::new(move || server.start(rpc)),
}
}
}

pub struct NodeServer(Box<dyn FnOnce() -> ServerHandle>);
pub struct NodeServer {
local_addr: SocketAddr,
run_fn: Box<dyn FnOnce() -> ServerHandle>,
}

impl NodeServer {
/// Returns the address the server is bound to.
pub fn local_addr(&self) -> SocketAddr {
self.local_addr
}

/// Start responding to connections requests.
///
/// This will run on the tokio runtime until the server is stopped or the `ServerHandle` is dropped.
///
/// See [`ServerHandle`](https://docs.rs/jsonrpsee-server/latest/jsonrpsee_server/struct.ServerHandle.html) docs for more details.
pub fn run(self) -> ServerHandle {
self.0()
(self.run_fn)()
}
}
4 changes: 3 additions & 1 deletion crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,9 @@ async fn main() -> anyhow::Result<()> {
let mut server_handles = Vec::with_capacity(config.host.len());
for host in &config.host {
let addr = SocketAddr::new(*host, config.port);
server_handles.push(server_builder.clone().build(addr).await.run());
let server = server_builder.clone().build(addr).await;
config.port = server.local_addr().port();
server_handles.push(server.run());
}
let any_server_stopped =
futures::future::select_all(server_handles.into_iter().map(|h| Box::pin(h.stopped())));
Expand Down

0 comments on commit b21c489

Please sign in to comment.