rs-zero 0.2.24

Rust-first microservice framework inspired by go-zero engineering practices
Documentation
use std::{future::Future, pin::Pin, sync::Arc};

use tokio::sync::Notify;

/// Cloneable shutdown token used by [`crate::core::ServiceGroup`].
#[derive(Debug, Clone)]
pub struct ShutdownToken {
    inner: Arc<ShutdownState>,
}

#[derive(Debug)]
struct ShutdownState {
    notify: Notify,
    cancelled: std::sync::atomic::AtomicBool,
}

impl Default for ShutdownToken {
    fn default() -> Self {
        Self::new()
    }
}

impl ShutdownToken {
    /// Creates a token in the running state.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(ShutdownState {
                notify: Notify::new(),
                cancelled: std::sync::atomic::AtomicBool::new(false),
            }),
        }
    }

    /// Requests shutdown. Calling this method multiple times is safe.
    pub fn cancel(&self) {
        if !self
            .inner
            .cancelled
            .swap(true, std::sync::atomic::Ordering::SeqCst)
        {
            self.inner.notify.notify_waiters();
        }
    }

    /// Returns whether shutdown has been requested.
    pub fn is_cancelled(&self) -> bool {
        self.inner
            .cancelled
            .load(std::sync::atomic::Ordering::SeqCst)
    }

    /// Waits until shutdown is requested.
    pub fn cancelled(&self) -> ShutdownFuture<'_> {
        Box::pin(async move {
            loop {
                let notified = self.inner.notify.notified();
                if self.is_cancelled() {
                    return;
                }
                notified.await;
            }
        })
    }
}

/// Future returned by [`ShutdownToken::cancelled`].
pub type ShutdownFuture<'a> = Pin<Box<dyn Future<Output = ()> + Send + 'a>>;

/// Waits until the process receives Ctrl-C or a Unix termination signal.
///
/// Services can pass this future to server helpers that support graceful
/// shutdown.
pub async fn shutdown_signal() {
    #[cfg(unix)]
    {
        let interrupt = async {
            if let Err(error) = tokio::signal::ctrl_c().await {
                tracing::warn!(%error, "failed to listen for ctrl-c");
                std::future::pending::<()>().await;
            }
        };
        let terminate = async {
            match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
                Ok(mut signal) => {
                    let _ = signal.recv().await;
                }
                Err(error) => {
                    tracing::warn!(%error, "failed to listen for sigterm");
                    std::future::pending::<()>().await;
                }
            }
        };
        wait_for_unix_shutdown(interrupt, terminate).await;
    }

    #[cfg(not(unix))]
    if let Err(error) = tokio::signal::ctrl_c().await {
        tracing::warn!(%error, "failed to listen for ctrl-c");
    }
}

#[cfg(unix)]
async fn wait_for_unix_shutdown<I, T>(interrupt: I, terminate: T)
where
    I: Future<Output = ()>,
    T: Future<Output = ()>,
{
    tokio::select! {
        _ = interrupt => {}
        _ = terminate => {}
    }
}

#[cfg(all(test, unix))]
mod tests {
    use std::{
        process::{Command, Stdio},
        time::{Duration, Instant, SystemTime, UNIX_EPOCH},
    };

    const SIGTERM_CHILD_ENV: &str = "RS_ZERO_SIGTERM_TEST_CHILD";
    const SIGTERM_READY_FILE_ENV: &str = "RS_ZERO_SIGTERM_TEST_READY_FILE";

    #[tokio::test]
    async fn unix_shutdown_completes_for_the_terminate_branch() {
        super::wait_for_unix_shutdown(std::future::pending::<()>(), std::future::ready(())).await;
    }

    #[tokio::test]
    async fn unix_shutdown_completes_for_the_interrupt_branch() {
        super::wait_for_unix_shutdown(std::future::ready(()), std::future::pending::<()>()).await;
    }

    #[tokio::test]
    async fn sigterm_child_entrypoint() {
        if std::env::var_os(SIGTERM_CHILD_ENV).is_none() {
            return;
        }

        let ready_file = std::env::var_os(SIGTERM_READY_FILE_ENV).expect("ready file path");
        let shutdown = tokio::spawn(super::shutdown_signal());
        tokio::task::yield_now().await;
        std::fs::write(ready_file, b"ready").expect("write ready marker");
        shutdown.await.expect("shutdown signal task");
    }

    #[test]
    fn shutdown_signal_exits_after_real_sigterm() {
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system clock")
            .as_nanos();
        let ready_file = std::env::temp_dir().join(format!(
            "rs-zero-sigterm-{}-{nonce}.ready",
            std::process::id()
        ));
        let mut child = Command::new(std::env::current_exe().expect("current test executable"))
            .args([
                "--exact",
                "core::shutdown::tests::sigterm_child_entrypoint",
                "--nocapture",
            ])
            .env(SIGTERM_CHILD_ENV, "1")
            .env(SIGTERM_READY_FILE_ENV, &ready_file)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .expect("spawn SIGTERM child");

        let ready_deadline = Instant::now() + Duration::from_secs(5);
        while !ready_file.exists() && Instant::now() < ready_deadline {
            std::thread::sleep(Duration::from_millis(10));
        }
        if !ready_file.exists() {
            let _ = child.kill();
            let _ = child.wait();
            panic!("SIGTERM child did not become ready");
        }

        let status = Command::new("kill")
            .args(["-TERM", &child.id().to_string()])
            .status()
            .expect("send SIGTERM");
        assert!(status.success(), "kill command failed: {status}");

        let exit_deadline = Instant::now() + Duration::from_secs(5);
        let exit = loop {
            if let Some(status) = child.try_wait().expect("poll SIGTERM child") {
                break status;
            }
            if Instant::now() >= exit_deadline {
                let _ = child.kill();
                let _ = child.wait();
                panic!("SIGTERM child did not exit");
            }
            std::thread::sleep(Duration::from_millis(10));
        };
        let _ = std::fs::remove_file(&ready_file);
        assert!(exit.success(), "SIGTERM child failed: {exit}");
    }
}