Skip to main content

agp_signal/
lib.rs

1// Copyright AGNTCY Contributors (https://github.com/agntcy)
2// SPDX-License-Identifier: Apache-2.0
3
4pub async fn shutdown() {
5    imp::shutdown().await
6}
7
8#[cfg(unix)]
9mod imp {
10    use tokio::signal::unix::{SignalKind, signal};
11    use tracing::info;
12
13    pub(super) async fn shutdown() {
14        tokio::select! {
15            // this will handle interrupt signal by users
16            _ = sig(SignalKind::interrupt(), "SIGINT") => {}
17            // this will handle SIGTERM signal
18            // e.g. k8s send this signal to stop the container
19            _ = sig(SignalKind::terminate(), "SIGTERM") => {}
20        };
21    }
22
23    async fn sig(kind: SignalKind, name: &str) {
24        signal(kind)
25            .expect("Failed to register signal handler")
26            .recv()
27            .await;
28        info!(
29            target: "gateway::signal",
30            "received signal {}, starting shutdown",
31            name,
32        );
33    }
34}
35
36#[cfg(not(unix))]
37mod imp {
38    use tracing::info;
39
40    pub(super) async fn shutdown() {
41        tokio::signal::windows::ctrl_c()
42            .expect("Failed to register signal handler")
43            .recv()
44            .await;
45        info!(
46            target: "gateway::signal",
47            "received signal Ctrl-C, starting shutdown",
48        );
49    }
50}