mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Cooperative shutdown.
//!
//! A signal never kills the process outright. It flips a cancellation token
//! that every task watches, so work stops at a point where the server has been
//! told and the output channel has been flushed.

use std::sync::Arc;
use tokio_util::sync::CancellationToken;

/// Why the invocation is stopping.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StopReason {
    /// The caller interrupted from the terminal.
    Interrupt,
    /// The caller asked the process to terminate.
    Terminate,
}

impl StopReason {
    /// The exit number this reason produces.
    #[must_use]
    pub const fn exit_number(self) -> crate::error::ExitNumber {
        match self {
            // Both map to the interrupted number: the caller stopped the work,
            // and the published table carries one number for that.
            Self::Interrupt | Self::Terminate => crate::error::ExitNumber::Interrupted,
        }
    }
}

/// The shutdown signal shared by every task of the invocation.
#[derive(Debug, Clone)]
pub struct Shutdown {
    token: CancellationToken,
    reason: Arc<std::sync::OnceLock<StopReason>>,
}

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

impl Shutdown {
    /// Creates a signal that has not fired.
    #[must_use]
    pub fn new() -> Self {
        Self {
            token: CancellationToken::new(),
            reason: Arc::new(std::sync::OnceLock::new()),
        }
    }

    /// The token tasks watch.
    #[must_use]
    pub fn token(&self) -> CancellationToken {
        self.token.clone()
    }

    /// Whether shutdown was asked for.
    #[must_use]
    pub fn is_stopping(&self) -> bool {
        self.token.is_cancelled()
    }

    /// Why the invocation stopped, once it has.
    #[must_use]
    pub fn reason(&self) -> Option<StopReason> {
        self.reason.get().copied()
    }

    /// Asks every task to stop.
    ///
    /// The first reason wins, so a later signal does not rewrite the record of
    /// what actually stopped the work.
    pub fn stop(&self, reason: StopReason) {
        let _ = self.reason.set(reason);
        self.token.cancel();
    }

    /// Watches the operating system signals and flips the token on the first.
    ///
    /// The returned task ends on its own once a signal arrives or the token is
    /// cancelled from elsewhere, so it never outlives the invocation.
    #[must_use]
    pub fn watch_signals(&self) -> tokio::task::JoinHandle<()> {
        let shutdown = self.clone();
        tokio::spawn(async move {
            let token = shutdown.token();
            tokio::select! {
                () = token.cancelled() => {}
                reason = next_signal() => shutdown.stop(reason),
            }
        })
    }
}

/// Resolves when the first stop signal arrives.
#[cfg(unix)]
async fn next_signal() -> StopReason {
    use tokio::signal::unix::{signal, SignalKind};

    // A failure to install a handler leaves that signal unwatched rather than
    // aborting the invocation: the work still runs, it just cannot be
    // interrupted through that particular signal.
    let Ok(mut interrupt) = signal(SignalKind::interrupt()) else {
        return std::future::pending().await;
    };
    let Ok(mut terminate) = signal(SignalKind::terminate()) else {
        return std::future::pending().await;
    };

    tokio::select! {
        _ = interrupt.recv() => StopReason::Interrupt,
        _ = terminate.recv() => StopReason::Terminate,
    }
}

/// Resolves when the first stop signal arrives.
#[cfg(windows)]
async fn next_signal() -> StopReason {
    use tokio::signal::windows;

    let mut ctrl_c = match windows::ctrl_c() {
        Ok(stream) => stream,
        Err(_) => return std::future::pending().await,
    };
    let mut ctrl_close = match windows::ctrl_close() {
        Ok(stream) => stream,
        Err(_) => return std::future::pending().await,
    };

    tokio::select! {
        _ = ctrl_c.recv() => StopReason::Interrupt,
        _ = ctrl_close.recv() => StopReason::Terminate,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_fresh_signal_has_not_fired() {
        let shutdown = Shutdown::new();
        assert!(!shutdown.is_stopping());
        assert_eq!(shutdown.reason(), None);
    }

    #[test]
    fn the_first_reason_wins() {
        let shutdown = Shutdown::new();
        shutdown.stop(StopReason::Interrupt);
        shutdown.stop(StopReason::Terminate);
        assert_eq!(shutdown.reason(), Some(StopReason::Interrupt));
        assert!(shutdown.is_stopping());
    }

    #[test]
    fn stopping_reaches_every_clone() {
        let shutdown = Shutdown::new();
        let watcher = shutdown.clone();
        shutdown.stop(StopReason::Terminate);
        assert!(watcher.is_stopping());
        assert!(watcher.token().is_cancelled());
    }
}