From 5a9e1e2e2be128fa728faf9b916bb3334d7ceef7 Mon Sep 17 00:00:00 2001 From: Mathias Wagner Date: Tue, 9 Sep 2025 10:38:24 +0200 Subject: [PATCH] Implement shutdown signal in main.rs --- server/Cargo.toml | 2 +- server/src/main.rs | 34 ++++++++++++++++++++++++++++++++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/server/Cargo.toml b/server/Cargo.toml index 84d10d9..d7ea383 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" [dependencies] axum = "0.8.4" -tokio = { version = "1.47.1", features = ["full"] } +tokio = { version = "1.47.1", features = ["full", "signal"] } sqlx = { version = "0.8.6", features = ["runtime-tokio-rustls", "sqlite", "chrono", "uuid"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" diff --git a/server/src/main.rs b/server/src/main.rs index 660bd06..83a0787 100644 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -8,6 +8,7 @@ use axum::{routing::{delete, get, post, put}, Router}; use routes::{admin, auth as auth_routes, machines, setup}; use tower_http::{cors::CorsLayer, services::{ServeDir, ServeFile}}; use std::path::Path; +use tokio::signal; #[tokio::main] async fn main() -> Result<()> { @@ -32,7 +33,7 @@ async fn main() -> Result<()> { .with_state(pool); - let dist_path = "../dist"; + let dist_path = "./dist"; let app = Router::new() .nest("/api", api_routes) .nest_service("/assets", ServeDir::new(format!("{}/assets", dist_path))) @@ -46,6 +47,35 @@ async fn main() -> Result<()> { let listener = tokio::net::TcpListener::bind("0.0.0.0:8379").await?; println!("Server running on http://0.0.0.0:8379"); - axum::serve(listener, app).await?; + + axum::serve(listener, app).with_graceful_shutdown(shutdown_signal()).await?; Ok(()) } + +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 => { + println!("\nShutting down due to Ctrl+C..."); + }, + _ = terminate => { + println!("\nShutting down due to terminate signal..."); + }, + } +}