Skip to content

Commit

Permalink
fix: do not panic when failed to start service (fix #362)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuezk committed May 19, 2024
1 parent af51bc2 commit a01c55e
Showing 1 changed file with 30 additions and 17 deletions.
47 changes: 30 additions & 17 deletions apps/gpservice/src/ws_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,28 +118,41 @@ impl WsServer {
}

pub async fn start(&self, shutdown_tx: mpsc::Sender<()>) {
if let Ok(listener) = TcpListener::bind("127.0.0.1:0").await {
let local_addr = listener.local_addr().unwrap();

self.lock_file.lock(local_addr.port().to_string()).unwrap();

info!("WS server listening on port: {}", local_addr.port());

tokio::select! {
_ = watch_vpn_state(self.ctx.vpn_state_rx(), Arc::clone(&self.ctx)) => {
info!("VPN state watch task completed");
}
_ = start_server(listener, self.ctx.clone()) => {
info!("WS server stopped");
}
_ = self.cancel_token.cancelled() => {
info!("WS server cancelled");
}
let listener = match self.start_tcp_server().await {
Ok(listener) => listener,
Err(err) => {
warn!("Failed to start WS server: {}", err);
let _ = shutdown_tx.send(()).await;
return;
},
};

tokio::select! {
_ = watch_vpn_state(self.ctx.vpn_state_rx(), Arc::clone(&self.ctx)) => {
info!("VPN state watch task completed");
}
_ = start_server(listener, self.ctx.clone()) => {
info!("WS server stopped");
}
_ = self.cancel_token.cancelled() => {
info!("WS server cancelled");
}
}

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>) {
Expand Down

0 comments on commit a01c55e

Please sign in to comment.