From b21c4898d44e3b775423b8d698d425fc43a85981 Mon Sep 17 00:00:00 2001 From: Igor Aleksanov Date: Tue, 7 Jan 2025 22:49:46 +0400 Subject: [PATCH] fix: Print correct port for spawned server (#513) --- crates/api_server/src/server.rs | 18 +++++++++++++++--- crates/cli/src/main.rs | 4 +++- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/crates/api_server/src/server.rs b/crates/api_server/src/server.rs index 8bd9de15..39488a5d 100644 --- a/crates/api_server/src/server.rs +++ b/crates/api_server/src/server.rs @@ -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 ServerHandle>); +pub struct NodeServer { + local_addr: SocketAddr, + run_fn: Box 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)() } } diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 3bf7f327..4796cdf3 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -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())));