From 9c8b39e98f2bba805d0acd57de57d1bbf46e369d Mon Sep 17 00:00:00 2001 From: Martin Brodbeck Date: Wed, 16 Apr 2025 14:30:59 +0200 Subject: [PATCH] Honor SIGTERM --- Cargo.lock | 12 +++++++++++- Cargo.toml | 4 ++-- src/main.rs | 28 ++++++++++++++++++++++++++-- 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 50bde5b..6bcc756 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -740,7 +740,7 @@ checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674" [[package]] name = "kosyncrs" -version = "2.1.0" +version = "2.1.1" dependencies = [ "axum", "serde", @@ -1200,6 +1200,15 @@ dependencies = [ "digest", ] +[[package]] +name = "signal-hook-registry" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" +dependencies = [ + "libc", +] + [[package]] name = "signature" version = "2.2.0" @@ -1565,6 +1574,7 @@ dependencies = [ "libc", "mio", "pin-project-lite", + "signal-hook-registry", "socket2", "tokio-macros", "windows-sys 0.52.0", diff --git a/Cargo.toml b/Cargo.toml index bc8c73d..3793f9d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kosyncrs" -version = "2.1.1" +version = "2.2.0" edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -10,4 +10,4 @@ axum = "0.8.1" serde = { version = "1.0.188", features = ["derive"] } serde_json = "1.0.107" sqlx = { version = "0.8.3", features = ["runtime-tokio", "postgres"] } -tokio = { version = "1.32.0", features = ["macros", "rt-multi-thread"] } +tokio = { version = "1.32.0", features = ["macros", "rt-multi-thread", "signal"] } diff --git a/src/main.rs b/src/main.rs index e4ecac4..c14fc7f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -28,6 +28,7 @@ use axum::{ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use sqlx::{PgExecutor, PgPool, postgres::PgPoolOptions}; +use tokio::signal; use std::env; use std::time::{Duration, SystemTime, UNIX_EPOCH}; @@ -88,17 +89,40 @@ async fn main() { let mut bind_with = "0.0.0.0:".to_owned(); bind_with += &listen_port; let listener = tokio::net::TcpListener::bind(bind_with).await.unwrap(); - axum::serve(listener, app).await.unwrap(); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await + .unwrap(); } async fn root() -> &'static str { - "KOreader sync server" + "KOReader sync server" } async fn version() -> &'static str { VERSION } +async fn shutdown_signal() { + let ctrl_c = async { + signal::ctrl_c() + .await + .expect("Failed to install CTRL-C handler"); + }; + + let terminate = async { + signal::unix::signal(signal::unix::SignalKind::terminate()) + .expect("Failed to install Terminate handler") + .recv() + .await; + }; + + tokio::select! { + _ = ctrl_c => {}, + _ = terminate => {}, + } +} + async fn create_user( State(db_pool): State, Json(payload): Json,