Skip to content

Commit f40b435

Browse files
authored
improved graceful shutdown (#176)
1 parent 5088706 commit f40b435

1 file changed

Lines changed: 41 additions & 1 deletion

File tree

volga/src/app.rs

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,11 @@ use tokio::{
2020
sync::{Semaphore, watch},
2121
};
2222

23+
#[cfg(unix)]
24+
use tokio::signal::unix::{SignalKind, signal as unix_signal};
25+
#[cfg(windows)]
26+
use tokio::signal::windows;
27+
2328
#[cfg(feature = "rate-limiting")]
2429
use {
2530
crate::rate_limiting::GlobalRateLimiter,
@@ -793,7 +798,7 @@ impl App {
793798
#[inline]
794799
fn shutdown_signal(shutdown_rx: watch::Receiver<()>) {
795800
tokio::spawn(async move {
796-
match signal::ctrl_c().await {
801+
match Self::wait_for_shutdown_signal().await {
797802
Ok(_) => (),
798803
#[cfg(feature = "tracing")]
799804
Err(err) => tracing::error!("unable to listen for shutdown signal: {err:#}"),
@@ -806,6 +811,41 @@ impl App {
806811
});
807812
}
808813

814+
#[inline]
815+
async fn wait_for_shutdown_signal() -> io::Result<()> {
816+
#[cfg(unix)]
817+
{
818+
let mut terminate = unix_signal(SignalKind::terminate())?;
819+
820+
tokio::select! {
821+
result = signal::ctrl_c() => result,
822+
_ = terminate.recv() => Ok(()),
823+
}
824+
}
825+
826+
#[cfg(not(unix))]
827+
{
828+
#[cfg(windows)]
829+
{
830+
let mut ctrl_break = windows::ctrl_break()?;
831+
let mut ctrl_close = windows::ctrl_close()?;
832+
let mut ctrl_shutdown = windows::ctrl_shutdown()?;
833+
834+
tokio::select! {
835+
result = signal::ctrl_c() => result,
836+
_ = ctrl_break.recv() => Ok(()),
837+
_ = ctrl_close.recv() => Ok(()),
838+
_ = ctrl_shutdown.recv() => Ok(()),
839+
}
840+
}
841+
842+
#[cfg(not(windows))]
843+
{
844+
signal::ctrl_c().await
845+
}
846+
}
847+
}
848+
809849
#[inline]
810850
async fn handle_connection(stream: TcpStream, app_instance: Weak<AppEnv>) {
811851
let peer_addr = match stream.peer_addr() {

0 commit comments

Comments
 (0)