pub async fn shutdown_signal(server: &str, shutdown_rx: Option<Receiver<()>>)
Expand description

Tokio signal handler that will wait for a user to press CTRL+C. This signal handler can be used in our [axum::Server] method with_graceful_shutdown and in our tonic::transport::Server method serve_with_shutdown.

Examples

axum

use svc_telemetry::shutdown_signal;
pub async fn server() {
    let app = axum::Router::new();
    axum::Server::bind(&"0.0.0.0:8000".parse().unwrap())
        .serve(app.into_make_service())
        .with_graceful_shutdown(shutdown_signal("rest", None));
}

tonic

use svc_telemetry::shutdown_signal;
pub async fn server() {
    let (_, health_service) = tonic_health::server::health_reporter();
    tonic::transport::Server::builder()
        .add_service(health_service)
        .serve_with_shutdown("0.0.0.0:50051".parse().unwrap(), shutdown_signal("grpc", None));
}

using a shutdown signal channel

use svc_telemetry::shutdown_signal;
pub async fn server() {
    let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
    let (_, health_service) = tonic_health::server::health_reporter();
    tokio::spawn(async move {
        tonic::transport::Server::builder()
            .add_service(health_service)
            .serve_with_shutdown("0.0.0.0:50051".parse().unwrap(), shutdown_signal("grpc", Some(shutdown_rx)))
            .await;
    });

    // Send server the shutdown request
    shutdown_tx.send(()).expect("Could not stop server.");
}