encore-dev 2.0.0-beta.21

Rust SDK for Encore applications
Documentation
//! Graceful shutdown on `SIGTERM` or `SIGINT` (`Ctrl+C`/`Ctrl+Break` on
//! Windows).
//!
//! When a shutdown signal arrives, Encore stops Pub/Sub intake, waits for
//! in-flight message handlers to complete, flushes metrics and telemetry, and
//! exits with status `0` if cleanup finished within the shutdown deadline (or
//! `1` otherwise).
//!
//! An application serving requests should drain them before Encore cleans up:
//! pass [`signal`] to your server's graceful shutdown hook, then await
//! [`drained`]. Encore starts cleanup as soon as the application finishes
//! draining or the shutdown deadline passes, whichever comes first.
//!
//! ```ignore
//! axum::serve(listener, app)
//!     .with_graceful_shutdown(encore::shutdown::signal())
//!     .await?;
//! std::process::exit(encore::shutdown::drained().await.code());
//! ```

use std::future::Future;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::OnceLock;

use encore_sdk_core::Runtime as CoreRuntime;
use tokio::sync::watch;

pub use encore_sdk_core::shutdown::ShutdownResult;

/// Set by [`signal`]: on the signal, cleanup waits for [`drained`].
static COOPERATIVE: AtomicBool = AtomicBool::new(false);
/// Set by [`drained`]: the app exits once cleanup completes.
static DRAINED: AtomicBool = AtomicBool::new(false);

/// True once a shutdown signal has begun the shutdown.
fn signalled() -> &'static watch::Sender<bool> {
    static SIGNALLED: OnceLock<watch::Sender<bool>> = OnceLock::new();
    SIGNALLED.get_or_init(|| watch::channel(false).0)
}

/// Resolves when a shutdown signal is received.
///
/// Calling this function defers Encore's cleanup until [`drained`] is awaited
/// or the shutdown deadline passes.
pub fn signal() -> impl Future<Output = ()> + Send + 'static {
    COOPERATIVE.store(true, Ordering::SeqCst);
    crate::runtime::core();
    let mut rx = signalled().subscribe();
    async move {
        _ = rx.wait_for(|signalled| *signalled).await;
    }
}

/// Notifies Encore that the application has finished draining its work, and
/// waits for Encore's cleanup to complete.
///
/// If no shutdown signal has been received yet, this initiates shutdown. Once
/// this function returns, the application should exit with the returned
/// [`ShutdownResult::code`].
pub async fn drained() -> ShutdownResult {
    DRAINED.store(true, Ordering::SeqCst);
    let core = crate::runtime::core();
    begin(core, false);
    core.shutdown_controller().mark_application_drained();
    completed(core).await
}

fn begin(core: &CoreRuntime, cooperative: bool) {
    let _guard = core.tokio_handle().enter();
    core.shutdown_controller().begin(cooperative);
}

async fn completed(core: &CoreRuntime) -> ShutdownResult {
    let result = core
        .shutdown_controller()
        .completed()
        .await
        .unwrap_or_else(|err| {
            tracing::error!("failed to await shutdown completion: {err}");
            ShutdownResult::Failed
        });
    crate::console_log::flush();
    result
}

/// Shuts down on SIGTERM or SIGINT, exiting once cleanup completes unless the
/// app has drained, in which case the app exits. Not in tests, as in Go.
pub(crate) fn watch(core: &'static CoreRuntime) {
    use encore_sdk_core::encore::runtime::v1::environment::Type;
    let testing = core
        .config_proto()
        .environment
        .as_ref()
        .is_some_and(|env| env.env_type() == Type::Test);
    if testing {
        return;
    }
    let _guard = core.tokio_handle().enter();
    let handle = match encore_sdk_core::shutdown::watch(core.shutdown_config().clone()) {
        Ok(handle) => handle,
        Err(err) => {
            tracing::error!("not listening for shutdown signals: {err}");
            return;
        }
    };
    core.tokio_handle().spawn(async move {
        handle.cancelled().await;
        begin(core, COOPERATIVE.load(Ordering::SeqCst));
        signalled().send_replace(true);
        let result = completed(core).await;
        if !DRAINED.load(Ordering::SeqCst) {
            std::process::exit(result.code());
        }
    });
}