Skip to content

Commit

Permalink
src: web: Add graceful shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
joaoantoniocardoso authored and patrickelectric committed Oct 3, 2024
1 parent f5215d3 commit 724d301
Showing 1 changed file with 37 additions and 3 deletions.
40 changes: 37 additions & 3 deletions src/web/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ use axum::{
};
use futures::{sink::SinkExt, stream::StreamExt};
use serde::Deserialize;
use tokio::sync::{broadcast, mpsc, RwLock};
use tokio::{
signal,
sync::{broadcast, mpsc, RwLock},
};
use tracing::*;
use uuid::Uuid;

Expand Down Expand Up @@ -227,9 +230,16 @@ pub async fn run(address: String) {
continue;
}
};
if let Err(error) = axum::serve(listener, router.clone()).into_future().await {
error!("WebServer error: {}", error);

if let Err(error) = axum::serve(listener, router.clone())
.with_graceful_shutdown(shutdown_signal())
.await
{
error!("WebServer error: {error}");
continue;
}

break;
}
}

Expand All @@ -240,3 +250,27 @@ where
let mut router = SERVER.router.lock().unwrap();
modifier(&mut router);
}

async fn shutdown_signal() {
let ctrl_c = async {
signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};

#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to install signal handler")
.recv()
.await;
};

#[cfg(not(unix))]
let terminate = std::future::pending::<()>();

tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
}

0 comments on commit 724d301

Please sign in to comment.