fix: do not panic when failed to start service (fix #362)

This commit is contained in:
Kevin Yue 2024-05-19 10:19:21 +08:00
parent 200d13ef15
commit e08f239176

View File

@ -118,12 +118,14 @@ impl WsServer {
} }
pub async fn start(&self, shutdown_tx: mpsc::Sender<()>) { pub async fn start(&self, shutdown_tx: mpsc::Sender<()>) {
if let Ok(listener) = TcpListener::bind("127.0.0.1:0").await { let listener = match self.start_tcp_server().await {
let local_addr = listener.local_addr().unwrap(); Ok(listener) => listener,
Err(err) => {
self.lock_file.lock(local_addr.port().to_string()).unwrap(); warn!("Failed to start WS server: {}", err);
let _ = shutdown_tx.send(()).await;
info!("WS server listening on port: {}", local_addr.port()); return;
},
};
tokio::select! { tokio::select! {
_ = watch_vpn_state(self.ctx.vpn_state_rx(), Arc::clone(&self.ctx)) => { _ = watch_vpn_state(self.ctx.vpn_state_rx(), Arc::clone(&self.ctx)) => {
@ -136,10 +138,21 @@ impl WsServer {
info!("WS server cancelled"); info!("WS server cancelled");
} }
} }
}
let _ = shutdown_tx.send(()).await; let _ = shutdown_tx.send(()).await;
} }
async fn start_tcp_server(&self) -> anyhow::Result<TcpListener> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let local_addr = listener.local_addr()?;
let port = local_addr.port();
info!("WS server listening on port: {}", port);
self.lock_file.lock(port.to_string())?;
Ok(listener)
}
} }
async fn watch_vpn_state(mut vpn_state_rx: watch::Receiver<VpnState>, ctx: Arc<WsServerContext>) { async fn watch_vpn_state(mut vpn_state_rx: watch::Receiver<VpnState>, ctx: Arc<WsServerContext>) {