via/server/
shutdown.rs

1use tokio::signal;
2use tokio::sync::watch;
3use tokio::task::{self, JoinHandle};
4
5use crate::Error;
6
7pub fn wait_for_shutdown() -> (JoinHandle<Result<(), Error>>, watch::Receiver<bool>) {
8    // Create a watch channel to notify the connections to initiate a
9    // graceful shutdown process when the `ctrl_c` future resolves.
10    let (tx, rx) = watch::channel(false);
11
12    // Spawn a task to wait for a "Ctrl-C" signal to be sent to the process.
13    let task = task::spawn(async move {
14        match signal::ctrl_c().await {
15            Ok(_) => tx.send(true).map_err(|_| {
16                let message = "unable to notify connections to shutdown.";
17                Error::new(message.to_string())
18            }),
19            Err(error) => {
20                if cfg!(debug_assertions) {
21                    eprintln!("unable to register the 'Ctrl-C' signal.");
22                }
23
24                Err(error.into())
25            }
26        }
27    });
28
29    (task, rx)
30}