app: Implement graceful shutdown

When calling `axum::serve`, use `.with_graceful_shutdown()` to register
a `ctrl+c` handler, so that Iocaine can be gracefully shut down. This
also allows gracefully shutting it down when running inside a container.

Fixes #1, thanks @alciregi!

Signed-off-by: Gergely Nagy <me@gergo.csillger.hu>
This commit is contained in:
Gergely Nagy 2025-01-19 22:04:55 +01:00
parent 85e6f4f66f
commit b214131d8b
No known key found for this signature in database

View file

@ -52,7 +52,29 @@ impl Iocaine {
.layer(Extension(self.clone()))
.layer(tower_http::trace::TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind(bind).await?;
axum::serve(listener, app).await
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await
}
}
async fn shutdown_signal() {
let ctrl_c = async {
tokio::signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};
let terminate = async {
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("failed to install signal handler")
.recv()
.await;
};
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
}