Gracefully shut down on SIGINT/SIGTERM

This commit is contained in:
Joscha 2023-08-04 16:25:16 +02:00
parent e76c94a57c
commit 4914b03fcd
2 changed files with 34 additions and 6 deletions

View file

@ -1,7 +1,7 @@
mod state; mod state;
mod r#static; mod r#static;
use std::path::PathBuf; use std::{io, path::PathBuf};
use askama::Template; use askama::Template;
use askama_axum::{IntoResponse, Response}; use askama_axum::{IntoResponse, Response};
@ -9,7 +9,8 @@ use axum::{extract::State, http::StatusCode, routing::get, Router};
use clap::Parser; use clap::Parser;
use sqlx::SqlitePool; use sqlx::SqlitePool;
use state::AppState; use state::AppState;
use tracing::info; use tokio::{select, signal::unix::SignalKind};
use tracing::{debug, info};
use tracing_subscriber::filter::LevelFilter; use tracing_subscriber::filter::LevelFilter;
const NAME: &str = env!("CARGO_PKG_NAME"); const NAME: &str = env!("CARGO_PKG_NAME");
@ -41,6 +42,21 @@ fn set_up_logging(verbose: bool) {
} }
} }
async fn wait_for_signal() -> io::Result<()> {
debug!("Listening to signals");
let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt())?;
let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate())?;
let signal = select! {
_ = sigint.recv() => "SIGINT",
_ = sigterm.recv() => "SIGTERM",
};
info!("Received {signal}, shutting down");
Ok(())
}
#[derive(Template)] #[derive(Template)]
#[template(path = "index.html")] #[template(path = "index.html")]
struct IndexTemplate { struct IndexTemplate {
@ -68,13 +84,20 @@ async fn run() -> anyhow::Result<()> {
let app = Router::new() let app = Router::new()
.route("/", get(index)) .route("/", get(index))
.fallback(get(r#static::static_handler)) .fallback(get(r#static::static_handler))
.with_state(state); .with_state(state.clone())
.into_make_service();
// TODO Add text body to body-less status codes // TODO Add text body to body-less status codes
// TODO Add anyhow-like error type for endpoints // TODO Add anyhow-like error type for endpoints
axum::Server::bind(&"0.0.0.0:8000".parse().unwrap()) let server = axum::Server::bind(&"0.0.0.0:8000".parse().unwrap());
.serve(app.into_make_service())
.await?; info!("Startup complete, running");
select! {
_ = wait_for_signal() => {},
_ = server.serve(app) => {},
}
state.shut_down().await;
Ok(()) Ok(())
} }

View file

@ -46,4 +46,9 @@ impl AppState {
db: pool(db_path).await?, db: pool(db_path).await?,
}) })
} }
pub async fn shut_down(self) {
info!("Closing db");
self.db.close().await;
}
} }