encore-dev 2.0.0-beta.9

Rust SDK for Encore applications
Documentation
//! Graceful shutdown on SIGTERM or SIGINT (Ctrl+C/Ctrl+Break on Windows).
//!
//! On the signal Encore stops Pub/Sub intake, waits for in-flight message
//! handlers, flushes metrics and telemetry, and exits: 0 when this finished
//! within the shutdown deadline, else 1.
//!
//! An app serving requests drains them first: it passes [`signal`] to its
//! server's graceful shutdown, then awaits [`drained`]. Encore cleans up when
//! the app has drained or the 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 once a shutdown signal is received. Calling it 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;
    }
}

/// Tells Encore the app has drained its work, and waits for Encore's cleanup.
/// Begins the shutdown if no signal has. The app exits once it returns.
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());
        }
    });
}